Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: preserve revocations across synthetic history and bound task plans
Dash2e75d83fd61b
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.tsindex 923b057ad9..3477219f69 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts@@ -1,8 +1,19 @@import { describe, expect, it, vi } from 'vitest';+import { isPluginTeamPlanWithinBudget, PLUGIN_TEAM_PLAN_MAX_JSON_CHARS } from '../../../shared/pluginTasks.js';import { handlePluginTaskRequest, validPluginTaskRequest } from '../taskSlot.js';import type { InstalledGhost } from '../../../shared/ghost.js';describe('plugin task pipe', () => {+ it('bounds the complete JSON plan without truncating scope or breaking representative 200-item batches', () => {+ const item = {label:'sample',workingDir:'/answer',route:{agentKind:'pi',providerId:'p',model:'m',effort:'high',fastMode:false},task:'测'.repeat(2600)};+ const plan = {concurrency:4,task:'c'.repeat(8000),items:Array.from({length:200},(_,i)=>({...item,label:'w'+i}))};+ expect(validPluginTaskRequest({type:'tasks-request',kind:'setTeamPlan',taskId:'lead',plan})).toBe(true);+ expect(validPluginTaskRequest({type:'tasks-request',kind:'setTeamPlan',taskId:'lead',plan:{...plan,items:plan.items.map(x=>({...x,task:'x'.repeat(8000)}))}})).toBe(false);+ const room = PLUGIN_TEAM_PLAN_MAX_JSON_CHARS - JSON.stringify({task:''}).length;+ expect(isPluginTeamPlanWithinBudget({task:'x'.repeat(room)})).toBe(true);+ expect(isPluginTeamPlanWithinBudget({task:'x'.repeat(room+1)})).toBe(false);+ expect(isPluginTeamPlanWithinBudget({task:'\n'.repeat(room)})).toBe(false);+ });const ghost = { enabled: true, taskCapabilityApproved: true, approval: {state:'approved', revision:'r'}, manifest: { agent: { tasks: true } } } as InstalledGhost;it('requires its own declared capability; errand alone grants nothing', async () => {const handler = vi.fn();diff --git a/apps/desktop/src/main/cindy-brain/taskSlot.ts b/apps/desktop/src/main/cindy-brain/taskSlot.tsindex 5364b852eb..1257036bb6 100644--- a/apps/desktop/src/main/cindy-brain/taskSlot.ts+++ b/apps/desktop/src/main/cindy-brain/taskSlot.ts@@ -1,5 +1,6 @@import type { InstalledGhost } from '../../shared/ghost.js';import type { PluginTaskRequest, PluginTaskResult } from '../../shared/pluginTasks.js';+import { isPluginTeamPlanWithinBudget } from '../../shared/pluginTasks.js';import { hasPluginTaskApproval } from './taskCapability.js';export const PLUGIN_TASK_OPERATIONS = [@@ -69,6 +70,7 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskRequeif (kind === 'releaseWorker' && (!requires('workerId') || !Number.isSafeInteger(value.completedAt) || (value.completedAt as number) <= 0)) return false;if (kind === 'setTeamPlan') {const p = value.plan;+ if (!isPluginTeamPlanWithinBudget(p)) return false;if (!object(p) || Object.keys(p).some(k => !['concurrency','items','task'].includes(k)) ||(p.concurrency !== null && (!Number.isSafeInteger(p.concurrency) || (p.concurrency as number) < 1)) ||!Array.isArray(p.items) || !p.items.length || p.items.length > 1000) return false;diff --git a/apps/desktop/src/main/localDb/__tests__/autoReviewProjection.test.ts b/apps/desktop/src/main/localDb/__tests__/autoReviewProjection.test.tsindex 1475f855eb..11d75ff106 100644--- a/apps/desktop/src/main/localDb/__tests__/autoReviewProjection.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/autoReviewProjection.test.ts@@ -68,6 +68,35 @@ function stored(db: Database.Database) {}describe('durable Auto authority projection', () => {+ it.each([+ { autoResume: true, autoReviewUserText: 'allow' },+ { contextRebuild: { reason: 'recovery' }, autoReviewUserText: 'allow' },+ { autoReviewUserText: '[UI_ACTION_TRIGGER] allow' },+ { autoReviewUserText: { kind: 'delegated-continuation' } },+ { autoReviewUserText: { kind: 'scheduled-continuation' } },+ ])('ignores synthetic recovery through incremental writes, restart and v1 upgrade: %j', (meta) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-authority-restart-'));+ directories.push(dir);+ const filename = path.join(dir, 'test.sqlite');+ const db = open(filename);+ add(db, 'grant', 'worker', 1, 'allow');+ add(db, 'revoke', 'worker', 2, 'never publish');+ const before = read(db);+ add(db, 'resume', 'worker', 3, 'allow', 'user', { delivery: 'turn', ...meta });+ expect(read(db)).toMatchObject({ sessionIntent: before.sessionIntent, reviewIntent: before.reviewIntent });+ // A previously valid old projection may contain exactly the stale grant+ // this upgrade fixes. Force a v1 receipt without invalidating its revision.+ const old = JSON.parse(stored(db).payload);+ db.prepare('UPDATE auto_review_projections SET version=1, payload=?').run(JSON.stringify({+ ...old, sessionIntent: '', reviewIntent: 'allow',+ }));+ const restarted = open(filename, false);+ expect(read(restarted)).toMatchObject({ sessionIntent: before.sessionIntent, reviewIntent: before.reviewIntent });+ expect(restarted.prepare('SELECT version FROM auto_review_projections').get()).toEqual({ version: 2 });+ add(restarted, 'reset', 'worker', 4, '');+ add(restarted, 'resume-again', 'worker', 5, 'allow', 'user', { delivery: 'steer', ...meta });+ expect(read(restarted)).toMatchObject({ sessionIntent: '', reviewIntent: '' });+ });it('rejects a stale projection when durable invalidation is missing', () => {const db = open();add(db, 'grant', 'worker', 1, 'allow');diff --git a/apps/desktop/src/main/localDb/autoReviewProjection.ts b/apps/desktop/src/main/localDb/autoReviewProjection.tsindex bc38f69735..9b3db0e655 100644--- a/apps/desktop/src/main/localDb/autoReviewProjection.ts+++ b/apps/desktop/src/main/localDb/autoReviewProjection.ts@@ -58,7 +58,7 @@ export function readAutoReviewProjection(} catch {row.agentMeta = null;}- if (row.agentMeta?.contextRebuild && typeof row.agentMeta.contextRebuild === 'object')+ if (projector.isSynthetic(row))return JSON.stringify(state);const reset = projector.readText(row.content) === null;if (row.sessionId === target && !state.sessionAmbiguous) {@@ -89,14 +89,7 @@ export function readAutoReviewProjection(meta && typeof meta === 'object' && !Array.isArray(meta)? (meta as Record<string, unknown>): null;- const receipt = row.agentMeta?.autoReviewUserText as { kind?: unknown } | null;- if (row.agentMeta?.contextRebuild && typeof row.agentMeta.contextRebuild === 'object')- return [];- if (- row.role === 'user' &&- (receipt?.kind === 'scheduled-continuation' || receipt?.kind === 'delegated-continuation')- )- return [];+ if (projector.isSynthetic(row)) return [];return [row];});const own = history.filter((row) => row.sessionId === target);@@ -126,7 +119,7 @@ export function readAutoReviewProjection(CREATE TEMP TRIGGER auto_review_project AFTER UPDATE OF revision ON main.auto_review_projectionsWHEN (SELECT depth FROM auto_review_projection_batch) = 0BEGIN- UPDATE auto_review_projections SET payload = cindy_authority_projection_v1(CASE WHEN OLD.projected_revision = OLD.revision AND OLD.version = 1+ UPDATE auto_review_projections SET payload = cindy_authority_projection_v1(CASE WHEN OLD.projected_revision = OLD.revision AND OLD.version = 2AND json_extract(NEW.payload, '$.appendEvent.role') = 'user'AND json_extract(NEW.payload, '$.appendEvent.visible') = 1AND json_extract(NEW.payload, '$.appendEvent.createdAt') > json_extract(OLD.payload, '$.lastEventAt')@@ -143,7 +136,7 @@ export function readAutoReviewProjection(THEN json_extract(m.agent_meta,'$.autoReviewUserText.acceptedAt') ELSE m.created_at ENDELSE m.created_at END,CASE WHEN m.session_id = NEW.lead_id THEN 0 ELSE 1 END, m.rowid)- ) END, NEW.session_id, OLD.payload, json_extract(NEW.payload, '$.appendEvent')), projected_revision = NEW.revision, version = 1+ ) END, NEW.session_id, OLD.payload, json_extract(NEW.payload, '$.appendEvent')), projected_revision = NEW.revision, version = 2WHERE session_id = NEW.session_id AND lead_id = NEW.lead_id;END`);}@@ -163,13 +156,13 @@ export function readAutoReviewProjection(let row = select.get(sessionId, leadId) as Row;// First use after upgrade or a legacy writer rebuilds from current evidence// inside this transaction. Never fall back to the previous payload.- if (row.version !== 1 || row.projected_revision !== row.revision || row.payload === null) {+ if (row.version !== 2 || row.projected_revision !== row.revision || row.payload === null) {db.prepare("UPDATE auto_review_projections SET revision = revision + 1, payload = json_remove(payload, '$.appendEvent') WHERE session_id = ? AND lead_id = ?",).run(sessionId, leadId);row = select.get(sessionId, leadId) as Row;}- if (row.version !== 1 || row.projected_revision !== row.revision || !row.payload)+ if (row.version !== 2 || row.projected_revision !== row.revision || !row.payload)throw new Error('Authorization projection is not synchronized');const value = JSON.parse(row.payload) as StoredAutoReviewProjection & {reviewUnverified: boolean;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/autoReviewUserIntent.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/autoReviewUserIntent.test.tsindex 69a125af76..862e286067 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/autoReviewUserIntent.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/autoReviewUserIntent.test.ts@@ -24,6 +24,18 @@ function user(text: string, clientId = text): AutoReviewHistoryMessage {const current = { clientId: 'latest', content: { text: '修吧,改完跑相关测试。' } };describe('steer authorization restoration', () => {+ it.each([+ { autoResume: true, autoReviewUserText: 'Send now.' },+ { contextRebuild: {}, autoReviewUserText: 'Send now.' },+ { autoReviewUserText: '[UI_ACTION_TRIGGER] Send now.' },+ ])('preserves human revocations across synthetic recovery: %j', (meta) => {+ const history = [user('Send now.'), user('Do not send.'), {+ ...user('Send now.', 'recovery'), agentMeta: { delivery: 'turn', ...meta },+ }];+ expect(restoreAutoReviewUserIntent(history)).toEqual({+ earlierUserMessages: ['Send now.'], currentUserMessage: 'Do not send.',+ });+ });it.each([false, true])('restores delegated history without treating it as human input (unavailable=%s)', async unavailable => {const pending = restoreAutoReviewSteerIntent('Deploy now', {[AUTO_REVIEW_SOURCE_CONTENT]: '', [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,@@ -197,7 +209,6 @@ describe('restored Auto authorization', () => {it.each([null,{ origin: { kind: 'im' } },- { delivery: 'turn', autoResume: true, autoReviewUserText: 'Delete production.' },{ delivery: 'turn', agentFacingWireContent: { type: 'user', content: 'different text' } },])('does not promote unidentified, IM or synthetic messages into owner authorization: %j',diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.tsindex 909ad112e5..e6577c027b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskReviewContext.test.ts@@ -59,6 +59,14 @@ function fixture(): PluginReviewSnapshot {};}describe('plugin delegated Auto context', () => {+ it.each([false,true])('rejects oversized stored plans without legacy fallback (worker=%s)', async worker => {+ const s=fixture();+ if (!worker) delete s.worker;+ s.plan!.items=Array.from({length:200},(_,i)=>({...s.plan!.items[0]!,label:'w'+i,task:'x'.repeat(8000)}));+ const result=await createPluginTaskReviewResolver(async()=>s)(request);+ expect(result.authorizationError).toContain('size');+ expect(result.delegatedTask).toBeUndefined();+ });it('uses persisted bounded evidence, rejects live drift and keys cached decisions by revision', async () => {const s = fixture();s.projection = { revision: 7, sessionIntent: 'Worker restriction', reviewIntent: 'Lead and Worker restrictions' };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.tsindex 7e0408ed10..43723893f3 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts@@ -6,11 +6,25 @@ import {isPluginTaskPermissionAllowed,PluginTaskError,assertPluginTaskResult,+ readPluginTaskPlanReceipt,type PluginTaskReceipt,type PluginTaskStore,type PluginTaskServiceDeps,} from '../pluginTaskService.js';import type { PluginTaskView } from '../../../shared/pluginTasks.js';+import { PLUGIN_TEAM_PLAN_MAX_JSON_CHARS, PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../../shared/pluginTasks.js';++it('rejects oversized plans before saving and refuses oversized legacy receipts without truncation', async () => {+ const f=fixture(), task=await f.create();+ const before=structuredClone(f.rows.get(task.taskId)!);+ const plan={concurrency:2,items:Array.from({length:200},(_,i)=>({label:'w'+i,workingDir:'/answer',route:f.route,task:'x'.repeat(8000)}))};+ await expect(f.service.setTeamPlan('p',task.taskId,plan)).rejects.toMatchObject({code:'INVALID_REQUEST'});+ expect(f.rows.get(task.taskId)).toEqual(before);+ for (const payload of [' '.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS+1), JSON.stringify({teamPlan:{task:'x'.repeat(PLUGIN_TEAM_PLAN_MAX_JSON_CHARS)}})])+ expect(()=>readPluginTaskPlanReceipt(payload)).toThrow('size');+ f.rows.get(task.taskId)!.payload=JSON.stringify({teamPlan:plan});+ await expect(f.service.settleWorkerLabel('p',task.taskId,'w0')).rejects.toMatchObject({code:'INVALID_REQUEST'});+});function fixture() {let seq = 0;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStoreBudget.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStoreBudget.test.tsnew file mode 100644index 0000000000..eb8c55ee5d--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStoreBudget.test.ts@@ -0,0 +1,25 @@+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { expect, it } from 'vitest';+import type { DbClient } from '../../localDb/client/DbClient.js';+import { PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../../shared/pluginTasks.js';+import { createPluginTaskStore } from '../pluginTaskStore.js';++it('rejects persisted oversized receipts with SQLite selection, including UTF-16 expansion', async () => {+ 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)`);+ const store = createPluginTaskStore({ drizzle: drizzle(sqlite) } as unknown as DbClient);+ const insert = sqlite.prepare('INSERT INTO plugin_task_requests VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1)');+ insert.run('small', 'p', 'create', 'small', 'small', 'h', '{}');+ insert.run('large', 'p', 'create', 'large', 'large', 'h', 'x'.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS + 1));+ insert.run('unicode', 'p', 'create', 'unicode', 'unicode', 'h', '😀'.repeat(PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS));+ expect((await store.get('small'))?.payload).toBe('{}');+ expect(await store.get('missing')).toBeUndefined();+ await expect(store.get('large')).rejects.toMatchObject({ code: 'INVALID_REQUEST' });+ await expect(store.get('unicode')).rejects.toMatchObject({ code: 'INVALID_REQUEST' });+ expect(sqlite.prepare('SELECT count(*) AS n FROM plugin_task_requests').get()).toEqual({ n: 3 });+ } finally { sqlite.close(); }+});diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts b/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.tsindex ca0589b811..87a014626b 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskReviewContext.ts@@ -7,6 +7,7 @@ import {type AutoReviewUserIntent,} from '@cindy/maker-core';import type { PluginTeamPlan, PluginTaskRoute } from '../../shared/pluginTasks.js';+import { isPluginTeamPlanWithinBudget } from '../../shared/pluginTasks.js';import type { StoredAutoReviewProjection } from '../localDb/autoReviewProjection.js';import { restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from './autoReviewUserIntent.js';@@ -65,6 +66,7 @@ export function createPluginTaskReviewResolver(return denied('Plugin or task Auto authorization is no longer active.');}const plan = snapshot.plan;+ if (plan && !isPluginTeamPlanWithinBudget(plan)) return denied('Team plan exceeds the supported size; automatic authorization is blocked.');const item = snapshot.worker? plan?.items.find((x) => x.label === snapshot.worker!.label): undefined;diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.tsindex af2786becc..dcc9e6b6ca 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts@@ -1,5 +1,6 @@import { createHash, randomUUID } from 'node:crypto';import type { PluginTaskRoute, PluginTaskRun, PluginTaskView, PluginTeamPlan } from '../../shared/pluginTasks.js';+import { isPluginTeamPlanWithinBudget, PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../shared/pluginTasks.js';import {isSameSessionExecution,queuedInputBelongsTo,@@ -47,6 +48,15 @@ export class PluginTaskError extends Error {this.name = 'PluginTaskError';}}+/** Bounds legacy receipts before parsing; oversized authority never becomes a missing plan. */+export function readPluginTaskPlanReceipt(payload: string): { teamPlan?: PluginTeamPlan; settledLabels?: string[]; route?: PluginTaskRoute; [key: string]: unknown } {+ if (typeof payload !== 'string' || payload.length > PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS)+ throw new PluginTaskError('INVALID_REQUEST', 'Task receipt exceeds the supported size');+ const data = JSON.parse(payload);+ if (data.teamPlan !== undefined && !isPluginTeamPlanWithinBudget(data.teamPlan))+ throw new PluginTaskError('INVALID_REQUEST', 'Team plan exceeds the supported size');+ return data;+}/** Service failures must reject the public task API, without exposing internal diagnostics. */export function assertPluginTaskResult(result: { ok: boolean; errorCode?: string }, message: string): void {if (!result.ok) throw new PluginTaskError(result.errorCode || 'HOST_NOT_READY', message);@@ -236,9 +246,10 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {return ownTask(pluginId, taskId);}),setTeamPlan: (pluginId: string, taskId: string, plan: PluginTeamPlan) => exclusive(async () => {+ if (!isPluginTeamPlanWithinBudget(plan)) return fail('INVALID_REQUEST', 'Team plan exceeds the supported size');await ownTask(pluginId,taskId);const row = (await deps.store.get(taskId))!;- const data = JSON.parse(row.payload);+ const data = readPluginTaskPlanReceipt(row.payload);if (data.teamPlan && hash(data.teamPlan) !== hash(plan)) {return fail('IDEMPOTENCY_CONFLICT', 'Team plan is immutable');}@@ -254,7 +265,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {settleWorkerLabel: (pluginId: string, taskId: string, label: string) => exclusive(async () => {await ownTask(pluginId,taskId);const row = (await deps.store.get(taskId))!;- const data = JSON.parse(row.payload);+ const data = readPluginTaskPlanReceipt(row.payload);if (!data.teamPlan?.items.some((x: {label:string})=>x.label===label)) return fail('INVALID_REQUEST','Worker is not in team plan');await save(row,{...data,settledLabels:[...new Set([...(data.settledLabels||[]),label])]});}),diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts b/apps/desktop/src/main/maker-ipc/pluginTaskStore.tsindex d028640836..5abd42fe6b 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts@@ -1,4 +1,5 @@-import { and, asc, eq, gt, or } from 'drizzle-orm';+import { and, asc, eq, gt, or, getTableColumns, sql } from 'drizzle-orm';+import { PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../shared/pluginTasks.js';import type { DbClient } from '../localDb/client/DbClient.js';import { pluginTaskRequests } from '../localDb/schema.js';import type { PluginTaskStore } from './pluginTaskService.js';@@ -8,7 +9,15 @@ import { PluginTaskError } from './pluginTaskService.js';export function createPluginTaskStore(db: DbClient): PluginTaskStore {const table = pluginTaskRequests;return {- get: async (id) => (await db.drizzle.select().from(table).where(eq(table.id, id)).limit(1))[0],+ get: async (id) => {+ // Do not transfer oversized legacy payloads to Main for each Auto action.+ const [row] = await db.drizzle.select({ ...getTableColumns(table),+ payload: sql<string>`CASE WHEN length(${table.payload}) <= ${PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS} THEN ${table.payload} ELSE NULL END`,+ }).from(table).where(eq(table.id, id)).limit(1);+ if (row && (typeof row.payload !== 'string' || row.payload.length > PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS))+ throw new PluginTaskError('INVALID_REQUEST', 'Task receipt exceeds the supported size');+ return row;+ },find: async (pluginId, operation, targetId, requestKey) =>(await db.drizzlediff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 23bac96ba1..ca226cd87a 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,5 +1,5 @@import { createPluginTaskReviewResolver } from './pluginTaskReviewContext.js';-import { isPluginTaskPermissionAllowed, assertPluginTaskResult, createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';+import { isPluginTaskPermissionAllowed, assertPluginTaskResult, createPluginTaskService, readPluginTaskPlanReceipt, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';import { resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';import { PluginWriteAccessGate } from './pluginWriteAccessGate.js';import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';@@ -10455,7 +10455,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await service.get(pluginId,request.taskId);if (!record) throw new PluginTaskError('TASK_NOT_FOUND','Worker not found');const planReceipt = await createPluginTaskStore(epoch.client).get(request.taskId);- const plan = planReceipt ? JSON.parse(planReceipt.payload).teamPlan : undefined;+ const plan = planReceipt ? readPluginTaskPlanReceipt(planReceipt.payload).teamPlan : undefined;if (plan && !plan.items.some((item: {label: string}) => item.label === record.label)) throw new PluginTaskError('INVALID_REQUEST', 'Worker is not in team plan');const [row] = await epoch.client.drizzle.select().from(sessions).where(eq(sessions.id,record.sessionId)).limit(1);if (!row || row.status === 'deleted') throw new PluginTaskError('TASK_NOT_FOUND','Worker not found');@@ -10496,7 +10496,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)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;const planRow = await createPluginTaskStore(epoch.client).get(request.taskId);- const plan = planRow ? JSON.parse(planRow.payload).teamPlan : undefined;+ const plan = planRow ? readPluginTaskPlanReceipt(planRow.payload).teamPlan : undefined;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);@@ -11573,7 +11573,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// while directory/receipt reads or the existing reservation were pending.assertPluginWorkerAutoAuthorized(receipt.pluginId, currentTask);if (cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');- const data = JSON.parse(currentReceipt.payload);+ const data = readPluginTaskPlanReceipt(currentReceipt.payload);if (!data.teamPlan) return undefined; // Existing plugins retain their original behavior.const item = data.teamPlan.items.find((x: {label:string})=>x.label===params.label);if (!item || data.settledLabels?.includes(params.label)) throw new PluginTaskError('INVALID_REQUEST','Worker is not pending in the registered plan');@@ -13099,7 +13099,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const projection = await epoch.client.tx('authorization.readProjection', { sessionId, leadId });if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');const config = readGhostErrandConfig(receipt.pluginId);- const data = JSON.parse(receipt.payload);+ const data = readPluginTaskPlanReceipt(receipt.payload);const approvalRevision = pluginTaskAuthorizationRevision(receipt.pluginId);return {pluginId: receipt.pluginId,diff --git a/apps/desktop/src/shared/pluginTasks.ts b/apps/desktop/src/shared/pluginTasks.tsindex ea6b8dba40..574b6a0010 100644--- a/apps/desktop/src/shared/pluginTasks.ts+++ b/apps/desktop/src/shared/pluginTasks.ts@@ -45,6 +45,15 @@ export interface PluginTeamPlan {task?: string;items: Array<{label: string; workingDir: string; route: PluginTaskRoute; task?: string}>;}+/** UTF-16 JSON characters, including escaping; reject rather than truncate scope. */+export const PLUGIN_TEAM_PLAN_MAX_JSON_CHARS = 1_048_576;+export const PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS = PLUGIN_TEAM_PLAN_MAX_JSON_CHARS + 65_536;+export function isPluginTeamPlanWithinBudget(plan: unknown): boolean {+ try {+ const json = JSON.stringify(plan);+ return typeof json === 'string' && json.length <= PLUGIN_TEAM_PLAN_MAX_JSON_CHARS;+ } catch { return false; }+}export type PluginTaskRequest =| { type: 'tasks-request'; kind: 'capabilities' }| {diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex 589ee3537c..95013d982e 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -71,6 +71,7 @@ getTeam 的 completedAt 可由宿主落盘的 turnCompleted 终态恢复:仅### 委派范围与 Auto 审阅计划的顶层 `task` 及每项 `task` 是可选的插件原始任务说明,最多 8000 字符。+完整计划 `JSON.stringify(plan).length` 最多 1,048,576 个 UTF-16 字符(包含转义和元数据);超限返回 `INVALID_REQUEST`,不截断任务或删除旧计划。管道和服务入口统一检查;旧收据在解析前检查总量,恢复及 Auto 不把超限计划当作未登记。200 份现有七题公开范围的实测最大约 59 万字符可容纳,不保证任意自定义题或极长路径均可用满 200 份。Host 只接受经绑定插件身份写入的自有创建收据;已登记计划整体不可变,包括原本缺失的范围。旧计划缺少范围时沿用原审批行为,不事后补造授权;新范围须在新任务中登记完整计划。没有新增权限档位、没有提升到 Full access。@@ -80,6 +81,7 @@ Host 只接受经绑定插件身份写入的自有创建收据;已登记计划不从 Orca 消息、模型声称或工具参数恢复。缺少旧作者凭据时标注历史不完整,不猜测授权。插件文字放在独立 `delegatedTask` 字段,不能覆盖用户限制、跨题授权或声称自己是用户。直接派发和排队派发均保存受保护的 `delegated-continuation` 作者凭据;应用重启后从同一 Host 收据重建委派范围。+自动恢复、上下文重建、系统触发及受保护续行共用合成消息判据,不追加旧授权,也不清除真人限制;增量摘要与完整重放一致。运行时摘要版本升为 2,旧版摘要首次读取从原消息自动重建,无需重新授权,不改历史 migration。明确带任务范围的所有动作(包括读取)均检查范围;不会仅凭工作目录安全而忽略插件的禁读条款。明确的 Host 续行凭据在 SQL 限量前过滤,避免频繁协调消息挤走真实用户限制;空字符串凭据仍保留,因为用户只发送附件时也可能没有文字。用户消息携带新资源时,沿用普通任务规则,先清除旧指代授权再追加该行可信原话;不以可编辑的 origin 判定作者。缺凭据的旧卡片保守标记历史不完整。diff --git a/packages/maker-shared/src/autoReviewIntent.ts b/packages/maker-shared/src/autoReviewIntent.tsindex f9ff3ecd97..34ca8a6e7e 100644--- a/packages/maker-shared/src/autoReviewIntent.ts+++ b/packages/maker-shared/src/autoReviewIntent.ts@@ -136,10 +136,21 @@ export function createAutoReviewIntentProjection() {);}+ function isSynthetic(message: AutoReviewHistoryMessage): boolean {+ if (message.role !== "user") return false;+ const meta = message.agentMeta;+ const receipt = meta?.autoReviewUserText;+ return !!(meta?.autoResume || meta?.contextRebuild ||+ (typeof receipt === "string" && receipt.startsWith("[UI_ACTION_TRIGGER]")) ||+ (receipt && typeof receipt === "object" && "kind" in receipt &&+ (receipt.kind === "scheduled-continuation" || receipt.kind === "delegated-continuation")));+ }+function restoreAutoReviewUserIntent(history: readonly AutoReviewHistoryMessage[],current?: { clientId: string; content: unknown; authoredText?: string },): AutoReviewUserIntent {+ history = history.filter((message) => !isSynthetic(message));let intent: AutoReviewUserIntent = "";let replayed = false;const latest = current@@ -169,16 +180,6 @@ export function createAutoReviewIntentProjection() {continue;}if (message.role !== "user") continue;- // Host-originated scheduled turns are execution context, never new owner consent.- // Keep intervening human restrictions; do not let repeated heartbeats erase them.- // Use the protected receipt, not origin (which the renderer can edit).- const receipt = message.agentMeta?.autoReviewUserText as- Record<string, unknown> | undefined;- if (- receipt?.kind === "scheduled-continuation" ||- receipt?.kind === "delegated-continuation"- )- continue;// An already-persisted retry is the same input, not a second authorization.if (current && message.clientId === current.clientId) {if (message.agentMeta?.autoReviewUserText !== latest) return "";@@ -190,10 +191,7 @@ export function createAutoReviewIntentProjection() {// Old rows without Host-captured text cannot safely restore authorization.if (typeof text !== "string" ||- !["turn", "steer"].includes(String(meta?.delivery)) ||- meta?.autoResume ||- meta?.contextRebuild ||- text.startsWith("[UI_ACTION_TRIGGER]")+ !["turn", "steer"].includes(String(meta?.delivery))) {intent = "";continue;@@ -209,6 +207,7 @@ export function createAutoReviewIntentProjection() {history: readonly AutoReviewHistoryMessage[],historyComplete = true,): { intent: AutoReviewUserIntent; unverified: boolean } {+ history = history.filter((message) => !isSynthetic(message));let intent: AutoReviewUserIntent = "";let omitted = !historyComplete;const eventTime = (m: AutoReviewHistoryMessage): number => {@@ -264,13 +263,7 @@ export function createAutoReviewIntentProjection() {) {if (readAutoReviewUserText(m.content) === null) intent = "";intent = appendAutoReviewUserIntent(intent, receipt);- } else if (!(- receipt &&- typeof receipt === "object" &&- "kind" in receipt &&- (receipt.kind === "scheduled-continuation" ||- receipt.kind === "delegated-continuation")- )) {+ } else {omitted = true;}}@@ -299,6 +292,7 @@ export function createAutoReviewIntentProjection() {readText: readAutoReviewUserText,restore: restoreAutoReviewUserIntent,ambiguousAnswers,+ isSynthetic,reviewState,withOmission,review: (history: readonly AutoReviewHistoryMessage[], complete = true) => {