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。

merge: sync plugin Worker input and completion fixes

Dash66b726e51c40
diff --cc apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 53e8297fe6,0205c808ff..c34e5b08ff
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@@ -1478,6 -1474,40 +1478,52 @@@ describe('AgentInputCoordinator send tr
expect(h.coordinator.getActiveInputClientIds(sid)).not.toContain('bot-delegation-completion:pending');
});
+ it('retains plugin provenance while native dispatch acknowledgement is pending', async () => {
+ const h = createHarness(), sid = 'plugin-pending-dispatch-ack';
+ let acknowledge!: () => void;
+ h.sendToAgent.mockImplementationOnce(async () => {
+ h.setRunning(true);
+ await new Promise<void>(resolve => { acknowledge = resolve; });
+ return sendSuccess();
+ });
+ h.coordinator.enqueue(sid, makeItem('plugin-task:run', 'Evaluate'));
+ await flush();
+ expect(h.coordinator.getAcceptedInputProvenance(sid)?.clientId).toBe('plugin-task:run');
+ acknowledge(); await flush();
+ expect(h.coordinator.getAcceptedInputProvenance(sid)?.clientId).toBe('plugin-task:run');
+ });
+
++ it.each([
++ { source: {kind: 'delegated-continuation'} as const, authoredText: undefined },
++ { source: 'My next task', authoredText: 'My next task' },
++ ])('exposes only human text as input takeover evidence: $source', async ({source, authoredText}) => {
++ const h = createHarness(), sid = 'typed-input-provenance';
++ h.sendToAgent.mockImplementationOnce(async () => { h.setRunning(true); return sendSuccess(); });
++ h.coordinator.enqueue(sid, {...makeItem('input', 'Continue'), autoReviewUserText: source});
++ await flush();
++ expect(h.coordinator.getAcceptedInputProvenance(sid)).toMatchObject({clientId: 'input', authoredText});
++ expect(h.sendToAgent.mock.calls[0]?.[3][AUTO_REVIEW_DELEGATED_CONTINUATION]).toBe(typeof source === 'object' ? true : undefined);
++ });
++
+ it('keeps accepted plugin authority through pending and rejected human steering', async () => {
+ const h = createHarness(), sid = 'accepted-plugin-authority';
+ h.sendToAgent.mockImplementationOnce(async () => { h.setRunning(true); return sendSuccess(); });
+ h.coordinator.enqueue(sid, makeItem('plugin-task:run', 'Evaluate'));
+ await flush();
+ let reject!: (error: Error) => void;
+ h.steerToAgent.mockImplementationOnce(() => new Promise((_, fail) => { reject = fail; }));
+ const steering = h.coordinator.steer(sid, makeItem('human-pending', 'New direction'));
+ await flush();
+ expect(h.coordinator.getAcceptedInputProvenance(sid)?.clientId).toBe('plugin-task:run');
+ reject(new Error('not accepted')); await steering;
+ expect(h.coordinator.getAcceptedInputProvenance(sid)?.clientId).toBe('plugin-task:run');
+ await h.coordinator.steer(sid, makeItem('human-accepted', 'New direction'));
+ expect(h.coordinator.getActiveInputClientIds(sid)).toContain('plugin-task:run');
+ expect(h.coordinator.getAcceptedInputProvenance(sid)?.clientId).toBe('human-accepted');
+ h.setRunning(false); h.coordinator.onTurnEvent(sid, 'done');
+ expect(h.coordinator.getAcceptedInputProvenance(sid)).toBeNull();
+ });
+
it('silently keeps a queue head when dispatch races with an already running turn', async () => {
const h = createHarness();
const sid = 'send-session-running-race';
diff --cc apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
index 69487557bc,88fdac0fec..53807bb876
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
@@@ -1,6 -1,7 +1,8 @@@
import type { SessionSendOptions, SessionSendResult, UserMessage } from '@cindy/maker-core';
+import { AUTO_REVIEW_DELEGATED_CONTINUATION, appendAutoReviewUserIntent, AUTO_REVIEW_USER_INTENT } from '@cindy/maker-core';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+ import { readFileSync } from 'node:fs';
+ import ts from 'typescript';
import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
import {
diff --cc apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index 7fbec19b44,c000918d1a..5b805ff6c4
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@@ -59,7 -59,8 +59,8 @@@ describe('Host provenance across Orca c
else if (change === 'disabled') enabled = false;
};
const bindings = {
+ maker: {getSession:()=>null}, inputCoordinator: { getAcceptedInputProvenance: () => null },
- PluginTaskError, getCurrentDbClientSnapshot: () => epoch,
+ PluginTaskError, readPluginTaskPlanReceipt: JSON.parse, getCurrentDbClientSnapshot: () => epoch,
createPluginTaskStore: () => ({ get: async () => receipt && { ...receipt } }),
pluginTaskServiceForCurrentOwner: () => ({ get: async (pluginId: string) => {
if (!receipt || receipt.pluginId !== pluginId || JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Revoked');
@@@ -2879,87 -2880,6 +2880,88 @@@ describe('production plugin Auto admiss
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 override = source.slice(source.indexOf(' getWorkerPermissionModeOverride: async (leadSessionId) => {'), source.indexOf(' setWorkerPermissionMode: applyWorkerPermissionModePreference,'));
+ const overrideJs = ts.transpileModule(`${helper}\nreturn ({${override}}).getWorkerPermissionModeOverride;`, { 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 = {
++ maker: {getSession:()=>null}, inputCoordinator: { getAcceptedInputProvenance: () => null },
+ 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 validateCreationPlan = new Function(...Object.keys(callbackDeps), js)(...Object.values(callbackDeps));
+ const { deps, service } = createDeps({ validateCreationPlan });
+ 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 getWorkerPermissionModeOverride = new Function(...Object.keys(callbackDeps), overrideJs)(...Object.values(callbackDeps));
+ const lifecycle = createOrcaLifecycleService({
+ getWorkerPermissionModeOverride,
+ 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'); });
diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerCompletion.test.ts
index f53d21aebe,47ebaaab57..34fee94084
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerCompletion.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWorkerCompletion.test.ts
@@@ -10,6 -12,63 +12,63 @@@ const final = {status:'idle',working:fa
describe('released Worker completion',()=>{
it('recovers a released final turn from host metadata',()=>expect(pluginWorkerCompletedAt(final)).toBe(200));
it.each([{working:true},{queued:1},{paused:true},{status:'error'},{startedAt:210},{clearedAt:195},{anchor:{...final.anchor,role:'user'}},{anchor:{...final.anchor,agentMeta:'{}'}},{anchor:{...final.anchor,agentMeta:'{"turnCompleted":false}'}},{anchor:{...final.anchor,agentMeta:'{"turnCompleted":true,"parentUuid":"child"}'}}])('does not infer completion from idle or old/report text: %j',patch=>expect(pluginWorkerCompletedAt({...final,...patch})).toBeNull());
+ it.each([undefined, {createdAt:90,content:JSON.stringify(ORCA_WORKER_READY_MESSAGE)}, {createdAt:90,content:ORCA_WORKER_READY_MESSAGE}, {createdAt:90,content:JSON.stringify({text:ORCA_WORKER_READY_MESSAGE})}])('does not settle a ready acknowledgement: %j',taskInput=>expect(pluginWorkerCompletedAt({...final,taskInput})).toBeNull());
+ });
+
+ it.each(['none', 'ready', 'auto-only', 'ready-auto', 'real', 'real-auto', 'ready-real', 'real-ready', 'cleared', 'rewound', 'child', 'other'].flatMap(scenario=>['idle','done'].map(status=>({scenario,status}))))('requires real visible input for $scenario completion from $status', async ({scenario,status}) => {
+ const sqlite = new Database(':memory:');
+ try {
+ sqlite.exec('CREATE TABLE sessions(id TEXT, active_turn_started_at INTEGER, last_turn_ended_at INTEGER, cleared_at INTEGER); CREATE TABLE messages(session_id TEXT, role TEXT, created_at INTEGER, agent_meta TEXT, rewind_at INTEGER, content TEXT);');
+ const sessions = sqliteTable('sessions', {id:text('id'),activeTurnStartedAt:integer('active_turn_started_at'),lastTurnEndedAt:integer('last_turn_ended_at'),clearedAt:integer('cleared_at')});
+ const messages = sqliteTable('messages', {sessionId:text('session_id'),role:text('role'),createdAt:integer('created_at'),agentMeta:text('agent_meta'),rewindAt:integer('rewind_at'),content:text('content')});
+ sqlite.prepare('INSERT INTO sessions VALUES (?, 100, 200, ?)').run('worker', scenario === 'cleared' ? 95 : null);
+ const insert = sqlite.prepare('INSERT INTO messages VALUES (?, ?, ?, ?, ?, ?)');
+ const user = (content:string, meta='{}', at=90, session='worker', rewind:number|null=null) => insert.run(session,'user',at,meta,rewind,JSON.stringify(content));
+ if (scenario.startsWith('ready')) user(ORCA_WORKER_READY_MESSAGE);
+ if (['real','real-auto','ready-real','real-ready','cleared'].includes(scenario)) user('Evaluate', '{}', 92);
+ if (scenario === 'real-ready') user(ORCA_WORKER_READY_MESSAGE, '{}', 94);
+ if (scenario.endsWith('auto') || scenario === 'auto-only') user('Continue', '{"autoResume":true}', 96);
+ if (scenario === 'rewound') user('Evaluate', '{}', 90, 'worker', 95);
+ if (scenario === 'child') user('Evaluate', '{"parentUuid":"child"}');
+ if (scenario === 'other') user('Evaluate', '{}', 90, 'other');
+ insert.run('worker','assistant',190,'{"turnCompleted":true}',null,'"Ready or done"');
+ const epoch = {client:{drizzle:drizzle(sqlite)}};
+ const source = readFileSync(new URL('../register.ts',import.meta.url),'utf8');
+ const start = source.indexOf(' const readPluginWorkerCompletion =');
+ const code = source.slice(start, source.indexOf(' const handlePluginTask =',start));
+ const deps = {sessions,messages,and,desc,eq,inArray,isNull,sql,pluginWorkerCompletedAt,getCurrentDbClientSnapshot:()=>epoch,createOrcaDiagnosticsDeps:()=>({getWorkerFlowStatus:async()=>({isWorking:false,queuedCount:0,queuePaused:false})})};
+ const read = new Function(...Object.keys(deps),ts.transpileModule(`${code}\nreturn readPluginWorkerCompletion;`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText)(...Object.values(deps));
+ const result = await read(epoch,'worker',status);
+ const completed = ['real','real-auto','ready-real'].includes(scenario);
+ expect(result.completedAt).toBe(completed ? 200 : null);
+ expect(result.status).toBe(completed ? 'done' : 'idle');
+ expect(result.row.lastTurnEndedAt).toBe(200);
+ const branch = source.slice(source.indexOf(" case 'getTeam': {"), source.indexOf(" case 'create': return service.create"));
- const bindings = {...deps, asc, gte, PluginTaskError, readPluginWorkerCompletion:read,
++ const bindings = {...deps, asc, gte, PluginTaskError, readPluginTaskPlanReceipt:JSON.parse, readPluginWorkerCompletion:read,
+ service:{get:async()=>({})},inputCoordinator:{ensureQueueRestored:async()=>{},isQueueRestored:()=>true,getQueueControlSnapshot:()=>({pendingQueue:[]})},
+ getOrcaWorkspaceInfoReadOnly:async()=>({ok:true,workers:[{session_id:'worker',status}]}),
+ maker:{getSession:()=>undefined},createPluginTaskStore:()=>({get:async()=>({payload:'{}'})}),readCollaborationSettings:()=>({workerHardLimit:4})};
+ const getTeam = new Function(...Object.keys(bindings),ts.transpileModule(`return async function(pluginId,request){switch(request.kind){${branch}}}`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText)(...Object.values(bindings));
+ const view = await getTeam('plugin',{kind:'getTeam',taskId:'lead'});
+ expect(view.workers[0]).toMatchObject({status:completed?'done':'idle',completedAt:completed?200:null,lastTurnEndedAt:200});
+ } finally {sqlite.close();}
+ });
+
+ it.each(['active','archived'])('refuses releasing %s Worker without task completion evidence', async status => {
+ const source = readFileSync(new URL('../register.ts',import.meta.url),'utf8');
+ const branch = source.slice(source.indexOf(" case 'releaseWorker': {"),source.indexOf(" case 'getTeam': {"));
+ const row={id:'worker',sessionId:'worker',label:'one',status};
+ const query={from:()=>query,innerJoin:()=>query,where:()=>query,limit:async()=>[row]};
+ const epoch={client:{drizzle:{select:()=>query}}};
+ const archive=vi.fn(),settleWorkerLabel=vi.fn();
- const bindings={PluginTaskError,getCurrentDbClientSnapshot:()=>epoch,eq:()=>true,and:()=>true,orcaWorkers:{},orcaTeams:{},sessions:{},
++ const bindings={PluginTaskError,readPluginTaskPlanReceipt:JSON.parse,getCurrentDbClientSnapshot:()=>epoch,eq:()=>true,and:()=>true,orcaWorkers:{},orcaTeams:{},sessions:{},
+ service:{completeOperation:(fn:()=>Promise<unknown>)=>fn(),get:async()=>({}),settleWorkerLabel},
+ createPluginTaskStore:()=>({get:async()=>({payload:'{"teamPlan":{"items":[{"label":"one"}]}}'})}),
+ readPluginWorkerCompletion:async()=>({row,completedAt:null}),
+ orcaTeamService:{archiveWorker:async({beforeArchive}:{beforeArchive:()=>Promise<void>})=>{await beforeArchive();archive();return {ok:true};}}};
+ const release=new Function(...Object.keys(bindings),ts.transpileModule(`return async function(pluginId,request){switch(request.kind){${branch}}}`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText)(...Object.values(bindings));
+ await expect(release('plugin',{kind:'releaseWorker',taskId:'lead',workerId:'worker',completedAt:200})).rejects.toMatchObject({code:'STALE_REVISION'});
+ expect(archive).not.toHaveBeenCalled();expect(settleWorkerLabel).not.toHaveBeenCalled();
});
it.each(['assistant', 'user'])('uses insertion order for same-millisecond latest %s evidence', async latest => {
diff --cc apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index d8bfa2fc83,247567ef73..2ddc1e563c
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@@ -1107,6 -1101,18 +1107,19 @@@ export class AgentInputCoordinator
return active.latestSteeringClientId ?? active.item?.clientId ?? null;
}
+ /** Authority follows the active input, never pending steering or cumulative reply attribution. */
+ getAcceptedInputProvenance(sessionId: string): {
+ clientId: string; autoResume?: boolean; retrySourceClientId?: string; authoredText?: string;
+ } | null {
+ const active = this.states.get(sessionId)?.activeTurn;
+ const item = active?.item;
+ // Native tools may arrive before sendToAgent returns its dispatch acknowledgement.
+ if (!item) return null;
- return { clientId: item.clientId, autoResume: item.autoResume, authoredText: item.autoReviewUserText,
++ return { clientId: item.clientId, autoResume: item.autoResume,
++ authoredText: typeof item.autoReviewUserText === 'string' ? item.autoReviewUserText : undefined,
+ retrySourceClientId: item.retrySourceClientId ?? item.supersedesUserClientId };
+ }
+
/** Inputs consumed by this native turn, excluding queued work and stale generations. */
getActiveInputClientIds(sessionId: string, vendorGeneration?: number): string[] {
const active = this.states.get(sessionId)?.activeTurn;
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index 4e4fa983ed,0107e2de6b..5d533fd8fd
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -11978,8 -11960,70 +11992,71 @@@ export function registerMakerIpc(maker
catch { return false; }
};
+ const captureOrcaPluginAuthority = async (leadSessionId: string) => {
+ const epoch = getCurrentDbClientSnapshot();
+ if (!epoch) throw new PluginTaskError('HOST_NOT_READY', 'Task storage unavailable', true);
+ const input = inputCoordinator.getAcceptedInputProvenance(leadSessionId);
+ const executing = !!input || !!maker.getSession(leadSessionId)?.isTurnRunning();
+ const store = createPluginTaskStore(epoch.client);
+ const receipt = await store.get(leadSessionId);
+ // Retry continues the original input; only a new accepted user message
+ // replaces that source. The stable lineage already survives automatic retries.
+ let inputId = input?.retrySourceClientId ?? input?.clientId;
+ if (receipt?.operation === 'create' && hasRevokedPluginTaskOwnership(receipt) && executing && !inputId?.startsWith('plugin-task:')) {
+ const authored = input && !input.autoResume && !input.retrySourceClientId && typeof input.authoredText === 'string'
+ && input.authoredText.trim() && !input.authoredText.startsWith('[UI_ACTION_TRIGGER]');
+ if (!authored) {
+ // Worker replies and automatic inputs are not user takeover. Direct native
+ // replies bypass the coordinator, so use the same accepted transcript evidence.
+ const meta = sql`CASE WHEN json_valid(${messages.agentMeta}) THEN ${messages.agentMeta} ELSE '{}' END`;
+ const [source] = await epoch.client.drizzle.select({clientId:messages.clientId, agentMeta:messages.agentMeta}).from(messages)
+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))
+ .where(and(eq(messages.sessionId, leadSessionId), eq(messages.role, 'user'), isNull(messages.rewindAt),
+ sql`${messages.createdAt} > COALESCE(${sessions.clearedAt}, 0)`,
+ sql`json_extract(${meta}, '$.parentUuid') IS NULL`,
+ sql`(${messages.clientId} LIKE 'plugin-task:%' OR (
+ COALESCE(json_extract(${meta}, '$.autoResume'), 0) != 1
+ AND COALESCE(json_extract(${meta}, '$.contextRebuild'), 0) != 1
+ AND COALESCE(json_extract(${meta}, '$.origin.kind'), '') != 'orca'))`))
+ .orderBy(desc(messages.createdAt), desc(sql`messages.rowid`)).limit(1);
+ if (!source) throw new PluginTaskError('PERMISSION_DENIED', 'Orca input provenance unavailable');
+ if (!source.clientId.startsWith('plugin-task:')) {
+ let evidence: Record<string, unknown> = {};
+ try { evidence = JSON.parse(source.agentMeta ?? '{}'); } catch { /* Unknown source rejects below. */ }
+ if (!evidence || !['turn', 'steer'].includes(String(evidence.delivery)) || typeof evidence.autoReviewUserText !== 'string'
+ || !evidence.autoReviewUserText.trim() || evidence.autoReviewUserText.startsWith('[UI_ACTION_TRIGGER]')) {
+ throw new PluginTaskError('PERMISSION_DENIED', 'Orca input provenance unavailable');
+ }
+ }
+ inputId = source.clientId;
+ }
+ }
+ const run = inputId?.startsWith('plugin-task:') ? await store.get(inputId.slice('plugin-task:'.length)) : undefined;
+ let inputPluginId: string | null = null;
+ if (inputId?.startsWith('plugin-task:')) {
+ if (!run || run.operation !== 'send' || run.targetId !== leadSessionId || JSON.parse(run.payload).inputMessageId !== inputId) {
+ throw new PluginTaskError('PERMISSION_DENIED', 'Plugin input provenance unavailable');
+ }
+ inputPluginId = run.pluginId;
+ }
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ const pluginId = inputPluginId ?? (receipt?.operation === 'create' && !hasRevokedPluginTaskOwnership(receipt) ? receipt.pluginId : null);
+ const assertCurrent = async () => {
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ const current = await store.get(leadSessionId);
+ const currentPluginId = current?.operation === 'create' && !hasRevokedPluginTaskOwnership(current) ? current.pluginId : null;
+ if (epoch !== getCurrentDbClientSnapshot() || currentPluginId !== pluginId) throw new PluginTaskError('PERMISSION_DENIED', 'Orca task ownership changed');
+ if (pluginId === null) return;
+ const task = await pluginTaskServiceForCurrentOwner!().get(pluginId, leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ assertPluginWorkerAutoAuthorized(pluginId, task);
+ };
+ await assertCurrent();
+ return { permissionMode: pluginId === null ? undefined : 'auto' as const, assertCurrent };
+ };
+
const orcaWorkerCreationService = createOrcaWorkerCreationService({
+ withLeadSendLock: withSendToSessionLock,
getActiveTeamByLead,
listWorkersByLead,
isActiveWorkerStatus,