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(permissions): 保留 Plan 执行态与媒体交接边界

liugaoweic595816f6c19
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 3b393e9202..8481d6061a 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -61,6 +61,7 @@ import { createMakeToolchainEnvironment } from '../cindy-make/toolchainEnvironme
import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
import { getWorkerLink, updateWorkerStatus } from '../localDb/orcaTeamStore.js';
import { cleanupSessionTempAttachments } from '../maker-ipc/normalizeAttachments.js';
+import { resolveGhostFsSessionSnapshot } from '../maker-ipc/ghostFsSessionSnapshot.js';
import { markKnownOrcaWorkerSession } from '../maker-ipc/orcaManualInterrupt.js';
import { markOrcaMcpHydratedIfNeeded } from '../maker-ipc/orcaMcpHydrationCache.js';
import { preparePersistedOrcaSessionStart } from '../maker-ipc/orcaSessionStartOptions.js';
@@ -929,17 +930,13 @@ export function getMaker(): Maker {
if (!sessionInstanceId) return null;
const session = _maker?.getSession(sessionId);
if (!session || session.instanceId !== sessionInstanceId) return null;
- const permission = session.stablePermissionModeState;
- if (!permission) return null;
+ const snapshot = resolveGhostFsSessionSnapshot((id) => _maker?.getSession(id), sessionId, sessionInstanceId);
return {
- permissionMode: permission.mode,
+ permissionMode: session.stablePermissionModeState?.mode ?? null,
remoteHostId: session.remoteHostId,
- reviewAction: async (action: import('@cindy/maker-core').ReviewableAction) => {
- const decision = await session.reviewHostPermissionAction(action);
- return _maker?.getSession(sessionId) === session
- ? decision
- : { verdict: 'block' as const, reason: 'The task instance changed during review.' };
- },
+ isCurrent: () => !!snapshot && !snapshot.planModeEnabled && snapshot.permissionMode !== 'plan'
+ && snapshot.isCurrent?.() === true,
+ reviewAction: snapshot?.reviewAction,
};
},
};
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 f185b412e3..2070a3e16e 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -2122,6 +2122,52 @@ describe('Full Access 插件文件交接', () => {
describe('Host Auto review', () => {
+ it.each(['bypassPermissions', 'auto', 'ask'] as const)('%s rejects media reveal and file handoff with unavailable Plan authority', async (permissionMode) => {
+ liveGrantStateMock.mockReturnValue({ permissionMode, remoteHostId: null, isCurrent: () => false });
+ const file = path.join(outsideDir, `plan-${permissionMode}.png`);
+ fs.writeFileSync(file, 'png');
+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+ callCindyMediaMock.mockResolvedValue({ ok: true, url, local_path: file, mime_type: 'image/png' });
+ const deps = makeDeps('claude-code', `plan-${permissionMode}`);
+ expect(await deps.callMedia?.({ action: 'resolve_local_path', url })).toMatchObject({ ok: false, errorCode: 'LOCAL_PATH_REVEAL_DENIED' });
+ expect(await deps.callGhostTool({ ghostId: 'art', tool: 'run', args: {}, attachments: [file] })).toMatchObject({ ok: false });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
+ it.each(['auto', 'ask'] as const)('%s cannot return media or hand off files after captured authority changes during approval', async (permissionMode) => {
+ const file = path.join(outsideDir, `late-plan-${permissionMode}.png`);
+ fs.writeFileSync(file, 'png');
+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+ callCindyMediaMock.mockResolvedValue({ ok: true, url, local_path: file, mime_type: 'image/png' });
+ for (const kind of ['media', 'handoff']) {
+ let current = true;
+ liveGrantStateMock.mockReturnValue({ permissionMode, remoteHostId: null, isCurrent: () => current,
+ reviewAction: async () => { current = false; return { verdict: 'allow' }; },
+ });
+ confirmRequestMock.mockImplementation(async () => { current = false; return { confirmed: true, allowDirs: false }; });
+ const deps = makeDeps('pi', `late-plan-${permissionMode}-${kind}`);
+ const result = kind === 'media'
+ ? await deps.callMedia?.({ action: 'resolve_local_path', url })
+ : await deps.callGhostTool({ ghostId: 'art', tool: 'run', args: {}, attachments: [file] });
+ expect(result).toMatchObject({ ok: false });
+ expect(result).not.toHaveProperty('local_path');
+ }
+ expect(dispatchMock).not.toHaveBeenCalled();
+ });
+
+ it('rechecks media authority at the final path return after the Full Access shortcut', async () => {
+ let current = true;
+ liveGrantStateMock.mockImplementation(() => {
+ queueMicrotask(() => { current = false; });
+ return { permissionMode: 'bypassPermissions', remoteHostId: null, isCurrent: () => current };
+ });
+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+ callCindyMediaMock.mockResolvedValue({ ok: true, url, local_path: process.execPath, mime_type: 'image/png' });
+ expect(await makeDeps('codex', 'late-full-media').callMedia?.({ action: 'resolve_local_path', url })).toMatchObject({ ok: false, errorCode: 'LOCAL_PATH_REVEAL_DENIED' });
+ expect(confirmRequestMock).not.toHaveBeenCalled();
+ });
+
it.each(['claude-code', 'codex', 'pi'] as const)('%s media reveal follows Full access and a later switch to Ask', async (agentKind) => {
let permissionMode = 'bypassPermissions';
const reviewAction = vi.fn();
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index e19e0b5ee8..443ff74323 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -183,6 +183,8 @@ async function packForgeSource(
export interface GhostGrantLiveSessionState {
permissionMode: PermissionMode | null;
remoteHostId: string | null;
+ /** Includes the captured permission/Plan generations and forbids active or unknown Plan. */
+ isCurrent?: () => boolean;
reviewAction?: (action: ReviewableAction) => Promise<AutoReviewDecision>;
}
@@ -390,9 +392,14 @@ async function requestGrantConfirm(params: {
| { ok: true; approvalSource: GhostGrantApprovalSource; allowDirs?: boolean }
| { ok: false; message: string }
> {
+ let isCurrent: (() => boolean) | undefined;
+ const expired = () => isCurrent?.() === false;
+ const denied = { ok: false as const, message: 'Task or Plan permissions changed; retry with the current scope.' };
if (params.sessionId && params.sessionInstanceId && params.getLiveSessionGrantState) {
try {
const live = params.getLiveSessionGrantState(params.sessionId, params.sessionInstanceId);
+ isCurrent = live?.isCurrent;
+ if (expired()) return denied;
// 远程会话的 workingDir 是另一台机器上的路径。即使档位为 Full Access,
// 也不能据此静默读取本机同名/任意路径;保留原确认边界。
if (live?.permissionMode === 'bypassPermissions' && !live.remoteHostId) {
@@ -410,6 +417,7 @@ async function requestGrantConfirm(params: {
lane: params.lane,
files: params.items.map(({ absPath, size, mimeType, isDirectory }) => ({ absPath, size, mimeType, isDirectory })),
}, live.remoteHostId ? 'These are files on the controller, NOT the remote task filesystem.' : undefined));
+ if (expired()) return denied;
if (decision.verdict === 'allow') {
log.info('ghost grant: AI approved outside-workdir handoff', { ghostId: params.ghostId, lane: params.lane, grantSource: 'auto-review' });
return { ok: true, approvalSource: 'auto-review' };
@@ -426,6 +434,7 @@ async function requestGrantConfirm(params: {
});
}
}
+ if (expired()) return denied;
const bridge = getGhostGrantConfirmBridge();
if (!bridge) {
return {
@@ -447,6 +456,7 @@ async function requestGrantConfirm(params: {
lane: params.lane,
items: params.items,
});
+ if (expired()) return denied;
if (decision.confirmed) {
return { ok: true, approvalSource: 'user', allowDirs: decision.allowDirs };
}
@@ -470,7 +480,11 @@ async function requestMediaPathRevealConfirm(params: {
getLiveSessionGrantState?: CindyGhostsHostDeps['getLiveSessionGrantState'];
absPath: string;
mimeType: string;
-}): Promise<{ ok: true } | { ok: false; errorCode: string; message: string }> {
+}): Promise<{ ok: true; isCurrent?: () => boolean } | { ok: false; errorCode: string; message: string }> {
+ let isCurrent: (() => boolean) | undefined;
+ const expired = () => isCurrent?.() === false;
+ const denied = { ok: false as const, errorCode: 'LOCAL_PATH_REVEAL_DENIED',
+ message: 'Task or Plan permissions changed; retry with the current scope.' };
if (!params.sessionId) {
return {
ok: false,
@@ -481,14 +495,17 @@ async function requestMediaPathRevealConfirm(params: {
if (params.sessionInstanceId && params.getLiveSessionGrantState) {
try {
const live = params.getLiveSessionGrantState(params.sessionId, params.sessionInstanceId);
+ isCurrent = live?.isCurrent;
+ if (expired()) return denied;
if (live?.permissionMode === 'bypassPermissions' && !live.remoteHostId) {
- return { ok: true };
+ return { ok: true, isCurrent };
}
if (live?.permissionMode === 'auto' && live.reviewAction) {
const decision = await live.reviewAction(toolAutoReviewAction('cindy_media.resolve_local_path', {
path: params.absPath, mimeType: params.mimeType,
}, 'Return the controller local path of this managed media to the agent.'));
- if (decision.verdict === 'allow') return { ok: true };
+ if (expired()) return denied;
+ if (decision.verdict === 'allow') return { ok: true, isCurrent };
if (decision.verdict === 'block') return {
ok: false, errorCode: 'LOCAL_PATH_REVEAL_DENIED', message: decision.reason ?? 'Automatic review denied revealing this path.',
};
@@ -498,6 +515,7 @@ async function requestMediaPathRevealConfirm(params: {
// must reach the existing confirmation path, never disclose the path.
}
}
+ if (expired()) return denied;
const bridge = getGhostGrantConfirmBridge();
if (!bridge) {
return {
@@ -531,7 +549,8 @@ async function requestMediaPathRevealConfirm(params: {
},
],
});
- if (decision.confirmed) return { ok: true };
+ if (expired()) return denied;
+ if (decision.confirmed) return { ok: true, isCurrent };
return {
ok: false,
errorCode: 'LOCAL_PATH_REVEAL_DENIED',
@@ -1406,6 +1425,10 @@ export function getCindyGhostsMcpDeps(
mimeType,
});
if (!confirmed.ok) return confirmed;
+ if (confirmed.isCurrent?.() === false) return {
+ ok: false, errorCode: 'LOCAL_PATH_REVEAL_DENIED',
+ message: 'Task or Plan permissions changed; retry with the current scope.',
+ };
}
if (request.action !== 'resolve_local_path' && result.ok !== false && sessionId) {
// Core 结果返回给当前 Agent 前先同步挂到本会话。后续消息落库钩子仍会
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index c1278dfd28..a6965df2c3 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -306,6 +306,9 @@
也不得跳过 Auto 审阅。审批期间实例、权限或调用归属失效时,旧 allow 不可执行。
Plan 与操作审批档位正交:Host 副作用须先检查实时 Plan 状态,未知或切换中拒绝;
Plan 切换代次也参与审批后和落盘前复核,不能以数据库镜像或切回原状态恢复旧授权。
+ 一次性 Plan 的 UI 开关在发送后熄灭,不代表当前 Plan 回合结束;授权判定使用 Provider
+ 的执行态,不能只读下一轮开关。Claude Code 本地/SSH 的 Full Access 短路同样不能
+ 放行当前 Plan 回合里的非只读工具;显式批准计划后才恢复底层操作审批档位。
这不扩大本轮来源/执行范围、不改变跨主机路径归属,不替用户填写 Setup、OAuth、Secret
等必要信息,也不改变第 3.1 节的安装/更新策略。自主面板或后台调用不得借用前台会话权限。
实现与回归见 [Session.reviewHostPermissionAction](../../packages/maker-core/src/session.ts)、
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index b32e75a2da..3ded826938 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -2266,6 +2266,9 @@ export interface AgentSessionHandle {
/** 当前 maker 进程内记录的计划模式状态;不支持的 agent 不实现。 */
getPlanMode?(): boolean | null;
+ /** Execution authority, including an active one-shot Plan turn after the UI toggle is consumed. */
+ getExecutionPlanMode?(): boolean | null;
+
/**
* 把当前会话导出成 HTML 文件,返回写入的绝对路径。
* `outputPath` 省略时由 agent 决定默认落盘位置。仅 Capabilities.sessionHtmlExport
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
index c5b3246b14..620bfd8056 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts
@@ -1305,6 +1305,27 @@ describe('fail-closed still precedes the MCP policy', () => {
});
describe('remote sessions share the same permission semantics', () => {
+ it('remote Full Access respects the active Plan turn until explicit plan approval', async () => {
+ const { handle, onApprovalRequest, seen } = await startRemoteSession(() => 'auto-approve', {
+ permissionMode: 'bypassPermissions',
+ attachResolver: (req) => req.kind === 'plan_review'
+ ? { kind: 'plan_review', behavior: 'allow' } : { kind: 'permission', behavior: 'allow' },
+ });
+ await handle.setPlanMode!(true);
+ await handle.send({ type: 'user', content: 'Plan the change.' });
+ expect(handle.getPlanMode?.()).toBe(false);
+ expect(handle.getExecutionPlanMode?.()).toBe(true);
+ for (const toolName of ['Write', 'Bash', 'mcp__cindy_contacts__call_tool']) {
+ expect(await onApprovalRequest({ requestId: `plan-${toolName}`, kind: 'permission', toolName, input: {} })).toMatchObject({ behavior: 'deny' });
+ }
+ expect(await onApprovalRequest({ requestId: 'plan-read', kind: 'permission', toolName: 'Read', input: {} })).toMatchObject({ behavior: 'allow' });
+ expect(seen).toHaveLength(0);
+ expect(await onApprovalRequest({ requestId: 'plan-exit', kind: 'plan_review', plan: 'Apply the change.' })).toMatchObject({ behavior: 'allow' });
+ expect(handle.getExecutionPlanMode?.()).toBe(false);
+ expect(await onApprovalRequest({ requestId: 'plan-done', kind: 'permission', toolName: 'Write', input: {} })).toMatchObject({ behavior: 'allow' });
+ await handle.close();
+ });
+
/** 起一个远端会话并拿到 daemon 侧的 approval 回调。 */
async function startRemoteSession(
policy: (context: McpToolApprovalContext) => McpToolApprovalPolicy,
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
index 5f02b7a0b1..1345b1790d 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
@@ -293,6 +293,32 @@ describe('ClaudeCodeAgent plan mode', () => {
await handle.close();
});
+ it('Full Access cannot bypass an active one-shot Plan turn, but resumes after plan approval', async () => {
+ const { handle, queryOptions } = await startPlanSession(true, {}, 'bypassPermissions');
+ const resolver = vi.fn(async () => ({ kind: 'plan_review' as const, behavior: 'allow' as const }));
+ handle.setInteractionResolver(resolver);
+ await handle.send({ type: 'user', content: 'Plan the change.' });
+ expect(handle.getPlanMode?.()).toBe(false);
+ expect(handle.getExecutionPlanMode?.()).toBe(true);
+ for (const tool of ['Write', 'Bash', 'mcp__cindy__ghost_call']) {
+ expect(await queryOptions.canUseTool!(tool, {}, { toolUseID: `plan-${tool}` })).toMatchObject({ behavior: 'deny' });
+ }
+ expect(await queryOptions.canUseTool!('Read', {}, { toolUseID: 'plan-read' })).toMatchObject({ behavior: 'allow' });
+ expect(resolver).not.toHaveBeenCalled();
+ expect(await queryOptions.canUseTool!('ExitPlanMode', { plan: 'Apply the change.' }, { toolUseID: 'plan-exit' })).toMatchObject({ behavior: 'allow' });
+ expect(handle.getExecutionPlanMode?.()).toBe(false);
+ expect(await queryOptions.canUseTool!('Write', {}, { toolUseID: 'after-plan-write' })).toMatchObject({ behavior: 'allow' });
+ await handle.close();
+ });
+
+ it('arming the next Plan turn does not rewrite the current ordinary Full Access turn', async () => {
+ const { handle, queryOptions } = await startPlanSession(false, {}, 'bypassPermissions');
+ await handle.send({ type: 'user', content: 'Apply the approved change.' });
+ await handle.setPlanMode!(true);
+ expect(await queryOptions.canUseTool!('Write', {}, { toolUseID: 'current-write' })).toMatchObject({ behavior: 'allow' });
+ await handle.close();
+ });
+
it('passes a session-stable copy of host-owned allowedTools to the local SDK query', async () => {
const source = ['mcp__cindy__ghost_list', 'mcp__cindy_memory__list_tools'];
const { handle, queryOptions } = await startPlanSession(false, {
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 829e6cd86f..f326e7d1a9 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -2164,6 +2164,9 @@ export class ClaudeCodeAgent extends BaseAgent {
: 'This downstream source was not selected.',
};
}
+ if (isPlanToolBlocked(toolName)) {
+ return { behavior: 'deny', message: 'The current Plan turn is read-only.' };
+ }
if (mutablePermissionMode === 'bypassPermissions' && !forceTurnConfirmation(toolName, input)) {
return { behavior: 'allow', updatedInput: input };
}
@@ -2234,6 +2237,9 @@ export class ClaudeCodeAgent extends BaseAgent {
// cast 破 TS 收窄:TS 不建模 await 期间经 setPermissionMode 闭包的重赋值,会把此处
// mutablePermissionMode 仍视为 'auto';运行期它确实可能已变,故按 union 类型现读。
const modeAfterReview = mutablePermissionMode as PermissionMode;
+ if (isPlanToolBlocked(toolName)) {
+ return { behavior: 'deny', message: 'The current Plan turn is read-only.' };
+ }
if (modeAfterReview === 'bypassPermissions') {
if (turnPolicyForcePrompt) {
return { behavior: 'deny', message: 'Permission mode changed; retry within the authorized turn scope.' };
@@ -2295,6 +2301,9 @@ export class ClaudeCodeAgent extends BaseAgent {
{ turnPolicyForcePrompt, directorySensitive: directorySensitivePermission },
);
notifyIfAutoReviewConfirmUndelivered(unavailableHandoff, decision);
+ if (isPlanToolBlocked(toolName)) {
+ return { behavior: 'deny', message: 'The current Plan turn is read-only.' };
+ }
if (decision.kind !== 'permission') {
log.warn('permission got mismatched decision', { tool: toolName, decKind: decision.kind });
return { behavior: 'deny', message: 'resolver kind mismatch' };
@@ -2604,6 +2613,12 @@ export class ClaudeCodeAgent extends BaseAgent {
*/
const currentTurnSdkPermissionMode = (): SdkPermissionMode =>
planTurnActive ? 'plan' : toSdkPermissionMode(mutablePermissionMode);
+ // Only the current SDK/turn state applies here; arming the next message must
+ // not turn an ordinary in-flight turn into a Plan turn. Keep other modes on
+ // their existing SDK/MCP approval path; Full Access is not a Plan override.
+ const isPlanToolBlocked = (toolName: string): boolean =>
+ mutablePermissionMode === 'bypassPermissions'
+ && (planTurnActive || sdkInPlanMode) && !isReadOnlyClaudeTool(toolName);
// Fast 模式运行时态:启动取 opts.fastMode 快照,setFastMode 覆盖。buildSettings 每次读最新值;
// host 只在「该 model 支持 + 走官方供应商」时才传 true(renderer 配置门控),agent 忠实消费。
let mutableFastMode = opts.fastMode === true;
@@ -3364,6 +3379,8 @@ export class ClaudeCodeAgent extends BaseAgent {
return { kind: 'plan_review', behavior: 'deny', reason: 'resolver kind mismatch' };
}
if (decision.behavior === 'allow') {
+ planTurnActive = false;
+ sdkInPlanMode = false;
appendActiveCapabilitySelectionText(
capabilitySelectionAddedByPlanEdit(
this.deps.capabilityRouting,
@@ -3412,6 +3429,9 @@ export class ClaudeCodeAgent extends BaseAgent {
};
}
// Auto allow/block do not need UI, including MCP operations.
+ if (isPlanToolBlocked(remoteToolName)) {
+ return { kind: 'permission', behavior: 'deny', reason: 'The current Plan turn is read-only.' };
+ }
const canReviewRemoteWithoutUi = mutablePermissionMode === 'auto';
if (!interactionResolver && !canReviewRemoteWithoutUi) {
if (isReadOnlyClaudeTool(remoteToolName)) {
@@ -3468,6 +3488,9 @@ export class ClaudeCodeAgent extends BaseAgent {
'linux',
);
const modeAfterReview = mutablePermissionMode as PermissionMode;
+ if (isPlanToolBlocked(remoteToolName)) {
+ return { kind: 'permission', behavior: 'deny', reason: 'The current Plan turn is read-only.' };
+ }
if (modeAfterReview === 'bypassPermissions') {
return remoteTurnPolicyForcePrompt
? { kind: 'permission', behavior: 'deny', reason: 'Permission mode changed; retry within the authorized turn scope.' }
@@ -3523,6 +3546,9 @@ export class ClaudeCodeAgent extends BaseAgent {
return { kind: 'permission', behavior: 'deny', reason: 'approval_timeout' };
}
notifyIfAutoReviewConfirmUndelivered(remoteUnavailableHandoff, decision);
+ if (isPlanToolBlocked(remoteToolName)) {
+ return { kind: 'permission', behavior: 'deny', reason: 'The current Plan turn is read-only.' };
+ }
if (decision.kind !== 'permission') {
return { kind: 'permission', behavior: 'deny', reason: 'resolver kind mismatch' };
}
@@ -6887,6 +6913,10 @@ export class ClaudeCodeAgent extends BaseAgent {
return mutablePlanMode;
},
+ getExecutionPlanMode() {
+ return mutablePlanMode || planTurnActive || sdkInPlanMode;
+ },
+
async setExtraDirs(newDirs: string[]) {
if (reviewMode) return;
// 只覆盖 closure。SDK 没有运行时 setAdditionalDirectories 入口, 但 buildQuery
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 5c62f9c046..45ceee863b 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -27478,6 +27478,7 @@ describe('CodexAgent plan mode', () => {
expect(params.collaborationMode).toEqual({ mode: 'plan', settings: PLAN_SETTINGS });
// 一次性语义: send 消耗武装态, 勾选自动熄灭(本轮循环由 planCycleActive 继续)。
expect(handle.getPlanMode?.()).toBe(false);
+ expect(handle.getExecutionPlanMode?.()).toBe(true);
await handle.close();
// 常规会话逐字节不变: 不携带 collaborationMode 字段。
@@ -28214,6 +28215,7 @@ describe('CodexAgent plan mode', () => {
// app-server 未接受 plan turn/start 前, thread history 里还没有 Plan Mode marker。
await handle.send({ type: 'user', content: 'make a plan' });
expect(handle.getPlanMode?.()).toBe(false);
+ expect(handle.getExecutionPlanMode?.()).toBe(false);
await handle.send({ type: 'user', content: 'just do it' });
const [, params] = turnStartCalls(host)[1] as [string, Record<string, unknown>];
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 8e2cc92393..f6e7ebe5b9 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -13497,6 +13497,10 @@ export class CodexAgent extends BaseAgent {
return mutablePlanMode;
},
+ getExecutionPlanMode() {
+ return mutablePlanMode || planCycleActive || currentTurnPlanModeActive;
+ },
+
async setFastMode(enabled: boolean) {
if (reviewMode) return;
// 去重以"fast 是否开启"为准: undefined(未覆盖) / null / 'default' 都视为未开,
diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.ts
index 0f052e048c..2d7a17e0e3 100644
--- a/packages/maker-core/src/session.close.test.ts
+++ b/packages/maker-core/src/session.close.test.ts
@@ -418,7 +418,7 @@ describe('Session close lifecycle', () => {
describe('Host automatic review lifecycle', () => {
- function setup(agentKind: 'pi' | 'codex' = 'pi', permissionMode: 'auto' | 'ask' | 'bypassPermissions' = 'auto') {
+ function setup(agentKind: 'pi' | 'codex' | 'claude-code' = 'pi', permissionMode: 'auto' | 'ask' | 'bypassPermissions' = 'auto') {
const events = createAsyncQueue<AgentEvent>();
let running = false;
const reviewGate = createDeferred();
@@ -450,6 +450,18 @@ describe('Host automatic review lifecycle', () => {
return { session, handle, review, reviewGate, closeGate, modeGate, planGate, setProviderPlanMode: (value: boolean | null) => { planMode = value; }, emit };
}
const action = { kind: 'other' as const, description: 'plugin file handoff' };
+ it('uses execution Plan authority after the one-shot UI toggle has been consumed', async () => {
+ const { session, handle, closeGate } = setup('claude-code', 'bypassPermissions');
+ expect(session.getPlanMode()).toBe(false);
+ for (const active of [true, null]) {
+ handle.getExecutionPlanMode = () => active;
+ expect(await session.reviewHostPermissionAction(action)).toMatchObject({ verdict: 'block' });
+ }
+ handle.getExecutionPlanMode = () => false;
+ expect(await session.reviewHostPermissionAction(action)).toMatchObject({ verdict: 'allow' });
+ closeGate.resolve();
+ await session.close();
+ });
it('does not invalidate Host authority for a no-op Plan update', async () => {
const { session, closeGate } = setup();
const before = session.stablePlanModeState;
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 1e37301b22..d47371d820 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -1492,7 +1492,9 @@ export class Session {
/** Host side effects must not use an unknown or in-flight Plan state. */
get stablePlanModeState(): { enabled: boolean; generation: number } | null {
if (this.status !== 'active' || this.terminationStarted || this.planModeChangesInFlight > 0) return null;
- const enabled = this.capabilities.planMode?.supported ? this.getPlanMode() : false;
+ const enabled = this.capabilities.planMode?.supported
+ ? (this.handle.getExecutionPlanMode ? this.handle.getExecutionPlanMode() : this.getPlanMode())
+ : false;
return enabled === null ? null : { enabled, generation: this.planModeGeneration };
}