Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(plugin): 允许插件自行管理任务配置

liugaowei7b212708f9ca
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 294066c785..34845cf03e 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -1705,6 +1705,15 @@ describe('scaffoldGhostDir', () => {
});
describe('FORGE_GUIDE', () => {
+ it('documents opting out of Host task configuration without bypassing user task authorization', () => {
+ expect(FORGE_GUIDE).toContain('"taskPreferences": false');
+ expect(FORGE_GUIDE).toContain('旧配置不参与执行');
+ expect(FORGE_GUIDE).toContain('仅更新该任务');
+ expect(FORGE_GUIDE).toContain('旧客户端忽略此字段,继续使用原卡片及配置');
+ expect(FORGE_GUIDE).toContain('"taskPreferences": true');
+ expect(FORGE_GUIDE).toContain('此声明只作用于当前插件,不关闭任务 API,也不影响其他插件');
+ });
+
it('账号业务元数据使用插件 KV,不声明 Host 昵称接口', () => {
expect(FORGE_GUIDE).toContain('昵称等自定义账号元数据由插件通过 `/kv` 保存');
expect(FORGE_GUIDE).toContain('执行仍传账号 id,不把昵称当作指令或授权');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
index fe8908e376..8814dcd3a0 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageService.test.ts
@@ -114,6 +114,23 @@ function setup(
};
}
describe('mobile plugin pages', () => {
+ it('disables Host task settings only for the instance declaring taskPreferences:false', async () => {
+ const h = setup();
+ h.ghost.manifest.agent = {tasks:true};
+ h.ghost.manifest.taskPreferences = false;
+ const other = {...h.ghost, manifest:{...h.ghost.manifest, id:'other', taskPreferences:true}};
+ h.ghosts.push(other);
+ const context = {controllerDeviceId:'phone-a'}, client = {protocolVersion:1,primitives:['plugin-capabilities']};
+ const ref = {collectionId:'plugins',kind:'plugin',id:'practice'};
+ const detail = await h.provider.get!(context,{ref,client});
+ expect(detail.blocks?.find(block=>block.id==='capabilities')?.data).toMatchObject({tasks:false});
+ for (const actionId of ['task-settings:get','task-settings:set'])
+ await expect(h.provider.invoke!(context,{collectionId:'plugins',resourceRef:ref,actionId,input:{},client})).rejects.toThrow();
+ expect(h.taskSettings.read).not.toHaveBeenCalled();
+ expect(h.taskSettings.update).not.toHaveBeenCalled();
+ await h.provider.invoke!(context,{collectionId:'plugins',resourceRef:{...ref,id:'other'},actionId:'task-settings:get',input:{},client});
+ expect(h.taskSettings.read).toHaveBeenCalledWith('other','r1');
+ });
it('adds usage facts to the existing capabilities block and preserves unknown setup on a failed read', async () => {
const h = setup({
setupAssessment: () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsMigration.test.ts
index 4da3cc04de..86b46acec1 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsMigration.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginModelPrefsMigration.test.ts
@@ -42,12 +42,43 @@ beforeEach(() => {
owner.id = 'owner-a';
cindy.__testing.resetStore();
task.__testing.resetLegacyPinMigration();
+ task.setPluginTaskPreferencesResolver(() => true);
});
afterEach(() => {
+ task.setPluginTaskPreferencesResolver(() => true);
fs.rmSync(owner.root, { recursive: true, force: true });
});
+describe('per-plugin Host configuration opt-out', () => {
+ it('ignores all saved defaults for the opted-out instance while another instance stays unchanged', () => {
+ const saved = { agentKind: 'codex', model: 'saved', providerId: 'source', effort: 'high', fastMode: true,
+ permissionMode: 'auto', workingDir: path.join(owner.root, 'project') };
+ writeJson(TASK_FILE, { errand: { '_root__ping': saved, '_ns__acme__ping': saved }, sessions: { '_root__ping': 'existing-task' } });
+ task.setPluginTaskPreferencesResolver(id => id !== '_root__ping');
+ expect(task.readPluginTaskConfig('_root__ping')).toEqual({});
+ expect(task.readPluginTaskPermissionMode('_root__ping')).toBeNull();
+ expect(task.readPluginTaskConfig('_ns__acme__ping')).toEqual(saved);
+ expect(task.readPluginTaskPermissionMode('_ns__acme__ping')).toBe('auto');
+ expect(() => task.writePluginTaskConfig('_root__ping', { model: 'replacement' })).toThrow('PLUGIN_TASK_PREFERENCES_DISABLED');
+ expect(() => task.writePluginTaskConfig('_root__ping', null)).toThrow('PLUGIN_TASK_PREFERENCES_DISABLED');
+ expect(task.readGhostErrandSessionId('_root__ping')).toBe('existing-task');
+ expect(readJson(TASK_FILE)).toMatchObject({ errand: { '_root__ping': saved } });
+ task.setPluginTaskPreferencesResolver(() => true);
+ expect(task.readPluginTaskConfig('_root__ping')).toEqual(saved);
+ });
+
+ it('does not create preference files or run legacy migration when the instance opts out', () => {
+ const legacy = { overrides: { ping: { 'text.oneshot': 'cat:xd:codex:old' } } };
+ writeJson(CINDY_FILE, legacy);
+ task.setPluginTaskPreferencesResolver(id => id !== 'ping');
+ expect(task.readPluginTaskConfig('ping')).toEqual({});
+ expect(() => task.writePluginTaskConfig('ping', { permissionMode: 'auto' })).toThrow('PLUGIN_TASK_PREFERENCES_DISABLED');
+ expect(readJson(TASK_FILE)).toBeUndefined();
+ expect(readJson(CINDY_FILE)).toEqual(legacy);
+ });
+});
+
describe('legacy per-ability pins → plugin model preference', () => {
it('migrates catalog pins, drops profile keys and media overrides, keeps other keys', () => {
// 旧布局:快问快答目录钉 / 轻量档位键 / 媒体与向量覆盖 / 并发上限 / 未知键。
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index a35c9dcd29..bb2f649435 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1743,7 +1743,8 @@ my-ghost/
// 一级主视图是独立能力,见 §4.20。使用时直接声明:
// "mainView": { "title": "工作台", "icon": "puzzle", "html": "main-view.html" }
"settingsHtml": "settings.html", // 可选:设置页「自定义设置区」自绘界面(见 §4.8;声明了用户填的凭证时仍必填,用于长期管理/替换/清除;调用前缺失时主机也会在统一 Setup 卡内联收单,见 §4.7)
- "settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮,高至 800);内容会动态增减时才声明,避免抖动
+ "settingsHeight": 360, // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮,高至 800);内容会动态增减时才声明,避免抖动
+ "taskPreferences": true // 可选:缺省/true 使用宿主模型与任务配置管理;false 仅本插件自行维护,见 §4.8
}
\`\`\`
@@ -2420,7 +2421,7 @@ const r = await cindy.send({
标题同一条),不拉起 Agent、没有工具、碰不到用户文件、不进任何会话——
要"干活"(读文件、查资料、多步操作)请用派活(§4.11.1);
- 选型仍不在你手里(没有 tier/model 参数),但有两级偏好:**用户可在插件
- 详情页「模型与任务」里给这个插件选一个模型**(插件只有这一个模型字段,快问
+ 详情页「模型与任务」里给这个插件选一个默认模型**(宿主只有这一个默认模型字段,快问
快答与你新建的任务共用;选了就钉死,失败不回落);你也可以在身份卡
\`cindy\` 里声明 \`"oneshotModel": "<目录模型 id>"\` 表达偏好——主机目录解析
得到(且用户没停用)就用它,解析不到按未声明处理。优先级:用户选的模型 >
@@ -3438,6 +3439,20 @@ tool-call 内轮询时记得定期发 tool-progress 心跳续命(见 §4"长任
"settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮),超 800 内部滚动
\`\`\`
+**宿主模型与任务配置管理(可选)**:顶层 \`taskPreferences\` 只接受布尔值。
+省略或设为 \`true\` 时,快问快答、普通任务、旧版代办或工作区插件沿用原有配置管理与卡片。
+声明 \`"taskPreferences": false\` 后,配置由插件自己维护(例如经 /kv 保存每项模型和任务去向):
+- Desktop 和手机不显示宿主「模型与任务」卡,宿主配置读写入口停用。
+- 宿主不再读取或写回该插件的默认模型、权限和目录,旧配置不参与执行,也不自动复制到插件。
+- 普通任务模型通过 §4.11.3 的 route 指定;未传仍按原 API 使用发起任务或当前新任务选择。
+ 快问快答未设宿主模型覆盖,按身份卡 oneshotModel/系统辅助模型链执行;旧 errand 与工作区同样跳过宿主配置。
+- 新普通任务初始权限为 ask、目录由宿主管理;目录选择仍走亲选记录和现有工作区 API。
+ requestWriteAccess 仍须用户确认,但仅更新该任务,不为插件后续任务保存全局默认权限。
+ 后续发送和协同检查该任务自身已获授的权限及 Plan 状态,不再套用宿主逐插件权限上限。
+此开关不关闭任务 API,也不授予额外权限;不要求声明 settingsHtml,没有相应能力也不会创建卡片。
+恢复为 \`true\` 或删除此字段后,宿主重新使用原来保存的配置;关闭期间不删除这些数据。
+旧客户端忽略此字段,继续使用原卡片及配置;依赖关闭语义的插件必须要求支持此字段的客户端版本。
+
**渲染环境**:与面板同款沙箱页(零桥、无通用网络直连,与同插件面板/逻辑页共用浏览器存储和
\`BroadcastChannel\`,脚本/样式/字体/媒体/数据请求仍只认同源)。所有插件 HTML 页面
(settingsHtml、panel、mainView 与逻辑页)唯一的网络直连例外都是**HTTPS 图片资源**:
@@ -3878,7 +3893,8 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });
后台隐藏只能经 §4.11.3 的 \`hiddenTasks\` 声明,且用户始终能在插件详情页查看与接手;
- 这是旧版任务接口,不是插件全部 AI 能力。普通任务管理用 §4.11.3,继续用户任务用 §4.11,
快问快答用 §4.0.2;不要把这些能力统一称为代办。
-- 新建任务共用插件详情「任务设置」中的模型组合(Agent、供应商、模型、推理强度、Fast)。
+- 使用宿主配置管理时,新建任务共用插件详情「任务设置」中的模型组合(Agent、供应商、模型、推理强度、Fast)。
+ 声明 \`taskPreferences:false\` 时跳过宿主配置,详见 §4.8;旧接口缺省权限仍按下述规则。
没有覆盖时,沿用宿主核实的同插件本机在途 \`callId\` 所属任务;面板直接创建使用当前新任务选择。
无显式覆盖的已有专属任务保留自身模型,用户在任务中改选后可继续复用。
显式配置发生冲突时,新任务创建成功才替换映射,旧任务与历史保留。
@@ -4057,6 +4073,11 @@ create/send 的 requestKey 持久去重;同键不同内容拒绝。删除后
省略 route 时使用用户给本插件的任务模型覆盖;无覆盖则沿用发起任务,面板直接创建时
沿用当前新任务选择。可显式传
\`{agentKind:'codex',providerId:'...',model:'...',effort:'high',fastMode:false}\`;无推理档位模型用空 effort。
+插件若自行维护各项模型、任务去向等配置,可在身份卡声明 \`taskPreferences:false\`(见 §4.8)。
+此时宿主不显示「模型与任务」卡,也不读写该插件的模型、权限或目录默认值;
+上述模型来源直接跳过插件宿主覆盖,新任务仍初始为 ask、宿主管理目录。
+\`requestWriteAccess\` 经用户确认后只更新该任务,后续派发按任务自身授权检查;
+此声明只作用于当前插件,不关闭任务 API,也不影响其他插件。
先查 \`capabilities().sourceCallContext\`:支持时,Agent 在途调用可在 create 中转传 \`callId\`。
宿主核对同插件本机调用后读取其模型;不能自报 sourceSessionId 或权限。面板直接创建省略 callId。
新字段需该能力为 true 才发送,旧客户端不能假定支持;同 requestKey 的重放保留原创建结果。
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 26f0701e7c..d2700129c4 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -359,7 +359,7 @@ import {
} from './cindySlot.js';
import { GhostAgentSlot, type GhostAgentTurnRunner } from './agentSlot.js';
import { GhostErrandSlot, type GhostErrandRunner } from './errandSlot.js';
-import { readPluginTaskConfig, writePluginTaskConfig, validatePluginTaskConfig, relocateGhostErrandPrefs } from './pluginTaskPrefsStore.js';
+import { readPluginTaskConfig, writePluginTaskConfig, validatePluginTaskConfig, relocateGhostErrandPrefs, setPluginTaskPreferencesResolver } from './pluginTaskPrefsStore.js';
import {
GhostNodeRuntimeBroker,
type NodeRuntimeStartAttemptContext,
@@ -727,6 +727,8 @@ function currentGhostAppContext() {
let managerSingleton: GhostManager | null = null;
let ghostSetupManifestTrackerSingleton: GhostSetupManifestTracker | null = null;
+setPluginTaskPreferencesResolver(id => findGhostForInstanceId(id)?.manifest.taskPreferences !== false);
+
function getGhostSetupManifestTracker(): GhostSetupManifestTracker {
if (!ghostSetupManifestTrackerSingleton) {
ghostSetupManifestTrackerSingleton = new GhostSetupManifestTracker(
@@ -8937,6 +8939,7 @@ export function registerGhostIpc(): void {
try {
const ghost = findGhostForInstanceId(ghostId);
if (!ghost) throwIpcError('NOT_FOUND', '插件实例已变化,请刷新后重试');
+ if (ghost.manifest.taskPreferences === false) throwIpcError('PERMISSION_DENIED', 'PLUGIN_TASK_PREFERENCES_DISABLED');
return { config: writePluginTaskConfig(installedGhostStoragePart(ghost), config) };
}
finally { release(); }
diff --git a/apps/desktop/src/main/cindy-brain/mobilePageService.ts b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
index e71c356706..872b41c9a7 100644
--- a/apps/desktop/src/main/cindy-brain/mobilePageService.ts
+++ b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
@@ -436,7 +436,7 @@ export class MobilePluginPages {
})) ?? [],
permissions,
details: detailFacts,
- tasks: Boolean(ghost.manifest.agent?.tasks || ghost.manifest.agent?.errand),
+ tasks: ghost.manifest.taskPreferences !== false && Boolean(ghost.manifest.agent?.tasks || ghost.manifest.agent?.errand),
mobile: parsePluginMobileDeclaration(ghost.manifest.mobile) !== null,
usage: mobilePluginUsage(
ghost,
@@ -460,6 +460,7 @@ export class MobilePluginPages {
if (
!settings ||
!ghost.enabled ||
+ ghost.manifest.taskPreferences === false ||
!(ghost.manifest.agent?.tasks || ghost.manifest.agent?.errand)
)
return fail();
diff --git a/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts b/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
index 36dc68b45c..d8ec13627f 100644
--- a/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts
@@ -150,6 +150,23 @@ function createStore() {
let store = createStore();
+// The installed manifest owns this policy; resolve it live rather than persisting
+// another switch in the preference file. Unchanged plugins keep the old behavior.
+let preferencesEnabled: (ghostId: string) => boolean = () => true;
+export function setPluginTaskPreferencesResolver(resolve: (ghostId: string) => boolean): void {
+ preferencesEnabled = resolve;
+}
+export function isPluginTaskPreferencesEnabled(ghostId: string): boolean {
+ return preferencesEnabled(ghostId);
+}
+
+/** null means the plugin manages settings; only the task's own granted mode applies. */
+export function readPluginTaskPermissionMode(ghostId: string): GhostErrandPermissionMode | null {
+ return isPluginTaskPreferencesEnabled(ghostId)
+ ? clampPluginTaskPermissionMode(readPluginTaskConfig(ghostId).permissionMode)
+ : null;
+}
+
// Register owns the runtime catalog; configuration persistence never builds another picker.
let validateSelection: ((config: PluginTaskConfig) => Promise<void>) | null = null;
export function setPluginTaskConfigValidator(validator: (config: PluginTaskConfig) => Promise<void>): void {
@@ -247,6 +264,7 @@ function migrateLegacyOneshotPins(): void {
/** 读某插件的任务配置(缺省空对象 = 全跟随默认)。 */
export function readPluginTaskConfig(ghostId: string): PluginTaskConfig {
+ if (!isPluginTaskPreferencesEnabled(ghostId)) return {};
migrateLegacyOneshotPins();
// mtime 守卫现读:直接改文件也算配置入口(与 cindy prefs 同契约)。
store.invalidateIfChanged();
@@ -259,6 +277,7 @@ export function readPluginTaskConfig(ghostId: string): PluginTaskConfig {
* 形状粗筛,逐字段值域清洗统一在这里(单一执法点)。返回清洗后的落盘值。
*/
export function writePluginTaskConfig(ghostId: string, config: unknown): PluginTaskConfig {
+ if (!isPluginTaskPreferencesEnabled(ghostId)) throw new Error('PLUGIN_TASK_PREFERENCES_DISABLED');
assertGhostPrefsWritable('ghost-errand-prefs.json');
migrateLegacyOneshotPins();
store.invalidateIfChanged();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
index 840633687f..beee20aac1 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
@@ -1186,7 +1186,7 @@ describe('retained tasks after explicit plugin uninstall', () => {
maker:{getSession:()=>null},inputCoordinator:{getAcceptedInputProvenance:()=>active},
createPluginTaskStore:()=>({get:async(id:string)=>id==='run'?{operation:'send',targetId:'lead',pluginId:'plugin',payload:'{"inputMessageId":"plugin-task:run"}'}:{operation:'create',pluginId:'plugin',payload:JSON.stringify({ownershipRevoked:state==='revoked'})}}),
pluginTaskServiceForCurrentOwner:()=>({get:async()=>({status:'active',permissionMode:state==='ask'?'default':'auto',planModeEnabled:state==='plan'})}),
- isPluginTaskAuthorized:()=>state!=='disabled',readPluginTaskConfig:()=>({permissionMode:'auto'})};
+ isPluginTaskAuthorized:()=>state!=='disabled',readPluginTaskConfig:()=>({permissionMode:'auto'}), readPluginTaskPermissionMode: () => 'auto'};
const override=new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings),js)(hasAcceptedUserTaskInput, ...Object.values(bindings));
const ordinary=state==='revoked'&&['human','idle'].includes(input);
if(state==='healthy'||ordinary)await expect(override('lead')).resolves.toMatchObject({permissionMode:ordinary?undefined:'auto'});
@@ -1199,7 +1199,7 @@ describe('retained tasks after explicit plugin uninstall', () => {
maker: {getSession:()=>null}, inputCoordinator: { getAcceptedInputProvenance: () => null },
createPluginTaskStore: () => ({ get: async () => ({ operation: 'create', pluginId: 'plugin', payload: '{}' }) }),
pluginTaskServiceForCurrentOwner: () => ({ get: async () => ({ status, permissionMode: 'auto', planModeEnabled }) }),
- isPluginTaskAuthorized: () => true, readPluginTaskConfig: () => ({ permissionMode: 'auto' }),
+ isPluginTaskAuthorized: () => true, readPluginTaskConfig: () => ({ permissionMode: 'auto' }), readPluginTaskPermissionMode: () => 'auto',
};
const override = new Function('hasAcceptedUserTaskInput', ...Object.keys(callbacks), js)(hasAcceptedUserTaskInput, ...Object.values(callbacks));
const { deps, service } = createDeps({ getWorkerPermissionModeOverride: override,
@@ -1222,7 +1222,7 @@ describe('retained tasks after explicit plugin uninstall', () => {
maker: {getSession:()=>null}, inputCoordinator: { getAcceptedInputProvenance: () => null },
createPluginTaskStore: () => ({ get: async () => ({ operation: 'create', pluginId: 'plugin', payload: JSON.stringify({ ownershipRevoked: true }) }) }),
pluginTaskServiceForCurrentOwner: () => ({ get }), isPluginTaskAuthorized: () => false,
- readPluginTaskConfig: () => ({ permissionMode: 'auto' }),
+ readPluginTaskConfig: () => ({ permissionMode: 'auto' }), readPluginTaskPermissionMode: () => 'auto',
};
const override = new Function('hasAcceptedUserTaskInput', ...Object.keys(callbacks), js)(hasAcceptedUserTaskInput, ...Object.values(callbacks));
const { deps, service } = createDeps({
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index 94f49061e6..94cf978273 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -445,7 +445,7 @@ describe('OrcaTeamService', () => {
? {operation:'send',targetId:'lead-1',pluginId:'plugin',payload:'{"inputMessageId":"plugin-task:run"}'}
: {operation:'create',pluginId:'plugin',payload:JSON.stringify({ownershipRevoked:revoked})}}),
pluginTaskServiceForCurrentOwner:()=>({get:async()=>({status:'active',permissionMode:'auto'})}),
- isPluginTaskAuthorized:()=>!revoked,readPluginTaskConfig:()=>({permissionMode:'auto'})};
+ isPluginTaskAuthorized:()=>!revoked,readPluginTaskConfig:()=>({permissionMode:'auto'}), readPluginTaskPermissionMode: () => 'auto'};
const capture = new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings),ts.transpileModule(`${helper}\nreturn captureOrcaPluginAuthority;`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText)(hasAcceptedUserTaskInput, ...Object.values(bindings));
const {deps,service,getWorker}=createDeps({captureControlAuthority:async id=>(await capture(id)).assertCurrent});
const list=deps.listWorkersByLead;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index 1a0a414d33..52ea7b0a88 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -82,7 +82,7 @@ describe('Host provenance across Orca creation waits', () => {
if (!receipt || receipt.pluginId !== pluginId || JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Revoked');
return { ...task };
} }),
- isPluginTaskAuthorized: () => enabled, readPluginTaskConfig: () => ({ permissionMode: 'auto', workingDir: directoryCase ? configured : task.workingDir }),
+ isPluginTaskAuthorized: () => enabled, readPluginTaskConfig: () => ({ permissionMode: 'auto', workingDir: directoryCase ? configured : task.workingDir }), readPluginTaskPermissionMode: () => 'auto',
resolvePluginWorkerDirectory: vi.fn(async () => {
directoryResolved = true; directoryReads = 0;
if (directoryCase && !configured && !picked) throw new PluginTaskError('PERMISSION_DENIED', 'Directory revoked');
@@ -3503,7 +3503,7 @@ describe('production plugin Auto admission after reservation', () => {
if (JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Not owned');
return { ...task };
} }),
- readPluginTaskConfig: () => ({ permissionMode: 'auto', workingDir: task.workingDir }),
+ readPluginTaskConfig: () => ({ permissionMode: 'auto', workingDir: task.workingDir }), readPluginTaskPermissionMode: () => 'auto',
isPluginTaskAuthorized: () => enabled,
resolvePluginWorkerDirectory: async () => task.workingDir,
isGhostPickedDir: () => false, PluginTaskError,
@@ -3567,7 +3567,7 @@ describe('production plugin Auto admission after reservation', () => {
const callbackDeps = { getCurrentDbClientSnapshot: () => epoch, PluginTaskError, assertPluginWorkerDirectoryScope,
createPluginTaskStore: () => ({ get: async () => ({ operation: 'create', pluginId: 'plugin', payload: state === 'malformed' ? '{' : JSON.stringify({ ownershipRevoked: true, teamPlan: { items: [] } }) }) }),
pluginTaskServiceForCurrentOwner: () => ({ get }), isPluginTaskAuthorized: () => state === 'reinstalled',
- readPluginTaskConfig: () => ({ permissionMode: 'auto' }),
+ readPluginTaskConfig: () => ({ permissionMode: 'auto' }), readPluginTaskPermissionMode: () => 'auto',
};
const validateCreationPlan = new Function(...Object.keys(callbackDeps), js)(...Object.values(callbackDeps));
const { deps, service } = createDeps({ validateCreationPlan });
@@ -3622,7 +3622,7 @@ describe('production plugin Auto admission after reservation', () => {
}
return task();
} }),
- readPluginTaskConfig: () => ({ permissionMode: mode, workingDir: path.resolve('repo') }),
+ readPluginTaskConfig: () => ({ permissionMode: mode, workingDir: path.resolve('repo') }), readPluginTaskPermissionMode: () => mode,
isPluginTaskAuthorized: () => enabled,
resolvePluginWorkerDirectory: async ({requested}: {requested: string}) => { if (reserved && point === 'directory') revoke(); return requested === path.resolve('other') ? requested : path.resolve('repo'); },
realpathWorkingDirectory: async (dir: string) => dir === path.resolve('other') ? dir : path.resolve('repo'),
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts
index e9021ea420..250ca8794f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts
@@ -24,7 +24,7 @@ function fixture(initial = 'active', afterConfirmation = initial) {
return create();
});
const deps = { service, getCurrentDbClientSnapshot: () => epoch, PluginTaskError, assertPluginTaskResult, startOrcaTeamForCaller: start,
- isPluginTaskAuthorized: () => true, readPluginTaskConfig: () => ({ permissionMode: 'auto' }) };
+ isPluginTaskAuthorized: () => true, readPluginTaskConfig: () => ({ permissionMode: 'auto' }), readPluginTaskPermissionMode: () => 'auto' };
const run = new Function(...Object.keys(deps), js)(...Object.values(deps));
return { run: () => run('plugin', { kind: 'startTeam', taskId: 'task' }), start, create };
}
@@ -84,7 +84,7 @@ describe('public start_team Full access admission', () => {
createPluginTaskStore: () => ({ get: async () => state === 'ordinary' ? null
: { operation: 'create', pluginId: 'plugin', payload: JSON.stringify({ ownershipRevoked: revoked }) } }),
pluginTaskServiceForCurrentOwner: () => ({ get: async () => task }),
- isPluginTaskAuthorized: () => state !== 'disabled', readPluginTaskConfig: () => ({ permissionMode: 'auto' }),
+ isPluginTaskAuthorized: () => state !== 'disabled', readPluginTaskConfig: () => ({ permissionMode: 'auto' }), readPluginTaskPermissionMode: () => 'auto',
assertLeadCollabProjectEnabled: async () => {}, getWorkerPermissionModeFromCreationPrefs: () => preference,
orcaWorkerPermissionConfirmBridge: { request }, t: (key: string) => key, orcaLifecycleService: lifecycle,
};
@@ -163,7 +163,7 @@ describe('plugin team activation uses the native lifecycle compensation', () =>
sendWorkerReadyPlaceholder: vi.fn(), rollbackCreatedWorker: vi.fn(), broadcastSessionCreated: vi.fn(), broadcastOrcaWorkerChanged: vi.fn(),
};
const callbacks = { service, getCurrentDbClientSnapshot: () => epoch, PluginTaskError, assertPluginTaskResult,
- isPluginTaskAuthorized: () => authorized, readPluginTaskConfig: () => ({ ...cfg }),
+ isPluginTaskAuthorized: () => authorized, readPluginTaskConfig: () => ({ ...cfg }), readPluginTaskPermissionMode: () => cfg.permissionMode,
assertLeadCollabProjectEnabled: async () => {}, getWorkerPermissionModeFromCreationPrefs: () => 'auto',
startOrcaTeamWithPermissionGate, orcaWorkerPermissionConfirmBridge: { request: vi.fn() }, t: (key: string) => key,
orcaLifecycleService: createOrcaLifecycleService(deps) };
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
index 43bf695043..dfdbc7f3af 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@ -30,7 +30,7 @@ it('rejects oversized plans before saving and refuses oversized legacy receipts
});
it.each([false,true])('production Auto context checks uninstall after its projection await (worker=%s)', async worker => {
- for (const revoked of [false,true]) {
+ for (const revoked of [false,true]) for (const configuredMode of ['auto', 'ask', null]) {
const f=fixture(),task=await f.create();
const session={...f.route,source:'plugin',workingDir:'/answer',permissionMode:'auto',status:'active'};
const results=[[session],worker?[{leadId:task.taskId,label:'w',teamId:'team',teamStatus:'active'}]:[],[session]];
@@ -40,7 +40,7 @@ it.each([false,true])('production Auto context checks uninstall after its projec
const deps={setAutoReviewContextResolver:(callback:typeof load)=>{load=callback;},createPluginTaskReviewResolver:(callback:typeof load)=>callback,
getCurrentDbClientSnapshot:()=>epoch,sessions:{},orcaWorkers:{},orcaTeams:{},eq:()=>true,
createPluginTaskStore:()=>f.deps.store,drainPersistQueue:async()=>{},
- pluginTaskServiceForCurrentOwner:()=>f.service,readPluginTaskConfig:()=>({permissionMode:'auto'}),
+ pluginTaskServiceForCurrentOwner:()=>f.service,readPluginTaskPermissionMode:()=>configuredMode,
readPluginTaskPlanReceipt,pluginTaskAuthorizationRevision:()=> 'new-install',isPluginTaskAuthorized:()=>true};
const source=readFileSync(new URL('../register.ts',import.meta.url),'utf8');
const start=source.indexOf(' setAutoReviewContextResolver(createPluginTaskReviewResolver(async sessionId => {');
@@ -48,7 +48,7 @@ it.each([false,true])('production Auto context checks uninstall after its projec
const js=ts.transpileModule(block,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
new Function(...Object.keys(deps),js)(...Object.values(deps));
if(revoked)await expect(load(worker?'worker':task.taskId)).rejects.toMatchObject({code:'TASK_NOT_FOUND'});
- else await expect(load(worker?'worker':task.taskId)).resolves.toMatchObject({authorized:true,pluginId:'p'});
+ else await expect(load(worker?'worker':task.taskId)).resolves.toMatchObject({authorized:configuredMode !== 'ask',pluginId:'p'});
}
});
@@ -865,6 +865,21 @@ it('a rejected operation does not poison subsequent drain', async () => {
describe('current plugin dispatch authority', () => {
+ it.each(['ask', 'acceptEdits', 'auto'])('uses the task-granted %s permission when Host preferences are disabled', async permissionMode => {
+ const f = fixture(), task = await f.create();
+ f.tasks.get(task.taskId)!.permissionMode = permissionMode;
+ f.deps.readPermissionMode = () => null;
+ const run = await f.service.send('p', {taskId:task.taskId,expectedRevision:task.revision,requestKey:'self-managed',text:'input'});
+ expect(run.status).toBe('queued');
+ expect(f.deps.dispatch).toHaveBeenCalledOnce();
+ await expect(f.service.accept(task.taskId,{clientId:run.inputMessageId},f.execution)).resolves.toBeUndefined();
+ expect(JSON.parse(f.rows.get(run.runId)!.payload)).toMatchObject({status:'running', execution:f.execution});
+ });
+ it('keeps Plan Mode and invalid task permissions blocked without a Host preference cap', () => {
+ expect(isPluginTaskPermissionAllowed('auto', null, true)).toBe(false);
+ for (const mode of ['bypassPermissions', 'unknown', undefined, null])
+ expect(isPluginTaskPermissionAllowed(mode, null)).toBe(false);
+ });
it.each(['before', 'route', 'insert'])('blocks independent Plan Mode before dispatch at %s', async point => {
const f=fixture(), task=await f.create();
const enable=()=>Object.assign(f.tasks.get(task.taskId)!,{permissionMode:'auto',planModeEnabled:true});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
index 53af65d30b..c6b12eba9b 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
@@ -20,7 +20,7 @@ const settingSource = source.slice(source.indexOf(' ipcMain.handle(\n MAKER_
const planSource = source.slice(source.indexOf(' ipcMain.handle(\n MAKER_INVOKE.SET_PLAN_MODE,'), source.indexOf(' ipcMain.handle(MAKER_INVOKE.EXPORT_SESSION_HTML,'));
const planJs = ts.transpileModule(planSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
const settingJs = ts.transpileModule(settingSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
-function fixture() {
+function fixture(preferencesEnabled = true) {
let identity = 'owner-epoch-install';
const gate = new PluginWriteAccessGate();
let cfg: Record<string, unknown> = { permissionMode: 'plan', model: 'old' };
@@ -39,7 +39,10 @@ function fixture() {
const dialog = { showMessageBox: vi.fn(async () => ({ response: 0 })) };
const write = vi.fn((_id: string, value: Record<string, unknown>) => { cfg = value; });
const deps = { isPluginTaskPermissionAllowed, withSessionPermissionChange, withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => ownership.current, readPluginTaskConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => cold ? null : live }, inputCoordinator: queue, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampPluginTaskPermissionMode: (x: string) => x, writePluginTaskConfig: write, broadcastSessionPatched: vi.fn() };
- const allDeps = {...deps, pluginWriteAccessGate:gate, pluginWriteAccessIdentity:()=>identity};
+ const allDeps = {...deps, readPluginTaskConfig: () => preferencesEnabled ? cfg : {},
+ readPluginTaskPermissionMode: () => preferencesEnabled ? cfg.permissionMode : null,
+ isPluginTaskPreferencesEnabled: () => preferencesEnabled,
+ pluginWriteAccessGate:gate, pluginWriteAccessIdentity:()=>identity};
const run = new Function(...Object.keys(allDeps), js)(...Object.values(allDeps));
let setMode!: (event: unknown, sessionId: string, mode: string) => Promise<unknown>;
let setPlan!: (event:unknown, sessionId:string, enabled:boolean)=>Promise<unknown>;
@@ -61,6 +64,25 @@ function fixture() {
});
return {setPlan:(enabled:boolean)=>setPlan({},'task',enabled),planPersist,forgetGrants,runtimePlan:()=>runtimePlan,nativePlan:(enabled:boolean|null)=>{runtimePlan=enabled;},setImMode, setMode:(mode:string)=>setMode({},'task',mode), persistedResults, remote:()=>{remote=true;}, cold:()=>{cold=true;}, runtimeMode:()=>runtimeMode, changeOwner:()=>{ownership.current={};}, run: (mode = 'acceptEdits', explicit = false) => run('plugin', { kind: 'requestWriteAccess', taskId: 'task', mode }, explicit), queue, gate, identity: (next: string) => {identity=next;}, service, live, epoch, dialog, slots, write, history, drain, config: () => cfg, change: (next: Record<string, unknown>) => { cfg = next; } };
}
+describe('plugin-managed task configuration', () => {
+ it.each(['acceptEdits', 'auto'])('confirms %s for this task without writing Host defaults', async mode => {
+ const f = fixture(false);
+ await expect(f.run(mode)).resolves.toMatchObject({granted:true});
+ expect(f.dialog.showMessageBox).toHaveBeenCalledOnce();
+ expect(f.history.permissionMode).toBe(mode);
+ expect(f.live.setPermissionMode).toHaveBeenCalledWith(mode);
+ expect(f.write).not.toHaveBeenCalled();
+ expect(f.config()).toEqual({permissionMode:'plan',model:'old'});
+ });
+ it('reuses the task grant without consulting the dormant Host permission preference', async () => {
+ const f = fixture(false);
+ f.service.get.mockResolvedValue({taskId:'task',revision:1,status:'active',permissionMode:'auto'});
+ await expect(f.run('auto')).resolves.toMatchObject({granted:true});
+ expect(f.dialog.showMessageBox).not.toHaveBeenCalled();
+ expect(f.write).not.toHaveBeenCalled();
+ });
+});
+
describe('shared-provider credential grants on permission changes', () => {
it('clears the task grant only when permission or Plan mode really changes, even without a running agent', async () => {
const f=fixture();f.cold();
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
index 5c42b24229..c97dd75333 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -74,11 +74,11 @@ export function readPluginTaskPlanReceipt(payload: string): { teamPlan?: PluginT
export function assertPluginTaskResult(result: { ok: boolean; errorCode?: string }, message: string): void {
if (!result.ok) throw new PluginTaskError(result.errorCode || 'HOST_NOT_READY', message);
}
-/** A live task cannot exercise more authority than the plugin's current setting. */
+/** Host-managed preferences cap task authority; null opts out of that cap, never of task/Plan checks. */
export function isPluginTaskPermissionAllowed(taskMode: unknown, configuredMode: unknown, planModeEnabled = false): boolean {
const rank = (mode: unknown) => mode === 'plan' ? 0 : mode === 'ask' ? 1 : mode === 'acceptEdits' ? 2 : mode === 'auto' ? 3 : -1;
const task = rank(taskMode);
- return !planModeEnabled && task >= 0 && task <= Math.max(0, rank(configuredMode));
+ return !planModeEnabled && task >= 0 && (configuredMode === null || task <= Math.max(0, rank(configuredMode)));
}
const fail = (code: string, message: string): never => {
throw new PluginTaskError(code, message);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 0c4bbebe0a..3827f11556 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1373,6 +1373,8 @@ import {
} from '../cindy-brain/index.js';
import {
readPluginTaskConfig,
+ readPluginTaskPermissionMode,
+ isPluginTaskPreferencesEnabled,
clampPluginTaskPermissionMode,
setPluginTaskConfigValidator,
writePluginTaskConfig,
@@ -12520,7 +12522,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
pluginTaskEpoch = snapshot;
pluginTasks = createPluginTaskService({
store: createPluginTaskStore(snapshot.client), assertCurrent, assertAuthorized: assertPlugin, resolveRoute,
- readPermissionMode: pluginId => clampPluginTaskPermissionMode(readPluginTaskConfig(pluginId).permissionMode),
+ readPermissionMode: readPluginTaskPermissionMode,
readLiveSession: taskId => maker.getSession(taskId),
setModel: async (taskId, route, assertUnchanged) => {
const current = await sessionControlService.getSessionRuntime({ targetSessionId: taskId });
@@ -12759,7 +12761,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const mode = request.mode ?? 'acceptEdits';
const cfg = readPluginTaskConfig(pluginId);
assertCallerCurrent();
- if (isPluginTaskPermissionAllowed(task.permissionMode, cfg.permissionMode) && (mode === 'acceptEdits' ? task.permissionMode === 'acceptEdits' || task.permissionMode === 'auto' : task.permissionMode === 'auto')) return { granted: true, task };
+ if (isPluginTaskPermissionAllowed(task.permissionMode, readPluginTaskPermissionMode(pluginId)) && (mode === 'acceptEdits' ? task.permissionMode === 'acceptEdits' || task.permissionMode === 'auto' : task.permissionMode === 'auto')) return { granted: true, task };
if (pluginPermissionRequests.size) throw new PluginTaskError('TASK_BUSY', 'A permission request is already open');
const identity = pluginWriteAccessIdentity(pluginId);
const assertRequestCurrent = () => {
@@ -12834,7 +12836,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertPlanInactive();
const currentConfig = readPluginTaskConfig(pluginId);
if (currentConfig.permissionMode !== cfg.permissionMode) throw new PluginTaskError('PERMISSION_DENIED', 'Permission settings changed');
- if (mode === 'auto' || ['ask', 'plan'].includes(clampPluginTaskPermissionMode(currentConfig.permissionMode))) writePluginTaskConfig(pluginId, {...currentConfig, permissionMode: mode});
+ if (isPluginTaskPreferencesEnabled(pluginId) && (mode === 'auto' || ['ask', 'plan'].includes(clampPluginTaskPermissionMode(currentConfig.permissionMode)))) writePluginTaskConfig(pluginId, {...currentConfig, permissionMode: mode});
broadcastSessionPatched(task.taskId, {permissionMode: mode});
return { granted: true, task: updatedTask };
} catch (error) {
@@ -14191,7 +14193,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (task.status !== 'active') {
throw new PluginTaskError('TASK_BUSY', 'Archived tasks cannot create Workers');
}
- if (!isPluginTaskAuthorized(pluginId) || task.planModeEnabled || task.permissionMode !== 'auto' || readPluginTaskConfig(pluginId).permissionMode !== 'auto') {
+ const configuredMode = readPluginTaskPermissionMode(pluginId);
+ if (!isPluginTaskAuthorized(pluginId) || task.planModeEnabled || task.permissionMode !== 'auto' || (configuredMode !== null && configuredMode !== 'auto')) {
throw new PluginTaskError('PERMISSION_DENIED', 'Authorize Auto for the plugin coordinator before creating Workers');
}
};
@@ -16065,12 +16068,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
projection.revision,
]);
if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');
- const config = readPluginTaskConfig(receipt.pluginId);
+ const configuredMode = readPluginTaskPermissionMode(receipt.pluginId);
const approvalRevision = pluginTaskAuthorizationRevision(receipt.pluginId);
return {
pluginId: receipt.pluginId,
- authorized: !!unchanged && approvalRevision !== null && isPluginTaskAuthorized(receipt.pluginId) && config.permissionMode === 'auto',
- revision: [epoch.userId, epoch.clientEpoch, approvalRevision, config.permissionMode, link],
+ authorized: !!unchanged && approvalRevision !== null && isPluginTaskAuthorized(receipt.pluginId) && (configuredMode === null || configuredMode === 'auto'),
+ revision: [epoch.userId, epoch.clientEpoch, approvalRevision, configuredMode, link],
plan: data.teamPlan, settledLabels: data.settledLabels,
registeredRoute: data.route,
session: { workingDir: session.workingDir, permissionMode: session.permissionMode, planModeEnabled: !!session.planModeEnabled, status: session.status,
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 2645b09920..2db5b1de12 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -1,5 +1,5 @@
/**
- * Regression coverage for Plugin detail sections, shared Switch wiring and interaction behavior.
+ * Regression coverage for Plugin detail sections, optional Host task settings and interaction behavior.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
* @vitest-environment jsdom
*/
@@ -851,9 +851,16 @@ describe('Ghost plugin detail sections', () => {
});
it.each([
- { name: 'quick answers only', manifest: { cindy: { text: ['oneshot'] } }, taskRows: false },
- { name: 'plugin tasks', manifest: { agent: { tasks: true } }, taskRows: true },
- ])('shows one model field for $name and no per-ability model card', ({ manifest, taskRows }) => {
+ { name: 'quick answers only', manifest: { cindy: { text: ['oneshot'] } }, taskRows: false, showCard: true },
+ { name: 'plugin tasks', manifest: { agent: { tasks: true } }, taskRows: true, showCard: true },
+ { name: 'legacy errands', manifest: { agent: { errand: true } }, taskRows: true, showCard: true },
+ { name: 'workspaces', manifest: { workspace: true }, taskRows: true, showCard: true },
+ { name: 'explicitly enabled tasks', manifest: { agent: { tasks: true }, taskPreferences: true }, taskRows: true, showCard: true },
+ { name: 'opted-out tasks', manifest: { agent: { tasks: true }, taskPreferences: false }, taskRows: true, showCard: false },
+ { name: 'opted-out quick answers', manifest: { cindy: { text: ['oneshot'] }, taskPreferences: false }, taskRows: false, showCard: false },
+ { name: 'opted-out legacy errands', manifest: { agent: { errand: true }, taskPreferences: false }, taskRows: true, showCard: false },
+ { name: 'opted-out workspaces', manifest: { workspace: true, taskPreferences: false }, taskRows: true, showCard: false },
+ ])('respects the Host task preferences choice for $name', ({ manifest, taskRows, showCard }) => {
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
Object.assign(window.electronAPI, {
ghosts: {
@@ -876,7 +883,7 @@ describe('Ghost plugin detail sections', () => {
trust: detail.trust,
};
const projected = toGhostPluginDetail(ghost);
- expect(projected).toMatchObject({ hasTaskPreferences: true, hasPluginTasks: taskRows });
+ expect(projected).toMatchObject({ hasTaskPreferences: showCard, hasPluginTasks: taskRows });
render(
<GhostPluginDetailView
ghost={ghost}
@@ -891,8 +898,15 @@ describe('Ghost plugin detail sections', () => {
toggleDisabled={false}
/>,
);
- expect(screen.getByText('settings.ghosts.detail.errandPrefs.title')).toBeTruthy();
expect(screen.queryByText('settings.ghosts.detail.cindyPrefs.title')).toBeNull();
+ if (!showCard) {
+ expect(screen.queryByText('settings.ghosts.detail.errandPrefs.title')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.detail.errandPrefs.model')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.detail.errandPrefs.permission')).toBeNull();
+ expect(screen.queryByText('settings.ghosts.detail.errandPrefs.workdir')).toBeNull();
+ return;
+ }
+ expect(screen.getByText('settings.ghosts.detail.errandPrefs.title')).toBeTruthy();
expect(screen.getAllByText('settings.ghosts.detail.errandPrefs.model')).toHaveLength(1);
expect(screen.getByText(`settings.ghosts.detail.errandPrefs.${taskRows ? 'desc' : 'descModelOnly'}`)).toBeTruthy();
expect(Boolean(screen.queryByText('settings.ghosts.detail.errandPrefs.permission'))).toBe(taskRows);
@@ -904,6 +918,7 @@ describe('Ghost plugin detail sections', () => {
manifest: {
schemaVersion: 3, minCindyVersion: '0.1.0', kind: 'chip', id: 'art', name: 'Art',
version: '1.0.0', entry: 'main.js', cindy: { image: ['generate', 'edit'], embed: ['text'] },
+ taskPreferences: true,
},
dir: '/plugins/art',
namespace: null,
diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index 2c2f925ae6..316c72dcfd 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@ -2,7 +2,7 @@
* Plugin list/detail view models derived only from the installed Ghost contract.
*
* Inputs: shared Ghost manifests and install records.
- * Outputs: renderer-safe list/detail facts without marketplace or runtime invention.
+ * Outputs: renderer-safe list/detail facts, including the optional Host task settings card.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
*/
@@ -74,9 +74,9 @@ export interface GhostPluginDetail extends GhostPluginListItem {
tools: readonly GhostToolDecl[];
hasSettingsUi: boolean;
/**
- * 宿主「模型与任务」卡:插件的唯一模型字段(快问快答与新建任务共用)。声明了
- * 快问快答(cindy.text 含 oneshot)或任何新建任务能力即展示;图像/视频/向量
- * 没有逐插件选模,始终跟随系统默认。
+ * 宿主「模型与任务」默认配置卡(快问快答与新建任务共用)。声明了快问快答
+ * 或任何新建任务能力时默认展示;taskPreferences:false 停用宿主配置管理。
+ * 图像/视频/向量没有逐插件选模,始终跟随系统默认。
*/
hasTaskPreferences: boolean;
/** 能新建任务(agent.tasks / 旧 agent.errand / workspace):卡片额外展示权限与工作目录。 */
@@ -313,7 +313,9 @@ export function toGhostPluginDetail(
permissions: ghostPermissionItems(manifest),
tools: manifest.tools ?? [],
hasSettingsUi: Boolean(manifest.settingsHtml),
- hasTaskPreferences: hasPluginTasks || (manifest.cindy?.text ?? []).includes('oneshot'),
+ hasTaskPreferences:
+ manifest.taskPreferences !== false &&
+ (hasPluginTasks || (manifest.cindy?.text ?? []).includes('oneshot')),
hasPluginTasks,
panelMinWidth: manifest.panel ? (manifest.panel.minWidth ?? 280) : null,
installDir: ghost.dir,
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index bf0e43d396..33c92977e0 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -3759,6 +3759,36 @@ describe('ghost · 交互卡 action id 形状(v2)', () => {
});
describe('ghost · settingsHtml 自绘设置区 + settingsHeight', () => {
+ it.each([2, 3])('taskPreferences 在 schema v%s 中保留配置管理选择,缺省不新增字段或权限', (schemaVersion) => {
+ const base = {
+ ...goodManifest(),
+ schemaVersion,
+ ...(schemaVersion === 3 ? { minCindyVersion: '0.1.0' } : {}),
+ slots: schemaVersion === 2 ? ['agent'] : undefined,
+ panel: undefined,
+ agent: { tasks: true },
+ };
+ const original = validateGhostManifest(base);
+ expect(original.ok).toBe(true);
+ if (!original.ok) return;
+ for (const taskPreferences of [undefined, true, false]) {
+ const result = validateGhostManifest({ ...base, taskPreferences });
+ expect(result.ok).toBe(true);
+ if (!result.ok) continue;
+ expect(result.manifest.taskPreferences).toBe(taskPreferences);
+ expect(Object.hasOwn(result.manifest, 'taskPreferences')).toBe(taskPreferences !== undefined);
+ expect(result.manifest.agent?.tasks).toBe(true);
+ expect(ghostPermissionItems(result.manifest)).toEqual(ghostPermissionItems(original.manifest));
+ expect(validateNormalizedGhostManifest(result.manifest)).toEqual(result);
+ }
+ for (const taskPreferences of [null, 0, 1, 'false', {}, []]) {
+ expect(validateGhostManifest({ ...base, taskPreferences })).toMatchObject({
+ ok: false,
+ reason: 'taskPreferences 必须是布尔值',
+ });
+ }
+ });
+
it('settingsHtml 合法相对路径通过并透传;非法路径拒', () => {
const ok = validateGhostManifest({ ...goodManifest(), settingsHtml: 'ui/settings.html' });
expect(ok.ok && ok.manifest.settingsHtml).toBe('ui/settings.html');
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 65f1971664..9e4fac5d0b 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -1472,6 +1472,11 @@ export interface GhostManifest {
* 页用它避免抖动)。须与 settingsHtml 成对声明。
*/
settingsHeight?: number;
+ /**
+ * 是否使用宿主「模型与任务」配置管理;缺省或 true 沿用原行为。
+ * false 由插件维护配置:不显示卡片,也不读写宿主的逐插件默认值。
+ */
+ taskPreferences?: boolean;
/**
* 卡片能力;空对象表示基础卡片渲染。
* externalLinks: true 时卡片内可声明 data-ghost-link,点击经宿主确认框后打开浏览器。
@@ -2992,6 +2997,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set([
'node',
'settingsHtml',
'settingsHeight',
+ 'taskPreferences',
'slots',
'card',
'tools',
@@ -4109,6 +4115,9 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
if (raw.settingsHtml !== undefined && !isSafeGhostRelativePath(raw.settingsHtml)) {
return { ok: false, reason: 'settingsHtml 必须是安装目录内的安全相对路径' };
}
+ if (raw.taskPreferences !== undefined && typeof raw.taskPreferences !== 'boolean') {
+ return { ok: false, reason: 'taskPreferences 必须是布尔值' };
+ }
if (raw.settingsHeight !== undefined) {
if (raw.settingsHtml === undefined) {
return {
@@ -6020,6 +6029,9 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
...(raw.settingsHtml !== undefined ? { settingsHtml: raw.settingsHtml as string } : {}),
...(raw.mobile !== undefined ? { mobile: raw.mobile as GhostManifest['mobile'] } : {}),
...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),
+ ...(raw.taskPreferences !== undefined
+ ? { taskPreferences: raw.taskPreferences as boolean }
+ : {}),
...(tools !== undefined ? { tools } : {}),
...(card !== undefined || prepared.v3BaseCard || slots.includes('card')
? { card: card ?? {} }
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 430e9d2218..666d7a980a 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -136,6 +136,16 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
但当前 Host 不展示、不授权、也不因此阻止安装或发布。
未来 Host 识别该字段后,才按正常的能力展示和运行时守门链路启用。不能把
未知字段猜成现有权限,也不能让它意外获得能力。
+- 顶层 `taskPreferences?: boolean` 选择是否使用宿主的「模型与任务」配置管理,默认启用。
+ `false` 时由插件自行存储配置,Desktop/手机隐藏配置卡、拒绝宿主配置写入,所有任务/
+ 快问快答入口不再读取旧的逐插件模型、权限与目录。旧数据不删除、关闭期间不参与执行;
+ 恢复启用后重新生效。不填或 `true` 时存量插件完全沿用原行为,无相应能力不创建卡片。
+ 任务能力批准不变;新普通任务仍以 ask 创建,插件用 route 和现有目录 API 表达配置,
+ 权限提升仍经用户确认,只修改该任务、不写回已停用的宿主配置;发送/协同以任务自身
+ 的已授权权限与 Plan 状态守门。不开 Full access,不绕过目录亲选或模型准入。
+ 旧客户端忽略字段并继续使用旧配置;依赖此语义须要求客户端版本支持。不要求 settingsHtml。
+ 实现见 `pluginTaskPrefsStore.ts`、`pluginTaskService.ts`、`ghostPluginViewModel.ts` 与
+ `mobilePageService.ts`;作者用法见 `FORGE_GUIDE` §4.8,回归覆盖协议、存储、任务授权与两端入口。
- `agent.tasks` 另需 Host receipt 的显式任务能力批准事实;旧 receipt 没有该事实时,
只在首次任务能力调用通过既有宿主权限界面确认,原插件的启用态、其它能力、凭证和
设置保持不变。拒绝、窗口不可用、账号或安装版本变化均不授予任务权限;同能力更新
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index 03ac1b673c..ecb8d6fd3a 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -83,6 +83,16 @@ if (capabilities.operations.includes('models')) {
新任务选择;用户可为插件单独覆盖。模型、Agent、供应商、推理强度和 Fast 作为完整组合
解析,绝不从另一 Agent 的历史草稿拼出一组值。权限独立设置,不随模型来源继承。
+以下宿主配置管理默认启用。插件可在自己的 `ghost.json` 顶层声明
+`taskPreferences: false`,仅让该插件自行维护配置:隐藏「模型与任务」卡片,宿主不再
+读写该插件的模型、权限和工作目录默认值,旧配置不参与执行;其他插件及任务 API 保持可用。
+插件通过显式 route、`setModel` 和既有目录/授权 API 管理任务,不得直接指定更高权限。
+未传 route 时跳过插件宿主覆盖,继续使用原发起任务/当前新任务选择;快问快答跳过
+宿主模型覆盖,仍依次使用身份卡 `oneshotModel` 和系统辅助模型链。新普通任务初始为
+`ask`、宿主管理目录;已有任务按自身授权派发,Plan、归属和能力批准检查保持。
+省略声明或设为 `true` 保持旧行为,并可恢复使用原宿主配置;旧客户端忽略该字段,
+因此依赖此语义的插件须使用已支持该声明的客户端。
+
| 入口 | 模型来源与复用 | 权限与结果 |
| --- | --- | --- |
| `tasks.create` | 显式 route → 插件任务设置 → 经验证的 callId 发起任务 → 当前新任务选择;保存准入后的完整 route | 用户插件权限,默认普通任务的 ask;返回普通任务及持久创建回执 |
@@ -216,7 +226,7 @@ Claude Code 适配层 `toSdkModelString` 会按目录窗口自动追加 `[1m]`
插件新增的 tasks 能力首次使用时复用宿主权限确认。拒绝、超时或确认失败后,同一账号代际和安装修订在当前宿主进程内不再自动弹窗;插件重载或重复调用不能清除该状态。用户可在本机插件详情权限区点击“确认任务权限”重新进入原确认流程,点击不等于批准;在途确认不并发,账号、安装修订或发起窗口改变时旧结果无效。旧插件的既有功能、启用态、凭证与设置不变。此显式入口不向插件页面或 device-link 暴露;重启宿主后可重新首次询问。
-逻辑页可调用 cindy.tasks.requestWriteAccess({taskId, mode?})。省略 mode 保留旧行为(acceptEdits,仅限未开始执行的任务);mode: auto 请求宿主原生确认,为空闲自有任务及插件后续任务启用 Auto。插件不能替用户确认,不能请求 Full access。拒绝不改状态;账号、配置、任务版本在确认期间改变则拒绝写入。Auto 插件主任务的 Worker 固定使用 Auto,不继承或改写全局 Worker 偏好;授权撤销后拒绝新建。Host 读取该次权限时一并保留账号与插件来源,在团队查询、Worker 准备/启动、落盘后以及首条输入的 accepted 回调中复核;在途卸载、重装、归属消失或降权不能将本次创建降为普通 Orca。调用开始前已明确撤销的旧用户任务仍可新发起普通 Orca。首条输入(任务或就绪消息)真正接收时沿现有回调再次复核;任务接收生命周期的异步更新前后均检查,失败回滚本次临时运行态并取消派发。直发拒绝后,在派发调用退出后才沿原生命周期清理新 Worker;排队后迟到的拒绝仅取消该输入并回滚本次临时状态,保留 Worker 和用户数据。既有内存回调不构成跨重启的授权事务,也不保证中断已接收执行。失败沿原生命周期尽力清理,不保证跨账号数据库补偿或跨进程事务。独立目录不是沙箱。返回 granted 与更新后的 task/revision,插件应继续原批次。
+逻辑页可调用 cindy.tasks.requestWriteAccess({taskId, mode?})。省略 mode 保留旧行为(acceptEdits,仅限未开始执行的任务);mode: auto 请求宿主原生确认,为空闲自有任务及插件后续任务启用 Auto。声明 `taskPreferences: false` 时仅更新该任务的授权,不读写插件宿主默认值,也不为后续新任务提权。插件不能替用户确认,不能请求 Full access。拒绝不改状态;账号、配置、任务版本在确认期间改变则拒绝写入。Auto 插件主任务的 Worker 固定使用 Auto,不继承或改写全局 Worker 偏好;授权撤销后拒绝新建。Host 读取该次权限时一并保留账号与插件来源,在团队查询、Worker 准备/启动、落盘后以及首条输入的 accepted 回调中复核;在途卸载、重装、归属消失或降权不能将本次创建降为普通 Orca。调用开始前已明确撤销的旧用户任务仍可新发起普通 Orca。首条输入(任务或就绪消息)真正接收时沿现有回调再次复核;任务接收生命周期的异步更新前后均检查,失败回滚本次临时运行态并取消派发。直发拒绝后,在派发调用退出后才沿原生命周期清理新 Worker;排队后迟到的拒绝仅取消该输入并回滚本次临时状态,保留 Worker 和用户数据。既有内存回调不构成跨重启的授权事务,也不保证中断已接收执行。失败沿原生命周期尽力清理,不保证跨账号数据库补偿或跨进程事务。独立目录不是沙箱。返回 granted 与更新后的 task/revision,插件应继续原批次。
### 主任务协调评测
@@ -273,7 +283,7 @@ Host 只接受经绑定插件身份写入的自有创建收据;已登记计划
已识别插件任务的协调任务或 Worker 缺少有效范围时返回既有 authorizationError,在缓存、本地安全动作或 Host MCP 快捷路径之前拒绝自动授权;不退回普通任务、不从消息补造范围。旧计划继续可读,不事后补填;新范围须在新任务中登记完整计划。Ask/acceptEdits 保留既有逐次人工确认,普通无插件归属任务不受此限制。
没有新增权限档位、没有提升到 Full access。
-审批在查询缓存前重新核对插件批准版本、启用状态、Auto 设置、账号 epoch、任务状态、
+审批在查询缓存前重新核对插件批准版本、启用状态、宿主管理时的 Auto 设置、账号 epoch、任务状态、
团队归属和计划匹配;异步结果返回前再次核对。
历史投影和归属读取完成后,以同一条只读 SQL 比较本次使用的任务/Lead 权限、独立 Plan、状态、路由目录、团队链接及计划收据,并复核授权投影修订号仍与读取值一致、投影已同步且版本为 3;变化拒绝本次授权,查询失败保留 unavailable。该检查同时覆盖 Lead 和 Worker 的真人证据变化,不只检查当前 Worker 的意图。Lead 或 Worker 已开启独立 Plan 时不恢复委派 Auto。
Worker 别名目录的异步解析在该次归属和最终授权核验之前完成;核验后只同步消费本次目录匹配结果,不再等待文件系统读取。该结果不写入回执,也不替代可信本地工作区边界。
diff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.ts
index 1d0884de1a..e540bb1456 100644
--- a/packages/plugin-protocol/src/__tests__/manifest.test.ts
+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts
@@ -31,6 +31,32 @@ const validManifest = {
} as const;
describe('Ghost manifest contract', () => {
+ it.each([2, 3])('preserves the optional Host task preferences flag in schema v%s', (schemaVersion) => {
+ const base = {
+ ...validManifest,
+ schemaVersion,
+ ...(schemaVersion === 3 ? { minCindyVersion: '0.1.0' } : {}),
+ slots: schemaVersion === 2 ? ['agent'] : undefined,
+ tools: undefined,
+ agent: { tasks: true },
+ };
+ for (const taskPreferences of [undefined, true, false]) {
+ const result = validateGhostManifest({ ...base, taskPreferences });
+ expect(result.ok).toBe(true);
+ if (!result.ok) continue;
+ expect(result.manifest.taskPreferences).toBe(taskPreferences);
+ expect(Object.hasOwn(result.manifest, 'taskPreferences')).toBe(taskPreferences !== undefined);
+ expect(result.manifest.agent?.tasks).toBe(true);
+ expect(validateGhostManifest(result.manifest)).toEqual(result);
+ }
+ for (const taskPreferences of [null, 0, 1, 'false', {}, []]) {
+ expect(validateGhostManifest({ ...base, taskPreferences })).toMatchObject({
+ ok: false,
+ reason: 'taskPreferences 必须是布尔值',
+ });
+ }
+ });
+
it('keeps main-view in the v2 compatibility contract', () => {
expect(LEGACY_GHOST_SLOTS).toContain('main-view');
expect(GHOST_MAIN_VIEW_ICONS).toEqual([
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index 953264669e..69936c5707 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -926,6 +926,11 @@ export interface GhostManifest {
* 页用它避免抖动)。须与 settingsHtml 成对声明。
*/
settingsHeight?: number;
+ /**
+ * 是否使用宿主「模型与任务」配置管理;缺省或 true 沿用原行为。
+ * false 由插件维护配置:不显示卡片,也不读写宿主的逐插件默认值。
+ */
+ taskPreferences?: boolean;
/** 仅 schemaVersion 2 存在的兼容声明。 */
slots?: LegacyGhostSlot[];
/**
@@ -1170,6 +1175,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set([
'node',
'settingsHtml',
'settingsHeight',
+ 'taskPreferences',
'slots',
'card',
'tools',
@@ -1641,6 +1647,9 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
if (raw.settingsHtml !== undefined && !isSafeGhostRelativePath(raw.settingsHtml)) {
return { ok: false, reason: 'settingsHtml 必须是安装目录内的安全相对路径' };
}
+ if (raw.taskPreferences !== undefined && typeof raw.taskPreferences !== 'boolean') {
+ return { ok: false, reason: 'taskPreferences 必须是布尔值' };
+ }
if (raw.settingsHeight !== undefined) {
if (raw.settingsHtml === undefined) {
return {
@@ -3746,6 +3755,9 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
...(raw.settingsHtml !== undefined ? { settingsHtml: raw.settingsHtml as string } : {}),
...(raw.mobile !== undefined ? { mobile: raw.mobile as GhostManifest['mobile'] } : {}),
...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),
+ ...(raw.taskPreferences !== undefined
+ ? { taskPreferences: raw.taskPreferences as boolean }
+ : {}),
...(prepared.schemaVersion === 2 ? { slots } : {}),
...(card !== undefined
|| prepared.v3BaseCard