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(pi): preserve per-message plan mode through dispatch (#6074)

Chris Zhang97cf41273df8
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index ff31272341..294066c785 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -449,6 +449,25 @@ describe('packGhostDir', () => {
}
});
+ it.each([0, 1])('does not write an in-workdir package after live Plan authority expires at check %s', async (remainingChecks) => {
+ const dir = await makeSrcDir({ 'ghost.json': JSON.stringify(GOOD_MANIFEST), 'main.js': 'export default {}' });
+ let remaining = remainingChecks;
+ expect(await packGhostDirRaw(dir, { sessionWorkdir: workDir, isCurrent: () => remaining-- > 0 }))
+ .toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(fs.existsSync(path.join(dir, 'demo-1.0.0.cindy'))).toBe(false);
+ });
+
+ it.each([0, 1])('does not scaffold inside workdir after live Plan authority expires at check %s', async (remainingChecks) => {
+ const dir = path.join(workDir, 'plan-blocked-plugin');
+ const writeScaffold = vi.fn(testScaffoldWriter);
+ let remaining = remainingChecks;
+ expect(await scaffoldGhostDirRaw({ dir, template: 'plain', id: 'plan-blocked-plugin', name: 'Plan test', minCindyVersion: '1.2.3' },
+ { sessionWorkdir: workDir, isCurrent: () => remaining-- > 0, writeScaffold }))
+ .toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ expect(writeScaffold).not.toHaveBeenCalled();
+ expect(fs.existsSync(dir)).toBe(false);
+ });
+
it('does not write a package after the outside grant expires', async () => {
const dir = await makeSrcDir({
'ghost.json': JSON.stringify(GOOD_MANIFEST),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
index 86e5ec2597..110d322733 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts
@@ -192,7 +192,7 @@ it('completes source replacement and another plugin uninstall without reversing
const archive = '_ns__cindy-archive-00000000-0000-4000-8000-000000000002__helper';
const service = createPluginTaskService({
store: tasks, assertCurrent: () => {}, assertAuthorized: vi.fn(), readPermissionMode: vi.fn(),
- resolveRoute: vi.fn(), createSession: vi.fn(), readSession: vi.fn(),
+ resolveRoute: vi.fn(), createSession: vi.fn(), readSession: vi.fn(), readLiveSession: vi.fn(),
dispatch: vi.fn(), inspect: vi.fn(), cancel: vi.fn(),
});
let entered!: () => void, finish!: () => void;
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 549e5ec29e..a35c9dcd29 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -246,10 +246,11 @@ type ForgeOutsideGrantOptions = {
isCurrent?: () => boolean;
};
-function staleOutsideForgeGrant(
+function staleForgeGrant(
options?: ForgeOutsideGrantOptions,
): { ok: false; errorCode: 'PERMISSION_DENIED'; message: string } | null {
- if (!options?.allowOutsideWorkdir || !options.authorizedDir) return null;
+ // Live authority also guards in-workdir writes after async preparation.
+ if (!options?.isCurrent && (!options?.allowOutsideWorkdir || !options.authorizedDir)) return null;
if (options.isCurrent?.() === true) return null;
return { ok: false, errorCode: 'PERMISSION_DENIED', message: FORGE_OUTSIDE_GRANT_STALE_MESSAGE };
}
@@ -615,7 +616,7 @@ export async function scaffoldGhostDir(
message: '会话工作目录不存在,无法确定骨架输出位置',
};
}
- const staleGrant = staleOutsideForgeGrant(options);
+ const staleGrant = staleForgeGrant(options);
if (staleGrant) return staleGrant;
let realTarget: string;
try {
@@ -780,7 +781,7 @@ export async function scaffoldGhostDir(
message: 'Forge scaffold stable-directory capability is unavailable',
};
}
- const staleBeforeWrite = staleOutsideForgeGrant(options);
+ const staleBeforeWrite = staleForgeGrant(options);
if (staleBeforeWrite) return staleBeforeWrite;
const writeResult = await options.writeScaffold({
parentDir,
@@ -1423,7 +1424,7 @@ export async function packGhostDir(
message: 'The current session workdir does not exist',
};
}
- const staleGrant = staleOutsideForgeGrant(options);
+ const staleGrant = staleForgeGrant(options);
if (staleGrant) return staleGrant;
let realSourceDir: string;
try {
@@ -1480,7 +1481,7 @@ export async function packGhostDir(
realSourceDir,
`${built.manifest.id}-${built.manifest.version}.cindy`,
);
- const staleBeforeWrite = staleOutsideForgeGrant(options);
+ const staleBeforeWrite = staleForgeGrant(options);
if (staleBeforeWrite) return staleBeforeWrite;
try {
await fs.promises.writeFile(cindyPath, built.buf);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
index 23bc1f367f..43bf695043 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import ts from 'typescript';
+import { Session } from '@cindy/maker-core';
import {
createPluginTaskService,
isPluginTaskPermissionAllowed,
@@ -114,6 +115,7 @@ function fixture() {
fastMode: false,
};
const execution = { instanceId: 'native', generation: 1 };
+ const live = { instanceId: execution.instanceId, stablePlanModeState: { enabled: false, generation: 0 } };
const deps: PluginTaskServiceDeps = {
store,
readPermissionMode: () => 'auto',
@@ -131,6 +133,7 @@ function fixture() {
tasks.set(taskId, { taskId, title, resolvedConfig, revision: 1, status: 'active', permissionMode: 'plan' });
}),
readSession: async (id) => copy(tasks.get(id) ?? null),
+ readLiveSession: () => live,
dispatch: vi.fn(async () => ({ ok: true })),
inspect: vi.fn(async () => ({ execution: null, pending: [] })),
cancel: vi.fn(async () => 'cancelled' as const),
@@ -161,6 +164,94 @@ function fixture() {
};
}
+describe('plugin dispatch uses live Plan execution authority', () => {
+ it.each(['send', 'accept'] as const)('%s rejects consumed Pi intent while execution is active, unknown or switching', async entry => {
+ const f = fixture(), task = await f.create();
+ Object.assign(f.tasks.get(task.taskId)!, { permissionMode: 'auto', planModeEnabled: false });
+ let executionPlan: boolean | null = false;
+ let releaseEvents!: () => void, releaseSwitch!: () => void;
+ const eventsClosed = new Promise<void>(resolve => { releaseEvents = resolve; });
+ const switching = new Promise<void>(resolve => { releaseSwitch = resolve; });
+ const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };
+ const session = new Session({ id: task.taskId, sessionInstanceId: f.execution.instanceId,
+ agentKind: 'pi', workDir: '/answer', permissionMode: 'auto', logger,
+ capabilities: { planMode: { supported: true } } as never,
+ handle: { id: 'pi', agentKind: 'pi', model: 'test',
+ async *events() { await eventsClosed; }, async close() { releaseEvents(); }, setInteractionResolver() {},
+ getPlanMode: () => false, getExecutionPlanMode: () => executionPlan,
+ setPlanMode: async () => { await switching; },
+ } as never,
+ });
+ f.deps.readLiveSession = () => session;
+ const request = { taskId: task.taskId, expectedRevision: task.revision, requestKey: 'live-plan', text: 'continue' };
+ const queued = entry === 'accept' ? await f.service.send('p', request) : undefined;
+ vi.mocked(f.deps.dispatch).mockClear();
+ const invoke = () => entry === 'send' ? f.service.send('p', request)
+ : f.service.accept(task.taskId, { clientId: queued!.inputMessageId }, f.execution);
+ try {
+ for (const value of [true, null]) {
+ executionPlan = value;
+ expect(session.getPlanMode()).toBe(false);
+ await expect(invoke()).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ }
+ executionPlan = false;
+ const pending = session.setPlanMode(true);
+ expect(session.stablePlanModeState).toBeNull();
+ await expect(invoke()).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(f.deps.dispatch).not.toHaveBeenCalled();
+ releaseSwitch();
+ await pending;
+ // Native/Host recovery to a stable non-plan state restores the same API.
+ if (entry === 'send') await expect(invoke()).resolves.toMatchObject({ status: 'queued' });
+ else await expect(invoke()).resolves.toBeUndefined();
+ } finally {
+ releaseSwitch();
+ await session.close();
+ }
+ });
+
+ it.each(['send', 'accept'] as const)('%s rechecks the same live session after async route and receipt work', async entry => {
+ for (const point of ['route', 'receipt', 'instance', 'generation']) {
+ const f = fixture(), task = await f.create();
+ Object.assign(f.tasks.get(task.taskId)!, { permissionMode: 'auto', planModeEnabled: false });
+ let live = { instanceId: f.execution.instanceId, stablePlanModeState: { enabled: false, generation: 0 } };
+ f.deps.readLiveSession = () => live;
+ const request = { taskId: task.taskId, expectedRevision: task.revision, requestKey: 'async-plan', text: 'continue' };
+ const queued = entry === 'accept' ? await f.service.send('p', request) : undefined;
+ vi.mocked(f.deps.dispatch).mockClear();
+ const change = () => {
+ if (point === 'instance') live = { ...live };
+ else if (point === 'generation') live.stablePlanModeState.generation++;
+ else live.stablePlanModeState.enabled = true;
+ };
+ if (point === 'receipt') {
+ const method = entry === 'send' ? 'insert' : 'save';
+ const original = f.deps.store[method];
+ f.deps.store[method] = async row => { await original(row); change(); };
+ } else f.deps.resolveRoute = async () => { change(); return f.route; };
+ const result = entry === 'send' ? f.service.send('p', request)
+ : f.service.accept(task.taskId, { clientId: queued!.inputMessageId }, f.execution);
+ if (entry === 'send' && point === 'receipt') await expect(result).resolves.toMatchObject({ status: 'failed' });
+ else await expect(result).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(f.deps.dispatch).not.toHaveBeenCalled();
+ }
+ });
+
+ it('allows cold tasks to queue but requires the accepting live instance', async () => {
+ const f = fixture();
+ f.deps.readLiveSession = () => undefined;
+ const run = await f.send();
+ await expect(f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution))
+ .rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ f.deps.readLiveSession = () => ({ instanceId: 'replacement', stablePlanModeState: { enabled: false, generation: 0 } });
+ await expect(f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution))
+ .rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ const live = { instanceId: f.execution.instanceId, stablePlanModeState: { enabled: false, generation: 0 } };
+ f.deps.readLiveSession = () => live;
+ await expect(f.service.accept(run.taskId, { clientId: run.inputMessageId }, f.execution)).resolves.toBeUndefined();
+ });
+});
+
it('serializes source archival behind creation and keeps old tasks inaccessible to the replacement', async () => {
const fixtureState = fixture();
let started!: () => void;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
index b1f8d2f30a..3a79685522 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
@@ -45,7 +45,7 @@ it('durably revokes only create ownership while retaining plans, run results and
const unused=async():Promise<never>=>{throw Error('unexpected dispatch/control');};
const service=createPluginTaskService({store,assertCurrent(){},assertAuthorized(){},
readSession:async taskId=>({taskId,title:'kept',revision:1,status:'active',resolvedConfig:route,permissionMode:'plan'}),
- readPermissionMode:()=> 'plan',resolveRoute:unused,createSession:unused,dispatch:unused,inspect:unused,cancel:unused,
+ readPermissionMode:()=> 'plan',readLiveSession:()=>undefined,resolveRoute:unused,createSession:unused,dispatch:unused,inspect:unused,cancel:unused,
});
expect((await service.list('p')).items.map(row=>row.taskId)).toEqual(['task']);
await store.revokePlugin('p');
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
index 7250e828f7..5c42b24229 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -1,4 +1,5 @@
import { createHash, randomUUID } from 'node:crypto';
+import type { Session } from '@cindy/maker-core';
import type { PluginTaskRoute, PluginTaskRun, PluginTaskView, PluginTeamPlan } from '../../shared/pluginTasks.js';
import { isPluginTeamPlanWithinBudget, PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../shared/pluginTasks.js';
import {
@@ -125,6 +126,7 @@ export interface PluginTaskServiceDeps {
revealPluginTasks?(pluginId: string): Promise<void>;
setModel?(taskId: string, route: PluginTaskRoute, assertCurrent: () => Promise<void>): Promise<{ status: string }>;
readSession(taskId: string): Promise<PluginTaskView | null>;
+ readLiveSession(taskId: string): Pick<Session, 'instanceId' | 'stablePlanModeState'> | undefined;
assertTeamPlanUnstarted?(taskId: string): Promise<void>;
dispatch(
pluginId: string,
@@ -171,9 +173,27 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
if (!deps.assertHiddenTasksAllowed) fail('PERMISSION_DENIED', 'Background tasks are unavailable');
deps.assertHiddenTasksAllowed!(pluginId);
};
- const assertDispatch = async (pluginId: string, taskId: string) => {
+ // The persisted/UI choice can be consumed while Pi is still executing Plan.
+ // Keep one live authority across awaits; queued acceptance must also match
+ // the runtime selected by the input coordinator, including for cold tasks.
+ const capturePlanGuard = (taskId: string, execution?: SessionExecutionIdentity) => {
+ const live = deps.readLiveSession(taskId);
+ const plan = live?.stablePlanModeState;
+ const generation = plan?.generation;
+ const assertCurrent = () => {
+ const current = deps.readLiveSession(taskId);
+ const state = current?.stablePlanModeState;
+ if (current !== live || (execution && current?.instanceId !== execution.instanceId)
+ || (live && (!plan || plan.enabled || !state || state.enabled || state.generation !== generation)))
+ fail('PERMISSION_DENIED', 'Task Plan Mode is active, unknown or changing');
+ };
+ assertCurrent();
+ return assertCurrent;
+ };
+ const assertDispatch = async (pluginId: string, taskId: string, assertPlanCurrent = capturePlanGuard(taskId)) => {
const view = await ownTask(pluginId, taskId);
deps.assertAuthorized(pluginId);
+ assertPlanCurrent();
if (view.status !== 'active') return fail('TASK_BUSY', 'Archived tasks cannot accept input');
if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(pluginId), view.planModeEnabled))
return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');
@@ -408,14 +428,15 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
fingerprint,
);
if (previous)
- return { run: JSON.parse(previous.payload) as PluginTaskRun, dispatch: false };
+ return { run: JSON.parse(previous.payload) as PluginTaskRun, dispatch: false as const };
+ const assertPlanCurrent = capturePlanGuard(view.taskId);
if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(pluginId), view.planModeEnabled)) return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');
if (view.status !== 'active')
return fail('TASK_BUSY', 'Archived tasks cannot accept input');
if (view.revision !== request.expectedRevision)
return fail('REVISION_CONFLICT', 'Task configuration changed');
await deps.resolveRoute(pluginId, view.resolvedConfig);
- await assertDispatch(pluginId, view.taskId);
+ await assertDispatch(pluginId, view.taskId, assertPlanCurrent);
const runId = id();
const run: PluginTaskRun = {
runId,
@@ -427,10 +448,11 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
usage: { status: 'unavailable', reason: 'Per-input usage has not been reconciled.' },
};
deps.assertAuthorized(pluginId);
+ assertPlanCurrent();
await deps.store.insert(
newReceipt(pluginId, 'send', view.taskId, request.requestKey, fingerprint, run, runId),
);
- return { run, dispatch: true };
+ return { run, dispatch: true as const, assertPlanCurrent };
});
if (!prepared.dispatch) return prepared.run;
let failure: 'failed' | 'reconciling' | undefined;
@@ -438,7 +460,8 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
// Never hold the receipt lock while entering Session dispatch/control. The
// coordinator awaits accept() before vendor dispatch under its own lock.
try {
- await assertDispatch(pluginId, prepared.run.taskId);
+ await assertDispatch(pluginId, prepared.run.taskId, prepared.assertPlanCurrent);
+ prepared.assertPlanCurrent();
dispatchStarted = true;
const outcome = await deps.dispatch(
pluginId,
@@ -521,18 +544,22 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
continue;
return fail('REQUEST_EXPIRED', 'Input was already settled');
}
+ const assertPlanCurrent = capturePlanGuard(taskId, execution);
const view = await ownTask(row.pluginId, taskId);
+ assertPlanCurrent();
if (view.status !== 'active') return fail('TASK_BUSY', 'Archived tasks cannot accept input');
if (!isPluginTaskPermissionAllowed(view.permissionMode, deps.readPermissionMode(row.pluginId), view.planModeEnabled)) return fail('PERMISSION_DENIED', 'Task permission exceeds plugin dispatch policy');
if (hash(view.resolvedConfig) !== hash(run.acceptedConfig))
return fail('ROUTE_UNAVAILABLE', 'Accepted route changed before dispatch');
await deps.resolveRoute(row.pluginId, run.acceptedConfig);
- await assertDispatch(row.pluginId, taskId);
+ await assertDispatch(row.pluginId, taskId, assertPlanCurrent);
+ assertPlanCurrent();
run.inputClientIds = [...new Set([...(run.inputClientIds ?? []), item.clientId])];
run.execution = execution;
run.status = 'running';
await save(row, run);
- await assertDispatch(row.pluginId, taskId);
+ await assertDispatch(row.pluginId, taskId, assertPlanCurrent);
+ assertPlanCurrent();
}
}),
settle: (
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 23924222fb..1bf90641dc 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -12454,6 +12454,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
pluginTasks = createPluginTaskService({
store: createPluginTaskStore(snapshot.client), assertCurrent, assertAuthorized: assertPlugin, resolveRoute,
readPermissionMode: pluginId => clampPluginTaskPermissionMode(readPluginTaskConfig(pluginId).permissionMode),
+ readLiveSession: taskId => maker.getSession(taskId),
setModel: async (taskId, route, assertUnchanged) => {
const current = await sessionControlService.getSessionRuntime({ targetSessionId: taskId });
if (!current.ok) throw new PluginTaskError('TASK_NOT_FOUND', current.message);
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index 07475636c8..7f3e16077a 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -23,6 +23,8 @@ import type {
GhostSetupEnsureResult,
} from '../../cindy-brain/ghostSetupCoordinator';
import { t } from '../../i18n';
+import { Session } from '@cindy/maker-core';
+import { resolveGhostFsSessionSnapshot } from '../../maker-ipc/ghostFsSessionSnapshot';
import type { CindyGhostsHostDeps } from '../ghost';
import type { GhostInstallConsentPrompt } from '../../cindy-brain/ghostInstallConsent';
import type { InstalledGhost, GhostSetupAssessment } from '../../../shared/ghost';
@@ -437,7 +439,7 @@ beforeEach(() => {
dirDepositMock.mockClear();
saveDepositMock.mockClear();
liveGrantStateMock.mockReset();
- liveGrantStateMock.mockReturnValue({ permissionMode: 'auto', remoteHostId: null });
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'auto', remoteHostId: null, isCurrent: () => true });
callCindyMediaMock.mockReset();
alsSessionContextMock.mockReset();
logWarnMock.mockClear();
@@ -500,6 +502,46 @@ beforeEach(() => {
});
describe('Forge session workdir gate', () => {
+ it.each(['forgeScaffold', 'forgePack', 'forgeInstall'] as const)('blocks Pi %s after the UI plan intent is consumed until native execution exits Plan', async (operation) => {
+ let executionPlan: boolean | null = true;
+ let close!: () => void;
+ const closed = new Promise<void>((resolve) => { close = resolve; });
+ const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };
+ const handle = {
+ id: 'pi', agentKind: 'pi', model: 'test',
+ async *events() { await closed; }, async close() { close(); }, setInteractionResolver() {},
+ getPlanMode: () => false, getExecutionPlanMode: () => executionPlan,
+ };
+ const session = new Session({ id: 's1', sessionInstanceId: 's1-instance', agentKind: 'pi', workDir: WORKDIR,
+ permissionMode: 'bypassPermissions', handle: handle as never,
+ capabilities: { planMode: { supported: true } } as never, logger });
+ sessionSnapshotMock.mockResolvedValue({ workingDir: WORKDIR, permissionMode: 'bypassPermissions', planModeEnabled: false, remoteHostId: null });
+ liveGrantStateMock.mockImplementation((id, instance) => {
+ const snapshot = resolveGhostFsSessionSnapshot(() => session, id, instance);
+ return { permissionMode: session.stablePermissionModeState?.mode ?? null, remoteHostId: null,
+ isCurrent: () => !!snapshot && !snapshot.planModeEnabled && snapshot.isCurrent?.() === true };
+ });
+ packGhostDirMock.mockResolvedValue({ ok: true, buf: Buffer.from('packed'),
+ cindyPath: path.join(WORKDIR, 'plugin-src', 'demo-1.0.0.cindy'),
+ manifest: { id: 'demo', name: 'Demo', version: '1.0.0' } });
+ const deps = makeDeps('pi');
+ const invoke = () => operation === 'forgeScaffold'
+ ? deps.forgeScaffold({ dir: path.join(WORKDIR, 'new-plugin'), template: 'plain', id: 'x', name: 'X' })
+ : deps[operation]({ dir: path.join(WORKDIR, 'plugin-src') });
+ try {
+ expect(session.getPlanMode()).toBe(false);
+ for (const state of [true, null]) {
+ executionPlan = state;
+ expect(await invoke()).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
+ }
+ expect(scaffoldGhostDirMock).not.toHaveBeenCalled();
+ expect(packGhostDirMock).not.toHaveBeenCalled();
+ expect(forgeInstallPackageMock).not.toHaveBeenCalled();
+ executionPlan = false;
+ expect(await invoke()).toMatchObject({ ok: true });
+ } finally { await session.close(); }
+ });
+
it('holds the owner mutation lease across the Forge operation', async () => {
const operation = makeDeps().forgePack({ dir: path.join(WORKDIR, 'plugin-src') });
expect(captureMutationOwnerMock).toHaveBeenCalledTimes(1);
@@ -514,6 +556,7 @@ describe('Forge session workdir gate', () => {
expect(packGhostDirMock).toHaveBeenCalledWith(path.join(WORKDIR, 'plugin-src'), {
sessionWorkdir: WORKDIR,
forbiddenRootDirs: [],
+ isCurrent: expect.any(Function),
});
});
@@ -550,6 +593,7 @@ describe('Forge session workdir gate', () => {
});
expect(forgeInstallPackageMock).toHaveBeenCalledWith(cindyPath, {
+ isCurrent: expect.any(Function),
ghostId: 'demo',
packageSha256: createHash('sha256').update(bytes).digest('hex'),
// Agent 安装的插件确认投给调用所在的任务。
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 6dc15e46d5..13685ccdef 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -198,7 +198,7 @@ function resolveCanonicalForgeDir(source: string): string {
}
type ForgeOutsideAccess =
- | { ok: true; allowOutsideWorkdir: false }
+ | { ok: true; allowOutsideWorkdir: false; isCurrent: () => boolean }
| {
ok: true;
allowOutsideWorkdir: true;
@@ -212,13 +212,13 @@ function forgeOutsidePackFlags(access: Extract<ForgeOutsideAccess, { ok: true }>
authorizedDir?: string;
isCurrent?: () => boolean;
} {
- return access.allowOutsideWorkdir
- ? {
- allowOutsideWorkdir: true,
- authorizedDir: access.authorizedDir,
- ...(access.isCurrent ? { isCurrent: access.isCurrent } : {}),
- }
- : {};
+ return {
+ ...(access.allowOutsideWorkdir ? {
+ allowOutsideWorkdir: true,
+ authorizedDir: access.authorizedDir,
+ } : {}),
+ ...(access.isCurrent ? { isCurrent: access.isCurrent } : {}),
+ };
}
function requireLiveSessionInstance(
@@ -257,7 +257,20 @@ async function authorizeForgeOutsideWorkdir(params: {
getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
}): Promise<ForgeOutsideAccess> {
const location = classifyForgeSourceRelativeToWorkdir(params.dir, params.sessionWorkdir);
- if (location !== 'outside') return { ok: true, allowOutsideWorkdir: false };
+ if (location !== 'outside') {
+ // The DB plan flag is the next-message checkbox, not execution authority.
+ // In-workdir Forge writes need the same live Plan guard as outside grants.
+ try {
+ const { sessionId, sessionInstanceId } = params.sessionContext ?? {};
+ const live = sessionId && sessionInstanceId
+ ? params.getLiveSessionGrantState?.(sessionId, sessionInstanceId) : null;
+ if (live?.permissionMode && live.permissionMode !== 'plan'
+ && !live.remoteHostId && live.isCurrent?.() === true) {
+ return { ok: true, allowOutsideWorkdir: false, isCurrent: live.isCurrent };
+ }
+ } catch { /* Unavailable runtime authority cannot authorize writes. */ }
+ return { ok: false, errorCode: 'PERMISSION_DENIED', message: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
+ }
const live = requireLiveSessionInstance(
params.sessionContext?.sessionId,
params.sessionContext?.sessionInstanceId,
@@ -313,7 +326,7 @@ async function authorizeForgeOutsideWorkdir(params: {
}
function assertForgeGrantCurrent(access: Extract<ForgeOutsideAccess, { ok: true }>): ForgeOutsideAccess {
- if (access.allowOutsideWorkdir && access.isCurrent?.() !== true) {
+ if (access.isCurrent?.() !== true) {
return { ok: false, errorCode: 'PERMISSION_DENIED', message: GRANT_AUTHORIZATION_CHANGED_MESSAGE };
}
return access;
@@ -402,7 +415,7 @@ async function packForgeSource(
});
}
}
- if (packFlags.allowOutsideWorkdir && packFlags.authorizedDir && packFlags.isCurrent?.() !== true) {
+ if (packFlags.isCurrent?.() === false) {
return {
ok: false as const,
result: { ok: false as const, errorCode: 'PERMISSION_DENIED' as const, message: GRANT_AUTHORIZATION_CHANGED_MESSAGE },
@@ -415,9 +428,9 @@ async function packForgeSource(
? {
allowOutsideWorkdir: true,
authorizedDir: packFlags.authorizedDir,
- ...(packFlags.isCurrent ? { isCurrent: packFlags.isCurrent } : {}),
}
: {}),
+ ...(packFlags.isCurrent ? { isCurrent: packFlags.isCurrent } : {}),
};
let packed = await packGhostDir(dir, iconPng ? { ...packOptions, iconPng } : packOptions);
// icon overlay 的任何失败都不是打包门槛:用原源码再打一次。若原源码
@@ -2562,7 +2575,7 @@ export function getCindyGhostsMcpDeps(
packed: attempt.packed,
iconNote: attempt.iconNote,
mutationOwner,
- ...(stillGranted.allowOutsideWorkdir && stillGranted.isCurrent
+ ...(stillGranted.isCurrent
? { isCurrent: stillGranted.isCurrent }
: {}),
};
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index dd0e952178..170f04d650 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -64,9 +64,15 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
MCP 请求接入 Pi 的取消信号;Bun fetch 的独立空闲计时关闭,由既有请求期限统一约束响应头与
正文。取消只中止本次 HTTP 等待,不承诺撤销服务端已执行的动作。网络错误只附白名单错误码,
仅 JSON-RPC `-32602` 明确参数错误附 schema,工具业务错误保留原反馈。
-- **plan 模式**:挂 pi 自带 plan-mode 扩展,`/plan` toggle 驱动;Cindy 维护镜像态并在 resume
- 时从本机 session JSONL 校正(只打开启动时 `--session-dir` 真身内的普通文件,
- 并有字节/时间预算,超限回退 RPC);远端仍走 `get_entries`。
+- **plan 模式**:自动挂载 Pi 分发包自带的 plan-mode 扩展,无需用户另装。UI 勾选是下一条
+ 消息的一次性意图,与原生运行态分开;`StartSessionOptions.planMode` 设置起始档,
+ `SendOptions.planMode` 快照决定本轮,切档与 prompt 在同一 RPC 串行段执行。发送后消耗
+ 勾选不关闭在途计划轮;下一条普通消息恢复普通工具。扩展缺失或切档失败时拒绝计划请求,
+ 不悄悄按普通模式执行。缺失扩展不阻止会话启动,启动计划意图保留到发送时拒绝;
+ 取消计划后普通消息仍可发送。resume 和原生 Execute/Refine 续轮从本机 session JSONL
+ 校正运行态;远端仍走 `get_entries`。原生续轮校正期间 Host 写操作保持不可用。
+ 启动校正失败且没有显式计划意图时,发送前重新读取原生状态;仍未知则拒绝发送及包变更,
+ 读回后沿用原生档位并按正常接受边界消耗一次性计划意图,不默认关闭计划模式。
> Cindy 自有子代理的委派、控制、结果收口与测试边界见 [Pi 子代理设计](../research/pi-subagent-delegation.md)。与 Orca 协作模式分别维护。
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 667e7fa455..430e9d2218 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -311,7 +311,9 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
全量运行时内容校验,也不要把安装确认当成完整性守门而删减现有校验。
- **Forge 的源码区与 Host 受管根互斥。** `ghost_forge_scaffold` / `ghost_forge_pack` /
`ghost_forge_install` 的目标必须是独立作者目录,不得是安装根或状态根;按 realpath
- 挡住大小写折叠与软链/junction 别名。会话工作目录内直接放行;工作目录外走与
+ 挡住大小写折叠与软链/junction 别名。目录内外均核对活跃任务的实际执行计划状态,
+ 不能用数据库的一次性计划勾选代替;计划中、状态未知或授权过期时禁止写入,落盘前复核。
+ 会话工作目录内无需额外确认;工作目录外走与
`ghost_call` 过户相同的会话权限路径(本地 Full Access 自动放行,Auto 交当前会话
AI 审阅,Ask 弹确认卡,远程/缺会话/查询失败 fail closed),禁止在 Host 已放行
后再因目录边界悄悄硬断。`ghost_forge_pack` 只负责校验与打包;只有用户明确
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index 138adcdff6..03ac1b673c 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -258,6 +258,11 @@ getTeam 的 completedAt 可由宿主落盘的 turnCompleted 终态恢复:仅
Plan Mode 的本地及 device-link 切换与插件确认复用同一内存权限提交队列,由 Host 完成 runtime、落库与失败恢复;renderer 不再另写 DB 或发第二次回滚。原生 Plan 事件只异步登记镜像,不阻塞事件消费和 turn 收尾;落库前核对原账号、绑定 Session 及当前 armed 值,忽略迟到的旧事件。插件授权另同步核对现有稳定 Plan 状态(含未知/切换中),不等同于仅看数据库镜像。普通新输入 IPC 在 send/restart fence 外等已有权限提交完成后才进入发送;内部续跑、steering 与独立停止不等待该队列。上述复用不新增 Plan 代次、持久字段或后台重试,也不承诺跨工具事务。
+插件 `tasks.send` 与排队输入最终 `accept` 同样核对 live Session 的 `stablePlanModeState`;
+DB 中下一条输入的 armed 值为 false 不代表原生执行已退出 Plan。执行态开启、未知或切换中时拒绝;
+路由查询、回执保存后复核同一 Session 对象及已有 Plan generation,变更后不沿用旧授权。
+冷任务仍可入队,但最终接受必须匹配已启动的执行实例。读取、取消和同 requestKey 的回执查询保持原行为。
+
### 委派范围与 Host Auto 审阅
首版保留 Codex 原生 `on-request`、`workspace-write` / `auto_review`。以下范围核验适用于进入 Host 审批的动作;原生常规工作区动作可能直接执行,不承诺每个读取或写入都经过 Host,也不把任务说明当作原生执行隔离。插件 API 的归属、撤权及权限检查保持;同一任务直接 Auto→Ask 仍沿原机制中断当前轮次。卸载仅撤销插件控制并移除包,不保证停止已派发的原生工作;Lead 降权也不承诺立即停止全部 Worker。用户可使用原有任务停止入口。此边界不新增原生沙箱、后台停机重试或另一套权限状态。
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index a2a7176a5c..ac55ed0a01 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -28,6 +28,8 @@ import { fileURLToPath } from 'node:url';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { PiAgent } from '../index.js';
+import { PiRpcProcess } from '../rpc-client.js';
+import * as sessionJsonlScan from '../session-jsonl-scan.js';
import { providerCatalogForPi, BUNDLED_CATALOG } from '@cindy/model-providers';
import { TurnPermissionPolicyUnsupportedError, type AgentDeps, type AgentSessionHandle } from '../../base-agent.js';
import type { AgentEvent } from '../../../types/events.js';
@@ -1509,6 +1511,82 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it.each(['snapshot', 'startup'] as const)(
+ 'runs one read-only plan turn from %s, then restores ordinary tools',
+ { timeout: 60_000 },
+ async (source) => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-plan-turn-'));
+ let handle: AgentSessionHandle | undefined;
+ try {
+ handle = await new PiAgent(buildDeps()).startSession({
+ sessionId: `plan-turn-${source}`, workingDir, model: 'pi-test-model',
+ ...(source === 'startup' ? { planMode: true } : {}),
+ });
+ if (source === 'snapshot') {
+ await handle.setPlanMode!(true);
+ // Desktop consumes the checkbox before dispatching the frozen message.
+ await handle.setPlanMode!(false);
+ }
+ const sendTurn = async (planMode?: boolean) => {
+ const before = seenRequests.length;
+ const done = (async () => {
+ for await (const event of handle!.events()) if (event.type === 'done') break;
+ })();
+ await handle!.send({ type: 'user', content: 'Give a short plan.' },
+ planMode === undefined ? undefined : { planMode });
+ await done;
+ const requests = seenRequests.slice(before);
+ expect(requests).toHaveLength(1);
+ return JSON.parse(requests[0]!.body) as { tools: Array<{ name: string }>; system: unknown };
+ };
+ const planned = await sendTurn(source === 'snapshot' ? true : undefined);
+ expect(planned.tools.map((tool) => tool.name)).toContain('read');
+ expect(planned.tools.map((tool) => tool.name)).not.toContain('write');
+ expect(planned.tools.map((tool) => tool.name)).not.toContain('edit');
+ expect(handle.getPlanMode!()).toBe(false);
+ const ordinary = await sendTurn();
+ expect(ordinary.tools.map((tool) => tool.name)).toContain('write');
+ expect(ordinary.tools.map((tool) => tool.name)).toContain('edit');
+ } finally {
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it('re-syncs native plan execution before the next ordinary message', { timeout: 60_000 }, async () => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-plan-execute-'));
+ let handle: AgentSessionHandle | undefined;
+ try {
+ handle = await new PiAgent(buildDeps()).startSession({
+ sessionId: 'plan-execute', workingDir, model: 'pi-test-model', planMode: true,
+ });
+ const resolver = vi.fn(async (request: { kind: string; questions?: Array<{ question: string }> }) => ({
+ kind: 'ask_user_question',
+ answers: { [request.questions![0]!.question]: 'Execute the plan (track progress)' },
+ }));
+ handle.setInteractionResolver!(resolver as never);
+ scriptedResponses.push(anthropicStreamBody('Plan:\n1. Say hello.'));
+ const before = seenRequests.length;
+ await handle.send({ type: 'user', content: 'Plan a greeting.' });
+ await vi.waitFor(() => expect(seenRequests.length).toBeGreaterThan(before + 1), { timeout: 20_000 });
+ await vi.waitFor(() => expect(handle!.isTurnRunning!()).toBe(false), { timeout: 20_000 });
+ expect(resolver).toHaveBeenCalled();
+ expect(handle.getPlanMode!()).toBe(false);
+ expect(handle.getExecutionPlanMode!()).toBe(false);
+ const next = seenRequests.length;
+ await handle.send({ type: 'user', content: 'An ordinary greeting.' });
+ await vi.waitFor(() => expect(seenRequests.length).toBeGreaterThan(next), { timeout: 20_000 });
+ const request = JSON.parse(seenRequests[next]!.body) as { tools: Array<{ name: string }> };
+ expect(request.tools.map((tool) => tool.name)).toContain('write');
+ await vi.waitFor(() => expect(handle!.isTurnRunning!()).toBe(false), { timeout: 20_000 });
+ } finally {
+ scriptedResponses.length = 0;
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ });
+
it.each(['anthropic-messages', 'openai-completions'] as const)(
'keeps native plan notifications separate from replies using %s',
{ timeout: 60_000 },
@@ -1554,14 +1632,16 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
- it(
- 're-syncs plan mode from pi persisted state on resume (no mirror desync)',
+ it.each([false, true])(
+ 're-syncs plan mode from pi persisted state on resume (scan initially unavailable=%s)',
{ timeout: 60_000 },
- async () => {
+ async (scanUnavailable) => {
const agent = new PiAgent(buildDeps());
const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-plan-resume-cwd-'));
let handle: AgentSessionHandle | null = null;
let resumed: AgentSessionHandle | null = null;
+ let restoreScan = () => {};
+ let restoreRpc = () => {};
try {
handle = await agent.startSession({
sessionId: 'plan-resume-session',
@@ -1583,6 +1663,21 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
await handle.close();
handle = null;
+ if (scanUnavailable) {
+ // Fault only the host's two state-read paths; Pi still restores its
+ // actual plan-mode extension and executes real prompts after recovery.
+ const scan = vi.spyOn(sessionJsonlScan, 'scanPiSessionJsonl').mockResolvedValue(null);
+ const request = PiRpcProcess.prototype.request;
+ const rpc = vi.spyOn(PiRpcProcess.prototype, 'request').mockImplementation(function (this: PiRpcProcess, command, options) {
+ if (command.type === 'get_entries') {
+ return Promise.resolve({ type: 'response', command: 'get_entries', success: false, error: 'scan unavailable' });
+ }
+ return request.call(this, command, options);
+ });
+ restoreScan = () => scan.mockRestore();
+ restoreRpc = () => rpc.mockRestore();
+ }
+
// resume 同一会话:pi 的 plan-mode 扩展自恢复 planModeEnabled=true,新会话的
// planModeActive 必须从 get_entries 校正回 true(而非默认 false),否则 /plan toggle 会锁死。
resumed = await agent.startSession({
@@ -1591,8 +1686,35 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
model: 'pi-test-model',
resumeSessionId: resumeKey,
});
- expect(resumed.getPlanMode?.()).toBe(true);
+ if (scanUnavailable) {
+ expect(resumed.getPlanMode?.()).toBeNull();
+ const requestsBefore = seenRequests.length;
+ await expect(resumed.send({ type: 'user', content: 'continue planning' }))
+ .rejects.toMatchObject({ code: 'TURN_DISPATCH_REJECTED' });
+ expect(seenRequests).toHaveLength(requestsBefore);
+ restoreScan();
+ restoreRpc();
+ for (const expectedPlan of [true, false]) {
+ const before = seenRequests.length;
+ const done = (async () => {
+ for await (const event of resumed!.events()) if (event.type === 'done') break;
+ })();
+ await resumed.send({ type: 'user', content: 'continue the task' });
+ await done;
+ const requests = seenRequests.slice(before);
+ expect(requests).toHaveLength(1);
+ const payload = JSON.parse(requests[0]!.body) as { tools: Array<{ name: string }> };
+ expect(payload.tools.some((tool) => tool.name === 'write')).toBe(!expectedPlan);
+ expect(payload.tools.some((tool) => tool.name === 'edit')).toBe(!expectedPlan);
+ expect(resumed.getPlanMode?.()).toBe(false);
+ expect(resumed.getExecutionPlanMode?.()).toBe(expectedPlan);
+ }
+ } else {
+ expect(resumed.getPlanMode?.()).toBe(true);
+ }
} finally {
+ restoreScan();
+ restoreRpc();
await handle?.close();
await resumed?.close();
rmSync(workingDir, { recursive: true, force: true });
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index 80a76c6377..01c167ddba 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -222,6 +222,7 @@ import { PiAgent } from "../index.js";
import { PiRpcRequestTimeoutError } from "../rpc-client.js";
import {
PiNativeProviderProxyNotReadyError,
+ MAIN_OWNED_SEND_CONTEXT,
type AgentDeps,
type PiNativeProvidersResult,
} from "../../base-agent.js";
@@ -5644,6 +5645,148 @@ describe("Pi provider-aware model routing", () => {
await handle.close();
});
+ it("arms startup plan mode without changing a running resumed Pi turn", async () => {
+ installPlanModeExtension();
+ captured.requestHandler = async (command) => {
+ if (command.type === "get_state") {
+ captured.onEvent?.({ type: "agent_start" });
+ return { success: true, data: { sessionFile: "/mock/s.jsonl", model: { contextWindow: 200_000 } } };
+ }
+ if (command.type === "get_entries") return { success: true, data: { entries: [] } };
+ return { success: true, data: {} };
+ };
+ const handle = await new PiAgent(byomDeps(async () => ({ providers: [], env: {} }))).startSession({
+ sessionId: "plan-resume-busy", workingDir: cwd, model: "local-model", planMode: true,
+ });
+ expect(handle.getPlanMode!()).toBe(true);
+ expect(handle.getExecutionPlanMode!()).toBe(false);
+ expect(captured.requests.some((request) => request.message === "/plan")).toBe(false);
+ await handle.close();
+ });
+
+ it("keeps a consumed plan snapshot active when a late checkbox clear arrives", async () => {
+ installPlanModeExtension();
+ const handle = await new PiAgent(byomDeps(async () => ({ providers: [], env: {} }))).startSession({
+ sessionId: "plan-late-clear", workingDir: cwd, model: "local-model",
+ });
+ await handle.send({ type: "user", content: "plan this" }, { planMode: true });
+ await handle.setPlanMode!(false);
+ expect(handle.getPlanMode!()).toBe(false);
+ expect(handle.getExecutionPlanMode!()).toBe(true);
+ expect(captured.requests.filter((request) => request.message === "/plan")).toHaveLength(1);
+ await handle.close();
+ });
+
+ it.each(["startup", "checkbox"])("preserves %s plan intent after prompt rejection for a snapshot-free retry", async (source) => {
+ installPlanModeExtension();
+ const handle = await new PiAgent(byomDeps(async () => ({ providers: [], env: {} }))).startSession({
+ sessionId: `plan-rejected-retry-${source}`, workingDir: cwd, model: "local-model",
+ planMode: source === "startup",
+ });
+ if (source === "checkbox") await handle.setPlanMode!(true);
+ let rejectPrompt = true;
+ captured.requestHandler = async (command) => command.type === "prompt" && command.message !== "/plan" && rejectPrompt
+ ? { command: "prompt", success: false, error: "prompt rejected before acceptance" }
+ : { success: true, data: {} };
+ const message = { type: "user" as const, content: "must remain read-only" };
+ await expect(handle.send(message)).rejects.toMatchObject({ code: "TURN_DISPATCH_REJECTED" });
+ expect(handle.getPlanMode!()).toBe(true);
+ expect(handle.getExecutionPlanMode!()).toBe(true);
+ rejectPrompt = false;
+ await handle.send(message);
+ expect(handle.getPlanMode!()).toBe(false);
+ expect(handle.getExecutionPlanMode!()).toBe(true);
+ // Retrying must not toggle the native read-only turn back to ordinary mode.
+ expect(captured.requests.filter((request) => request.message === "/plan")).toHaveLength(1);
+ expect(captured.requests.filter((request) => request.message === message.content)).toHaveLength(2);
+ await handle.close();
+ });
+
+ it.each(["pi install npm:fixture-extension", "pi update --all"].flatMap((command) =>
+ ["missing", "sync", "sync-no-intent", "toggle"].map((failure) => ({ command, failure })),
+ ))("rejects $command before mutation when plan setup fails: $failure", async ({ command, failure }) => {
+ if (failure !== "missing") installPlanModeExtension();
+ const mutatePiManagedPackage = vi.fn(async () => ({ changed: true }));
+ const handle = await new PiAgent({
+ ...byomDeps(async () => ({ providers: [], env: {} })), mutatePiManagedPackage,
+ }).startSession({ sessionId: `plan-package-${failure}`, workingDir: cwd, model: "local-model" });
+ captured.requestHandler = async (request) => request.message === "/plan" || request.type === "get_entries"
+ ? { success: false, error: "plan setup failed" }
+ : { success: true, data: {} };
+ if (failure.startsWith("sync")) {
+ // A failed native switch makes the mirror unknown; the send must resync.
+ await expect(handle.setPlanMode!(true)).rejects.toThrow("plan setup failed");
+ }
+ captured.requests = [];
+ await expect(handle.send({ type: "user", content: command }, {
+ ...(failure === "sync-no-intent" ? {} : { planMode: true }),
+ [MAIN_OWNED_SEND_CONTEXT]: { origin: { kind: "desktop" }, rawChannelText: command },
+ })).rejects.toThrow(failure === "missing" ? "extension is unavailable"
+ : failure.startsWith("sync") ? "plan-mode state is unavailable" : "plan setup failed");
+ expect(mutatePiManagedPackage).not.toHaveBeenCalled();
+ expect(captured.requests.filter((request) => request.type === "prompt" && request.message !== "/plan")).toHaveLength(0);
+ await handle.close();
+ });
+
+ it("finishes plan setup before accepting a managed package mutation", async () => {
+ installPlanModeExtension();
+ const order: string[] = [];
+ const mutatePiManagedPackage = vi.fn(async () => {
+ order.push("mutation");
+ return { changed: true };
+ });
+ const handle = await new PiAgent({
+ ...byomDeps(async () => ({ providers: [], env: {} })), mutatePiManagedPackage,
+ }).startSession({ sessionId: "plan-package-order", workingDir: cwd, model: "local-model" });
+ captured.requestHandler = async (request) => {
+ if (request.type === "prompt") order.push(request.message === "/plan" ? "plan" : "receipt");
+ return { success: true, data: {} };
+ };
+ const command = "pi install npm:fixture-extension";
+ await handle.send({ type: "user", content: command }, {
+ planMode: true,
+ [MAIN_OWNED_SEND_CONTEXT]: { origin: { kind: "desktop" }, rawChannelText: command },
+ });
+ expect(order).toEqual(["plan", "mutation", "receipt"]);
+ expect(mutatePiManagedPackage).toHaveBeenCalledOnce();
+ expect(handle.getExecutionPlanMode!()).toBe(true);
+ await handle.close();
+ });
+
+ it("does not dispatch a planned message when the native toggle fails", async () => {
+ installPlanModeExtension();
+ const handle = await new PiAgent(byomDeps(async () => ({ providers: [], env: {} }))).startSession({
+ sessionId: "plan-send-failure", workingDir: cwd, model: "local-model",
+ });
+ captured.requestHandler = async (command) => command.message === "/plan"
+ ? { success: false, error: "toggle failed" }
+ : { success: true, data: {} };
+ await expect(handle.send({ type: "user", content: "must remain read-only" }, { planMode: true }))
+ .rejects.toThrow("toggle failed");
+ expect(captured.requests.some((request) => request.message === "must remain read-only")).toBe(false);
+ expect(handle.getExecutionPlanMode!()).toBeNull();
+ await handle.close();
+ });
+
+ it.each(["startup", "snapshot"])("keeps ordinary sends usable when the unavailable plan extension rejects %s intent", async (source) => {
+ const handle = await new PiAgent(byomDeps(async () => ({ providers: [], env: {} }))).startSession({
+ sessionId: "plan-missing-extension", workingDir: cwd, model: "local-model",
+ planMode: source === "startup",
+ });
+ await expect(handle.send({ type: "user", content: "plan only" }, source === "snapshot" ? { planMode: true } : undefined))
+ .rejects.toThrow("plan-mode extension is unavailable");
+ expect(captured.requests.some((request) => request.message === "plan only")).toBe(false);
+ expect(handle.getPlanMode!()).toBe(source === "startup");
+ expect(handle.getExecutionPlanMode!()).toBe(false);
+ expect(captured.closes).toBe(0);
+ await handle.setPlanMode!(false);
+ await handle.send({ type: "user", content: "ordinary message" });
+ expect(captured.requests.some((request) => request.message === "ordinary message")).toBe(true);
+ expect(captured.requests.some((request) => request.message === "/plan")).toBe(false);
+ expect(captured.closes).toBe(0);
+ await handle.close();
+ });
+
it("keeps plan mode unknown after sync failure and refuses a blind toggle until it can resync", async () => {
installPlanModeExtension();
let entriesAvailable = false;
@@ -5698,6 +5841,54 @@ describe("Pi provider-aware model routing", () => {
await handle.close();
});
+ it.each([true, false])("refuses sends with unknown plan state and recovers persisted=%s without a blind toggle", async (enabled) => {
+ installPlanModeExtension();
+ let entriesAvailable = false;
+ let rejectPrompt = true;
+ captured.requestHandler = async (command) => {
+ if (command.type === "get_state") {
+ return { success: true, data: { sessionFile: "/mock/s.jsonl", model: { contextWindow: 200_000 } } };
+ }
+ if (command.type === "get_entries") {
+ return entriesAvailable
+ ? { success: true, data: { entries: [{ customType: "plan-mode", data: { enabled } }] } }
+ : { success: false, error: "temporary rpc failure" };
+ }
+ if (command.type === "prompt" && rejectPrompt) return { command: "prompt", success: false, error: "prompt rejected" };
+ return { success: true, data: {} };
+ };
+ const handle = await new PiAgent(byomDeps(async () => ({ providers: [], env: {} }))).startSession({
+ sessionId: `plan-unknown-send-${enabled}`, workingDir: cwd, model: "local-model",
+ });
+ const message = { type: "user" as const, content: "continue the task" };
+ try {
+ expect(handle.getPlanMode!()).toBeNull();
+ expect(handle.getExecutionPlanMode!()).toBeNull();
+ await expect(handle.send(message)).rejects.toMatchObject({ code: "TURN_DISPATCH_REJECTED" });
+ expect(captured.requests.filter((request) => request.type === "prompt")).toHaveLength(0);
+ expect(handle.getExecutionPlanMode!()).toBeNull();
+ expect(captured.closes).toBe(0);
+
+ // A later retry recovers the native choice, including an existing plan.
+ entriesAvailable = true;
+ await expect(handle.send(message)).rejects.toThrow("prompt rejected");
+ expect(handle.getPlanMode!()).toBe(enabled);
+ expect(handle.getExecutionPlanMode!()).toBe(enabled);
+ rejectPrompt = false;
+ await handle.send(message);
+ expect(captured.requests.filter((request) => request.message === "/plan")).toHaveLength(0);
+ expect(handle.getPlanMode!()).toBe(false);
+ expect(handle.getExecutionPlanMode!()).toBe(enabled);
+
+ captured.onEvent?.({ type: "agent_end", messages: [] });
+ await handle.send({ type: "user", content: "next ordinary turn" });
+ expect(handle.getExecutionPlanMode!()).toBe(false);
+ expect(captured.requests.filter((request) => request.message === "/plan")).toHaveLength(enabled ? 1 : 0);
+ } finally {
+ await handle.close();
+ }
+ });
+
it("marks plan mode unknown when a toggle transport failure may have happened after execution", async () => {
installPlanModeExtension();
let persistedEnabled = false;
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 9e5671f11f..6e9f36b741 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -3778,7 +3778,7 @@ export class PiAgent extends BaseAgent {
: sessionRuntimeBinaryPath!;
// plan 模式:挂载 pi 自带的 plan-mode example 扩展(随 pi 分发,版本匹配,免 vendoring)。
- // 只在文件存在时 --extension;缺失则 plan 模式静默降级(setPlanMode 时 warn)。
+ // 只在文件存在时 --extension;缺失时拒绝计划请求,普通消息仍可发送。
// 加载本身零副作用:plan 模式默认关,扩展 hook 全早返;仅 /plan 开启后才注入 plan 提示词。
// 远端:扩展随远端 pi 分发(installer 解压整包),路径基于远端二进制。
// 轮 40-w4-t15:远端二进制是 POSIX 路径, 本地是平台路径 —— 按会话远端性
@@ -4996,11 +4996,13 @@ export class PiAgent extends BaseAgent {
};
piSubagentRefreshTimer?.unref?.();
if (localSubagentSupported) void requestPiSubagentRefresh();
- // Cindy 侧对 pi plan 模式的镜像态;setPlanMode 经 /plan toggle 驱动,与 pi 内部
- // planModeEnabled 保持一致(RPC 下 Execute/Refine 选择框被 auto-cancel,pi 不会自行
- // 翻转,故镜像不漂移)。
+ // Native /plan toggles and Execute/Refine continuations share this mirror.
+ // Native continuations re-read persisted state before Host side effects can use it.
let planModeActive: boolean | null = planModeExtAvailable ? null : false;
- let planModeWriteChain: Promise<void> = Promise.resolve();
+ // The checkbox arms the next send; the native flag belongs to the executing turn.
+ let armedPlanMode: boolean | null = null;
+ let planModeRevision = 0;
+ let syncNativePlanMode: (() => void) | undefined;
// proc 构造即 spawn 子进程 —— spawn 参数非法等会**同步**抛。此刻 ctx 已在
// preparePiExtraSpawnConfig 注册、但 handle 尚未交出,close() 不会跑 → 单独
@@ -5563,6 +5565,9 @@ export class PiAgent extends BaseAgent {
transport,
logger: this.deps.logger,
onEvent: (event: PiRpcEvent) => {
+ if (event.type === 'agent_start' && !ctx.pendingHostTurnStartToken) {
+ syncNativePlanMode?.();
+ }
if (event.type === 'agent_start' || event.type === 'agent_settled') {
piAgentLifecycleSequence += 1;
}
@@ -5950,6 +5955,46 @@ export class PiAgent extends BaseAgent {
return readPersistedPlanModeFromEntries();
};
+ syncNativePlanMode = () => {
+ if (!planModeExtAvailable) return;
+ // Execute/Refine can start a native continuation without a host prompt.
+ // Execute exits Plan itself; an old mirror would invert the next /plan.
+ const revision = ++planModeRevision;
+ planModeActive = null;
+ void readPersistedPlanMode().then((enabled) => {
+ if (!closed && revision === planModeRevision) planModeActive = enabled;
+ }).catch(() => { /* Remain unknown; the next control request re-syncs. */ });
+ };
+
+ // Caller holds sessionRpcChain: mode selection and prompt dispatch must be atomic.
+ const applyPlanMode = async (enabled: boolean): Promise<void> => {
+ if (reviewMode) return;
+ if (!planModeExtAvailable) {
+ if (enabled) throw new Error('Pi plan-mode extension is unavailable');
+ return;
+ }
+ planModeRevision += 1;
+ if (planModeActive === null) {
+ planModeActive = await readPersistedPlanMode();
+ if (planModeActive === null) {
+ throw new Error('pi setPlanMode refused: persisted plan-mode state is unavailable');
+ }
+ }
+ if (enabled === planModeActive) return;
+ planModeActive = null; // Host side effects must wait for the native switch to finish.
+ try {
+ const resp = await proc.request({ type: 'prompt', message: '/plan' });
+ if (!resp.success) {
+ throw new Error(`pi setPlanMode(/plan) rejected: ${resp.error ?? 'unknown'}`);
+ }
+ planModeActive = enabled;
+ } catch (error) {
+ // A failed response can follow an executed toggle. Re-read before retrying.
+ planModeActive = null;
+ throw error;
+ }
+ };
+
const readPiUserEntryIdsFromEntries = async (): Promise<Set<string> | null> => {
const response = await proc.request({ type: 'get_entries' });
if (!response.success) return null;
@@ -6093,6 +6138,7 @@ export class PiAgent extends BaseAgent {
imageCount: number,
hasAdditionalContent: boolean,
mainOwnedContext?: MainOwnedSendContext,
+ beforeAccept?: () => Promise<void>,
): Promise<{ text: string; accepted: boolean }> => {
if (!allowPiPackageManagement || imageCount > 0 || hasAdditionalContent) {
return { text, accepted: false };
@@ -6118,6 +6164,7 @@ export class PiAgent extends BaseAgent {
}
}
if (parsed && ('error' in parsed || parsed.action === 'command')) {
+ await beforeAccept?.();
let receipt: Record<string, unknown>;
try {
receipt = 'error' in parsed ? { ok: false, error: parsed.error } : {
@@ -6136,6 +6183,7 @@ export class PiAgent extends BaseAgent {
}
const command = commandText === undefined ? undefined : parsePiManagedPackageCommand(commandText);
if (!command) return { text, accepted: false };
+ await beforeAccept?.();
const uiStrings = resolvePiExtensionUiStrings(this.deps);
let outcome: PiManagedPackageCommandOutcome;
let shouldInvalidateRuntimes = false;
@@ -6348,6 +6396,12 @@ export class PiAgent extends BaseAgent {
});
}
}
+ armedPlanMode = reviewMode ? false : (opts.planMode ?? planModeActive);
+ // Missing optional plan support must not tear down an otherwise usable
+ // session. Keep the armed intent; planned sends will reject before dispatch.
+ if (!reviewMode && planModeExtAvailable && opts.planMode !== undefined && !ctx.isStreaming && !ctx.pendingHostTurnStartToken) {
+ await runExclusivePiRpc(() => applyPlanMode(opts.planMode!));
+ }
} catch (err) {
if (!rpcReadyLogged) {
logPiStartupStage(this.deps.logger, startupTraceId, 'rpc-ready', rpcReadyStartedAt, 'degraded');
@@ -7171,6 +7225,7 @@ export class PiAgent extends BaseAgent {
},
async send(message: UserMessage, sendOpts?: SendOptions): Promise<void> {
+ let requestedPlanTurn = !reviewMode && (sendOpts?.planMode ?? armedPlanMode);
rejectIfCancelled(sendOpts, 'send');
await waitForSessionRpcIdle();
updateRequestPrefs();
@@ -7203,12 +7258,37 @@ export class PiAgent extends BaseAgent {
assertImageInputSupported(images);
setAutoReviewIntent(appendAutoReviewUserIntent(priorAutoReviewIntent(), message.content, sendOpts), { authority: autoReviewContext() });
reviewIntentUpdated = true;
- const managedPackageRoute = await routeManagedPackageCommand(
+ const applyRequestedPlanMode = async () => {
+ if (requestedPlanTurn === null) {
+ // A failed startup/resume scan is not ordinary-mode intent. Recover
+ // the native choice before either a prompt or a host mutation.
+ const revision = ++planModeRevision;
+ planModeActive = null;
+ const restoredPlanMode = await readPersistedPlanMode();
+ if (restoredPlanMode === null || revision !== planModeRevision) {
+ throw new TurnDispatchRejectedError('Pi plan-mode state is unavailable before prompt dispatch');
+ }
+ planModeActive = restoredPlanMode;
+ requestedPlanTurn = restoredPlanMode;
+ if (armedPlanMode === null) armedPlanMode = restoredPlanMode;
+ }
+ if (ctx.isStreaming && requestedPlanTurn !== planModeActive) {
+ throw new TurnDispatchRejectedError('Cannot change Pi plan mode while a turn is active');
+ }
+ await applyPlanMode(requestedPlanTurn);
+ };
+ const managedPackageRoute = await runExclusivePiRpc(() => routeManagedPackageCommand(
text,
images.length,
Array.isArray(message.content) && message.content.some((block) => block.type !== 'text'),
sendOpts?.[MAIN_OWNED_SEND_CONTEXT],
- );
+ async () => {
+ // Native plan setup can fail. Finish it before a host command's
+ // irreversible acceptance boundary, while holding the RPC chain.
+ await applyRequestedPlanMode();
+ rejectIfCancelled(sendOpts, 'send');
+ },
+ ));
text = managedPackageRoute.text;
// Starting a host-owned package mutation is this transaction's
// acceptance boundary. A Stop that races after that point must not
@@ -7309,6 +7389,12 @@ export class PiAgent extends BaseAgent {
throw new TurnDispatchRejectedError('Pi RPC is unavailable before prompt dispatch');
}
}
+ // Accepted host commands already passed plan setup before the
+ // mutation. A later toggle failure must not make them replayable.
+ if (!managedPackageRoute.accepted) {
+ await applyRequestedPlanMode();
+ rejectIfCancelled(sendOpts, 'send');
+ }
const pendingTurnStartToken = markPiHostTurnStartPending(ctx);
promptRequestStarted = true;
const resp = await proc.request(command, {
@@ -7319,6 +7405,14 @@ export class PiAgent extends BaseAgent {
refreshTimeoutOnEvent: (event) =>
PI_PROMPT_ACCEPTANCE_PROGRESS_EVENTS.has(event.type),
});
+ // Only consume the one-shot choice after acceptance. A confirmed
+ // rejection must preserve it for a retry without a message snapshot.
+ // Keep this in the RPC chain so a newer checkbox choice cannot be
+ // consumed by an older prompt's acceptance response.
+ if ((resp.success || managedPackageRoute.accepted) && requestedPlanTurn && armedPlanMode) {
+ armedPlanMode = false;
+ queue.push({ type: 'plan_mode_changed', data: { enabled: false }, source: 'pi' });
+ }
return { resp, pendingTurnStartToken };
});
firstModelRequestStatus = resp.success ? 'ok' : 'degraded';
@@ -7898,42 +7992,25 @@ export class PiAgent extends BaseAgent {
async setPlanMode(enabled: boolean): Promise<void> {
if (reviewMode) return;
- if (!planModeExtAvailable) {
- deps.logger.warn('pi setPlanMode ignored: plan-mode extension not available');
- return;
- }
- // /plan 是 toggle,必须把全部调用串行;否则两个并发“开启”都会看到 false,
- // 连续 toggle 两次后实际回到关闭。未知镜像先重新读取,无法证明方向就拒绝,
- // 不能把 sync 失败伪报成 false 后盲切。
- const run = planModeWriteChain.then(async () => {
- if (planModeActive === null) {
- planModeActive = await readPersistedPlanMode();
- if (planModeActive === null) {
- throw new Error('pi setPlanMode refused: persisted plan-mode state is unavailable');
+ await runExclusivePiRpc(async () => {
+ // Consuming/arming the checkbox must not change an in-flight turn's tools.
+ if (!ctx.isStreaming && !ctx.pendingHostTurnStartToken) {
+ try {
+ await applyPlanMode(enabled);
+ } catch (error) {
+ armedPlanMode = planModeActive;
+ throw error;
}
}
- if (enabled === planModeActive) return;
- let resp: Awaited<ReturnType<typeof proc.request>>;
- try {
- resp = await runExclusivePiRpc(() => proc.request({ type: 'prompt', message: '/plan' }));
- } catch (error) {
- // transport 超时/断线不能证明命令未到达 Pi;它可能已经完成 toggle。
- // 旧 boolean 此后不再可信,下次调用必须先从持久 entry 重同步。
- planModeActive = null;
- throw error;
- }
- if (!resp.success) {
- // RPC 失败响应也不拿旧镜像继续猜 toggle 方向,统一回到未知态。
- planModeActive = null;
- throw new Error(`pi setPlanMode(/plan) rejected: ${resp.error ?? 'unknown'}`);
- }
- planModeActive = enabled;
+ armedPlanMode = enabled;
});
- planModeWriteChain = run.catch(() => {});
- return run;
},
getPlanMode(): boolean | null {
+ return armedPlanMode;
+ },
+
+ getExecutionPlanMode(): boolean | null {
return planModeActive;
},
@@ -7999,8 +8076,9 @@ export class PiAgent extends BaseAgent {
// 状态可能与旧闭包 planModeActive 不一致, 不校正会让 UI/DB 残留旧分支
// 状态, 且下次 setPlanMode 因 enabled===planModeActive 直接 no-op。
const planModeAfterFork = planModeExtAvailable ? await readPersistedPlanMode() : null;
- if (planModeAfterFork !== null && planModeAfterFork !== planModeActive) {
+ if (planModeAfterFork !== null && (planModeAfterFork !== planModeActive || planModeAfterFork !== armedPlanMode)) {
planModeActive = planModeAfterFork;
+ armedPlanMode = planModeAfterFork;
queue.push({
type: 'plan_mode_changed',
data: { enabled: planModeAfterFork },
@@ -8010,6 +8088,7 @@ export class PiAgent extends BaseAgent {
// 新分支读不到 plan entry(异常/旧格式):不能假定沿用旧分支的开启态,
// 置回未开启并通知(保守, 用户可再开)。
planModeActive = false;
+ armedPlanMode = false;
queue.push({
type: 'plan_mode_changed',
data: { enabled: false },