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。

fix(plugins): 启动 Worker 后复核创建授权

Dash24daa8361a54
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 97cc6a1cbf..8fe29f1480 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -17,6 +17,7 @@ import {
} from '../orcaWorkerCreationService';
import type { DispatchWorkerTaskResult, OrcaWorkerStatus } from '../orcaTeamService';
import type { MakerSessionCreateOpts } from '../sessionRequest';
+import { createOrcaLifecycleService } from '../orcaLifecycleService';
import { CredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch';
import { isActiveWorkerStatus } from '../../../shared/orca-worker-status';
import { sshCodexWorkerRoutingContext } from '../orcaProviderRoutingContext';
@@ -2727,20 +2728,20 @@ describe('SSH remote worker model/provider compatibility gate (R23 P2)', () => {
});
});
-it('applies plan limit in atomic reservation',async()=>{const {deps,service}=createDeps({validateCreationPlan:vi.fn(async()=>2)});await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});expect(deps.reserveWorkerCreation).toHaveBeenCalledWith(expect.objectContaining({hardLimit:2}));});
-it('uses one canonical label at all three plan checks without mutating the caller', async () => {
+it('applies plan limit in atomic reservation',async()=>{const {deps,service}=createDeps({createCreationPlanValidator:()=>vi.fn(async()=>2)});await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});expect(deps.reserveWorkerCreation).toHaveBeenCalledWith(expect.objectContaining({hardLimit:2}));});
+it('uses one canonical label at all plan checks without mutating the caller', async () => {
const validateCreationPlan = vi.fn(async (_params: OrcaWorkerCreateParams) => 2);
- const { service } = createDeps({ validateCreationPlan });
+ const { service } = createDeps({ createCreationPlanValidator: () => validateCreationPlan });
const params = Object.freeze({ leadSessionId: 'lead-1', teamId: 'team-1', role: 'eval', agent: 'codex' as const, label: ' SAMPLE ', workerPermissionMode: 'auto' as const });
await expect(service.createWorkerInTeam(params)).resolves.toMatchObject({ ok: true });
- expect(validateCreationPlan).toHaveBeenCalledTimes(3);
+ expect(validateCreationPlan).toHaveBeenCalledTimes(4);
for (const call of validateCreationPlan.mock.calls) expect(call[0]).toMatchObject({ label: 'sample' });
expect(params.label).toBe(' SAMPLE ');
});
-it('rejects invalid plan before reservation',async()=>{const {deps,service}=createDeps({validateCreationPlan:vi.fn(async()=>{throw Error('not pending');})});await expect(service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'})).rejects.toThrow('not pending');expect(deps.reserveWorkerCreation).not.toHaveBeenCalled();expect(deps.bootstrapSession).not.toHaveBeenCalled();});
+it('rejects invalid plan before reservation',async()=>{const {deps,service}=createDeps({createCreationPlanValidator:()=>vi.fn(async()=>{throw Error('not pending');})});await expect(service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'})).rejects.toThrow('not pending');expect(deps.reserveWorkerCreation).not.toHaveBeenCalled();expect(deps.bootstrapSession).not.toHaveBeenCalled();});
it('revalidates a plan registered during creation preflight and releases the reservation on rejection', async () => {
let reserved = false;
- const {deps, service} = createDeps({validateCreationPlan: vi.fn(async () => {
+ const {deps, service} = createDeps({createCreationPlanValidator: () => vi.fn(async () => {
if (reserved) throw new Error('Worker not in newly registered plan');
return undefined;
})});
@@ -2756,7 +2757,7 @@ it('checks the resolved creation directory before bootstrap and releases a rejec
if (directory !== undefined && validateCreationPlan.mock.calls.length >= 3) throw new Error('Directory authorization revoked');
return undefined;
});
- const {deps, service} = createDeps({validateCreationPlan, resolveWorkerWorkingDir: vi.fn(async () => resolved)});
+ const {deps, service} = createDeps({createCreationPlanValidator: () => validateCreationPlan, resolveWorkerWorkingDir: vi.fn(async () => resolved)});
const params = {leadSessionId:'lead-1',role:'eval',agent:'codex' as const,label:'sample',workingDir:path.resolve('candidate')};
await expect(service.createWorker(params)).rejects.toThrow('Directory authorization revoked');
expect(validateCreationPlan).toHaveBeenLastCalledWith(expect.objectContaining(params), resolved, expect.objectContaining({ model: 'gpt-5.5', providerId: 'xd' }));
@@ -2767,8 +2768,85 @@ it('checks the resolved creation directory before bootstrap and releases a rejec
describe('production plugin Auto admission after reservation', () => {
const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
const helper = source.slice(source.indexOf(' const assertPluginWorkerAutoAuthorized ='), source.indexOf(' const orcaWorkerCreationService ='));
- const callback = source.slice(source.indexOf(' validateCreationPlan: async (params, resolvedWorkingDir, resolvedRoute) => {'), source.indexOf(' getLeadSessionRow: async (leadSessionId) => {'));
- const js = ts.transpileModule(`${helper}\nreturn ({${callback}}).validateCreationPlan;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const callback = source.slice(source.indexOf(' createCreationPlanValidator: () => {'), source.indexOf(' getLeadSessionRow: async (leadSessionId) => {'));
+ const js = ts.transpileModule(`${helper}\nreturn ({${callback}}).createCreationPlanValidator;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+
+ it.each([false, true].flatMap(planned => ['bootstrap', 'renewal'].flatMap(stage =>
+ ['disabled', 'uninstalled', 'reinstalled', 'account', 'owner', 'missing', 'downgraded', 'plan', 'archived', 'storage', 'healthy'].map(change => ({ planned, stage, change })),
+ )))('rechecks $change after $stage with planned=$planned before persistence and dispatch', async ({ planned, stage, change }) => {
+ let epoch = { client: {} };
+ let enabled = true, missing = false, storageFailed = false;
+ const task = { revision: 1, status: 'active', permissionMode: 'auto', planModeEnabled: false, workingDir: path.resolve('repo') };
+ const receipt = { pluginId: 'plugin', operation: 'create', payload: JSON.stringify(planned ? {
+ teamPlan: { concurrency: 2, items: [{ label: 'sample', workingDir: task.workingDir,
+ route: { agentKind: 'codex', model: 'gpt-5.5', providerId: 'xd', effort: 'medium', fastMode: false } }] },
+ } : {}) };
+ const callbackDeps = {
+ readPluginTaskPlanReceipt: JSON.parse, getCurrentDbClientSnapshot: () => epoch,
+ createPluginTaskStore: () => ({ get: async () => {
+ if (storageFailed) throw new Error('storage unavailable');
+ return missing ? null : structuredClone(receipt);
+ } }),
+ pluginTaskServiceForCurrentOwner: () => ({ get: async () => {
+ if (JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Not owned');
+ return { ...task };
+ } }),
+ readGhostErrandConfig: () => ({ permissionMode: 'auto', workingDir: task.workingDir }),
+ isPluginTaskAuthorized: () => enabled,
+ resolvePluginWorkerDirectory: async () => task.workingDir,
+ isGhostPickedDir: () => false, PluginTaskError,
+ };
+ const createCreationPlanValidator = new Function(...Object.keys(callbackDeps), js)(...Object.values(callbackDeps));
+ const { deps, service } = createDeps({ createCreationPlanValidator });
+ const mutate = () => {
+ if (change === 'disabled') enabled = false;
+ if (['uninstalled', 'reinstalled'].includes(change)) {
+ receipt.payload = JSON.stringify({ ...JSON.parse(receipt.payload), ownershipRevoked: true });
+ enabled = change === 'reinstalled';
+ }
+ if (change === 'account') epoch = { client: {} };
+ if (change === 'owner') receipt.pluginId = 'other-plugin';
+ if (change === 'missing') missing = true;
+ if (change === 'downgraded') task.permissionMode = 'default';
+ if (change === 'plan') task.planModeEnabled = true;
+ if (change === 'archived') task.status = 'archived';
+ if (change === 'storage') storageFailed = true;
+ };
+ const bootstrap = deps.bootstrapSession;
+ deps.bootstrapSession = vi.fn(async opts => { const result = await bootstrap(opts); if (stage === 'bootstrap') mutate(); return result; });
+ deps.renewWorkerCreationReservation = vi.fn(async () => { if (stage === 'renewal') mutate(); return true; });
+ const markTeamEnded = vi.fn(async () => undefined);
+ const lifecycle = createOrcaLifecycleService({
+ getActiveTeamByLead: async () => planned ? null : { id: 'team-1', leadSessionId: 'lead-1' },
+ createActiveTeam: async () => ({ id: 'team-1', leadSessionId: 'lead-1' }),
+ isOrphanedTeamInit: async () => false, getWorkerPermissionMode: () => 'auto',
+ setWorkerPermissionMode: vi.fn(), createWorkerInTeam: service.createWorkerInTeam,
+ dispatchWorkerTask: deps.dispatchWorkerTask, markTeamEnded, setSessionOrcaRole: vi.fn(async () => undefined),
+ clearKnownNonOrcaSession: vi.fn(), setLeadVendorOptions: vi.fn(async () => undefined), clearLeadVendorOptions: vi.fn(async () => undefined),
+ sendWorkerReadyPlaceholder: vi.fn(async () => undefined), rollbackCreatedWorker: vi.fn(async () => undefined),
+ broadcastSessionCreated: deps.broadcastSessionCreated, broadcastOrcaWorkerChanged: deps.broadcastOrcaWorkerChanged,
+ });
+ const result = planned
+ ? await lifecycle.enableTeam({ leadSessionId: 'lead-1', workerAgent: 'codex', role: 'eval', label: 'sample', delegateTask: 'Evaluate sample' })
+ : await lifecycle.createWorker({ leadSessionId: 'lead-1', agent: 'codex', role: 'eval', label: 'sample', initialTask: 'Evaluate sample' });
+ expect(deps.bootstrapSession).toHaveBeenCalledOnce();
+ expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledOnce();
+ if (change === 'healthy') {
+ expect(result.ok).toBe(true);
+ expect(deps.addOrUpdateWorker).toHaveBeenCalledOnce();
+ expect(deps.dispatchWorkerTask).toHaveBeenCalledOnce();
+ expect(deps.closeWorkerSession).not.toHaveBeenCalled();
+ } else {
+ expect(result).toMatchObject({ ok: false, errorCode: 'INTERNAL' });
+ expect(deps.addOrUpdateWorker).not.toHaveBeenCalled();
+ expect(deps.markOrcaRoleIfNeeded).not.toHaveBeenCalled();
+ expect(deps.dispatchWorkerTask).not.toHaveBeenCalled();
+ for (const cleanup of [deps.closeWorkerSession, deps.forgetWorkerSession, deps.archiveWorkerSession]) {
+ expect(cleanup).toHaveBeenCalledExactlyOnceWith(WORKER_SESSION_ID);
+ }
+ if (planned) expect(markTeamEnded).toHaveBeenCalledExactlyOnceWith('team-1', 'failed');
+ }
+ });
it.each(['uninstalled', 'reinstalled', 'malformed'])('keeps ordinary Worker creation separate from %s plugin receipts', async state => {
const epoch = { client: {} }, get = vi.fn(async () => { throw new PluginTaskError('TASK_NOT_FOUND', 'Not owned'); });
@@ -2777,8 +2855,8 @@ describe('production plugin Auto admission after reservation', () => {
pluginTaskServiceForCurrentOwner: () => ({ get }), isPluginTaskAuthorized: () => state === 'reinstalled',
readGhostErrandConfig: () => ({ permissionMode: 'auto' }),
};
- const validateCreationPlan = new Function(...Object.keys(callbackDeps), js)(...Object.values(callbackDeps));
- const { deps, service } = createDeps({ validateCreationPlan });
+ const createCreationPlanValidator = new Function(...Object.keys(callbackDeps), js)(...Object.values(callbackDeps));
+ const { deps, service } = createDeps({ createCreationPlanValidator });
const result = service.createWorker({ leadSessionId: 'lead-1', role: 'worker', label: 'sample', agent: 'codex' });
if (state === 'malformed') {
await expect(result).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });
@@ -2836,8 +2914,8 @@ describe('production plugin Auto admission after reservation', () => {
isGhostPickedDir: () => false,
PluginTaskError,
};
- const validateCreationPlan = new Function(...Object.keys(depsForCallback), js)(...Object.values(depsForCallback));
- const { deps, service } = createDeps({ validateCreationPlan, withLeadSendLock: async (_id, operation) => {
+ const createCreationPlanValidator = new Function(...Object.keys(depsForCallback), js)(...Object.values(depsForCallback));
+ const { deps, service } = createDeps({ createCreationPlanValidator, withLeadSendLock: async (_id, operation) => {
if (point === 'archive-admission') taskStatus = 'archived';
return operation();
} });
@@ -2880,8 +2958,9 @@ describe('production plugin Auto admission after reservation', () => {
});
it('rechecks a newly registered plan under the Lead send lock before reserving', async () => {
let locked = false, limit: number | undefined;
+ const validateCreationPlan = vi.fn(async () => limit);
const {deps,service}=createDeps({
- validateCreationPlan: vi.fn(async () => limit),
+ createCreationPlanValidator: () => validateCreationPlan,
withLeadSendLock: async (_id, operation) => {
limit = 1; locked = true;
try { return await operation(); } finally { locked = false; }
@@ -2894,12 +2973,12 @@ it('rechecks a newly registered plan under the Lead send lock before reserving',
const bootstrap=deps.bootstrapSession;
deps.bootstrapSession=vi.fn(async (opts: MakerSessionCreateOpts) => {expect(locked).toBe(false);return bootstrap(opts);});
await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});
- expect(deps.validateCreationPlan).toHaveBeenCalledTimes(3);
+ expect(validateCreationPlan).toHaveBeenCalledTimes(4);
expect(deps.reserveWorkerCreation).toHaveBeenCalledOnce();
});
it('rejects a plan changed during preparation without reserving or bootstrapping', async () => {
const validate=vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error('not pending'));
- const {deps,service}=createDeps({validateCreationPlan:validate,withLeadSendLock:async (_id, operation)=>operation()});
+ const {deps,service}=createDeps({createCreationPlanValidator:()=>validate,withLeadSendLock:async (_id, operation)=>operation()});
const result=await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});
expect(result.ok).toBe(false);expect(deps.reserveWorkerCreation).not.toHaveBeenCalled();expect(deps.bootstrapSession).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
index 859da539cf..6a49f4b75e 100644
--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
@@ -203,14 +203,20 @@ export interface OrcaWorkerCreateInTeamParams extends OrcaWorkerCreateParams {
workerPermissionMode: OrcaWorkerPermissionMode;
}
+export type OrcaWorkerCreationPlanValidator = (
+ params: OrcaWorkerCreateInTeamParams,
+ resolvedWorkingDir?: string,
+ resolvedRoute?: { model: string; providerId: string | null; effort: string | null; fastMode: boolean },
+) => Promise<number | null | undefined>;
+
/** creation service 的 I/O 边界;register.ts 负责把 DB、Maker 与 broadcast 注入进来。 */
export interface OrcaWorkerCreationDeps {
getActiveTeamByLead(leadSessionId: string): Promise<OrcaTeamSnapshot | null>;
listWorkersByLead(leadSessionId: string): Promise<OrcaWorkerListSnapshot[]>;
isActiveWorkerStatus(status: OrcaWorkerStatus): boolean;
withLeadSendLock?<T>(leadSessionId: string, operation: () => Promise<T>): Promise<T>;
- validateCreationPlan?(params: OrcaWorkerCreateInTeamParams, resolvedWorkingDir?: string,
- resolvedRoute?: { model: string; providerId: string | null; effort: string | null; fastMode: boolean }): Promise<number | null | undefined>;
+ /** One validator per creation keeps its original account and ownership across awaits. */
+ createCreationPlanValidator?(): OrcaWorkerCreationPlanValidator;
readCollaborationSettings(): { workerSoftLimit: number; workerHardLimit: number };
getLeadSessionRow(leadSessionId: string): Promise<OrcaLeadSessionSnapshot | null>;
getWorkerDefaults(agent: AgentKind): OrcaWorkerDefaultsSnapshot;
@@ -622,13 +628,14 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
const label = normalizeOrcaWorkerLabel(params.label);
if (!label.ok) return { ok: false, errorCode: 'INVALID_PARAMS', message: label.message };
params = { ...params, label: label.value };
+ const validateCreationPlan = deps.createCreationPlanValidator?.();
const existing = await deps.listWorkersByLead(params.leadSessionId);
if (existing.some((worker) => worker.label?.toLowerCase() === label.value)) {
return { ok: false, errorCode: 'DUPLICATE_LABEL', message: `label "${label.value}" already used in this team` };
}
- const planLimit = await deps.validateCreationPlan?.(params);
+ const planLimit = await validateCreationPlan?.(params);
const settings = {...deps.readCollaborationSettings()};
if (planLimit != null) settings.workerHardLimit = Math.min(settings.workerHardLimit, planLimit);
const activeCount = existing.filter((worker) => deps.isActiveWorkerStatus(worker.status)).length;
@@ -996,7 +1003,7 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
const admit = async () => {
// Preparation may await providers or remote state. Re-read the plan at
// the final admission boundary shared with plan registration and input.
- const latestLimit = await deps.validateCreationPlan?.(params, workingDir, resolved);
+ const latestLimit = await validateCreationPlan?.(params, workingDir, resolved);
settings.workerHardLimit = deps.readCollaborationSettings().workerHardLimit;
if (latestLimit != null) settings.workerHardLimit = Math.min(settings.workerHardLimit, latestLimit);
return deps.reserveWorkerCreation({
@@ -1039,7 +1046,7 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
try {
// Registration may race the preflight. Once a reservation exists, a new
// plan cannot be registered; reread any plan that won before reservation.
- const reservedPlanLimit = await deps.validateCreationPlan?.(params, workingDir, resolved);
+ const reservedPlanLimit = await validateCreationPlan?.(params, workingDir, resolved);
if (reservedPlanLimit != null && reservation.occupiedSlotsBefore >= reservedPlanLimit) {
return { ok: false, errorCode: 'WORKER_LIMIT_HARD_EXCEEDED', message: 'Registered plan concurrency reached' };
}
@@ -1095,6 +1102,13 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
}
try {
+ // Bootstrap and lease renewal both await external work. Reuse the same
+ // admission validator before recording a Worker that lifecycle can dispatch.
+ const finalPlanLimit = await validateCreationPlan?.(params, workingDir, resolved);
+ if (finalPlanLimit != null && reservation.occupiedSlotsBefore >= finalPlanLimit) {
+ await cleanupBootstrappedWorkerSession(workerSession.id);
+ return { ok: false, errorCode: 'WORKER_LIMIT_HARD_EXCEEDED', message: 'Registered plan concurrency reached' };
+ }
await deps.addOrUpdateWorker({
id: workerId,
teamId: params.teamId,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 85f8f11d6e..e7212411c8 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -11914,48 +11914,58 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
listWorkersByLead,
isActiveWorkerStatus,
readCollaborationSettings,
- validateCreationPlan: async (params, resolvedWorkingDir, resolvedRoute) => {
+ createCreationPlanValidator: () => {
const epoch = getCurrentDbClientSnapshot();
- if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable');
- const receipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
- if (!receipt || receipt.operation !== 'create' || hasRevokedPluginTaskOwnership(receipt)) return undefined;
- const task = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
- if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
- assertPluginWorkerAutoAuthorized(receipt.pluginId, task);
- const cfg = readGhostErrandConfig(receipt.pluginId);
- const resolveAuthorizedDirectory = (requested: string) => resolvePluginWorkerDirectory({
- requested, leadDirectory: task.workingDir,
- configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId,dir),
- assertCurrent: () => {
- if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');
- },
- });
- const directory = await resolveAuthorizedDirectory(params.workingDir ?? task.workingDir ?? '');
- if (resolvedWorkingDir !== undefined && directory !== await resolveAuthorizedDirectory(resolvedWorkingDir)) throw new PluginTaskError('PERMISSION_DENIED','Worker directory changed during creation');
- // Drain plan registration before taking the receipt snapshot. Waiting only
- // after this read leaves a stale no-plan payload even when get() sees the
- // newly persisted plan. Keep the final task check after directory awaits.
- await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
- if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
- const currentReceipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
- if (!currentReceipt || currentReceipt.operation !== 'create' || epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Task ownership changed');
- const data = readPluginTaskPlanReceipt(currentReceipt.payload);
- const item = data.teamPlan?.items.find((x: {label:string})=>x.label===params.label);
- const plannedDirectory = item && resolvedRoute
- ? await resolveAuthorizedDirectory(item.workingDir) : undefined;
- const currentTask = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
- if (epoch !== getCurrentDbClientSnapshot() || currentTask.revision !== task.revision) throw new PluginTaskError('STALE_REVISION','Task changed during directory validation');
- // 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 !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');
- 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;
- // Defaults and provider capabilities are resolved by the creation service.
- // Compare that exact spawn route at the post-reservation admission check.
- if (resolvedRoute && (directory!==plannedDirectory || resolvedRoute.model!==route.model || resolvedRoute.providerId!==route.providerId || resolvedRoute.effort!==route.effort || resolvedRoute.fastMode!==route.fastMode || params.agent!==(route.agentKind==='cc'?'claude-code':route.agentKind))) throw new PluginTaskError('INVALID_REQUEST','Worker configuration differs from registered plan');
- return data.teamPlan.concurrency;
+ // Keep provenance only for this create call. An in-flight plugin request
+ // must not become ordinary Orca after uninstall or switch to another account.
+ let originalPluginId: string | null | undefined;
+ return async (params, resolvedWorkingDir, resolvedRoute) => {
+ if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable');
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ const receipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ const currentPluginId = receipt?.operation === 'create' && !hasRevokedPluginTaskOwnership(receipt) ? receipt.pluginId : null;
+ if (originalPluginId === undefined) originalPluginId = currentPluginId;
+ if (currentPluginId !== originalPluginId) throw new PluginTaskError('PERMISSION_DENIED', 'Task ownership changed');
+ if (!receipt || currentPluginId === null) return undefined;
+ const task = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ assertPluginWorkerAutoAuthorized(receipt.pluginId, task);
+ const cfg = readGhostErrandConfig(receipt.pluginId);
+ const resolveAuthorizedDirectory = (requested: string) => resolvePluginWorkerDirectory({
+ requested, leadDirectory: task.workingDir,
+ configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId,dir),
+ assertCurrent: () => {
+ if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');
+ },
+ });
+ const directory = await resolveAuthorizedDirectory(params.workingDir ?? task.workingDir ?? '');
+ if (resolvedWorkingDir !== undefined && directory !== await resolveAuthorizedDirectory(resolvedWorkingDir)) throw new PluginTaskError('PERMISSION_DENIED','Worker directory changed during creation');
+ // Drain plan registration before taking the receipt snapshot. Waiting only
+ // after this read leaves a stale no-plan payload even when get() sees the
+ // newly persisted plan. Keep the final task check after directory awaits.
+ await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ const currentReceipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
+ if (!currentReceipt || currentReceipt.operation !== 'create' || currentReceipt.pluginId !== originalPluginId || hasRevokedPluginTaskOwnership(currentReceipt) || epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Task ownership changed');
+ const data = readPluginTaskPlanReceipt(currentReceipt.payload);
+ const item = data.teamPlan?.items.find((x: {label:string})=>x.label===params.label);
+ const plannedDirectory = item && resolvedRoute
+ ? await resolveAuthorizedDirectory(item.workingDir) : undefined;
+ const currentTask = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot() || currentTask.revision !== task.revision) throw new PluginTaskError('STALE_REVISION','Task changed during directory validation');
+ // 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 !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');
+ 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;
+ // Defaults and provider capabilities are resolved by the creation service.
+ // Compare that exact spawn route at the post-reservation admission check.
+ if (resolvedRoute && (directory!==plannedDirectory || resolvedRoute.model!==route.model || resolvedRoute.providerId!==route.providerId || resolvedRoute.effort!==route.effort || resolvedRoute.fastMode!==route.fastMode || params.agent!==(route.agentKind==='cc'?'claude-code':route.agentKind))) throw new PluginTaskError('INVALID_REQUEST','Worker configuration differs from registered plan');
+ return data.teamPlan.concurrency;
+ };
},
getLeadSessionRow: async (leadSessionId) => {
const db = getDbClient().drizzle;
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 2488daa646..9883cc5e51 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -122,6 +122,11 @@
### 3.1 安装与自动更新
插件普通任务创建的 Worker 目录由宿主校验:允许当前任务目录及解析符号链接后仍在其中的子目录、插件 AI 配置目录、用户通过目录选择器授权的确切目录。Library 绑定本身不授予 Agent 工作目录权限,协同计划也不构成目录授权。登记计划和实际创建 Worker 均复核授权;账号、配置或任务归属发生变化时拒绝继续创建。
+同一次 Worker 创建沿用最初的账号与任务归属,在启动 Session、续租完成后、写入 Worker 前再次复核。
+复核失败沿用既有尽力清理路径(关闭、移除运行缓存、归档 Session 与释放预留),不派发初始任务;新团队沿用创建失败收尾。
+卸载后用户新发起的普通 Orca 创建仍可使用旧任务,但在途插件创建不得因卸载转成普通创建。
+此检查不构成跨持久化与派发的事务,也未新增跨账号数据库补偿;实现及回归见
+`apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts`、`register.ts` 与 `__tests__/orcaWorkerCreationService.test.ts`。
插件任务目录在文件系统查询前拒绝 UNC/device 路径,并先按上述宿主目录记录核验候选路径;不通过探测未登记别名发现授权目标。本地 Windows 盘符长路径保留支持。解析后仍复核真实目录;这不构成执行隔离,也不能阻止已授权目录内的链接置换。
- 首次安装只来自明确依据:用户导入本地 `.cindy`、明确要求当前 Agent 调用