Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): stabilize task plan and runtime snapshots
Dash62f515ce0543
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.tsindex e3d6fdc1f8..7b9c2a5185 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) => {');+const start = source.indexOf(' createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute) => {');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[] = [];@@ -33,6 +33,7 @@ function fixture(workingDir?: string, afterResolve?: () => void) {});const deps = {snapshot, PluginTaskError,+ resolveRoute: async () => ({}),assertPlugin: () => { if (owner !== snapshot || !authorized) throw new PluginTaskError('PERMISSION_DENIED', 'Owner changed'); },readGhostErrandConfig: () => ({ ...cfg }),resolvePluginWorkerDirectory: resolve,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.tsindex df141e8aff..644fd981de 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from 'vitest';import { readFileSync } from 'node:fs';+import { createHash } from 'node:crypto';import ts from 'typescript';import {createPluginTaskService,@@ -220,7 +221,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);+ expect(f.deps.createSession).toHaveBeenCalledWith('p', task.taskId, 'Test', f.route, true, undefined);await f.service.create('p', input);expect(f.deps.createSession).toHaveBeenCalledTimes(1);await expect(f.service.create('p', { ...input, isolatedWorkspace: false }))@@ -451,6 +452,30 @@ it('permission elevation blocks new sends but preserves inspection of existing wawait expect(f.service.send('p',{taskId:task.taskId,expectedRevision:task.revision,requestKey:'new-send',text:'new'})).rejects.toMatchObject({code:'PERMISSION_DENIED'});});+it('replays create and frozen plans across key-order changes and a service restart', async () => {+ const f = fixture();+ const request = { requestKey: 'ordered', title: 'Test', route: f.route };+ const task = await f.service.create('p', request);+ const route = { fastMode: false, effort: 'high', model: 'model', providerId: 'mine', agentKind: 'codex' as const };+ const restarted = createPluginTaskService(f.deps);+ await expect(restarted.create('p', { ...request, route })).resolves.toEqual(task);+ expect(f.deps.createSession).toHaveBeenCalledOnce();+ const plan = { concurrency: 2, items: [{ label: 'sample', workingDir: '/answer', route: f.route }] };+ await restarted.setTeamPlan('p', task.taskId, plan);+ await expect(restarted.setTeamPlan('p', task.taskId, {+ items: [{ route, workingDir: '/answer', label: 'sample' }], concurrency: 2,+ })).resolves.toEqual({ ok: true });+ await expect(restarted.create('p', { ...request, route: { ...route, model: 'changed' } })).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });+ await expect(restarted.setTeamPlan('p', task.taskId, { ...plan, concurrency: 3 })).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });+});+it('preserves exact retries of pre-canonical development receipts', async () => {+ const f = fixture();+ const request = { requestKey: 'legacy', title: 'Test', route: f.route };+ const task = await f.service.create('p', request);+ f.rows.get(task.taskId)!.fingerprint = createHash('sha256').update(JSON.stringify([request.title, request.route])).digest('hex');+ await expect(createPluginTaskService(f.deps).create('p', request)).resolves.toEqual(task);+ await expect(f.service.create('p', { ...request, route: { ...f.route, model: 'changed' } })).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });+});it('freezes owned plan and retains settled labels',async()=>{const f=fixture(),task=await f.create();const plan={concurrency:2,items:[{label:'sample',workingDir:'/answer',route:f.route}]};await f.service.setTeamPlan('p',task.taskId,plan);await f.service.setTeamPlan('p',task.taskId,plan);await expect(f.service.setTeamPlan('other',task.taskId,plan)).rejects.toThrow('Task not found');await expect(f.service.setTeamPlan('p',task.taskId,{...plan,concurrency:3})).rejects.toThrow('immutable');await f.service.settleWorkerLabel('p',task.taskId,'sample');expect(JSON.parse(f.rows.get(task.taskId)!.payload).settledLabels).toEqual(['sample']);});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.tsnew file mode 100644index 0000000000..6dc45eda87--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts@@ -0,0 +1,149 @@+import { readFileSync } from 'node:fs';+import { mkdtemp, mkdir, realpath, rm, symlink, unlink } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { expect, it, vi } from 'vitest';+import ts from 'typescript';+import { PluginTaskError } from '../pluginTaskService.js';+import type { PluginTaskRoute } from '../../../shared/pluginTasks.js';+import { resolvePluginWorkerDirectory } from '../pluginWorkerDirectory.js';++const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');+function compile(text: string, deps: Record<string, unknown>) {+ return new Function(...Object.keys(deps), ts.transpileModule(text, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText)(...Object.values(deps));+}+function handler(kind: string, next: string, deps: Record<string, unknown>) {+ const branch = source.slice(source.indexOf(` case '${kind}':`), source.indexOf(` case '${next}':`));+ return compile(`return async function(pluginId,request){switch(request.kind){${branch}}}`, deps);+}++it('freezes the directory returned by admission without mutating the caller plan', async () => {+ const epoch = {};+ const save = vi.fn();+ const plan = { concurrency: 1, items: [{ label: 'sample', workingDir: '/root/link', route: {} }] };+ const run = handler('setTeamPlan', 'releaseWorker', {+ PluginTaskError, withSendToSessionLock: async (_: string, fn: () => unknown) => fn(),+ getCurrentDbClientSnapshot: () => epoch,+ service: { get: async () => ({ revision: 1, workingDir: '/root' }), setTeamPlan: save },+ readGhostErrandConfig: () => ({ workingDir: '/root' }), isPluginTaskAuthorized: () => true,+ isGhostPickedDir: () => false, resolvePluginWorkerDirectory: async () => '/root/original',+ });+ await run('plugin', { kind: 'setTeamPlan', taskId: 'task', plan });+ expect(save).toHaveBeenCalledWith('plugin', 'task', {+ ...plan, items: [{ ...plan.items[0], workingDir: '/root/original' }],+ });+ expect(plan.items[0].workingDir).toBe('/root/link');+});++it('retargeting a real symlink cannot change the stored plan directory', async () => {+ const root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'plugin-plan-target-')));+ try {+ const original = path.join(root, 'original'), other = path.join(root, 'other'), link = path.join(root, 'link');+ await mkdir(original); await mkdir(other); await symlink(original, link, 'junction');+ const epoch = {}, save = vi.fn();+ const plan = { concurrency: 1, items: [{ label: 'sample', workingDir: link, route: {} }] };+ const run = handler('setTeamPlan', 'releaseWorker', {+ PluginTaskError, withSendToSessionLock: async (_: string, fn: () => unknown) => fn(),+ getCurrentDbClientSnapshot: () => epoch,+ service: { get: async () => ({ revision: 1, workingDir: root }), setTeamPlan: save },+ readGhostErrandConfig: () => ({ workingDir: root }), isPluginTaskAuthorized: () => true,+ isGhostPickedDir: () => false, resolvePluginWorkerDirectory,+ });+ await run('plugin', { kind: 'setTeamPlan', taskId: 'task', plan });+ const stored = save.mock.calls[0][2].items[0].workingDir;+ await unlink(link); await symlink(other, link, 'junction');+ const resolve = (requested: string) => resolvePluginWorkerDirectory({ requested, leadDirectory: root, isPickedDirectory: () => false, assertCurrent: () => {} });+ expect(await resolve(stored)).toBe(original);+ expect(await resolve(link)).toBe(other);+ } finally { await rm(root, { recursive: true, force: true }); }+});++it.each(['provider', 'receipt', 'directory', 'creator'])('keeps default-route configuration current through %s awaits', async phase => {+ const resolveStart = source.indexOf(' const resolveRoute = async');+ const resolveSource = source.slice(resolveStart, source.indexOf(' const readExecution', resolveStart));+ const createStart = source.indexOf(' createSession: async');+ const createSource = source.slice(createStart, source.indexOf(' readSession:', createStart)).trim().replace(/,$/, '');+ for (const field of ['agentKind', 'model', 'providerId', 'effort', 'fastMode'] as const) {+ const epoch = {};+ const initial: PluginTaskRoute = { agentKind: 'codex', model: 'model', providerId: 'one', effort: 'high', fastMode: false };+ const cfg = { ...initial, workingDir: '/root', permissionMode: 'plan' };+ const change = () => {+ if (field === 'agentKind') cfg.agentKind = 'pi';+ if (field === 'model') cfg.model = 'other';+ if (field === 'providerId') cfg.providerId = 'two';+ if (field === 'effort') cfg.effort = 'low';+ if (field === 'fastMode') cfg.fastMode = true;+ };+ let lookups = 0;+ const create = vi.fn(async ({ shouldContinue }: { shouldContinue: () => boolean }) => {+ if (phase === 'creator') change();+ if (!shouldContinue()) throw new PluginTaskError('PERMISSION_DENIED', 'changed');+ });+ const api = compile(`${resolveSource}\nreturn {resolveRoute, create: ({${createSource}}).createSession};`, {+ PluginTaskError, snapshot: epoch, assertPlugin: vi.fn(),+ readGhostErrandConfig: () => ({ ...cfg }), getWorkerDefaultsFromNewMaker: () => ({}),+ getDesktopProviderService: () => ({ listProviders: async () => {+ if (++lookups === 1 && phase === 'provider') change();+ return ['one', 'two'].map(id => ({ id, connected: true }));+ } }), getActiveCatalog: () => ({}),+ findCatalogModel: () => ({ efforts: ['high', 'low'], supportsFastMode: true }),+ isModelSelectableForNewRoute: () => true,+ routeUnavailable: () => { throw Error('unavailable'); },+ resolvePluginWorkerDirectory: async () => { if (phase === 'directory') change(); return '/root'; },+ createGhostErrandSession: create, clampErrandPermissionMode: (value: string) => value,+ getCurrentDbClientSnapshot: () => epoch, isPluginTaskAuthorized: () => true,+ notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),+ });+ const route = await api.resolveRoute('plugin');+ if (phase === 'receipt') change();+ await expect(api.create('plugin', 'task', 'title', route, false)).rejects.toThrow();+ if (phase !== 'creator') expect(create).not.toHaveBeenCalled();+ }+});++it('forwards the explicit route when revalidating creation', async () => {+ const start = source.indexOf(' createSession: async');+ const property = source.slice(start, source.indexOf(' readSession:', start)).trim().replace(/,$/, '');+ const epoch = {};+ const route: PluginTaskRoute = { agentKind: 'codex', providerId: 'mine', model: 'explicit', effort: 'high', fastMode: false };+ const resolveRoute = vi.fn(async () => route);+ const create = vi.fn();+ const run = compile(`return ({${property}}).createSession;`, {+ PluginTaskError, snapshot: epoch, assertPlugin: vi.fn(),+ readGhostErrandConfig: () => ({ model: 'different-default', permissionMode: 'plan' }),+ resolveRoute, createGhostErrandSession: create, clampErrandPermissionMode: (x: string) => x,+ getCurrentDbClientSnapshot: () => epoch, isPluginTaskAuthorized: () => true,+ notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),+ });+ await run('plugin', 'task', 'title', route, true, route);+ expect(resolveRoute).toHaveBeenCalledWith('plugin', route);+ expect(create).toHaveBeenCalledOnce();+});++it.each(['pending', 'empty', 'incomplete', 'error'])('restores Lead input before reporting team state: %s', async state => {+ let restored = false;+ let pending: string[] = [];+ const query = { from: () => query, where: () => query, limit: async () => [{ totalTokenUsage: 0 }] };+ const epoch = { client: { drizzle: { select: () => query } } };+ const workspace = vi.fn(async () => ({ ok: true, workers: [] }));+ const run = handler('getTeam', 'create', {+ PluginTaskError, getCurrentDbClientSnapshot: () => epoch, service: { get: async () => ({}) },+ getOrcaWorkspaceInfoReadOnly: workspace, createOrcaDiagnosticsDeps: () => ({}),+ maker: { getSession: () => undefined }, sessions: {}, eq: vi.fn(),+ createPluginTaskStore: () => ({ get: async () => ({ payload: '{}' }) }),+ readCollaborationSettings: () => ({ workerHardLimit: 4 }),+ inputCoordinator: {+ ensureQueueRestored: async () => {+ if (state === 'error') throw Error('queue unavailable');+ restored = state !== 'incomplete'; pending = state === 'pending' ? ['old input'] : [];+ },+ isQueueRestored: () => restored,+ getQueueControlSnapshot: () => ({ pendingQueue: pending }),+ },+ });+ const result = run('plugin', { kind: 'getTeam', taskId: 'task' });+ if (state === 'incomplete' || state === 'error') await expect(result).rejects.toThrow();+ else expect((await result).leadWorking).toBe(state === 'pending');+});diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.tsindex 29b41bf0e5..64b7602ddc 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts@@ -73,7 +73,12 @@ const terminal = (run: PluginTaskRun) =>['completed', 'failed', 'cancelled', 'interrupted'].includes(run.status);const ownsInput = (run: PluginTaskRun, value: string) =>value === run.inputMessageId || run.inputClientIds?.includes(value) === true;-const hash = (data: unknown) => createHash('sha256').update(JSON.stringify(data)).digest('hex');+// Object insertion order is not part of the task API; array order still is.+const hash = (data: unknown) => createHash('sha256').update(JSON.stringify(data, (_key, value) =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? Object.fromEntries(Object.keys(value).sort().map(key => [key, value[key]]))+ : value,+)).digest('hex');export interface PluginTaskServiceDeps {store: PluginTaskStore;/** Bound to the captured account/database epoch and plugin availability. */@@ -87,6 +92,7 @@ export interface PluginTaskServiceDeps {title: string,route: PluginTaskRoute,isolatedWorkspace?: boolean,+ requestedRoute?: PluginTaskRoute,): Promise<void>;readSession(taskId: string): Promise<PluginTaskView | null>;assertTeamPlanUnstarted?(taskId: string): Promise<void>;@@ -165,8 +171,8 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {await ownTask(pluginId, row.targetId);return row;};- const replay = (row: PluginTaskReceipt | undefined, fingerprint: string) => {- if (row && row.fingerprint !== fingerprint)+ const replay = (row: PluginTaskReceipt | undefined, fingerprint: string, legacyFingerprint?: string) => {+ if (row && row.fingerprint !== fingerprint && row.fingerprint !== legacyFingerprint)fail('IDEMPOTENCY_CONFLICT', 'Request key was used with different input');return row;};@@ -232,10 +238,13 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {) =>exclusive(async () => {deps.assertAuthorized(pluginId);- const fingerprint = hash([request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : [])]);+ const input = [request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : [])];+ const fingerprint = hash(input);let row = replay(await deps.store.find(pluginId, 'create', '', request.requestKey),fingerprint,+ // Preserve exact retries of receipts written by earlier development builds.+ createHash('sha256').update(JSON.stringify(input)).digest('hex'),);if (row) {// Do not recreate a deleted/ambiguous task on replay.@@ -255,7 +264,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {);await deps.store.insert(row);deps.assertCurrent();- await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace);+ await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace, request.route);return ownTask(pluginId, taskId);}),setTeamPlan: (pluginId: string, taskId: string, plan: PluginTeamPlan) => exclusive(async () => {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex f1d7f8f242..ea9dfb79ad 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -10472,13 +10472,22 @@ 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) => {+ createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute) => {assertPlugin(pluginId);const cfg = readGhostErrandConfig(pluginId);const configurationIsCurrent = () => {const current = readGhostErrandConfig(pluginId);- return current.workingDir === cfg.workingDir && current.permissionMode === cfg.permissionMode;+ return current.workingDir === cfg.workingDir && current.permissionMode === cfg.permissionMode+ && current.agentKind === cfg.agentKind && current.model === cfg.model+ && current.providerId === cfg.providerId && current.effort === cfg.effort+ && current.fastMode === cfg.fastMode;};+ // Receipt persistence/provider lookup can yield after the first resolution.+ // Reuse the resolver with the original request, then guard this configuration+ // through directory validation and the creator's final continuation.+ const currentRoute = await resolveRoute(pluginId, requestedRoute);+ if ((Object.keys(currentRoute) as Array<keyof PluginTaskRoute>).some(key => currentRoute[key] !== route[key]))+ throw new PluginTaskError('ROUTE_UNAVAILABLE', 'Plugin task route changed');const workingDir = !isolatedWorkspace && cfg.workingDir? await resolvePluginWorkerDirectory({requested: cfg.workingDir, configuredDirectory: cfg.workingDir,@@ -10721,11 +10730,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const assertCurrent = () => {if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(pluginId) || cfg.workingDir !== readGhostErrandConfig(pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');};- for (const item of request.plan.items) await resolvePluginWorkerDirectory({requested:item.workingDir,leadDirectory:task.workingDir,configuredDirectory:cfg.workingDir,isPickedDirectory:dir=>isGhostPickedDir(pluginId,dir),assertCurrent});+ const items = [];+ for (const item of request.plan.items) {+ const workingDir = await resolvePluginWorkerDirectory({requested:item.workingDir,leadDirectory:task.workingDir,configuredDirectory:cfg.workingDir,isPickedDirectory:dir=>isGhostPickedDir(pluginId,dir),assertCurrent});+ items.push({...item, workingDir});+ }const current = await service.get(pluginId, request.taskId);assertCurrent();if (current.revision !== task.revision) throw new PluginTaskError('STALE_REVISION', 'Task changed during directory validation');- return service.setTeamPlan(pluginId, request.taskId, request.plan);+ return service.setTeamPlan(pluginId, request.taskId, {...request.plan, items});});case 'releaseWorker': {return service.completeOperation(async () => {@@ -10763,6 +10776,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const epoch = getCurrentDbClientSnapshot();if (!epoch) throw new PluginTaskError('HOST_NOT_READY', 'Task storage unavailable', true);await service.get(pluginId, request.taskId);+ await inputCoordinator.ensureQueueRestored(request.taskId);+ if (!inputCoordinator.isQueueRestored(request.taskId)) throw new PluginTaskError('HOST_NOT_READY', 'Task input queue is unavailable', true);+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');+ await service.get(pluginId, request.taskId);const team = await getOrcaWorkspaceInfoReadOnly(createOrcaDiagnosticsDeps(), request.taskId);if (!team.ok) throw new PluginTaskError('HOST_NOT_READY', 'Collaboration state unavailable', true);const workers = await Promise.all(team.workers.map(async worker => {@@ -10773,7 +10790,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}));if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');await service.get(pluginId, request.taskId);- const live = maker.getSession(request.taskId);const [leadRow] = await epoch.client.drizzle.select().from(sessions).where(eq(sessions.id,request.taskId)).limit(1);const reservations = team.workflow ? await epoch.client.drizzle.select({id:orcaWorkerCreationReservations.id}).from(orcaWorkerCreationReservations).where(and(eq(orcaWorkerCreationReservations.teamId,team.workflow.workflow_id),gte(orcaWorkerCreationReservations.expiresAt,Date.now()))) : [];const occupiedSlots=workers.length+reservations.length;@@ -10782,6 +10798,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');await service.get(pluginId,request.taskId);const hardLimit = Math.min(readCollaborationSettings().workerHardLimit, plan?.concurrency ?? Infinity);+ const live = maker.getSession(request.taskId);return {...team, capacity:{hardLimit,occupiedSlots,remainingSlots:Math.max(0,hardLimit-occupiedSlots),advisory:true}, coordinatorUsage:{scope:'session-total',tokens:leadRow?.totalTokenUsage ?? null,costUSD:leadRow?.totalCostCurrency==='USD' && leadRow.totalCostAmount>0 ? leadRow.totalCostAmount : null, approximate:leadRow?.totalCostIsApproximate ?? false}, workers, waitingForUser:!!live && live.getTurnControlSnapshot().pendingInteractionCount > 0, leadWorking:(!!live && (live.isTurnRunning() || live.getTurnControlSnapshot().pendingInteractionCount > 0)) || inputCoordinator.getQueueControlSnapshot(request.taskId).pendingQueue.length > 0};}case 'create': return service.create(pluginId, request);diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex 62894bfdad..4e991960ee 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -9,6 +9,8 @@- 创建用户可见的普通本地 Session;工作目录及权限来自用户配置,不接受插件传入绕过权限、任意目录或另一插件身份。普通任务创建前复用 Worker 的目录身份判据:配置路径必须仍为原规范路径,改链、缺失或非目录拒绝;异步解析后复核账号、tasks 批准及配置。缺省/isolatedWorkspace 仍由宿主分配目录,旧 errand 路径不变。旧别名配置没有原目标证据,不自动授权当前目标;这不解决校验后的目录置换窗口。- 发送走普通输入协调器,使用持久 requestKey 去重和稳定输入 ID;重复请求不会再次启动模型。- 指定 provider、model、effort、Fast 必须通过当前目录核验;派发前再次核验,不静默 fallback。+- 创建回执写入后、创建 Session 前,按原始请求重新解析路由并与已受理路由比较;默认模型配置变化则拒绝,不静默使用旧值。目录解析及创建器的最终 continuation 同时复核 agentKind/model/provider/effort/Fast、目录和权限。+- 新请求的幂等摘要忽略对象键顺序,保留数组顺序;计划及已受理配置共用相同比较。早期开发版创建回执保留原序列化输入的精确重试兼容;这类旧摘要未保存原始键序,不能承诺首次以不同键序重放成功。- 回执独立落库,区分任务、输入执行及原生执行代次;原生终态按 instanceId + generation 结算,不以 idle 或最后一条 assistant 消息猜测完成。- 读取限定于本插件创建的任务;返回消息 clientId。list/listRuns 按 (createdAt, id) 排序,现有回执 ID 游标在同插件与目标内解析,不再只按随机 UUID 排序。列表是分页查询,不是增量订阅;刷新应从首页重扫,不能把游标当永久同步水位(同毫秒追加、系统时钟回退或既有回执终态更新均需刷新)。- 取消只撤回自己的排队输入或其原生重试别名;停止前在 Session 锁内再次核对执行身份与插件权限。@@ -63,6 +65,8 @@ getTeam 的 completedAt 可由宿主落盘的 turnCompleted 终态恢复:仅`setTeamPlan({taskId,plan:{concurrency,items}})` 在本插件自己的创建收据中冻结计划。首次登记必须早于输入派发和 Worker 创建(包括创建预留);同一计划的幂等重放不受此限制。每项含唯一 label、workingDir 和精确 route;重复设置必须一致。未登记计划的存量插件沿用原行为。Worker 创建复用原子 reservation,预留后再次核对计划,计划上限只可收窄宿主硬上限。已结算 label 持久保留,不因归档再次变成可派发项。+计划保存目录准入返回的 canonical 路径,后续别名改链不会把冻结计划改成新目标;这不构成 OS 目录对象隔离。`getTeam` 先恢复 Lead 的持久输入队列,恢复失败或未确认时拒绝返回空闲;最终读取实时 Lead 状态,不以启动后的空内存队列报告批次完成。+`releaseWorker({taskId,workerId,completedAt})` 仅释放本插件 Lead 内、结束时间仍匹配、无活动/排队输入的 Worker。它与 getTeam 共用宿主成功终态判据,不能以 Worker 更新时间或失败轮结束时间替代交卷凭据。调用方应先保存交卷快照和评分。复用 Orca 的归档路径、transition 锁和发送锁;持锁后再次核对 completedAt 与归属。有计划时必须在归档前确认标签归属;无计划的兼容调用不写标签结算。已有发送锁时直接拒绝释放,不等待而形成锁反转;只有归档成功才结算 label。拒绝正在发送或运行的 Worker,保留任务历史与作答文件。`getTeam` 增加包含创建预留的 capacity 快照(advisory;准入仍由创建事务裁决)、逐 Worker 的等待确认状态、首条输入/首条执行消息时间、最近轮结束时间,以及 Worker/Lead 分列的 session-total 用量。`host-message-window` 是可观测作答窗口,不是精确模型计算时长。无确切 USD 金额时返回 null,不把订阅估值或其他币种直接当美元。