Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(permissions): 修复插件授权热切换竞态
liugaowei628dbdcb3a5f
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.tsindex 65702f9078..57fd831c9a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts@@ -7,8 +7,10 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';+import { Session } from '@cindy/maker-core';import { GhostFsSlot, validateFsRelPath, workdirWriteVerdict, type FsSlotDeps, type FsSessionSnapshot } from '../fsSlot.js';+import { resolveGhostFsSessionSnapshot } from '../../maker-ipc/ghostFsSessionSnapshot.js';import { GHOST_FS_WRITE_MAX_BYTES, type InstalledGhost } from '../../../shared/ghost.js';const GHOST_ID = 'test-ghost';@@ -86,6 +88,27 @@ function makeHarness(dataRoot: string, overrides: HarnessOverrides = {}) {return { slot: new GhostFsSlot(deps), confirmCalls };}+/** Real Session authority with an in-memory provider, so the production resolver is exercised. */+function makeLiveSession(workDir: string, permissionMode: 'auto' | 'ask' | 'bypassPermissions') {+ let planMode: boolean | null = false;+ 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: 'provider-session', agentKind: 'pi', model: 'test',+ async *events() { await closed; },+ async close() { close(); },+ setInteractionResolver() {},+ getPlanMode: () => planMode,+ setPlanMode: async (enabled: boolean) => { planMode = enabled; },+ reviewAutoPermissionAction: vi.fn(async () => ({ verdict: 'allow' as const })),+ };+ const session = new Session({ id: 'sess-1', sessionInstanceId: 'instance-1', agentKind: 'pi', workDir,+ permissionMode, handle: handle as never, capabilities: { planMode: { supported: true } } as never, logger,+ });+ return { session, handle, setProviderPlan: (enabled: boolean | null) => { planMode = enabled; } };+}+describe('workdirWriteVerdict(权限映射表)', () => {it('免批模式直写,逐条模式确认,plan 拒,未知模式保守确认', () => {expect(workdirWriteVerdict('acceptEdits', false)).toBe('allow');@@ -443,6 +466,53 @@ describe('GhostFsSlot', () => {expect(confirmCalls).toHaveLength(1);});+ it.each(['auto', 'ask', 'bypassPermissions'] as const)('workdir %s honors live Plan even when the database mirror says false', async (mode) => {+ const { session, handle, setProviderPlan } = makeLiveSession(workdir, mode);+ const { slot, confirmCalls } = makeHarness(dataRoot, {+ session: { workingDir: workdir, permissionMode: mode, planModeEnabled: false, remoteHostId: null },+ });+ slot.setSessionSnapshotResolver(async (id, instance) => resolveGhostFsSessionSnapshot(() => session, id, instance));+ try {+ for (const enabled of [true, null]) {+ setProviderPlan(enabled);+ expect(await slot.handleFsRequest(GHOST_ID, {+ type: 'fs-request', op: 'write', root: 'workdir', path: 'plan.txt', content: 'blocked', callId: 'call-1',+ })).toMatchObject({ ok: false });+ }+ expect(fs.existsSync(path.join(workdir, 'plan.txt'))).toBe(false);+ expect(confirmCalls).toHaveLength(0);+ expect(handle.reviewAutoPermissionAction).not.toHaveBeenCalled();+ } finally {+ await session.close();+ }+ });++ it.each(['review', 'confirm', 'mkdir'] as const)('workdir invalidates live Plan authority during %s', async (phase) => {+ const { session, handle } = makeLiveSession(workdir, phase === 'review' ? 'auto' : phase === 'confirm' ? 'ask' : 'bypassPermissions');+ const { slot } = makeHarness(dataRoot, {+ confirm: async () => { await session.setPlanMode(true); return { confirmed: true }; },+ });+ slot.setSessionSnapshotResolver(async (id, instance) => resolveGhostFsSessionSnapshot(() => session, id, instance));+ handle.reviewAutoPermissionAction.mockImplementation(async () => {+ await session.setPlanMode(true);+ return { verdict: 'allow' };+ });+ const originalMkdir = fs.promises.mkdir;+ const mkdir = phase === 'mkdir' ? vi.spyOn(fs.promises, 'mkdir').mockImplementationOnce(async (...args) => {+ await session.setPlanMode(true);+ return originalMkdir(...args);+ }) : null;+ try {+ expect(await slot.handleFsRequest(GHOST_ID, {+ type: 'fs-request', op: 'write', root: 'workdir', path: 'late-plan.txt', content: 'blocked', callId: 'call-1',+ })).toMatchObject({ ok: false });+ expect(fs.existsSync(path.join(workdir, 'late-plan.txt'))).toBe(false);+ } finally {+ mkdir?.mockRestore();+ await session.close();+ }+ });+it('workdir:read/list/delete 一律拒(仅 write)', async () => {const { slot } = makeHarness(dataRoot, {session: { workingDir: workdir, permissionMode: 'bypassPermissions', planModeEnabled: false, remoteHostId: null },diff --git a/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.tsindex ea9cc81e16..828635c242 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts@@ -433,4 +433,38 @@ describe('workspace Auto review', () => {expect(reviewPermissionAction).not.toHaveBeenCalled();expect(deps.confirmDir).toHaveBeenCalledOnce();});+ it('rejects unavailable live authorization without showing confirmation or creating a draft', async () => {+ const service = makeService({ captureSessionAuthorization: () => null });+ const { slot, deps } = makeSlot({ isInsideWorkdir: () => false }, service);+ expect(await slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(deps.confirmDir).not.toHaveBeenCalled();+ expect(service.createDraftSession).not.toHaveBeenCalled();+ });+ it.each(['review', 'confirm', 'lookup', 'commit'] as const)('rechecks captured authority after %s while the call remains active', async (phase) => {+ let current = true;+ const service = makeService({+ captureSessionAuthorization: () => () => current,+ reviewPermissionAction: async () => {+ if (phase === 'review') current = false;+ return { verdict: phase === 'confirm' ? 'ask' : 'allow' };+ },+ findActiveSessionByWorkdir: vi.fn(async () => {+ if (phase === 'lookup') current = false;+ return null;+ }),+ createDraftSession: vi.fn(async ({ shouldContinue }) => {+ if (phase === 'commit') current = false;+ expect(shouldContinue?.()).toBe(false);+ return null;+ }),+ });+ const { slot } = makeSlot({+ isInsideWorkdir: () => false,+ resolveCallContext: () => ({ ghostId: 'ws-ghost', sessionId: 'sess-1', sessionInstanceId: 'instance-1' }),+ confirmDir: async () => { current = false; return { ok: true }; },+ }, service);+ expect(await slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({ ok: false, errorCode: 'CANCELLED' });+ expect(service.createDraftSession).toHaveBeenCalledTimes(phase === 'commit' ? 1 : 0);+ expect(service.focusSession).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts b/apps/desktop/src/main/cindy-brain/workspaceSlot.tsindex b5dd272e81..4c4b50882e 100644--- a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts+++ b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts@@ -39,6 +39,8 @@ import { sanitizeGhostNoticeText } from './notifySlot.js';/** 会话判重/创建/聚焦服务(maker-ipc 初始化完成后经 setter 注入)。 */export interface WorkspaceSessionService {+ /** Capture live authority once; queued creation and late confirmations must revalidate it. */+ captureSessionAuthorization?(sessionId: string, instanceId?: string): (() => boolean) | null;reviewPermissionAction?(sessionId: string, instanceId: string, action: ReviewableAction): Promise<AutoReviewDecision>;/*** 按目录判重:命中返回已有 active 会话 id(口径 = 侧边栏"同一工作区",@@ -200,7 +202,12 @@ export class GhostWorkspaceSlot {'本次调用没有会话语境,无法向用户弹确认卡;请改用 mode:"pick" 让用户亲自选目录',);}+ const authorization = service.captureSessionAuthorization?.(ctx.sessionId, ctx.sessionInstanceId);+ if (service.captureSessionAuthorization && !authorization) {+ return fail('PERMISSION_DENIED', 'The originating task cannot authorize this workspace operation.');+ }callIsCurrent = () => {+ if (authorization && !authorization()) return false;const current = this.deps.resolveCallContext(request.callId as string);return current?.ghostId === ctx.ghostId && current?.sessionId === ctx.sessionId&& current?.sessionInstanceId === ctx.sessionInstanceId;diff --git a/apps/desktop/src/main/maker-ipc/ghostFsSessionSnapshot.ts b/apps/desktop/src/main/maker-ipc/ghostFsSessionSnapshot.tsnew file mode 100644index 0000000000..9c37740c15--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/ghostFsSessionSnapshot.ts@@ -0,0 +1,37 @@+import type { Session } from '@cindy/maker-core';+import type { FsSessionSnapshot } from '../cindy-brain/fsSlot.js';++/** Only live Session authority can authorize a plugin's workdir write, never the DB mirror. */+export function resolveGhostFsSessionSnapshot(+ getSession: (sessionId: string) => Session | undefined,+ sessionId: string,+ instanceId?: string,+): FsSessionSnapshot | null {+ const session = getSession(sessionId);+ if (!instanceId || !session || session.instanceId !== instanceId) return null;+ const permission = session.stablePermissionModeState;+ const plan = session.stablePlanModeState;+ if (!permission || !plan) return null;+ const workDir = session.workDir;+ const isCurrent = () => {+ const currentPlan = session.stablePlanModeState;+ return getSession(sessionId) === session+ && session.workDir === workDir+ && session.stablePermissionModeState?.generation === permission.generation+ && currentPlan?.generation === plan.generation+ && currentPlan.enabled === plan.enabled;+ };+ return {+ workingDir: workDir,+ remoteHostId: session.remoteHostId,+ permissionMode: permission.mode ?? 'ask',+ planModeEnabled: plan.enabled,+ isCurrent,+ reviewAction: async (action) => {+ const decision = await session.reviewHostPermissionAction(action);+ return isCurrent()+ ? decision+ : { verdict: 'block', reason: 'Task or permissions changed; retry with the current scope.' };+ },+ };+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 9f69bcb76e..6b2c1ded4a 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -313,6 +313,7 @@ import {} from '../reviewer/reviewSourceLease.js';import { broadcastSubagentRunsChanged } from '../localDb/ipc/subagentRuns.js';+import { resolveGhostFsSessionSnapshot } from './ghostFsSessionSnapshot.js';import { clearSubagentObservationRewindState } from '../subagentObservationRewindFence.js';import {applyAgentSwitchToSessionRow,@@ -321,7 +322,6 @@ import {captureSessionRecycleScope,clearSessionContextInDb,createSessionRemoteHostIdReader,- getSessionFsSnapshot,getSessionRowSnapshot,getSessionRowSnapshotStrict,persistSessionFields,@@ -9566,32 +9566,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 的会话聚焦通道。注入方式与 setGhostAgentTurnRunner 同款倒置,避免// cindy-brain 反向依赖 maker-ipc / localDb 形成模块环。setGhostLibraryExtraDirSync(syncLibraryReadonlyExtraDir);- getGhostFsSlot().setSessionSnapshotResolver(async (sessionId, instanceId) => {- const session = getMaker().getSession(sessionId);- if (!instanceId || !session || session.instanceId !== instanceId) return null;- const permission = session.stablePermissionModeState;- if (!permission) return null;- const workDir = session.workDir;- const isCurrent = () => getMaker().getSession(sessionId) === session- && session.workDir === workDir- && session.stablePermissionModeState?.generation === permission.generation;- const snapshot = await getSessionFsSnapshot(sessionId);- if (!snapshot || !isCurrent()) return null;- return {- ...snapshot,- workingDir: workDir,- remoteHostId: session.remoteHostId,- permissionMode: permission.mode ?? 'ask',- isCurrent,- reviewAction: async (action) => {- const decision = await session.reviewHostPermissionAction(action);- return isCurrent()- ? decision- : { verdict: 'block', reason: 'Task or permissions changed; retry with the current scope.' };- },- };- });+ getGhostFsSlot().setSessionSnapshotResolver(async (sessionId, instanceId) =>+ resolveGhostFsSessionSnapshot((id) => getMaker().getSession(id), sessionId, instanceId));setGhostWorkspaceSessionService({+ captureSessionAuthorization: (sessionId, instanceId) => {+ const snapshot = resolveGhostFsSessionSnapshot((id) => getMaker().getSession(id), sessionId, instanceId);+ return snapshot && !snapshot.planModeEnabled && snapshot.permissionMode !== 'plan'+ ? snapshot.isCurrent ?? null : null;+ },reviewPermissionAction: async (sessionId, instanceId, action) => {const session = getMaker().getSession(sessionId);if (!session || session.instanceId !== instanceId) {diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 1abe3bdc10..c1278dfd28 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -304,6 +304,8 @@草稿创建、工作目录写入和媒体路径揭示,Full Access 不额外审批,Auto 进入现有统一审阅器,Ask 沿用原确认流程。MCP 的 `prompt-each-time` 仅限制授权记忆,不得覆盖 Full Access,也不得跳过 Auto 审阅。审批期间实例、权限或调用归属失效时,旧 allow 不可执行。+ Plan 与操作审批档位正交:Host 副作用须先检查实时 Plan 状态,未知或切换中拒绝;+ Plan 切换代次也参与审批后和落盘前复核,不能以数据库镜像或切回原状态恢复旧授权。这不扩大本轮来源/执行范围、不改变跨主机路径归属,不替用户填写 Setup、OAuth、Secret等必要信息,也不改变第 3.1 节的安装/更新策略。自主面板或后台调用不得借用前台会话权限。实现与回归见 [Session.reviewHostPermissionAction](../../packages/maker-core/src/session.ts)、diff --git a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.tsindex 2705880c35..6c619813a4 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/auto-review-wiring.test.ts@@ -847,6 +847,26 @@ describe('Auto-review wiring: lightweight reviewer controls gray actions', () =>await next.handle.close();});+ it.each([false, true])('Auto to Full access retains turn scope without restoring MCP forced prompts (%s)', async (restricted) => {+ let release!: (decision: { verdict: 'allow' }) => void;+ const reviewer = vi.fn(() => new Promise<{ verdict: 'allow' }>((resolve) => { release = resolve; }));+ const { handle, canUseTool, seen } = await startSession('auto', {+ reviewer, mcpProviderNames: ['cindy'], mcpToolApprovalPolicy: () => 'prompt-each-time',+ });+ await handle.send({ type: 'user', content: 'Send the approved report.' }, restricted ? {+ turnPermissionPolicy: {+ origin: { kind: 'im', channel: 'telegram' }, confirmationSurface: 'channel', forceConfirmToolCall: () => true,+ },+ } : undefined);+ const pending = canUseTool('mcp__cindy__ghost_call', { tool: 'send', args: {} }, { toolUseID: 'scope-switch' });+ await vi.waitFor(() => expect(reviewer).toHaveBeenCalledOnce());+ await handle.setPermissionMode!('bypassPermissions');+ release({ verdict: 'allow' });+ expect(await pending).toMatchObject({ behavior: restricted ? 'deny' : 'allow' });+ expect(permissionRequests(seen)).toHaveLength(0);+ await handle.close();+ });+it('reviewer allow → proceeds silently without hitting the resolver', async () => {const { handle, canUseTool, reviewAutoPermissionAction, seen } = await startSession('auto', {reviewVerdict: 'allow',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.tsindex 0b14d5f78a..c5b3246b14 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@@ -1650,6 +1650,29 @@ describe('remote sessions share the same permission semantics', () => {await handle.close();});+ it.each([false, true])('remote Auto to Full access retains turn scope without restoring MCP forced prompts (%s)', async (restricted) => {+ let release!: (decision: { verdict: 'allow' }) => void;+ const reviewer = vi.fn(() => new Promise<{ verdict: 'allow' }>((resolve) => { release = resolve; }));+ const { handle, onApprovalRequest, seen } = await startRemoteSession(() => 'prompt-each-time', {+ permissionMode: 'auto', reviewAutoPermissionAction: reviewer,+ attachResolver: () => ({ kind: 'permission', behavior: 'allow' }),+ });+ await handle.send({ type: 'user', content: 'Send the approved report.' }, restricted ? {+ turnPermissionPolicy: {+ origin: { kind: 'im', channel: 'telegram' }, confirmationSurface: 'channel', forceConfirmToolCall: () => true,+ },+ } : undefined);+ const pending = onApprovalRequest({ requestId: 'remote-scope-switch', kind: 'permission',+ toolName: 'mcp__cindy_contacts__call_tool', input: { name: 'contacts_merge' },+ });+ await vi.waitFor(() => expect(reviewer).toHaveBeenCalledOnce());+ await handle.setPermissionMode!('bypassPermissions');+ release({ verdict: 'allow' });+ expect(await pending).toMatchObject({ behavior: restricted ? 'deny' : 'allow' });+ expect(permissionRequests(seen)).toHaveLength(0);+ await handle.close();+ });+it('reviews remote destructive paths with explicit unavailable realpath evidence', async () => {const reviewer = vi.fn(async () => ({ verdict: 'allow' as const }));const { handle, onApprovalRequest, seen } = await startRemoteSession(diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 0bef2bd55c..829e6cd86f 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -2235,6 +2235,9 @@ export class ClaudeCodeAgent extends BaseAgent {// mutablePermissionMode 仍视为 'auto';运行期它确实可能已变,故按 union 类型现读。const modeAfterReview = mutablePermissionMode as PermissionMode;if (modeAfterReview === 'bypassPermissions') {+ if (turnPolicyForcePrompt) {+ return { behavior: 'deny', message: 'Permission mode changed; retry within the authorized turn scope.' };+ }return { behavior: 'allow', updatedInput: executionInput };}if (modeAfterReview !== 'auto') {@@ -3423,15 +3426,17 @@ export class ClaudeCodeAgent extends BaseAgent {reason: 'no interaction resolver attached; denying non-read-only tool (fail-closed)',};}- if (mutablePermissionMode === 'bypassPermissions') {- return { kind: 'permission', behavior: 'allow' };- }- // 远端会话走同一份 host MCP 策略 —— 否则 SSH 会话里可信 server 又要逐次- // 弹窗, prompt-each-time 的"禁止持久化授权"保护也整套缺失。const remoteTurnPolicyForcePrompt = forceTurnConfirmation(remoteToolName || 'unknown',params.input ?? {},);+ if (mutablePermissionMode === 'bypassPermissions') {+ return remoteTurnPolicyForcePrompt+ ? { kind: 'permission', behavior: 'deny', reason: 'Permission mode changed; retry within the authorized turn scope.' }+ : { kind: 'permission', behavior: 'allow' };+ }+ // 远端会话走同一份 host MCP 策略 —— 否则 SSH 会话里可信 server 又要逐次+ // 弹窗, prompt-each-time 的"禁止持久化授权"保护也整套缺失。const remoteMcpPolicy = classifyMcpApprovalPolicy(remoteToolName, params.input ?? {});const remoteHostApprovalPresentation = mcpApprovalPresentation(remoteToolName,@@ -3463,7 +3468,11 @@ export class ClaudeCodeAgent extends BaseAgent {'linux',);const modeAfterReview = mutablePermissionMode as PermissionMode;- if (modeAfterReview === 'bypassPermissions') return { kind: 'permission', behavior: 'allow' };+ if (modeAfterReview === 'bypassPermissions') {+ return remoteTurnPolicyForcePrompt+ ? { kind: 'permission', behavior: 'deny', reason: 'Permission mode changed; retry within the authorized turn scope.' }+ : { kind: 'permission', behavior: 'allow' };+ }if (modeAfterReview === 'auto' && autoDecision.verdict === 'allow') {return { kind: 'permission', behavior: 'allow' };}diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex a7dc55712f..5c62f9c046 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -13732,6 +13732,31 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});+ it.each([false, true])('Auto to Full access retains turn scope without restoring MCP forced prompts (%s)', async (restricted) => {+ const gate = deferred<{ verdict: 'allow' }>();+ const review = vi.fn<AutoReviewDelegate>(() => gate.promise);+ const agent = new CodexAgent(createDeps({}, { reviewAutoPermissionAction: review, getMcpToolApprovalPolicy: () => 'prompt-each-time' }));+ const host = installFakeHost(agent, (method) => method === Method.TurnStart ? { turn: { id: 'scope-turn' } } : undefined);+ const handle = await agent.startSession({ sessionId: 'scope-switch', model: 'gpt-5.5', providerId: 'xd', workingDir: '/repo', permissionMode: 'auto' });+ const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'allow' }) as const);+ handle.setInteractionResolver(resolver);+ await handle.send({ type: 'user', content: 'Send the approved report.' }, restricted ? {+ turnPermissionPolicy: {+ origin: { kind: 'im', channel: 'telegram' }, confirmationSurface: 'channel', forceConfirmToolCall: () => true,+ },+ } : undefined);+ const pending = host.getThreadHandlers()!.mcpServerElicitation!({+ threadId: 'start-thread-id', turnId: 'scope-turn', serverName: 'cindy', mode: 'form',+ _meta: { codex_approval_kind: 'mcp_tool_call', tool_name: 'send', tool_params: {} }, message: 'Allow tool call', requestedSchema: {},+ });+ await vi.waitFor(() => expect(review).toHaveBeenCalledOnce());+ await handle.setPermissionMode!('bypassPermissions');+ gate.resolve({ verdict: 'allow' });+ expect(await pending).toEqual({ action: restricted ? 'decline' : 'accept', content: null, _meta: null });+ expect(resolver).not.toHaveBeenCalled();+ await handle.close();+ });+it.each(['prompt', 'prompt-each-time'] as const)('Auto MCP policy %s uses AI allow/block/ask', async (policy) => {for (const verdict of ['allow', 'block', 'ask'] as const) {const review = vi.fn<AutoReviewDelegate>(async () => ({ verdict }));diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 40d611a056..8e2cc92393 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -6986,7 +6986,14 @@ export class CodexAgent extends BaseAgent {// (codex review P1;与已修复的 Pi / Claude 线程同口径)。cast 破 TS 收窄:TS 不建模// await 期间经 setPermissionMode 的重赋值,仍视此处为 'auto';运行期确实可能已变。const modeAfterReview = mutablePermissionMode as PermissionMode;- if (modeAfterReview === 'bypassPermissions') return 'accept';+ if (modeAfterReview === 'bypassPermissions') {+ if (turnPolicyForcePrompt) {+ denialReason = formatPermissionDenial('system', 'Permission mode changed; retry within the authorized turn scope.');+ reportMcpDenial('system');+ return 'decline';+ }+ return 'accept';+ }if (modeAfterReview !== 'auto') {forcePrompt = true;} else if (decision.verdict === 'allow') {diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.tsindex 127f176a62..0f052e048c 100644--- a/packages/maker-core/src/session.close.test.ts+++ b/packages/maker-core/src/session.close.test.ts@@ -424,15 +424,19 @@ describe('Host automatic review lifecycle', () => {const reviewGate = createDeferred();const closeGate = createDeferred();const modeGate = createDeferred();+ const planGate = createDeferred();+ let planMode: boolean | null = false;const review = vi.fn(async () => { await reviewGate.promise; return { verdict: 'allow' as const }; });const handle = { id: 'host-review', agentKind, model: 'm',send: async () => { running = true; }, events: () => events, isTurnRunning: () => running,requestGracefulStop: async () => ({ status: 'requested' }),close: () => closeGate.promise.finally(() => events.end()), setPermissionMode: () => modeGate.promise, abort: async () => {},setInteractionResolver() {}, reviewAutoPermissionAction: review,+ getPlanMode: () => planMode,+ setPlanMode: async (enabled: boolean) => { await planGate.promise; planMode = enabled; },} as unknown as AgentSessionHandle;const session = new Session({ id: 'host-review', agentKind, workDir: '/repo', handle,- capabilities: { permissionModes: [{ id: 'ask', displayName: 'Ask' }], setPermissionModeMidSession: { supported: true } } as never,+ capabilities: { permissionModes: [{ id: 'ask', displayName: 'Ask' }], setPermissionModeMidSession: { supported: true }, planMode: { supported: true } } as never,logger: createLogger(), permissionMode, turnStallMs: 0,});const emit = async (event: AgentEvent) => {@@ -443,9 +447,49 @@ describe('Host automatic review lifecycle', () => {await vi.waitFor(() => expect(seen).toHaveBeenCalled());unsubscribe();};- return { session, review, reviewGate, closeGate, modeGate, emit };+ 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('does not invalidate Host authority for a no-op Plan update', async () => {+ const { session, closeGate } = setup();+ const before = session.stablePlanModeState;+ await session.setPlanMode(false);+ expect(session.stablePlanModeState).toEqual(before);+ closeGate.resolve();+ await session.close();+ });+ it.each(['bypassPermissions', 'auto', 'ask'] as const)('Host %s cannot override enabled or unknown Plan mode', async (mode) => {+ const { session, review, setProviderPlanMode, closeGate } = setup('pi', mode);+ for (const enabled of [true, null]) {+ setProviderPlanMode(enabled);+ expect(await session.reviewHostPermissionAction(action)).toMatchObject({ verdict: 'block' });+ }+ expect(review).not.toHaveBeenCalled();+ closeGate.resolve();+ await session.close();+ });+ it.each(['enabled', 'restored', 'failed'] as const)('Plan changes invalidate pending Host approvals even when %s', async (outcome) => {+ const { session, handle, review, reviewGate, planGate, closeGate } = setup();+ const oldGeneration = session.stablePlanModeState?.generation;+ const pending = session.reviewHostPermissionAction(action);+ await vi.waitFor(() => expect(review).toHaveBeenCalledOnce());+ const changing = session.setPlanMode(true);+ expect(session.stablePlanModeState).toBeNull();+ expect(await session.reviewHostPermissionAction(action)).toMatchObject({ verdict: 'block' });+ planGate.resolve();+ await changing;+ if (outcome !== 'enabled') await session.setPlanMode(false);+ if (outcome === 'failed') {+ // Even a provider transport failure invalidates the previous authority.+ handle.setPlanMode = async () => { throw new Error('transport failed'); };+ await expect(session.setPlanMode(true)).rejects.toThrow('transport failed');+ }+ expect(session.stablePlanModeState?.generation).not.toBe(oldGeneration);+ reviewGate.resolve();+ expect(await pending).toMatchObject({ verdict: 'block' });+ closeGate.resolve();+ await session.close();+ });it.each(['bypassPermissions', 'ask'] as const)('Host operations follow %s without AI review', async (mode) => {const { session, review, closeGate } = setup('pi', mode);expect(await session.reviewHostPermissionAction(action)).toEqual({ verdict: mode === 'ask' ? 'ask' : 'allow' });diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 87577d9bb7..1e37301b22 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -413,6 +413,9 @@ export class Session {private permissionModeStateValue: PermissionModeState;private permissionModeChangeChain: Promise<void> = Promise.resolve();private permissionModeChangesInFlight = 0;+ /** Invalidation only; the provider remains the sole owner of the live Plan flag. */+ private planModeGeneration = 0;+ private planModeChangesInFlight = 0;/** User/API permission changes, serialized separately so host restores cannot deadlock. */private externalPermissionModeChangeChain: Promise<void> = Promise.resolve();private externalPermissionModeChangesInFlight = 0;@@ -1486,10 +1489,21 @@ export class Session {return this.permissionModeState;}+ /** 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;+ return enabled === null ? null : { enabled, generation: this.planModeGeneration };+ }+/** Review a Host-side tool step without reconstructing or persisting another copy of user intent. */async reviewHostPermissionAction(action: ReviewableAction): Promise<AutoReviewDecision> {const permission = this.stablePermissionModeState;if (!permission) return { verdict: 'block', reason: 'Session permissions are changing or the task has closed.' };+ const plan = this.stablePlanModeState;+ if (!plan || plan.enabled || permission.mode === 'plan') {+ return { verdict: 'block', reason: 'Plan mode is active or changing; Host side effects are not allowed.' };+ }if (permission.mode === 'bypassPermissions') return { verdict: 'allow' };if (permission.mode !== 'auto') return { verdict: 'ask' };// Host steps can belong to a still-active descendant after the foreground@@ -1510,7 +1524,9 @@ export class Session {unsubscribe();}const current = this.stablePermissionModeState;+ const currentPlan = this.stablePlanModeState;if (invalidated || !current || current.generation !== permission.generation+ || !currentPlan || currentPlan.enabled || currentPlan.generation !== plan.generation|| (turnControl?.gracefulStopState ?? 'none') !== gracefulStop|| (this.turnControlState?.gracefulStopState ?? 'none') !== gracefulStop) {return { verdict: 'block', reason: 'Task or permissions changed; retry with the current scope.' };@@ -1707,7 +1723,16 @@ export class Session {if (!this.handle.setPlanMode) {throw new NotSupportedError('planMode', { supported: false, reason: 'not-implemented' });}- await this.handle.setPlanMode(enabled);+ if (this.planModeChangesInFlight === 0 && this.getPlanMode() === enabled) return;+ // Invalidate before awaiting the provider (Pi may queue its RPC). A switch+ // back, or a failed switch, must not revive an earlier Host approval.+ this.planModeGeneration += 1;+ this.planModeChangesInFlight += 1;+ try {+ await this.handle.setPlanMode(enabled);+ } finally {+ this.planModeChangesInFlight -= 1;+ }}getPlanMode(): boolean | null {