Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): allow retry after unstarted task creation
Dashaa02a2f781f9
diff --git a/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts b/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.tsindex 12fe90af5e..c818b7ecbe 100644--- a/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts+++ b/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts@@ -6,19 +6,20 @@ const mocks = vi.hoisted(() => {return {run, values, insert: vi.fn(() => ({ values })),bootstrap: vi.fn(async (): Promise<void> => undefined), recent: vi.fn(async () => undefined),+ workspace: vi.fn(),};});vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: { insert: mocks.insert } }) }));vi.mock('../localDb/schema', () => ({ sessions: {} }));vi.mock('../localDb/mapper', () => ({ sessionCreateToRow: (id: string, row: object) => ({ id, ...row }) }));-vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));+vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: mocks.workspace }));vi.mock('../git-snapshot/projectGitBootstrap', () => ({ ensureProjectGitInitialized: mocks.bootstrap }));vi.mock('../maker-host/git-safety-settings-store', () => ({ readGitSafetySettings: () => ({ mode: 'all-projects', autoSnapshotEnabled: true, autoInitProjectGit: true }) }));vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: mocks.recent }));vi.mock('../localDb/pluginWorkspaceDedupe', () => ({ pickSessionForWorkdir: vi.fn() }));vi.mock('../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));-import { createPluginDraftSession } from '../localDb/ipc/pluginWorkspaceSessions';+import { createGhostErrandSession, createPluginDraftSession } from '../localDb/ipc/pluginWorkspaceSessions';beforeEach(() => {vi.clearAllMocks();@@ -26,6 +27,33 @@ beforeEach(() => {mocks.run.mockResolvedValue(undefined);});+describe('plugin errand creation persistence boundary', () => {+ const params = { ghostId: 'test-plugin', sessionId: 'task', title: 'Task', permissionMode: 'plan' as const };+ it.each(['initial', 'workspace allocation', 'bootstrap', 'after bootstrap'] as const)('does not begin persistence on %s failure', async phase => {+ const onPersistenceStarted = vi.fn();+ if (phase === 'workspace allocation') mocks.workspace.mockImplementationOnce(() => { throw new Error('Workspace unavailable'); });+ if (phase === 'bootstrap') mocks.bootstrap.mockRejectedValueOnce(new Error('Workspace unavailable'));+ const shouldContinue = () => phase !== 'initial' && (phase !== 'after bootstrap' || !mocks.bootstrap.mock.calls.length);+ await expect(createGhostErrandSession({ ...params, shouldContinue, onPersistenceStarted })).rejects.toThrow();+ expect(onPersistenceStarted).not.toHaveBeenCalled();+ expect(mocks.insert).not.toHaveBeenCalled();+ });+ it.each(['success', 'insert error', 'after insert'] as const)('marks the boundary before any %s outcome', async phase => {+ const onPersistenceStarted = vi.fn();+ mocks.values.mockImplementationOnce(() => {+ expect(onPersistenceStarted).toHaveBeenCalledOnce();+ if (phase === 'insert error') throw new Error('Storage unavailable');+ return { run: mocks.run };+ });+ const shouldContinue = () => phase !== 'after insert' || !mocks.values.mock.calls.length;+ const result = createGhostErrandSession({ ...params, shouldContinue, onPersistenceStarted });+ if (phase === 'success') await expect(result).resolves.toBe('task');+ else await expect(result).rejects.toThrow();+ expect(onPersistenceStarted).toHaveBeenCalledOnce();+ expect(mocks.insert).toHaveBeenCalledOnce();+ });+});+describe('plugin draft creation commit boundary', () => {const params = { dirAbs: '/project', title: 'Project', ghostId: 'test-plugin' };diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 3c9640496e..e05e75eb93 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3913,6 +3913,7 @@ const r = await cindy.agent.requestSchedule({可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,items}})\`,每项包含\`label, workingDir, route\`。计划冻结后不可改写。计划不授予目录权限。Worker 仅可使用宿主任务目录及解析后仍在其中的子目录、插件 AI 配置目录或用户亲选的确切目录;Library 绑定不自动变成 Agent 工作根。宿主在登记和创建时均复核。+这描述准入检查,不是持续的 OS 目录隔离保证。首版用于可信本地工作区;同权限进程在检查后恶意置换目录对象仍可能改变实际 cwd,不提供此类对抗性沙箱。暂不支持选择现有任务、远程/伙伴任务、任意更新配置、归档、队列暂停或事件订阅。旧 \`agent.errand\` 接口不变。diff --git a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.tsindex b4309b1b51..c00de03aba 100644--- a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts+++ b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts@@ -170,6 +170,8 @@ export async function createGhostErrandSession(params: {ghostId: string;/** Host-allocated durable task identity; never taken directly from plugin payload. */sessionId?: string;+ /** Synchronous boundary: after this callback, a failed INSERT is not proof of absence. */+ onPersistenceStarted?: () => void;shouldContinue?: () => boolean;title: string | null;agentKind?: 'cc' | 'codex' | 'pi';@@ -221,6 +223,7 @@ export async function createGhostErrandSession(params: {source: 'plugin-errand-session',});if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');+ params.onPersistenceStarted?.();await db.insert(sessions).values(insertRow);if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');if (projectDir && insertRow.workingDir) {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.tsindex 7b9c2a5185..69e95ed81c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts@@ -8,7 +8,7 @@ import { resolvePluginWorkerDirectory } from '../pluginWorkerDirectory.js';import { PluginTaskError } from '../pluginTaskService.js';const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');-const start = source.indexOf(' createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute) => {');+const start = source.indexOf(' createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted) => {');const branch = source.slice(start, source.indexOf(' readSession:', start)).trim().replace(/,$/, '');const js = ts.transpileModule(`return ({ ${branch} }).createSession;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;const roots: string[] = [];@@ -25,7 +25,8 @@ function fixture(workingDir?: string, afterResolve?: () => void) {let owner = snapshot;let authorized = true;const cfg = { workingDir, permissionMode: 'plan' };- const create = vi.fn(async (_args: { shouldContinue: () => boolean }) => 'task');+ const create = vi.fn(async (_args: { shouldContinue: () => boolean; onPersistenceStarted: () => void }) => 'task');+ const onPersistenceStarted = vi.fn();const resolve = vi.fn(async (input: Parameters<typeof resolvePluginWorkerDirectory>[0]) => {const result = await resolvePluginWorkerDirectory(input);afterResolve?.();@@ -44,7 +45,7 @@ function fixture(workingDir?: string, afterResolve?: () => void) {notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),};const run = new Function(...Object.keys(deps), js)(...Object.values(deps));- return { cfg, create, resolve, switchOwner: () => { owner = {}; }, revoke: () => { authorized = false; }, run: (isolated = false) => run('plugin', 'task', 'title', {}, isolated) };+ return { cfg, create, resolve, onPersistenceStarted, switchOwner: () => { owner = {}; }, revoke: () => { authorized = false; }, run: (isolated = false) => run('plugin', 'task', 'title', {}, isolated, undefined, onPersistenceStarted) };}describe('ordinary plugin task configured-directory admission', () => {it('creates in the unchanged real directory', async () => {@@ -52,6 +53,8 @@ describe('ordinary plugin task configured-directory admission', () => {const f = fixture(selected);await f.run();expect(f.create).toHaveBeenCalledWith(expect.objectContaining({ workingDir: selected }));+ expect(f.create.mock.calls[0][0].onPersistenceStarted).toBe(f.onPersistenceStarted);+ expect(f.onPersistenceStarted).not.toHaveBeenCalled();});it('rejects a saved root replaced by a link before any creator side effects', async () => {const { root, selected } = await directory();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.tsindex 8b08899b4e..f011a55820 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts@@ -52,6 +52,11 @@ function fixture() {expect(rows.has(r.id)).toBe(false);rows.set(r.id, copy(r));},+ discardUncreated: vi.fn(async r => {+ const current = rows.get(r.id);+ if (current && current.pluginId === r.pluginId && current.operation === 'create'+ && current.revision === r.revision && !tasks.has(r.id)) rows.delete(r.id);+ }),save: async (r) => {expect(rows.get(r.id)?.revision).toBe(r.revision);rows.set(r.id, copy({ ...r, revision: r.revision + 1 }));@@ -77,7 +82,8 @@ function fixture() {id: () => `id-${++seq}`,now: () => 1,resolveRoute: vi.fn(async (_, r) => r ?? route),- createSession: vi.fn(async (_, taskId, title, resolvedConfig) => {+ createSession: vi.fn(async (_, taskId, title, resolvedConfig, _isolated, _requested, onPersistenceStarted) => {+ onPersistenceStarted();tasks.set(taskId, { taskId, title, resolvedConfig, revision: 1, status: 'active', permissionMode: 'plan' });}),readSession: async (id) => copy(tasks.get(id) ?? null),@@ -156,6 +162,75 @@ it.each(['restore','restart'] as const)('the production cancel adapter rechecks});describe('plugin ordinary task receipts', () => {+ it.each(['same service', 'restart', 'concurrent'] as const)('retries a conclusively uncreated task with the original key after %s', async mode => {+ const f = fixture();+ const create = vi.mocked(f.deps.createSession);+ create.mockRejectedValueOnce(new Error('Directory unavailable'));+ await expect(f.create()).rejects.toThrow('Directory unavailable');+ const service = mode === 'restart' ? createPluginTaskService(f.deps) : f.service;+ const request = { requestKey: 'create', title: 'Test' };+ const calls = mode === 'concurrent' ? 2 : 1;+ const tasks = await Promise.all(Array.from({ length: calls }, () => service.create('p', request)));+ expect(new Set(tasks.map(task => task.taskId)).size).toBe(1);+ expect(create).toHaveBeenCalledTimes(2);+ expect(f.tasks.size).toBe(1);+ expect(f.rows.size).toBe(1);+ await expect(service.create('p', { ...request, title: 'Changed' })).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });+ });+ it.each(['insert error', 'persisted', 'deleted after insert'] as const)('retains the request key after persistence started: %s', async phase => {+ const f = fixture();+ const create = f.deps.createSession;+ f.deps.createSession = vi.fn(async (...args: Parameters<PluginTaskServiceDeps['createSession']>) => {+ args[6]();+ if (phase !== 'insert error') await create(...args);+ if (phase === 'deleted after insert') f.tasks.delete(args[1]);+ throw new Error('Creation response failed');+ });+ await expect(f.create()).rejects.toThrow('Creation response failed');+ expect(f.rows.size).toBe(1);+ expect(f.deps.store.discardUncreated).not.toHaveBeenCalled();+ if (phase === 'persisted') await expect(f.create()).resolves.toMatchObject({ taskId: 'id-1' });+ else await expect(f.create()).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });+ expect(f.deps.createSession).toHaveBeenCalledOnce();+ });+ it('retains the receipt when rollback fails and does not silently retry creation', async () => {+ const f = fixture();+ vi.mocked(f.deps.createSession).mockRejectedValueOnce(new Error('Directory unavailable'));+ vi.mocked(f.deps.store.discardUncreated).mockRejectedValueOnce(new Error('Storage unavailable'));+ await expect(f.create()).rejects.toThrow('Storage unavailable');+ await expect(f.create()).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });+ expect(f.rows.size).toBe(1);+ expect(f.deps.createSession).toHaveBeenCalledOnce();+ });+ it('rolls back an unstarted creation through its captured store after an account switch', async () => {+ const f = fixture();+ const insert = f.deps.store.insert;+ f.deps.store.insert = async row => { await insert(row); f.switchOwner(); };+ await expect(f.create()).rejects.toThrow('Owner changed');+ expect(f.rows.size).toBe(0);+ expect(f.deps.createSession).not.toHaveBeenCalled();+ });+ it('never releases an already revoked creation key on a preparation failure', async () => {+ const f = fixture();+ vi.mocked(f.deps.createSession).mockImplementationOnce(async () => {+ await f.deps.store.revokePlugin('p');+ throw new Error('Plugin unavailable');+ });+ await expect(f.create()).rejects.toThrow('Plugin unavailable');+ expect(f.rows.size).toBe(1);+ await expect(createPluginTaskService(f.deps).create('p', { requestKey: 'create', title: 'Test' }))+ .rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });+ expect(f.deps.createSession).toHaveBeenCalledOnce();+ });+ it('does not recreate a deleted task or an old ambiguous orphan receipt', async () => {+ const f = fixture();+ const task = await f.create();+ f.tasks.delete(task.taskId);+ await expect(createPluginTaskService(f.deps).create('p', { requestKey: 'create', title: 'Test' }))+ .rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });+ expect(f.deps.store.discardUncreated).not.toHaveBeenCalled();+ expect(f.deps.createSession).toHaveBeenCalledOnce();+ });it('retains user tasks and receipts but denies every old task capability after reinstall and restart', async () => {const f = fixture(); const task = await f.create(); const run = await f.send();const before = structuredClone([...f.tasks]);@@ -221,7 +296,7 @@ describe('plugin ordinary task receipts', () => {const f = fixture();const input = { requestKey: 'isolated', title: 'Test', isolatedWorkspace: true };const task = await f.service.create('p', input);- expect(f.deps.createSession).toHaveBeenCalledWith('p', task.taskId, 'Test', f.route, true, undefined);+ expect(f.deps.createSession).toHaveBeenCalledWith('p', task.taskId, 'Test', f.route, true, undefined, expect.any(Function));await f.service.create('p', input);expect(f.deps.createSession).toHaveBeenCalledTimes(1);await expect(f.service.create('p', { ...input, isolatedWorkspace: false }))diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.tsindex e18ebdf653..5f1ee17693 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts@@ -4,6 +4,29 @@ import { expect, it } from 'vitest';import type { DbClient } from '../../localDb/client/DbClient.js';import { createPluginTaskStore } from '../pluginTaskStore.js';+it.each(['absent', 'raw session', 'revoked', 'changed revision', 'other plugin', 'send'] as const)(+ 'rolls back only its uncreated receipt in SQLite: %s', async state => {+ const sqlite = new Database(':memory:');+ try {+ sqlite.exec(`CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, plugin_id TEXT,+ operation TEXT, target_id TEXT, request_key TEXT, fingerprint TEXT, payload TEXT,+ revision INTEGER, created_at INTEGER); CREATE TABLE sessions(id TEXT PRIMARY KEY)`);+ const store = createPluginTaskStore({ drizzle: drizzle(sqlite) } as unknown as DbClient);+ const row = { id: 'task', pluginId: 'p', operation: 'create' as const, targetId: '',+ requestKey: 'key', fingerprint: 'hash', payload: '{}', revision: 0, createdAt: 1 };+ await store.insert(row);+ if (state === 'raw session') sqlite.prepare('INSERT INTO sessions VALUES (?)').run(row.id);+ if (state === 'revoked') await store.revokePlugin('p');+ if (state === 'changed revision') await store.save(row);+ if (state === 'other plugin') sqlite.exec("UPDATE plugin_task_requests SET plugin_id='other'");+ if (state === 'send') sqlite.exec("UPDATE plugin_task_requests SET operation='send'");+ await store.discardUncreated(row);+ expect(await store.get(row.id)).toEqual(state === 'absent' ? undefined : expect.any(Object));+ expect(sqlite.prepare('SELECT COUNT(*) AS n FROM sessions').get()).toEqual({ n: state === 'raw session' ? 1 : 0 });+ } finally { sqlite.close(); }+ },+);+it('durably revokes only create ownership while retaining plans, run results and request identities', async () => {const sqlite=new Database(':memory:');try {diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.tsindex c092afb5c3..8d19ec6204 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts@@ -43,6 +43,8 @@ export interface PluginTaskStore {): Promise<PluginTaskReceipt[]>;forSession(taskId: string): Promise<PluginTaskReceipt[]>;insert(row: PluginTaskReceipt): Promise<void>;+ /** Roll back only this new receipt, before any Session INSERT was attempted. */+ discardUncreated(row: PluginTaskReceipt): Promise<void>;save(row: PluginTaskReceipt): Promise<void>;revokePlugin(pluginId: string): Promise<void>;}@@ -91,8 +93,9 @@ export interface PluginTaskServiceDeps {taskId: string,title: string,route: PluginTaskRoute,- isolatedWorkspace?: boolean,- requestedRoute?: PluginTaskRoute,+ isolatedWorkspace: boolean | undefined,+ requestedRoute: PluginTaskRoute | undefined,+ onPersistenceStarted: () => void,): Promise<void>;readSession(taskId: string): Promise<PluginTaskView | null>;assertTeamPlanUnstarted?(taskId: string): Promise<void>;@@ -263,8 +266,17 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {taskId,);await deps.store.insert(row);- deps.assertCurrent();- await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace, request.route);+ let persistenceStarted = false;+ try {+ deps.assertCurrent();+ await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace, request.route,+ () => { persistenceStarted = true; });+ } catch (error) {+ // Once INSERT starts, even an error is ambiguous. Never free that key+ // or infer failure from a subsequently deleted/filtered Session.+ if (!persistenceStarted) await deps.store.discardUncreated(row);+ throw error;+ }return ownTask(pluginId, taskId);}),setTeamPlan: (pluginId: string, taskId: string, plan: PluginTeamPlan) => exclusive(async () => {diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts b/apps/desktop/src/main/maker-ipc/pluginTaskStore.tsindex f2320d8475..c5baf42a94 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts@@ -1,6 +1,6 @@import { and, asc, eq, gt, or, sql } from 'drizzle-orm';import type { DbClient } from '../localDb/client/DbClient.js';-import { pluginTaskRequests } from '../localDb/schema.js';+import { pluginTaskRequests, sessions } from '../localDb/schema.js';import type { PluginTaskStore } from './pluginTaskService.js';import { PluginTaskError } from './pluginTaskService.js';@@ -56,6 +56,15 @@ export function createPluginTaskStore(db: DbClient): PluginTaskStore {insert: async (row) => {await db.drizzle.insert(table).values(row);},+ discardUncreated: async (row) => {+ // The caller proves INSERT never started; retain any changed/revoked+ // receipt or raw Session row, even one hidden by the task view.+ await db.drizzle.delete(table).where(and(+ eq(table.id, row.id), eq(table.pluginId, row.pluginId),+ eq(table.operation, 'create'), eq(table.revision, row.revision),+ sql`NOT EXISTS (SELECT 1 FROM ${sessions} WHERE ${sessions.id} = ${row.id})`,+ ));+ },revokePlugin: async (pluginId) => {// Keep the identity/request key so reinstall cannot replay or recreate old tasks.await db.drizzle.update(table).set({diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 393c34c664..666cad3871 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -10499,7 +10499,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertCurrent();if (workers.length || reservations.length) throw new PluginTaskError('TASK_BUSY', 'Register the team plan before creating Workers');},- createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute) => {+ createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted) => {assertPlugin(pluginId);const cfg = readGhostErrandConfig(pluginId);const configurationIsCurrent = () => {@@ -10529,6 +10529,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (!configurationIsCurrent()) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin task configuration changed');await createGhostErrandSession({ghostId: pluginId, sessionId: taskId, title, ...route,+ onPersistenceStarted,permissionMode: clampErrandPermissionMode(cfg.permissionMode),...(workingDir ? { workingDir } : {}),shouldContinue: () => getCurrentDbClientSnapshot() === snapshot && isPluginTaskAuthorized(pluginId) && configurationIsCurrent(),diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex 1aacd6a630..3768d2152e 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -10,6 +10,7 @@- 发送走普通输入协调器,使用持久 requestKey 去重和稳定输入 ID;重复请求不会再次启动模型。- 指定 provider、model、effort、Fast 必须通过当前目录核验;派发前再次核验,不静默 fallback。- 创建回执写入后、创建 Session 前,按原始请求重新解析路由并与已受理路由比较;默认模型配置变化则拒绝,不静默使用旧值。目录解析及创建器的最终 continuation 同时复核 agentKind/model/provider/effort/Fast、目录和权限。+- 本次创建在 Session INSERT 开始前明确失败(如配置、目录或工作区准备失败)时,沿现有回执队列撤回仍为原版本、且原始 Session 行不存在的新回执;修正原因后可用原 requestKey 显式重试,不自动重派。回执存储固定原账号数据库,撤销或版本变化的回执不删除。- 新请求的幂等摘要忽略对象键顺序,保留数组顺序;计划及已受理配置共用相同比较。早期开发版创建回执保留原序列化输入的精确重试兼容;这类旧摘要未保存原始键序,不能承诺首次以不同键序重放成功。- 回执独立落库,区分任务、输入执行及原生执行代次;原生终态按 instanceId + generation 结算,不以 idle 或最后一条 assistant 消息猜测完成。- 读取限定于本插件创建的任务;返回消息 clientId。list/listRuns 按 (createdAt, id) 排序,现有回执 ID 游标在同插件与目标内解析,不再只按随机 UUID 排序。列表是分页查询,不是增量订阅;刷新应从首页重扫,不能把游标当永久同步水位(同毫秒追加、系统时钟回退或既有回执终态更新均需刷新)。@@ -28,7 +29,7 @@- 仅本插件创建的本地普通任务;不支持选择既有任务、远端任务或 Bot;自有普通任务可通过 startTeam 成为 Orca Lead。- 尚未开放修改/归档任务、队列暂停、事件订阅、逐输入费用与用量。usage 明确返回 unavailable。- 回执已经持久化,但完整的重启后终态补账、无输入别名的自动续跑归属尚未闭环。缺少原生证据时返回 reconciling,不重放请求、不报告成功;目前不应作为无人值守正式评测的完成依据。-- 创建回执落库后若 Session 创建中断,重放不会再建一个任务,可能返回 TASK_NOT_FOUND;尚无自动修复入口。+- 一旦 Session INSERT 已开始、创建进程中断或回执撤回失败,结果仍可能不明:保留回执,重放只读取已存在任务,不补建,可能返回 TASK_NOT_FOUND。旧孤立回执没有本次失败证据,不自动修复;已删除任务不复活、已撤销任务及旧 key 不接管。此限制与创建前明确失败后的显式重试不同。- 无推理档位的模型暂不支持;不支持的 route 明确拒绝。- cancel 的 requestKey 当前不建立独立账本;同一 run 的终态保持幂等,进行中的重复取消仍可能再次请求原生停止。- 评测插件已接入此接口;实际 UI 联调结果另记,未自动启动付费模型。@@ -65,7 +66,7 @@ getTeam 的 completedAt 可由宿主落盘的 turnCompleted 终态恢复:仅`setTeamPlan({taskId,plan:{concurrency,items}})` 在本插件自己的创建收据中冻结计划。首次登记必须早于输入派发和 Worker 创建(包括创建预留);同一计划的幂等重放不受此限制。每项含唯一 label、workingDir 和精确 route;重复设置必须一致。未登记计划的存量插件沿用原行为。Worker 创建复用原子 reservation,预留后再次核对计划,计划上限只可收窄宿主硬上限。已结算 label 持久保留,不因归档再次变成可派发项。-计划保存目录准入返回的 canonical 路径,后续别名改链不会把冻结计划改成新目标;这不构成 OS 目录对象隔离。`getTeam` 先恢复 Lead 的持久输入队列,恢复失败或未确认时拒绝返回空闲;最终读取实时 Lead 状态,不以启动后的空内存队列报告批次完成。+计划保存目录准入返回的 canonical 路径,后续别名改链不会把冻结计划改成新目标;这不构成 OS 目录对象隔离。首版仅用于可信本地工作区,不防御同权限进程在最后校验后、harness 使用 cwd 前恶意替换目录对象;路径复核或 JS 锁不能消除该窗口,不把另建 OS 隔离后端列为本接口的发布前提。插件归属、显式撤权、用户降权与任务范围的检查仍须成立。`getTeam` 先恢复 Lead 的持久输入队列,恢复失败或未确认时拒绝返回空闲;最终读取实时 Lead 状态,不以启动后的空内存队列报告批次完成。`releaseWorker({taskId,workerId,completedAt})` 仅释放本插件 Lead 内、结束时间仍匹配、无活动/排队输入的 Worker。它与 getTeam 共用宿主成功终态判据,不能以 Worker 更新时间或失败轮结束时间替代交卷凭据。调用方应先保存交卷快照和评分。复用 Orca 的归档路径、transition 锁和发送锁;持锁后再次核对 completedAt 与归属。有计划时必须在归档前确认标签归属;无计划的兼容调用不写标签结算。已有发送锁时直接拒绝释放,不等待而形成锁反转;只有归档成功才结算 label。拒绝正在发送或运行的 Worker,保留任务历史与作答文件。