Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): 将任务默认配置与宿主授权解耦
liugaowei9bae435d1ed2
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.tsindex 793178fb95..4d8d50406e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts@@ -191,7 +191,7 @@ it('completes source replacement and another plugin uninstall without reversingawait seedSourceResources();const archive = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__helper';const service = createPluginTaskService({- store: tasks, assertCurrent: () => {}, assertAuthorized: vi.fn(), readPermissionMode: vi.fn(),+ store: tasks, assertCurrent: () => {}, assertAuthorized: vi.fn(),readModelPreference: vi.fn(), resolveRoute: vi.fn(), createSession: vi.fn(), readSession: vi.fn(), readLiveSession: vi.fn(),dispatch: vi.fn(), inspect: vi.fn(), cancel: vi.fn(),});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.tsindex de9304b089..5b5110daeb 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts@@ -50,15 +50,15 @@ describe('Host provenance across Orca creation waits', () => {};function setup(action: Action, phase: string, change: string, entry = 'task') {let epoch = { client: {} }, enabled = true;- const directoryCase = ['config', 'pick'].includes(change);+ const directoryCase = ['lead-directory', 'pick'].includes(change);const candidate = path.resolve('synthetic-worker');- let configured = change === 'config' ? candidate : undefined, picked = change === 'pick';+ let picked = change === 'pick';let directoryResolved = false, directoryReads = 0;let queuedAcceptance: (() => void | Promise<void>) | undefined;let receipt: { operation: string; pluginId: string; payload: string } | null = change === 'ordinary' ? null : {operation: 'create', pluginId: 'plugin', payload: JSON.stringify({ ownershipRevoked: change === 'already-revoked' }),};- const task = { revision: 1, status: 'active', permissionMode: 'auto', planModeEnabled: false, workingDir: path.resolve('synthetic-project') };+ const task = { revision: 1, status: 'active', permissionMode: 'auto', planModeEnabled: false, workingDir: change === 'lead-directory' ? candidate : path.resolve('synthetic-project') };const mutate = (point: string) => {if (point !== phase) return;if (change === 'uninstalled' || change === 'reinstalled') {@@ -70,7 +70,7 @@ describe('Host provenance across Orca creation waits', () => {else if (change === 'plan') task.planModeEnabled = true;else if (change === 'archived') task.status = 'archived';else if (change === 'disabled') enabled = false;- else if (change === 'config') configured = undefined;+ else if (change === 'lead-directory') task.workingDir = path.resolve('other-project');else if (change === 'pick') picked = false;};const bindings = {@@ -86,10 +86,10 @@ 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, getPluginTaskDefaults: () => ({ permissionMode: 'auto', workingDir: directoryCase ? configured : task.workingDir }),+ isPluginTaskAuthorized: () => enabled, getPluginTaskDefaults: () => ({ permissionMode: 'auto', workingDir: candidate }),resolvePluginWorkerDirectory: vi.fn(async () => {directoryResolved = true; directoryReads = 0;- if (directoryCase && !configured && !picked) throw new PluginTaskError('PERMISSION_DENIED', 'Directory revoked');+ if (directoryCase && task.workingDir !== candidate && !picked) throw new PluginTaskError('PERMISSION_DENIED', 'Directory revoked');return directoryCase ? candidate : task.workingDir;}), isGhostPickedDir: () => picked,};@@ -234,8 +234,8 @@ describe('Host provenance across Orca creation waits', () => {['owner', 'missing', 'ask', 'plan', 'archived', 'disabled'].map(change => ({ action, phase: 'bootstrap', change }))));cases.push(...(['createWorker', 'enableTeam'] as Action[]).flatMap(action =>['worker-write', 'role-write', 'release', 'final-task', 'final-source', ...(action === 'enableTeam' ? ['lead-activation'] : [])].flatMap(phase =>- ['config', 'pick'].map(change => ({ action, phase, change })))));- it.each((['createWorker', 'enableTeam'] as const).flatMap(action => ['config', 'pick'].flatMap(change => ['', 'accepted'].map(phase => ({ action, change, phase }))))) (+ ['lead-directory', 'pick'].map(change => ({ action, phase, change })))));+ it.each((['createWorker', 'enableTeam'] as const).flatMap(action => ['lead-directory', 'pick'].flatMap(change => ['', 'accepted'].map(phase => ({ action, change, phase }))))) ('retains $action $change directory authority after the queued reply: $phase', async ({ action, change, phase }) => {const { run, acceptQueued, deps, lifecycleDeps } = setup(action, phase, change, 'queued');expect(await run()).toMatchObject({ ok: true, dispatched: false });@@ -266,7 +266,7 @@ describe('Host provenance across Orca creation waits', () => {});it.each((['createWorker', 'enableTeam'] as const).flatMap(action =>(action === 'createWorker' ? ['task', 'placeholder'] : ['task', 'placeholder', 'deferred']).flatMap(entry =>- ['config', 'pick'].flatMap(change => ['', 'accepted'].map(phase => ({ action, entry, change, phase }))))))(+ ['lead-directory', 'pick'].flatMap(change => ['', 'accepted'].map(phase => ({ action, entry, change, phase }))))))('retains resolved scope until $action $entry acceptance: $change $phase', async ({ action, entry, change, phase }) => {const { run, deps, lifecycleDeps } = setup(action, phase, change, entry);const result = await run();@@ -3656,7 +3656,7 @@ describe('production plugin Auto admission after reservation', () => {let receiptReads = 0;let reservedTaskReads = 0;const epoch = { client: {} };- const revoke = () => { mode = 'acceptEdits'; };+ const revoke = () => { enabled = false; };const task = () => ({ revision: 1, status: taskStatus, permissionMode: taskMode, planModeEnabled, workingDir: path.resolve('repo') });const planItem = { label: 'sample', workingDir: path.resolve(point === 'canonical-directory' ? 'alias' : point === 'different-directory' ? 'other' : 'repo'), route: { agentKind: 'codex', model: 'gpt-5.5', providerId: 'xd', effort: 'medium', fastMode: point === 'normalized-fast' } };const payload = () => JSON.stringify(planned ? { teamPlan: { concurrency: 2, items: [planItem] }, settledLabels: point === 'settled-label' ? ['sample'] : [] } : {});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.tsindex 1e39b9740d..38045bbe83 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts@@ -158,7 +158,6 @@ const duringPathChanges = {ownership: ({control}: ReturnType<typeof fixture>) => {control.ownershipValid=false;},approval: ({control}: ReturnType<typeof fixture>) => {control.authorized=false;},approvalRemoved: ({control}: ReturnType<typeof fixture>) => {control.approvalRevision=null;},- configAsk: ({control}: ReturnType<typeof fixture>) => {control.permissionMode='default';},account: ({control}: ReturnType<typeof fixture>) => {control.accountChanged=true;},userInstruction: ({db}: ReturnType<typeof fixture>) => db.prepare('INSERT INTO messages VALUES (?,?,?,?,?,?,?,NULL)').run('revoke','worker','revoke','user',JSON.stringify({text:'Do not run'}),1,JSON.stringify({delivery:'turn',autoReviewUserText:'Do not run'})),@@ -194,6 +193,20 @@ it.each(['initial', 'after cached allow'].flatMap(phase => Object.keys(duringPat} finally {f.db.close();}},);+// unit: preferences are not authorization; changing them must not invalidate a+// still-approved task's review. Actual permission/approval revocation stays above.+it('ignores card defaults in Auto authorization and its cache identity', async () => {+ const f = fixture();+ try {+ setPlan(f.db);+ const before = await f.resolve(request);+ f.control.permissionMode = 'ask';+ const after = await f.resolve(request);+ expect(after.authorizationError).toBeUndefined();+ expect(after.delegatedTask).toEqual(before.delegatedTask);+ expect(after.delegatedTask).toBeDefined();+ } finally { f.db.close(); }+});it('allows a healthy alias through both preparations without changing its authorization revision', async()=>{const f=fixture();try {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.tsindex 3b6c482cfb..9b824e5196 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts@@ -171,7 +171,7 @@ describe('plugin team activation uses the native lifecycle compensation', () =>orcaLifecycleService: createOrcaLifecycleService(deps) };const run = new Function(...Object.keys(callbacks), wired)(...Object.values(callbacks));const operation = run('plugin', { kind: 'startTeam', taskId: 'task' });- if (change === 'healthy') {+ if (change === 'healthy' || change === 'configuredPermission' || change === 'configuredDirectory') {await expect(operation).resolves.toMatchObject({ ok: true, teamId: 'team' });expect(teamActive).toBe(true); expect(role).toBe('lead'); expect(vendorActive).toBe(true);expect(epoch).toBe(originalEpoch);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.tsindex 5692010784..466ba02705 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts@@ -158,7 +158,6 @@ function fixture() {const live = { instanceId: execution.instanceId, stablePlanModeState: { enabled: false, generation: 0 } };const deps: PluginTaskServiceDeps = {store,- readPermissionMode: () => 'auto',readModelPreference: () => route,assertAuthorized: () => {if (!current) throw new Error('Owner changed');@@ -222,19 +221,18 @@ function useProductionPermissionCreator(f: ReturnType<typeof fixture>, configuref.tasks.set(options.sessionId, { taskId: options.sessionId, title: options.title, status: 'active',resolvedConfig: f.route, revision: 1, permissionMode: options.permissionMode });});- const deps = { assertPlugin: () => {}, getPluginTaskDefaults: () => ({ ...configured }),+ const deps = { assertPlugin: () => f.deps.assertAuthorized('p'), getPluginTaskDefaults: () => ({ ...configured }),resolveRoute: (...args: Parameters<typeof f.deps.resolveRoute>) => f.deps.resolveRoute(...args),PluginTaskError, isPluginTaskPermissionAllowed, createPluginTaskSession: persist,clampPluginTaskPermissionMode: (mode: unknown) => mode ?? 'ask', snapshot,getCurrentDbClientSnapshot: () => snapshot, isPluginTaskAuthorized: () => true,};- f.deps.readPermissionMode = () => configured.permissionMode;f.deps.createSession = new Function(...Object.keys(deps), permissionCreatorCode)(...Object.values(deps));return persist;}// unit: new per-create permissions must reach ordinary Session persistence while-// remaining within the user policy. Previous cases only exercised the default.+// keeping Host approval separate. Previous cases only exercised the default.it('persists the chosen creation permission without changing defaults or duplicate requests', async () => {const f = fixture(), configured = { permissionMode: 'bypassPermissions' };const persist = useProductionPermissionCreator(f, configured);@@ -252,16 +250,31 @@ it('persists the chosen creation permission without changing defaults or duplicaexpect(configured).toEqual({ permissionMode: 'bypassPermissions' });});+// unit: task parameters are independent of host defaults; installing/enabling+// tasks is still required. Previously an empty/hidden card capped creation at ask.+it('creates and sends with explicit permission independently of card defaults', async () => {+ const f = fixture(), configured = { permissionMode: 'ask' };+ useProductionPermissionCreator(f, configured);+ const task = await f.service.create('p', { requestKey: 'independent', title: 'Work', permissionMode: 'auto' });+ configured.permissionMode = 'plan';+ const run = await f.service.send('p', { taskId: task.taskId, expectedRevision: task.revision, requestKey: 'input', text: 'Continue' });+ await f.service.accept(task.taskId, { clientId: run.inputMessageId }, f.execution);+ f.deps.inspect = async () => ({ execution: f.execution, pending: [] });+ expect((await f.service.getRun('p', run.runId)).status).toBe('running');+ expect((await f.service.get('p', task.taskId)).permissionMode).toBe('auto');+ expect(configured.permissionMode).toBe('plan');+});+// unit: full access must work through ordinary send/accept, but a revoked user-// ceiling must block the queued input before execution. No full-access path existed before.-it('delivers an authorized full-access task and rechecks the ceiling before acceptance', async () => {+// capability approval must block the queued input before execution. No full-access path existed before.+it('delivers an authorized full-access task and rechecks capability approval before acceptance', async () => {const f = fixture(), configured = { permissionMode: 'bypassPermissions' };useProductionPermissionCreator(f, configured);const task = await f.service.create('p', { requestKey: 'full', title: 'Work', permissionMode: 'bypassPermissions' });const run = await f.service.send('p', { taskId: task.taskId, expectedRevision: task.revision,requestKey: 'send', text: 'Continue' });expect(f.deps.dispatch).toHaveBeenCalledOnce();- configured.permissionMode = 'auto';+ f.deps.assertAuthorized = () => { throw new PluginTaskError('PERMISSION_DENIED', 'Plugin approval revoked'); };await expect(f.service.accept(task.taskId, { clientId: run.inputMessageId }, f.execution)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });await expect(f.service.create('p', { requestKey: 'denied', title: 'Work', permissionMode: 'bypassPermissions' }))@@ -272,19 +285,22 @@ it('rejects an unauthorized creation permission before reserving a task', asyncconst f = fixture(), configured = { permissionMode: 'ask' };const persist = useProductionPermissionCreator(f, configured);const request = { requestKey: 'new', title: 'Work', permissionMode: 'auto' as const };+ const allowed = f.deps.assertAuthorized;+ f.deps.assertAuthorized = () => { throw new PluginTaskError('PERMISSION_DENIED', 'Plugin approval revoked'); };await expect(f.service.create('p', request)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });expect(persist).not.toHaveBeenCalled();expect(f.rows.size).toBe(0);- configured.permissionMode = 'auto';+ f.deps.assertAuthorized = allowed;expect((await f.service.create('p', request)).permissionMode).toBe('auto');});it.each(['route', 'persistence'] as const)('rechecks creation permission after %s preparation', async phase => {const f = fixture(), configured = { permissionMode: 'auto' };const persist = useProductionPermissionCreator(f, configured);- if (phase === 'route') f.deps.resolveRoute = async () => { configured.permissionMode = 'ask'; return f.route; };+ const revoke = () => { f.deps.assertAuthorized = () => { throw new PluginTaskError('PERMISSION_DENIED', 'Plugin approval revoked'); }; };+ if (phase === 'route') f.deps.resolveRoute = async () => { revoke(); return f.route; };else persist.mockImplementationOnce(async options => {- configured.permissionMode = 'ask';+ revoke();options.onPersistenceStarted();});await expect(f.service.create('p', { requestKey: 'new', title: 'Work', permissionMode: 'auto' }))@@ -949,9 +965,9 @@ describe('plugin ordinary task receipts', () => {});});-it('permission elevation blocks new sends but preserves inspection of existing work',async()=>{+it('unknown task permission blocks new sends but preserves inspection of existing work',async()=>{const f=fixture();const task=await f.create();const run=await f.send();- f.tasks.set(task.taskId,{...f.tasks.get(task.taskId)!,permissionMode:'bypassPermissions'});+ f.tasks.set(task.taskId,{...f.tasks.get(task.taskId)!,permissionMode:'unknown'});expect((await f.service.get('p',task.taskId)).taskId).toBe(task.taskId);expect((await f.service.getRun('p',run.runId)).runId).toBe(run.runId);await expect(f.service.send('p',{taskId:task.taskId,expectedRevision:task.revision,requestKey:'new-send',text:'new'})).rejects.toMatchObject({code:'PERMISSION_DENIED'});@@ -986,7 +1002,7 @@ it('freezes owned plan and retains settled labels',async()=>{const f=fixture(),tit('rechecks permissions when queued input reaches native dispatch', async () => {const f=fixture(), run=await f.send();- f.tasks.get(run.taskId)!.permissionMode='bypassPermissions';+ f.tasks.get(run.taskId)!.permissionMode='unknown';await expect(f.service.accept(run.taskId,{clientId:run.inputMessageId},f.execution)).rejects.toMatchObject({code:'PERMISSION_DENIED'});expect(JSON.parse(f.rows.get(run.runId)!.payload).status).toBe('queued');});@@ -1157,12 +1173,12 @@ describe('current plugin dispatch authority', () => {it.each(['before', 'route', 'insert'])('blocks a new dispatch after revocation at %s', async point => {const f = fixture(), task = await f.create();f.tasks.get(task.taskId)!.permissionMode = 'auto';- let mode = 'auto'; f.deps.readPermissionMode = () => mode;- if (point === 'before') mode = 'plan';- if (point === 'route') f.deps.resolveRoute = async () => { mode = 'plan'; return f.route; };+ const revoke = () => { f.tasks.get(task.taskId)!.planModeEnabled = true; };+ if (point === 'before') revoke();+ if (point === 'route') f.deps.resolveRoute = async () => { revoke(); return f.route; };if (point === 'insert') {const insert = f.deps.store.insert;- f.deps.store.insert = async row => { await insert(row); mode = 'plan'; };+ f.deps.store.insert = async row => { await insert(row); revoke(); };}const attempt = f.service.send('p', {taskId:task.taskId,expectedRevision:task.revision,requestKey:'new',text:'input'});if (point === 'insert') await expect(attempt).resolves.toMatchObject({status:'failed'});@@ -1172,12 +1188,12 @@ describe('current plugin dispatch authority', () => {it.each(['before', 'route', 'save'])('blocks queued acceptance after revocation at %s and keeps cancel available', async point => {const f = fixture(), run = await f.send();f.tasks.get(run.taskId)!.permissionMode = 'auto';- let mode = 'auto'; f.deps.readPermissionMode = () => mode;- if (point === 'before') mode = 'plan';- if (point === 'route') f.deps.resolveRoute = async () => { mode = 'plan'; return f.route; };+ const revoke = () => { f.tasks.get(run.taskId)!.planModeEnabled = true; };+ if (point === 'before') revoke();+ if (point === 'route') f.deps.resolveRoute = async () => { revoke(); return f.route; };if (point === 'save') {const save = f.deps.store.save;- f.deps.store.save = async row => { await save(row); mode = 'plan'; };+ f.deps.store.save = async row => { await save(row); revoke(); };}await expect(f.service.accept(run.taskId,{clientId:run.inputMessageId},f.execution)).rejects.toMatchObject({code:'PERMISSION_DENIED'});// Same-key retries observe the existing receipt; they never reopen dispatch.@@ -1195,7 +1211,7 @@ describe('current plugin dispatch authority', () => {f.deps.store.insert = async row => {await insert(row);if (change === 'plan') f.tasks.get(task.taskId)!.planModeEnabled = true;- if (change === 'permission') f.deps.readPermissionMode = () => 'plan';+ if (change === 'permission') f.tasks.get(task.taskId)!.permissionMode = 'unknown';if (change === 'archive') f.tasks.get(task.taskId)!.status = 'archived';if (change === 'read failure') f.deps.readSession = vi.fn().mockRejectedValueOnce(new Error('Read unavailable')).mockImplementation(readSession);@@ -1212,7 +1228,7 @@ describe('current plugin dispatch authority', () => {// Restored authority permits an explicit new request, never replay of the old input.f.deps.store.insert = insert;Object.assign(f.tasks.get(task.taskId)!, { planModeEnabled: false, status: 'active' });- f.deps.readPermissionMode = () => 'auto';+ f.tasks.get(task.taskId)!.permissionMode = 'auto';expect(await restarted.send('p', request)).toEqual(run);expect(await restarted.send('p', { ...request, requestKey: 'new' })).toMatchObject({ status: 'queued' });expect(f.deps.dispatch).toHaveBeenCalledTimes(1);@@ -1417,7 +1433,7 @@ it.each([});const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');const preferenceStart = source.indexOf(' readModelPreference:');- const preference = source.slice(preferenceStart, source.indexOf(' readPermissionMode:', preferenceStart));+ const preference = source.slice(preferenceStart, source.indexOf(' readLiveSession:', preferenceStart));const resolveStart = source.indexOf(' const resolveRoute = async');const resolve = source.slice(resolveStart, source.indexOf(' const readExecution', resolveStart));const deps = { getPluginTaskDefaults: () => config, getSelectedNewMakerRoute: () => selected,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.tsindex 953146ccae..7e87d46c7d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts@@ -10,6 +10,8 @@ import type { PluginTaskRoute } from '../../../shared/pluginTasks.js';import { resolvePluginWorkerDirectory } from '../pluginWorkerDirectory.js';import { createSessionExecutionResolver } from '../sessionExecutionSelection';+import { createGhostProductionCallbacks } from '../../cindy-brain/__tests__/ghostProductionCallbacksFixture.js';+import { clampPluginTaskPermissionMode } from '../../cindy-brain/pluginTaskPrefsStore.js';const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');function compile(text: string, deps: Record<string, unknown>) {@@ -203,6 +205,42 @@ it.each(['provider', 'receipt', 'directory', 'creator'])('keeps default-route co}});+// unit: exercise the production defaults reader and creator together. Hidden+// legacy values must neither supply creation fields nor invalidate an await.+const loadTaskDefaults = createGhostProductionCallbacks<{+ getPluginTaskDefaults(id: string): Record<string, unknown>;+}>({ functions: ['getPluginTaskDefaults'] });+it.each([undefined, 'auto'] as const)('creates independently of hidden defaults with permission %s', async permissionMode => {+ const start = source.indexOf(' createSession: async');+ const property = source.slice(start, source.indexOf(' readSession:', start)).trim().replace(/,$/, '');+ const epoch = {};+ const stored = { model: 'old', permissionMode: 'bypassPermissions', workingDir: '/old' };+ const read = vi.fn(() => stored);+ const defaults = loadTaskDefaults({ readPluginTaskConfig: read,+ findGhostForInstanceId: () => ({ manifest: { showTaskPreferences: false } }) });+ const route: PluginTaskRoute = { agentKind: 'codex', providerId: 'mine', model: 'current', effort: 'high', fastMode: false };+ let approved = true;+ const create = vi.fn(async ({ shouldContinue }: { shouldContinue(): boolean }) => {+ stored.model = 'changed'; stored.permissionMode = 'ask'; stored.workingDir = '/changed';+ expect(shouldContinue()).toBe(true);+ approved = false;+ expect(shouldContinue()).toBe(false);+ });+ const directory = vi.fn();+ const run = compile(`return ({${property}}).createSession;`, {+ ...defaults, PluginTaskError, snapshot: epoch, assertPlugin: vi.fn(),+ resolveRoute: async () => route, resolvePluginWorkerDirectory: directory,+ createPluginTaskSession: create, clampPluginTaskPermissionMode,+ getCurrentDbClientSnapshot: () => epoch, isPluginTaskAuthorized: () => approved,+ notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),+ });+ await run('plugin', 'task', 'title', route, false, undefined, undefined, undefined, false, undefined, permissionMode);+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ ...route, permissionMode: permissionMode ?? 'ask' }));+ expect(create.mock.calls[0]![0]).not.toHaveProperty('workingDir');+ expect(directory).not.toHaveBeenCalled();+ expect(read).not.toHaveBeenCalled();+});+it('forwards the explicit route when revalidating creation', async () => {const start = source.indexOf(' createSession: async');const property = source.slice(start, source.indexOf(' readSession:', start)).trim().replace(/,$/, '');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.tsindex 7c6c93a162..38260b8296 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts@@ -46,7 +46,7 @@ it('durably revokes only create ownership while retaining plans, run results andconst unused=async():Promise<never>=>{throw Error('unexpected dispatch/control');};const service=createPluginTaskService({store,assertCurrent(){},assertAuthorized(){},readSession:async taskId=>({taskId,title:'kept',revision:1,status:'active',resolvedConfig:route,permissionMode:'plan'}),- readModelPreference:()=>route,readPermissionMode:()=> 'plan',readLiveSession:()=>undefined,resolveRoute:unused,createSession:unused,dispatch:unused,inspect:unused,cancel:unused,+ readModelPreference:()=>route,readLiveSession:()=>undefined,resolveRoute:unused,createSession:unused,dispatch:unused,inspect:unused,cancel:unused,});expect((await service.list('p')).items.map(row=>row.taskId)).toEqual(['task']);await store.revokePlugin('p');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.tsindex 3209104cc3..65ec04e5d1 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts@@ -76,8 +76,23 @@ describe('shared-provider credential grants on permission changes', () => {});});describe('plugin write confirmation interleavings', () => {+ // unit: native consent authorizes only the chosen Session. It must not rewrite+ // plugin defaults and thereby affect unrelated future tasks.+ it('keeps host confirmation independent of card defaults', async () => {+ const f = fixture();+ f.change({ permissionMode: 'ask', model: 'chosen' });+ f.dialog.showMessageBox.mockImplementationOnce(async () => {+ f.change({ permissionMode: 'bypassPermissions', model: 'changed' });+ return { response: 0 };+ });+ await expect(f.run('auto')).resolves.toMatchObject({ granted: true });+ expect(f.live.setPermissionMode).toHaveBeenCalledWith('auto');+ expect(f.write).not.toHaveBeenCalled();+ expect(f.config()).toEqual({ permissionMode: 'bypassPermissions', model: 'changed' });+ });+// unit: adding full access must not make an older write-access request lower- // an already granted task or the user's independent plugin permission ceiling.+ // an already granted task, nor overwrite unrelated defaults.it('keeps full-access grants when an older client requests Auto', async () => {const f=fixture();f.change({permissionMode:'bypassPermissions'});f.service.get.mockResolvedValue({taskId:'task',revision:1,status:'active',permissionMode:'bypassPermissions'});@@ -86,7 +101,7 @@ describe('plugin write confirmation interleavings', () => {expect(f.live.setPermissionMode).not.toHaveBeenCalled();expect(f.write).not.toHaveBeenCalled();});- it('grants Auto to a task without reducing the plugin full-access ceiling', async () => {+ it('grants Auto to a task without changing plugin defaults', async () => {const f=fixture();f.change({permissionMode:'bypassPermissions'});await expect(f.run('auto')).resolves.toMatchObject({granted:true});expect(f.live.setPermissionMode).toHaveBeenCalledWith('auto');@@ -181,18 +196,19 @@ describe('plugin write confirmation interleavings', () => {if (point === 'runtime') f.live.setPermissionMode.mockImplementationOnce(async () => { change(); });if (point === 'database') f.epoch.client.tx.mockImplementationOnce(async () => { change(); return { updated: true }; });if (point === 'lastRead') f.service.get.mockImplementationOnce(async () => ({ taskId: 'task', revision: 1, status: 'active', permissionMode: 'plan' })).mockImplementationOnce(async () => ({ taskId: 'task', revision: 1, status: 'active', permissionMode: 'plan' })).mockImplementationOnce(async () => { change(); return { taskId: 'task', revision: 1, status: 'active', permissionMode: 'plan' }; });- await f.run('auto'); expect(f.config()).toEqual({ permissionMode: 'auto', model: 'new', workingDir: '/chosen', fastMode: true });+ await f.run('auto'); expect(f.config()).toEqual({ permissionMode: 'plan', model: 'new', workingDir: '/chosen', fastMode: true });+ expect(f.write).not.toHaveBeenCalled();});- it('does not overwrite a later permission change', async () => {+ it('does not treat a later default change as a Session permission revocation', async () => {const f = fixture(); f.live.setPermissionMode.mockImplementationOnce(async () => { f.change({ permissionMode: 'acceptEdits', model: 'new' }); });- await expect(f.run('auto')).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });+ await expect(f.run('auto')).resolves.toMatchObject({ granted: true });expect(f.write).not.toHaveBeenCalled(); expect(f.slots.size).toBe(0);- expect(f.live.setPermissionMode).toHaveBeenLastCalledWith('plan');- expect(f.epoch.client.tx).toHaveBeenLastCalledWith('bots.persistSessionPermission', {sessionId:'task', mode:'plan'});+ expect(f.live.setPermissionMode).toHaveBeenLastCalledWith('auto');+ expect(f.config()).toEqual({permissionMode:'acceptEdits',model:'new'});});it.each(['database', 'lastRead'] as const)('rolls back runtime and stored permission after late %s revocation', async point => {const f=fixture();- const revoke=()=>f.change({permissionMode:'acceptEdits',model:'new'});+ const revoke=()=>{f.change({permissionMode:'acceptEdits',model:'new'});f.identity('revoked-install');};if(point==='database') f.epoch.client.tx.mockImplementationOnce(async()=>{revoke();return {updated:true};});else f.service.get.mockImplementationOnce(async()=>({taskId:'task',revision:1,status:'active',permissionMode:'plan'})).mockImplementationOnce(async()=>({taskId:'task',revision:1,status:'active',permissionMode:'plan'}))@@ -264,13 +280,13 @@ describe('first plugin write approval checks actual task history', () => {});-it.each(['bypassPermissions', 'auto', 'acceptEdits'])('does not report %s as granted after plugin authority is lowered', async permissionMode => {+it.each(['bypassPermissions', 'auto', 'acceptEdits'])('reuses the task %s permission regardless of lower card defaults', async permissionMode => {const f = fixture();f.service.get.mockImplementation(async () => ({taskId:'task',revision:1,status:'active',permissionMode}));- f.dialog.showMessageBox.mockResolvedValue({response:1});- await expect(f.run()).resolves.toMatchObject({granted:false});- expect(f.dialog.showMessageBox).toHaveBeenCalledOnce();+ await expect(f.run()).resolves.toMatchObject({granted:true});+ expect(f.dialog.showMessageBox).not.toHaveBeenCalled();expect(f.live.setPermissionMode).not.toHaveBeenCalled();+ expect(f.write).not.toHaveBeenCalled();});it.each(['acceptEdits', 'auto'])('reuses an effective %s grant without another confirmation',async permissionMode=>{const f=fixture();f.change({permissionMode});diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.tsindex 21357cbd5a..f5ba07a605 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';import type { Session } from '@cindy/maker-core';import type { PluginTaskPermissionMode, PluginTaskRoute, PluginTaskRun, PluginTaskView, PluginTeamPlan } from '../../shared/pluginTasks.js';import { isPluginTaskPermissionMode, isPluginTeamPlanWithinBudget, PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../shared/pluginTasks.js';+import { GHOST_ERRAND_PERMISSION_MODES } from '../../shared/ghost.js';import type { PluginMessageAttachment } from '../../shared/pluginAttachments.js';import { withParsedPluginMessageAttachments, type PluginMessageImage } from '../cindy-media/pluginMessageAttachments.js';import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';@@ -111,11 +112,11 @@ export function isTeamPlanLabelLockedByReceipt(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. */-export function isPluginTaskPermissionAllowed(taskMode: unknown, configuredMode: unknown, planModeEnabled = false): boolean {+/** Compare a requested permission with a Session's current mode, never card defaults. */+export function isPluginTaskPermissionAllowed(taskMode: unknown, currentMode: unknown, planModeEnabled = false): boolean {const rank = (mode: unknown) => mode === 'plan' ? 0 : mode === 'ask' ? 1 : mode === 'acceptEdits' ? 2 : mode === 'auto' ? 3 : mode === 'bypassPermissions' ? 4 : -1;const task = rank(taskMode);- return !planModeEnabled && task >= 0 && task <= Math.max(0, rank(configuredMode));+ return !planModeEnabled && task >= 0 && task <= Math.max(0, rank(currentMode));}const fail = (code: string, message: string): never => {throw new PluginTaskError(code, message);@@ -141,7 +142,6 @@ export interface PluginTaskServiceDeps {/** Bound to the captured account/database epoch and plugin availability. */assertCurrent(): void;assertAuthorized(pluginId: string): void;- readPermissionMode(pluginId: string): unknown;/** Include the inherited new-task selection when the resolver can use it. */readModelPreference(pluginId: string): Partial<PluginTaskRoute> & { inheritedDefault?: string };resolveRoute(pluginId: string, route?: PluginTaskRoute, callId?: string): Promise<PluginTaskRoute>;@@ -243,13 +243,17 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {assertCurrent();return assertCurrent;};+ // Actual Session state is authoritative after creation. Defaults are not grants+ // and cannot revoke or elevate an existing task. The runtime enforces its mode.+ const isTaskRunnable = (view: PluginTaskView) => !view.planModeEnabled+ && (GHOST_ERRAND_PERMISSION_MODES as readonly unknown[]).includes(view.permissionMode);const assertDispatch = async (pluginId: string, taskId: string, assertPlanCurrent = capturePlanGuard(taskId)) => {const view = await ownTask(pluginId, taskId);deps.assertAuthorized(pluginId);assertPlanCurrent();if (view.status !== 'active') return fail('TASK_BUSY', 'Archived tasks cannot accept input');- if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(pluginId), view.planModeEnabled))- return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');+ if (!isTaskRunnable(view))+ return fail('PERMISSION_DENIED', 'Task permission is unavailable or Plan Mode is active');return view;};const save = async (row: PluginTaskReceipt, payload: unknown) => {@@ -359,12 +363,6 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {return fail('INVALID_REQUEST', 'Supply a title or opt into automatic naming');if (request.permissionMode !== undefined && !isPluginTaskPermissionMode(request.permissionMode))return fail('INVALID_REQUEST', 'Unsupported task creation permission');- const assertRequestedPermission = () => {- if (request.permissionMode === undefined) return;- deps.assertAuthorized(pluginId);- if (!isPluginTaskPermissionAllowed(request.permissionMode, deps.readPermissionMode(pluginId)))- fail('PERMISSION_DENIED', 'Requested permission exceeds plugin dispatch policy');- };const title = request.autoTitle ? DEFAULT_DRAFT_SESSION_TITLE : request.title!;const hidden = request.hidden === true;if (hidden) assertHiddenTasksAllowed(pluginId);@@ -382,11 +380,11 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {// Do not recreate a deleted/ambiguous task on replay.return ownTask(pluginId, row.id);}- assertRequestedPermission();+ deps.assertAuthorized(pluginId);const route = await deps.resolveRoute(pluginId, request.route, request.callId);deps.assertCurrent();targetContext?.assertCurrent();- assertRequestedPermission();+ deps.assertAuthorized(pluginId);const taskId = targetContext?.taskId ?? id();row = newReceipt(pluginId,@@ -401,7 +399,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {let persistenceStarted = false;try {deps.assertCurrent();- const onPersistenceStarted = () => { assertRequestedPermission(); persistenceStarted = true; };+ const onPersistenceStarted = () => { deps.assertAuthorized(pluginId); persistenceStarted = true; };// Omitted new fields keep the original creator call shape.if (request.permissionMode !== undefined) {targetContext?.assertCurrent();@@ -529,7 +527,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {if (previous)return { run: JSON.parse(previous.payload) as PluginTaskRun, dispatch: false as const };const assertPlanCurrent = capturePlanGuard(view.taskId);- if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(pluginId), view.planModeEnabled)) return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');+ if (!isTaskRunnable(view)) return fail('PERMISSION_DENIED', 'Task permission is unavailable or Plan Mode is active');if (view.status !== 'active')return fail('TASK_BUSY', 'Archived tasks cannot accept input');if (view.revision !== request.expectedRevision)@@ -668,7 +666,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {const view = await ownTask(row.pluginId, taskId);assertPlanCurrent();if (view.status !== 'active') return fail('TASK_BUSY', 'Archived tasks cannot accept input');- if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(row.pluginId), view.planModeEnabled)) return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');+ if (!isTaskRunnable(view)) return fail('PERMISSION_DENIED', 'Task permission is unavailable or Plan Mode is active');if (hash(view.resolvedConfig) !== hash(run.acceptedConfig))return fail('ROUTE_UNAVAILABLE', 'Accepted route changed before dispatch');await deps.resolveRoute(row.pluginId, run.acceptedConfig);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 3b200a9ecc..1d04d4c7a0 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -51,7 +51,7 @@ import {import { listPluginTargetCandidates, resolvePluginTargetSession } from './pluginTargetCandidates.js';import { createPluginTargetStore } from './pluginTargetStore.js';import { collectPluginAttachmentPayloadTexts, withPluginMessageAttachments } from '../cindy-media/pluginMessageAttachments.js';-import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';+import { isPluginTaskPermissionMode, type PluginTaskRoute, type PluginTaskRequest } from '../../shared/pluginTasks.js';import { buildPluginMessage } from '../../shared/pluginMessage.js';import { createHash as pluginTaskConfigHash } from 'node:crypto';import { finishCompanionEnvironmentRemoval } from '../bot-import/runtime.js';@@ -1513,7 +1513,6 @@ import {import {clampPluginTaskPermissionMode,setPluginTaskConfigValidator,- writePluginTaskConfig,readGhostErrandSessionId,writeGhostErrandSessionId,} from '../cindy-brain/pluginTaskPrefsStore.js';@@ -13968,7 +13967,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const routeUnavailable = (): never => { throw new PluginTaskError('ROUTE_UNAVAILABLE', 'The selected provider, model or effort is unavailable'); };const resolveRoute = async (pluginId: string, requested?: PluginTaskRoute, callId?: string): Promise<PluginTaskRoute> => {assertPlugin(pluginId);- const selection = { ...getPluginTaskDefaults(pluginId), ...requested };+ const selection = requested ?? getPluginTaskDefaults(pluginId);const sourceSessionId = getPluginTaskSourceSessionId(pluginId, callId);if (callId && !sourceSessionId && !(selection.agentKind && selection.model && selection.providerId)) throw new PluginTaskError('ROUTE_UNAVAILABLE', '发起任务已不可用,请重新调用,或在面板选择模型后创建任务');try {@@ -14003,7 +14002,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)fallback.harness, fallback.model, fallback.providerId, fallback.effort, fallback.fastMode,]) : undefined };},- readPermissionMode: pluginId => clampPluginTaskPermissionMode(getPluginTaskDefaults(pluginId).permissionMode),readLiveSession: taskId => maker.getSession(taskId),setModel: async (taskId, route, assertUnchanged) => {const current = await sessionControlService.getSessionRuntime({ targetSessionId: taskId });@@ -14039,15 +14037,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertPlugin(pluginId);const cfg = getPluginTaskDefaults(pluginId);const configuredPermission = clampPluginTaskPermissionMode(cfg.permissionMode);- if (permissionMode !== undefined && !isPluginTaskPermissionAllowed(permissionMode, configuredPermission))- throw new PluginTaskError('PERMISSION_DENIED', 'Requested permission exceeds plugin dispatch policy');const configurationIsCurrent = () => {targetContext?.assertCurrent();const current = getPluginTaskDefaults(pluginId);- return current.workingDir === cfg.workingDir && current.permissionMode === cfg.permissionMode- && current.agentKind === cfg.agentKind && current.model === cfg.model- && current.providerId === cfg.providerId && current.effort === cfg.effort- && current.fastMode === cfg.fastMode;+ return (targetContext || isolatedWorkspace || current.workingDir === cfg.workingDir)+ && (permissionMode !== undefined || current.permissionMode === cfg.permissionMode)+ && (requestedRoute !== undefined || (current.agentKind === cfg.agentKind && current.model === cfg.model+ && current.providerId === cfg.providerId && current.effort === cfg.effort+ && current.fastMode === cfg.fastMode));};// Receipt persistence/provider lookup can yield after the first resolution.// Reuse the resolver with the original request, then guard this configuration@@ -14256,16 +14253,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertPlanInactive();if (task.planModeEnabled) throw new PluginTaskError('PERMISSION_DENIED', 'Exit Plan Mode before requesting write access');const mode = request.mode ?? 'acceptEdits';- const cfg = getPluginTaskDefaults(pluginId);assertCallerCurrent();- if (isPluginTaskPermissionAllowed(task.permissionMode, cfg.permissionMode) && isPluginTaskPermissionAllowed(mode, task.permissionMode)) return { granted: true, task };+ if (isPluginTaskPermissionAllowed(mode, task.permissionMode)) return { granted: true, task };if (pluginPermissionRequests.size) throw new PluginTaskError('TASK_BUSY', 'A permission request is already open');const identity = pluginWriteAccessIdentity(pluginId);const assertRequestCurrent = () => {assertCallerCurrent();if (snapshot !== getCurrentDbClientSnapshot() || identity !== pluginWriteAccessIdentity(pluginId)) throw new PluginTaskError('PERMISSION_DENIED', 'Permission request identity changed');};- const before = JSON.stringify(cfg);const assertIdle = async () => {await inputCoordinator.ensureQueueRestored(task.taskId);assertRequestCurrent();@@ -14308,7 +14303,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// permission writers never hold that fence while awaiting this queue.return await withBotPermissionChange(task.taskId, () => withSessionPermissionChange(task.taskId, () => service.completeOperation(() => withSessionRestartLock(task.taskId, async () => {assertRequestCurrent();- if (snapshot !== getCurrentDbClientSnapshot() || before !== JSON.stringify(getPluginTaskDefaults(pluginId))) throw new PluginTaskError('PERMISSION_DENIED', 'Account or permission settings changed');const fresh = await service.get(pluginId, task.taskId);if (fresh.status !== 'active') throw new PluginTaskError('TASK_BUSY', 'Archived tasks cannot request write access');if (fresh.planModeEnabled) throw new PluginTaskError('PERMISSION_DENIED', 'Exit Plan Mode before requesting write access');@@ -14331,9 +14325,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertRequestCurrent();if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');assertPlanInactive();- const currentConfig = getPluginTaskDefaults(pluginId);- if (currentConfig.permissionMode !== cfg.permissionMode) throw new PluginTaskError('PERMISSION_DENIED', 'Permission settings changed');- if (!isPluginTaskPermissionAllowed(mode, clampPluginTaskPermissionMode(currentConfig.permissionMode))) writePluginTaskConfig(pluginId, {...currentConfig, permissionMode: mode});broadcastSessionPatched(task.taskId, {permissionMode: mode});return { granted: true, task: updatedTask };} catch (error) {@@ -14348,7 +14339,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)case 'startTeam': {const epoch = getCurrentDbClientSnapshot();const task = await service.get(pluginId, request.taskId);- const configuredDirectory = getPluginTaskDefaults(pluginId).workingDir;// Becoming Lead changes revision through orcaRole, but may not change admission facts.const admission = (view: typeof task) => JSON.stringify([view.resolvedConfig, view.permissionMode, view.planModeEnabled, view.workingDir]);const expectedAdmission = admission(task);@@ -14358,7 +14348,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const fresh = await service.get(pluginId, task.taskId);if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');assertPluginWorkerAutoAuthorized(pluginId, fresh);- if (configuredDirectory !== getPluginTaskDefaults(pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');if ((!activationStarted && fresh.revision !== task.revision) || admission(fresh) !== expectedAdmission) throw new PluginTaskError('STALE_REVISION', 'Task changed during team activation');}, service.completeOperation);assertPluginTaskResult(result, 'Collaboration could not be started');@@ -14367,13 +14356,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)case 'setTeamPlan': return withSendToSessionLock(request.taskId, async () => {const epoch = getCurrentDbClientSnapshot();const task = await service.get(pluginId, request.taskId);- const cfg = getPluginTaskDefaults(pluginId);const assertCurrent = () => {- if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(pluginId) || cfg.workingDir !== getPluginTaskDefaults(pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');+ if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(pluginId)) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');};const items = [];for (const item of request.plan.items) {- const workingDir = await resolvePluginWorkerDirectory({requested:item.workingDir,leadDirectory:task.workingDir,configuredDirectory:cfg.workingDir,isPickedDirectory:dir=>isGhostPickedDir(pluginId,dir),assertCurrent});+ const workingDir = await resolvePluginWorkerDirectory({requested:item.workingDir,leadDirectory:task.workingDir,isPickedDirectory:dir=>isGhostPickedDir(pluginId,dir),assertCurrent});items.push({...item, workingDir});}const current = await service.get(pluginId, request.taskId);@@ -14502,8 +14490,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)candidates: listPluginTargetCandidates,session: resolvePluginTargetSession,assertCreatePermission: (pluginId, permissionMode) => {- if (!isPluginTaskPermissionAllowed(permissionMode, clampPluginTaskPermissionMode(getPluginTaskDefaults(pluginId).permissionMode)))- throw new PluginTaskError('PERMISSION_DENIED', 'Requested permission exceeds plugin dispatch policy');+ if (!isPluginTaskAuthorized(pluginId)) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin task capability is unavailable');+ if (!isPluginTaskPermissionMode(permissionMode)) throw new PluginTaskError('INVALID_REQUEST', 'Unsupported task creation permission');},assertProjectDispatch: async (pluginId, taskId) => {await pluginTaskServiceForCurrentOwner!().assertDispatch(pluginId, taskId);@@ -15883,7 +15871,7 @@ 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' || getPluginTaskDefaults(pluginId).permissionMode !== 'auto') {+ if (!isPluginTaskAuthorized(pluginId) || task.planModeEnabled || task.permissionMode !== 'auto') {throw new PluginTaskError('PERMISSION_DENIED', 'Authorize Auto for the plugin coordinator before creating Workers');}};@@ -16048,12 +16036,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)) {throw new PluginTaskError('PERMISSION_DENIED', 'Plugin-owned tasks cannot run a Worker Agent on another computer');}- const cfg = getPluginTaskDefaults(receipt.pluginId);const resolveAuthorizedDirectory = (requested: string) => resolvePluginWorkerDirectory({requested, leadDirectory: task.workingDir,- configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId,dir),+ isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId,dir),assertCurrent: () => {- if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== getPluginTaskDefaults(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');+ if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId)) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');},});const directory = await resolveAuthorizedDirectory(params.workingDir ?? task.workingDir ?? '');@@ -16075,9 +16062,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// Last admission check also covers no-plan plugin tasks and revocation// while directory/receipt reads or the existing reservation were pending.assertPluginWorkerAutoAuthorized(receipt.pluginId, currentTask);- if (cfg.workingDir !== getPluginTaskDefaults(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');assertPluginWorkerDirectoryScope({ requested: directory, leadDirectory: currentTask.workingDir,- configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId, dir) });+ isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId, dir) });if (!data.teamPlan) return undefined; // Existing plugins retain their original behavior.if (!item || data.settledLabels?.includes(params.label)) throw new PluginTaskError('INVALID_REQUEST','Worker is not pending in the registered plan');const route = item.route;@@ -18056,12 +18042,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)projection.revision,]);if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');- const config = getPluginTaskDefaults(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),+ revision: [epoch.userId, epoch.clientEpoch, approvalRevision, link],plan: data.teamPlan, settledLabels: data.settledLabels,registeredRoute: data.route,session: { workingDir: session.workingDir, permissionMode: session.permissionMode, planModeEnabled: !!session.planModeEnabled, status: session.status,