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(plugin): 保持撤权后在途任务的历史读取边界

Dashdbb9a4317e33
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 44c31b9296..06f56e447f 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -3911,7 +3911,7 @@ const r = await cindy.agent.requestSchedule({
先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:
\`create\`、\`get\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`。
可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。
-这些任务及其 Worker 不提供 \`cindy_helper\` 的账号级历史或跨任务控制能力,\`cindy_memory.session_search\` 也拒绝历史检索;协调使用独立 Orca 工具,结果由插件通过 \`readMessages/getTeam\` 读取。旧 errand/workspace 不因来源标记受到限制;明确卸载撤销归属后,保留的用户任务恢复普通 helper 与历史检索能力。这不构成通用执行沙箱。
+这些任务及其 Worker 不提供 \`cindy_helper\` 的账号级历史或跨任务控制能力,\`cindy_memory.session_search\` 也拒绝历史检索;协调使用独立 Orca 工具,结果由插件通过 \`readMessages/getTeam\` 读取。旧 errand/workspace 不因来源标记受到限制;明确卸载撤销归属后,调用方已无正在执行的输入或已接受新真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限,自动回报和插件输入重试不构成真人接管。这不恢复插件控制权,也不保证停止已接受执行,不构成通用执行沙箱。
在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,items}})\`,每项包含\`label, workingDir, route\`。计划冻结后不可改写。
计划不授予目录权限。Worker 仅可使用宿主任务目录及解析后仍在其中的子目录、插件 AI 配置目录或用户亲选的确切目录;Library 绑定不自动变成 Agent 工作根。宿主在登记和创建时均复核。
这描述准入检查,不是持续的 OS 目录隔离保证。首版用于可信本地工作区;同权限进程在检查后恶意置换目录对象仍可能改变实际 cwd,不提供此类对抗性沙箱。
diff --git 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
index 0205c808ff..3f40a1b59e 100644
--- 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
@@ -1489,6 +1489,16 @@ describe('AgentInputCoordinator send transaction', () => {
expect(h.coordinator.getAcceptedInputProvenance(sid)?.clientId).toBe('plugin-task:run');
});
+ it('keeps a Worker Lead directive distinct from accepted human input', async () => {
+ const h = createHarness(), sid = 'worker-input-origin';
+ h.sendToAgent.mockImplementationOnce(async () => { h.setRunning(true); return sendSuccess(); });
+ h.coordinator.enqueue(sid, { ...makeItem('directive', 'Evaluate'), origin: { kind: 'orca', senderLabel: 'Lead' } });
+ await flush();
+ expect(h.coordinator.getAcceptedInputProvenance(sid)).toMatchObject({ clientId: 'directive', originKind: 'orca' });
+ await h.coordinator.steer(sid, { ...makeItem('human', 'New direction'), autoReviewUserText: 'New direction' });
+ expect(h.coordinator.getAcceptedInputProvenance(sid)).toMatchObject({ clientId: 'human', authoredText: 'New direction', originKind: 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(); });
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
index f54af9dabd..6e624f0d21 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
@@ -1,3 +1,4 @@
+import { hasAcceptedUserTaskInput } from '../pluginTaskInput.js';
import { readFileSync } from 'node:fs';
import ts from 'typescript';
import { PluginTaskError } from '../pluginTaskService.js';
@@ -158,7 +159,7 @@ describe('OrcaLifecycleService', () => {
finally { insideSend = false; }
} }) }, ORCA_WORKER_READY_MESSAGE, AcceptedCallbackDispatchCancelled, assertDesktopSendDispatched: vi.fn(), log: { info: vi.fn() } };
const js = ts.transpileModule(`return ({${callback}}).sendWorkerReadyPlaceholder;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- deps.sendWorkerReadyPlaceholder = new Function(...Object.keys(bindings), js)(...Object.values(bindings));
+ deps.sendWorkerReadyPlaceholder = new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings), js)(hasAcceptedUserTaskInput, ...Object.values(bindings));
deps.rollbackCreatedWorker = vi.fn(async () => { expect(insideSend).toBe(false); });
const result = action.startsWith('create')
? await service.createWorker({ leadSessionId: 'lead-1', agent: 'codex', role: 'reviewer', label: 'reviewer', ...(action.endsWith('task') ? { initialTask: 'Evaluate' } : {}) })
@@ -1131,9 +1132,9 @@ describe('retained tasks after explicit plugin uninstall', () => {
add('worker-reply',400,{delivery:'turn',origin:{kind:'orca'}});
const epoch={client:{drizzle:drizzle(sqlite)}};
const bindings={getCurrentDbClientSnapshot:()=>epoch,PluginTaskError,sessions,messages,and,desc,eq,isNull,sql,
- maker:{getSession:()=>({isTurnRunning:()=>true})},inputCoordinator:{getAcceptedInputProvenance:()=>delivery==='queued'?{clientId:'worker-reply'}:null},
+ maker:{getSession:()=>({isTurnRunning:()=>true})},inputCoordinator:{getAcceptedInputProvenance:()=>delivery==='queued'?{clientId:'worker-reply',originKind:'orca'}:null},
createPluginTaskStore:()=>({get:async(id:string)=>id==='run'?{operation:'send',targetId:'lead',pluginId:'plugin',payload:'{"inputMessageId":"plugin-task:run"}'}:{operation:'create',pluginId:'plugin',payload:'{"ownershipRevoked":true}'}})};
- const override=new Function(...Object.keys(bindings),js)(...Object.values(bindings));
+ const override=new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings),js)(hasAcceptedUserTaskInput, ...Object.values(bindings));
if(history==='human-after')await expect(override('lead')).resolves.toMatchObject({permissionMode:undefined});
else await expect(override('lead')).rejects.toMatchObject({code:'PERMISSION_DENIED'});
} finally {sqlite.close();}
@@ -1147,7 +1148,7 @@ describe('retained tasks after explicit plugin uninstall', () => {
createPluginTaskStore:()=>({get:async(id:string)=>id==='run'?{operation:'send',targetId:'lead',pluginId:'plugin',payload:'{"inputMessageId":"plugin-task:run"}'}:{operation:'create',pluginId:'plugin',payload:JSON.stringify({ownershipRevoked:state==='revoked'})}}),
pluginTaskServiceForCurrentOwner:()=>({get:async()=>({status:'active',permissionMode:state==='ask'?'default':'auto',planModeEnabled:state==='plan'})}),
isPluginTaskAuthorized:()=>state!=='disabled',readGhostErrandConfig:()=>({permissionMode:'auto'})};
- const override=new Function(...Object.keys(bindings),js)(...Object.values(bindings));
+ const override=new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings),js)(hasAcceptedUserTaskInput, ...Object.values(bindings));
const ordinary=state==='revoked'&&['human','idle'].includes(input);
if(state==='healthy'||ordinary)await expect(override('lead')).resolves.toMatchObject({permissionMode:ordinary?undefined:'auto'});
else await expect(override('lead')).rejects.toThrow();
@@ -1161,7 +1162,7 @@ describe('retained tasks after explicit plugin uninstall', () => {
pluginTaskServiceForCurrentOwner: () => ({ get: async () => ({ status, permissionMode: 'auto', planModeEnabled }) }),
isPluginTaskAuthorized: () => true, readGhostErrandConfig: () => ({ permissionMode: 'auto' }),
};
- const override = new Function(...Object.keys(callbacks), js)(...Object.values(callbacks));
+ const override = new Function('hasAcceptedUserTaskInput', ...Object.keys(callbacks), js)(hasAcceptedUserTaskInput, ...Object.values(callbacks));
const { deps, service } = createDeps({ getWorkerPermissionModeOverride: override,
getActiveTeamByLead: vi.fn(async () => action === 'createWorker' ? activeTeam() : null),
});
@@ -1184,7 +1185,7 @@ describe('retained tasks after explicit plugin uninstall', () => {
pluginTaskServiceForCurrentOwner: () => ({ get }), isPluginTaskAuthorized: () => false,
readGhostErrandConfig: () => ({ permissionMode: 'auto' }),
};
- const override = new Function(...Object.keys(callbacks), js)(...Object.values(callbacks));
+ const override = new Function('hasAcceptedUserTaskInput', ...Object.keys(callbacks), js)(hasAcceptedUserTaskInput, ...Object.values(callbacks));
const { deps, service } = createDeps({
getWorkerPermissionModeOverride: override,
getWorkerPermissionMode: () => 'bypassPermissions',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index 8c8790921c..713f97bbe5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -1,3 +1,4 @@
+import { hasAcceptedUserTaskInput } from '../pluginTaskInput.js';
import { describe, expect, it, vi } from 'vitest';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
@@ -279,7 +280,7 @@ describe('OrcaTeamService', () => {
: {operation:'create',pluginId:'plugin',payload:JSON.stringify({ownershipRevoked:revoked})}}),
pluginTaskServiceForCurrentOwner:()=>({get:async()=>({status:'active',permissionMode:'auto'})}),
isPluginTaskAuthorized:()=>!revoked,readGhostErrandConfig:()=>({permissionMode:'auto'})};
- const capture = new Function(...Object.keys(bindings),ts.transpileModule(`${helper}\nreturn captureOrcaPluginAuthority;`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText)(...Object.values(bindings));
+ const capture = new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings),ts.transpileModule(`${helper}\nreturn captureOrcaPluginAuthority;`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText)(hasAcceptedUserTaskInput, ...Object.values(bindings));
const {deps,service,getWorker}=createDeps({captureControlAuthority:async id=>(await capture(id)).assertCurrent});
const list=deps.listWorkersByLead;
deps.listWorkersByLead=vi.fn(async id=>{const r=await list(id);if(phase==='lookup')revoked=true;return r;});
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 c000918d1a..aad7b722a0 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -1,3 +1,4 @@
+import { hasAcceptedUserTaskInput } from '../pluginTaskInput.js';
import path from 'node:path';
import { readFileSync } from 'node:fs';
import ts from 'typescript';
@@ -31,7 +32,7 @@ describe('Host provenance across Orca creation waits', () => {
expect(from).toBeGreaterThan(0);
expect(to).toBeGreaterThan(from);
const js = ts.transpileModule(`${helper}\nreturn ({${source.slice(from, to)}});`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- return new Function(...Object.keys(bindings), js)(...Object.values(bindings));
+ return new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings), js)(hasAcceptedUserTaskInput, ...Object.values(bindings));
}
type Action = 'createWorker' | 'enableTeam' | 'startNew' | 'startExisting';
const phases: Record<Action, string[]> = {
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 247567ef73..4bdbc3dbd2 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -1103,13 +1103,14 @@ export class AgentInputCoordinator {
/** Authority follows the active input, never pending steering or cumulative reply attribution. */
getAcceptedInputProvenance(sessionId: string): {
- clientId: string; autoResume?: boolean; retrySourceClientId?: string; authoredText?: string;
+ clientId: string; autoResume?: boolean; retrySourceClientId?: string; authoredText?: string; originKind?: 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,
+ originKind: item.origin?.kind,
retrySourceClientId: item.retrySourceClientId ?? item.supersedesUserClientId };
}
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskInput.ts b/apps/desktop/src/main/maker-ipc/pluginTaskInput.ts
new file mode 100644
index 0000000000..82bd072810
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskInput.ts
@@ -0,0 +1,46 @@
+import { and, desc, eq, isNull, sql } from 'drizzle-orm';
+import type { DbClient } from '../localDb/client/DbClient.js';
+import { messages, sessions } from '../localDb/schema.js';
+
+export interface AcceptedTaskInput {
+ clientId: string;
+ autoResume?: boolean;
+ retrySourceClientId?: string;
+ authoredText?: string;
+ originKind?: string;
+}
+
+/** Existing Host input evidence, shared by Orca control and retained-task tools. */
+export async function hasAcceptedUserTaskInput(
+ db: Pick<DbClient, 'drizzle'>,
+ sessionId: string,
+ input: AcceptedTaskInput | null,
+ isWorker = false,
+): Promise<boolean> {
+ if ((input?.retrySourceClientId ?? input?.clientId)?.startsWith('plugin-task:')) return false;
+ const authored = (text: unknown) => typeof text === 'string' && !!text.trim() && !text.startsWith('[UI_ACTION_TRIGGER]');
+ // Human retries retain this Host stamp even after supersede rewinds the
+ // original message. The stable plugin source above always takes precedence.
+ if (input && !input.originKind && (!input.autoResume || input.retrySourceClientId) && authored(input.authoredText)) return true;
+ if (input && !input.originKind && !input.autoResume && !input.retrySourceClientId) return false;
+ // A new Lead directive to a Worker supersedes any older human assignment,
+ // including the window before the native send acknowledgement is persisted.
+ if (isWorker && input?.originKind === 'orca') return false;
+ const meta = sql`CASE WHEN json_valid(${messages.agentMeta}) THEN ${messages.agentMeta} ELSE '{}' END`;
+ const [source] = await db.drizzle.select({ clientId: messages.clientId, agentMeta: messages.agentMeta }).from(messages)
+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))
+ .where(and(eq(messages.sessionId, sessionId), eq(messages.role, 'user'), isNull(messages.rewindAt),
+ input?.retrySourceClientId ? eq(messages.clientId, input.retrySourceClientId) : undefined,
+ 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 (${isWorker ? 1 : 0} = 1 OR COALESCE(json_extract(${meta}, '$.origin.kind'), '') != 'orca')))`))
+ .orderBy(desc(messages.createdAt), desc(sql`messages.rowid`)).limit(1);
+ if (!source || source.clientId.startsWith('plugin-task:')) return false;
+ let evidence: Record<string, unknown> | null;
+ try { evidence = JSON.parse(source.agentMeta ?? '{}'); } catch { return false; }
+ return !!evidence && !evidence.origin && ['turn', 'steer'].includes(String(evidence.delivery))
+ && authored(evidence.autoReviewUserText);
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 0107e2de6b..5f52e42657 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -3,6 +3,7 @@ import { resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';
import { PluginWriteAccessGate } from './pluginWriteAccessGate.js';
import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';
import { createPluginTaskStore } from './pluginTaskStore.js';
+import { hasAcceptedUserTaskInput } from './pluginTaskInput.js';
import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
import { setPluginTaskHandler, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision } from '../cindy-brain/index.js';
import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';
@@ -3599,6 +3600,12 @@ export function isSessionInTurn(sessionId: string): boolean {
return sessionTurnActivityTracker.isSessionInTurn(sessionId);
}
+/** Runtime-only attribution; queued or rejected steering cannot take ownership. */
+export function getSessionInputProvenance(sessionId: string) {
+ const input = agentInputCoordinatorHolder?.getAcceptedInputProvenance(sessionId) ?? null;
+ return { input, executing: !!input || !!getMakerIfReady()?.getSession(sessionId)?.isTurnRunning() };
+}
+
/**
* 标题素材读取需要覆盖 `status:isRunning=false` 到 terminal event 的短窗口:
* 逻辑 running 已结束,但最后一条 Assistant 还没有拿到 durable turn seal。
@@ -11969,35 +11976,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
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 inputId = input?.retrySourceClientId ?? input?.clientId;
+ if (receipt?.operation === 'create' && hasRevokedPluginTaskOwnership(receipt) && executing
+ && !await hasAcceptedUserTaskInput(epoch.client, leadSessionId, input)) {
+ throw new PluginTaskError('PERMISSION_DENIED', 'Orca input provenance unavailable');
}
const run = inputId?.startsWith('plugin-task:') ? await store.get(inputId.slice('plugin-task:'.length)) : undefined;
let inputPluginId: string | null = null;
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts
index 58f2150757..d9847d8af6 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts
@@ -21,12 +21,13 @@ const wired = ts.transpileModule(`return {${callback}}.resolveSurface;`, {
function fixture() {
const sqlite = new Database(':memory:');
- sqlite.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, source TEXT);
+ sqlite.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, source TEXT, cleared_at INTEGER DEFAULT 0);
+ CREATE TABLE messages(client_id TEXT, session_id TEXT, role TEXT, created_at INTEGER, agent_meta TEXT, rewind_at INTEGER);
CREATE TABLE bot_session_links(session_id TEXT, bot_id TEXT);
CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, operation TEXT, payload TEXT);
CREATE TABLE orca_teams(id TEXT PRIMARY KEY, lead_session_id TEXT, status TEXT);
CREATE TABLE orca_workers(session_id TEXT PRIMARY KEY, team_id TEXT);
- INSERT INTO sessions VALUES ('lead','plugin'),('worker','orca'),('legacy','plugin'),('user','user'),('bot','bot');
+ INSERT INTO sessions(id,source) VALUES ('lead','plugin'),('worker','orca'),('legacy','plugin'),('user','user'),('bot','bot');
INSERT INTO bot_session_links VALUES ('bot','b');
INSERT INTO plugin_task_requests VALUES ('lead','create','{}');
INSERT INTO orca_teams VALUES ('team','lead','completed');
@@ -34,7 +35,9 @@ function fixture() {
const db = { drizzle: drizzle(sqlite), queryOne: async (sql: string, args: unknown[]) => sqlite.prepare(sql).get(...args) } as unknown as DbClient;
let current: DbClient | undefined = db;
let pending = false;
+ let execution = { executing: false, input: null as null | { clientId: string; authoredText?: string; autoResume?: boolean; retrySourceClientId?: string; originKind?: string } };
const deps = { ...surfaces, sessions, botSessionLinks, eq, tryGetDbClient: () => current,
+ getSessionInputProvenance: () => execution,
isAppSessionBoundaryPending: () => pending };
const resolve = new Function(...Object.keys(deps), wired)(...Object.values(deps)) as
(input: { sessionId: string }) => Promise<'default' | 'bot' | 'restricted'>;
@@ -48,6 +51,7 @@ function fixture() {
const searchSessions = new Function(...Object.keys(searchDeps), searchWired)(...Object.values(searchDeps)) as
(query: string, opts: { callerSessionId: string; sessionId?: string }) => Promise<unknown[]>;
return { sqlite, db, resolve, searchSessions, searchSessionsFn, setCurrent: (next?: DbClient) => { current = next; },
+ setExecution: (next: typeof execution) => { execution = next; },
setPending: () => { pending = true; } };
}
@@ -68,6 +72,29 @@ it.each(['lead', 'worker'])('restricts owned %s and preserves explicit revocatio
} finally { f.sqlite.close(); }
});
+it.each(['lead', 'worker'].flatMap(sessionId => ['plugin', 'auto-retry', 'manual-retry', 'queued-orca', 'native', 'unknown'].map(state => ({ sessionId, state }))))(
+ 'keeps revoked $sessionId restricted during $state execution on helper and memory', async ({ sessionId, state }) => {
+ const f = fixture();
+ try {
+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);
+ const insert = f.sqlite.prepare('INSERT INTO messages VALUES (?, ?, ?, ?, ?, NULL)');
+ insert.run('older-human', sessionId, 'user', 10, JSON.stringify({ delivery: 'turn', autoReviewUserText: 'Previous user task' }));
+ insert.run('plugin-task:run', sessionId, 'user', 20, '{"delivery":"turn"}');
+ if (state === 'unknown') insert.run('unknown', sessionId, 'user', 30, '{}');
+ f.setExecution({ executing: true, input: state === 'native' ? null : state === 'plugin' ? { clientId: 'plugin-task:run' }
+ : state.includes('retry') ? { clientId: 'retry', retrySourceClientId: 'plugin-task:run', autoResume: state === 'auto-retry' }
+ : { clientId: state, originKind: state === 'queued-orca' ? 'orca' : undefined } });
+ expect(await f.resolve({ sessionId })).toBe('restricted');
+ await expect(f.searchSessions('private', { callerSessionId: sessionId })).rejects.toThrow();
+ expect(f.searchSessionsFn).not.toHaveBeenCalled();
+ f.setExecution({ executing: false, input: null });
+ expect(await f.resolve({ sessionId })).toBe('default');
+ f.setExecution({ executing: true, input: { clientId: 'new-human', authoredText: 'Continue my retained task' } });
+ expect(await f.resolve({ sessionId })).toBe('default');
+ } finally { f.sqlite.close(); }
+ },
+);
+
it.each(['lead', 'worker'])('also rejects the separate memory history search for %s', async callerSessionId => {
const f = fixture();
try {
@@ -81,6 +108,57 @@ it.each(['lead', 'worker'])('also rejects the separate memory history search for
} finally { f.sqlite.close(); }
});
+it.each(['lead', 'worker'].flatMap(sessionId => ['human', 'orca-after-human', 'unknown-after-human', 'retry-unknown', 'retry-human', 'cleared', 'rewound', 'child', 'ui-trigger'].map(history => ({ sessionId, history }))))(
+ 'uses only current accepted evidence for revoked $sessionId after $history', async ({ sessionId, history }) => {
+ const f = fixture();
+ try {
+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);
+ const add = (id: string, at: number, meta: object, rewind: number | null = null) =>
+ f.sqlite.prepare('INSERT INTO messages VALUES (?, ?, ?, ?, ?, ?)').run(id, sessionId, 'user', at, JSON.stringify(meta), rewind);
+ add('plugin-task:run', 10, { delivery: 'turn' });
+ add('human', 20, { delivery: 'turn', autoReviewUserText: history === 'ui-trigger' ? '[UI_ACTION_TRIGGER] Continue' : 'New human task',
+ ...(history === 'child' ? { parentUuid: 'child' } : {}) }, history === 'rewound' ? 25 : null);
+ if (history === 'cleared') f.sqlite.exec('UPDATE sessions SET cleared_at=25');
+ if (history === 'orca-after-human') add('orca', 30, { delivery: 'turn', origin: { kind: 'orca' } });
+ if (history === 'unknown-after-human' || history === 'retry-unknown') add('unknown', 30, { delivery: 'turn' });
+ f.setExecution({ executing: true, input: history.startsWith('retry-') ? { clientId: 'retry', retrySourceClientId: history.slice(6) } : null });
+ const allowed = ['human', 'retry-human'].includes(history) || (sessionId === 'lead' && history === 'orca-after-human');
+ expect(await f.resolve({ sessionId })).toBe(allowed ? 'default' : 'restricted');
+ if (allowed) await expect(f.searchSessions('private', { callerSessionId: sessionId })).resolves.toHaveLength(1);
+ else await expect(f.searchSessions('private', { callerSessionId: sessionId })).rejects.toThrow();
+ } finally { f.sqlite.close(); }
+ },
+);
+
+it.each(['lead', 'worker'])('rejects late history and helper results when accepted input changes for %s', async sessionId => {
+ const f = fixture();
+ try {
+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);
+ const human = { executing: true, input: { clientId: 'human', authoredText: 'My new input' } };
+ const plugin = { executing: true, input: { clientId: 'plugin-task:run' } };
+ f.setExecution(human);
+ f.searchSessionsFn.mockImplementationOnce(async () => { f.setExecution(plugin); return [{ sessionId: 'user', snippet: 'private' }]; });
+ await expect(f.searchSessions('private', { callerSessionId: sessionId })).rejects.toThrow();
+ f.setExecution(human);
+ const pending = f.resolve({ sessionId });
+ queueMicrotask(() => f.setExecution(plugin));
+ expect(await pending).toBe('restricted');
+ } finally { f.sqlite.close(); }
+});
+
+it.each(['lead', 'worker'].flatMap(sessionId => [false, true].flatMap(autoResume => ['human', 'plugin-task:run'].map(retrySourceClientId => ({ sessionId, autoResume, retrySourceClientId })))))(
+ 'preserves superseded $retrySourceClientId authority for $sessionId retry auto=$autoResume', async ({ sessionId, autoResume, retrySourceClientId }) => {
+ const f = fixture();
+ try {
+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);
+ f.sqlite.prepare('INSERT INTO messages VALUES (?, ?, ?, ?, ?, ?)').run(retrySourceClientId, sessionId, 'user', 10,
+ JSON.stringify({ delivery: 'turn', autoReviewUserText: 'Original task' }), 20);
+ f.setExecution({ executing: true, input: { clientId: 'retry', retrySourceClientId, autoResume, authoredText: 'Original task' } });
+ expect(await f.resolve({ sessionId })).toBe(retrySourceClientId === 'human' ? 'default' : 'restricted');
+ } finally { f.sqlite.close(); }
+ },
+);
+
it.each(['missing caller', 'missing DB', 'pending', 'switched after read'] as const)('fails closed: %s', async state => {
const f = fixture();
try {
@@ -97,6 +175,24 @@ it.each(['missing caller', 'missing DB', 'pending', 'switched after read'] as co
} finally { f.sqlite.close(); }
});
+it.each(['lead', 'worker'].flatMap(sessionId => ['human', 'idle'].map(next => ({ sessionId, next }))))(
+ 'does not transfer the old $sessionId tool call to $next during its first query', async ({ sessionId, next }) => {
+ const f = fixture();
+ try {
+ f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);
+ f.setExecution({ executing: true, input: { clientId: 'plugin-task:run' } });
+ const query = f.db.queryOne.bind(f.db);
+ f.db.queryOne = async <T = unknown>(sql: string, params?: unknown[]): Promise<T | undefined> => {
+ const row = await query<T>(sql, params);
+ f.setExecution(next === 'human' ? { executing: true, input: { clientId: 'human', authoredText: 'New user task' } } : { executing: false, input: null });
+ return row;
+ };
+ expect(await f.resolve({ sessionId })).toBe('restricted');
+ expect(await f.resolve({ sessionId })).toBe('default');
+ } finally { f.sqlite.close(); }
+ },
+);
+
it.each(['codex', 'claude-code', 'pi'] as const)('blocks helper discovery and guessed calls for %s, rechecking each call', async agentKind => {
const f = fixture();
const history = { resolveSessionScope: vi.fn(), listWorkdirs: vi.fn(), listSessions: vi.fn(), getMessages: vi.fn(), searchChatHistory: vi.fn() };
@@ -121,6 +217,11 @@ it.each(['codex', 'claude-code', 'pi'] as const)('blocks helper discovery and gu
}
for (const fn of [...Object.values(history), listSessionQueue, sendToSession, messageAgent]) expect(fn).not.toHaveBeenCalled();
f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{"ownershipRevoked":true}'`);
+ f.setExecution({ executing: true, input: { clientId: 'plugin-task:run' } });
+ expect(payload(await client.callTool({ name: 'list_tools', arguments: {} })).categories).toEqual([]);
+ expect(payload(await client.callTool({ name: 'call_tool', arguments: { name: 'get_chat_history', args: { session_id: 'user' } } })))
+ .toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE' });
+ f.setExecution({ executing: true, input: { clientId: 'new-human', authoredText: 'My new input' } });
expect(payload(await client.callTool({ name: 'list_tools', arguments: {} })).categories.length).toBeGreaterThan(0);
f.sqlite.exec(`UPDATE plugin_task_requests SET payload='{}'`);
expect(payload(await client.callTool({ name: 'list_tools', arguments: {} })).categories).toEqual([]);
diff --git a/apps/desktop/src/main/mcp-integrations/helperSurface.ts b/apps/desktop/src/main/mcp-integrations/helperSurface.ts
index 2ce460e218..02c79221ea 100644
--- a/apps/desktop/src/main/mcp-integrations/helperSurface.ts
+++ b/apps/desktop/src/main/mcp-integrations/helperSurface.ts
@@ -1,4 +1,5 @@
import type { DbClient } from '../localDb/client/DbClient.js';
+import { hasAcceptedUserTaskInput, type AcceptedTaskInput } from '../maker-ipc/pluginTaskInput.js';
/**
* Either legacy ownership signal is enough to keep a caller on the Bot surface.
@@ -14,11 +15,15 @@ export function classifyHelperSurface(
/** Reuse the helper's existing runtime gate; plugin tasks need Orca, not account-wide helper tools. */
export async function resolveHelperSurface(
- db: Pick<DbClient, 'queryOne'>,
+ db: Pick<DbClient, 'queryOne' | 'drizzle'>,
sessionId: string,
+ readExecution: (sessionId: string) => { executing: boolean; input: AcceptedTaskInput | null },
): Promise<'bot' | 'default' | 'restricted'> {
- const row = await db.queryOne<{ source: string; botId: string | null; pluginOwned: number }>(
- `SELECT s.source AS source, b.bot_id AS botId,
+ const execution = readExecution(sessionId);
+ const row = await db.queryOne<{ source: string; botId: string | null; pluginOwned: number; retainedPlugin: number; isWorker: number }>(
+ `SELECT s.source AS source, b.bot_id AS botId, w.session_id IS NOT NULL AS isWorker,
+ EXISTS (SELECT 1 FROM plugin_task_requests p
+ WHERE p.operation = 'create' AND p.id IN (s.id, t.lead_session_id)) AS retainedPlugin,
EXISTS (
SELECT 1 FROM plugin_task_requests p
WHERE p.operation = 'create' AND p.id IN (s.id, t.lead_session_id)
@@ -36,8 +41,16 @@ export async function resolveHelperSurface(
[sessionId],
);
// Retained Workers inherit the Lead's receipt even after the team ends.
- // Only explicit ownership revocation restores the user's ordinary surface.
+ // Revocation does not make still-executing plugin input a trusted user input.
// Bad receipts stay restricted; legacy plugin-source tasks have no receipt.
if (!row || row.pluginOwned) return 'restricted';
+ if (row.retainedPlugin) {
+ if (execution.executing && !await hasAcceptedUserTaskInput(db, sessionId, execution.input, !!row.isWorker)) return 'restricted';
+ // Do not transfer an in-flight tool call to a different accepted input.
+ const current = readExecution(sessionId);
+ if (current.executing !== execution.executing
+ || (['clientId', 'autoResume', 'retrySourceClientId', 'authoredText', 'originKind'] as const)
+ .some(key => current.input?.[key] !== execution.input?.[key])) return 'restricted';
+ }
return classifyHelperSurface(row.source, Boolean(row.botId));
}
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 072bf2f8ae..ff1a3d103e 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -52,6 +52,7 @@ import {
tryGetBotDirectMessageService,
tryGetOrcaCollabService,
isSessionInTurn,
+ getSessionInputProvenance,
} from '../maker-ipc/register.js';
import { createBotProfile } from '../localDb/ipc/bots.js';
import { submitGithubIssueForSession } from '../github-issue/index.js';
@@ -360,11 +361,15 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
if (!dbClient || isAppSessionBoundaryPending() || !opts.callerSessionId)
throw new Error('Task history caller unavailable');
// session_search bypasses cindy_helper, so share its ownership predicate.
- if (await resolveHelperSurface(dbClient, opts.callerSessionId) === 'restricted')
+ if (await resolveHelperSurface(dbClient, opts.callerSessionId, getSessionInputProvenance) === 'restricted')
throw new Error('Task history search is unavailable for plugin-managed tasks');
if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient())
throw new Error('Task history caller unavailable');
const hits = await searchSessionsFn(query, opts);
+ if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient())
+ throw new Error('Task history caller unavailable');
+ if (await resolveHelperSurface(dbClient, opts.callerSessionId, getSessionInputProvenance) === 'restricted')
+ throw new Error('Task history search is unavailable for plugin-managed tasks');
if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient())
throw new Error('Task history caller unavailable');
return hits;
@@ -528,7 +533,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
resolveSurface: async ({ sessionId }) => {
const dbClient = tryGetDbClient();
if (!dbClient || isAppSessionBoundaryPending()) return 'restricted';
- const surface = await resolveHelperSurface(dbClient, sessionId);
+ const surface = await resolveHelperSurface(dbClient, sessionId, getSessionInputProvenance);
if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) return 'restricted';
return surface;
},
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index aa6ae09d44..9d30845afe 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -14,7 +14,7 @@
- 新请求的幂等摘要忽略对象键顺序,保留数组顺序;计划及已受理配置共用相同比较。早期开发版创建回执保留原序列化输入的精确重试兼容;这类旧摘要未保存原始键序,不能承诺首次以不同键序重放成功。
- 回执独立落库,区分任务、输入执行及原生执行代次;原生终态按 instanceId + generation 结算,不以 idle 或最后一条 assistant 消息猜测完成。
- 读取限定于本插件创建的任务;返回消息 clientId。list/listRuns 按 (createdAt, id) 排序,现有回执 ID 游标在同插件与目标内解析,不再只按随机 UUID 排序。列表是分页查询,不是增量订阅;刷新应从首页重扫,不能把游标当永久同步水位(同毫秒追加、系统时钟回退或既有回执终态更新均需刷新)。
-- 插件持有 create 归属的任务及其 Orca Worker 使用既有 restricted `cindy_helper` 能力面,不提供账号级历史、待发消息或跨任务控制;发现与实际调用共用实时 Host 判据,猜工具名也不放行。另一个原始历史入口 `cindy_memory.session_search` 复用同一判据,在查询前拒绝,不伪装为空结果;读取期间账号变化也不返回结果。按创建回执和 Worker→Team→Lead 关系判断,不按 `source=plugin` 一刀切,也不因团队结束而放开。旧 errand/workspace 无回执时保持原行为;明确 `ownershipRevoked=true` 后保留的用户任务恢复普通能力面,损坏回执或查询失败保持拒绝。独立 Orca 工具不受影响。这只收住宿主 helper 与原始历史检索入口,不是通用执行或文件系统隔离。
+- 插件持有 create 归属的任务及其 Orca Worker 使用既有 restricted `cindy_helper` 能力面,不提供账号级历史、待发消息或跨任务控制;发现与实际调用共用实时 Host 判据,猜工具名也不放行。另一个原始历史入口 `cindy_memory.session_search` 复用同一判据,在查询前拒绝,不伪装为空结果;读取期间账号变化也不返回结果。按创建回执和 Worker→Team→Lead 关系判断,不按 `source=plugin` 一刀切,也不因团队结束而放开。旧 errand/workspace 无回执时保持原行为;明确 `ownershipRevoked=true` 后,调用方已无正在执行的输入或已接受新的 Host 真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限。发现、调用和 memory 检索复用 Orca 的只读来源判据,首个异步查询前固定当前来源、返回前复核;真人重试保留 Host 文本及稳定来源,插件重试不变真人。Lead 自动回报可沿当前可见输入追溯,但 Worker 的新 Lead 指令阻断对更早真人的回溯。损坏回执、未知来源或查询失败保持拒绝;这不恢复插件归属、旧 requestKey 或插件控制权,也不承诺停止已接受执行。独立 Orca 工具不受影响。这只收住宿主 helper 与原始历史检索入口,不是通用执行或文件系统隔离。
- 取消只撤回自己的排队输入或其原生重试别名;停止前在 Session 锁内再次核对执行身份与插件权限。
- 请求跨账号切换后不能继续操作新账号数据库。禁用插件后不能继续发送或停止。
- 用户通过插件页或市场卸载时,在删除插件包前持久撤销其旧任务归属;保留任务、消息、作答文件、成绩和回执。正常更新保留归属;卸载重装后旧任务和旧 requestKey 不再可用,新请求键可创建新任务。撤销写入失败则不删除包;删除包失败时已撤销的归属不回滚。此处不改变内置插件 orphan/audience 自动回收路径。