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(plugins): review delegated scope before trusted MCP shortcuts

Dashd6e1d3cb4cf7
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index 3d85f337b0..6671e38913 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -91,6 +91,12 @@ Host 只接受经绑定插件身份写入的自有创建收据;已登记计划
明确带任务范围的所有动作(包括读取)均检查范围;不会仅凭工作目录安全而忽略插件的禁读条款。明确的 Host 续行凭据在 SQL 限量前过滤,避免频繁协调消息挤走真实用户限制;空字符串凭据仍保留,因为用户只发送附件时也可能没有文字。用户消息携带新资源时,沿用普通任务规则,先清除旧指代授权再追加该行可信原话;不以可编辑的 origin 判定作者。缺凭据的旧卡片保守标记历史不完整。
+Host 信任的 MCP 工具也先经过现有委派上下文复核;只有复核后的普通任务可跳过模型审阅。
+同一判据覆盖 Claude 本地/SSH、Codex MCP elicitation/Host dynamic tool、Pi 主进程/持久子代理;
+保留真实工具参数、审阅前后 Host 核验及最后的意图/缓存/目录时效检查。
+Host 快捷放行标志计入既有审阅缓存键;Pi 子代理未成功投递的 Auto allow 再次投递前重走现有核验,
+不把旧决定当成持久授权。普通任务的可信 MCP 快捷放行、非 Auto 档位及故障 ask/unavailable 语义保持。
+
验证入口:`pluginTaskReviewContext.test.ts`、`pluginTaskService.test.ts`、`taskSlot.test.ts`、
`auto-review-context.test.ts`、Pi/Claude Code 审批接线回归以及 `eval-auto-approval.mts` 的
`delegated-*` 正反对照(后者需要真实审阅模型,当前拆分 PR 未运行付费验证)。主机身份校验是确定性边界,动作与任务是否相符仍由 Auto 审阅,
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 688248a666..804dc3f000 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
@@ -27,6 +27,7 @@ import type {
TurnPermissionPolicy,
} from '../../base-agent.js';
import type { PermissionMode } from '../../../types/common.js';
+import type { AutoReviewRequest } from '../../shared/auto-review-decision.js';
import type { CapabilityRoutingPolicy } from '../../../types/capability-routing.js';
import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';
import type { InteractionDecision, InteractionRequest } from '../../../types/events.js';
@@ -206,6 +207,7 @@ async function startSession(
}>;
turnChangeCapture?: AgentDeps['turnChangeCapture'];
getMcpToolApprovalPresentation?: AgentDeps['getMcpToolApprovalPresentation'];
+ reviewAutoPermissionAction?: AgentDeps['reviewAutoPermissionAction'];
resolveClaudeSubagentModelAccess?: AgentDeps['resolveClaudeSubagentModelAccess'];
resolveVerifiedContextWindow?: AgentDeps['resolveVerifiedContextWindow'];
availableModels?: NonNullable<AgentDeps['capabilityAdditions']>['availableModels'];
@@ -227,6 +229,7 @@ async function startSession(
deps.capabilityRouting = options?.capabilityRouting;
deps.turnChangeCapture = options?.turnChangeCapture;
deps.getMcpToolApprovalPresentation = options?.getMcpToolApprovalPresentation;
+ deps.reviewAutoPermissionAction = options?.reviewAutoPermissionAction;
deps.resolveClaudeSubagentModelAccess = options?.resolveClaudeSubagentModelAccess;
deps.resolveVerifiedContextWindow = options?.resolveVerifiedContextWindow;
deps.capabilityAdditions = options?.availableModels
@@ -1433,6 +1436,49 @@ describe('remote sessions share the same permission semantics', () => {
};
}
+ describe.each(['local', 'remote'] as const)('delegated trusted MCP %s', (transport) => {
+ it.each(['ordinary', 'allow', 'block', 'ask', 'revoked', 'unavailable', 'late-revoke', 'late-scope'] as const)(
+ 'keeps live authorization before the Host shortcut: %s', async (scenario) => {
+ let active = scenario !== 'revoked';
+ let revision = 'scope-1';
+ const review = Object.assign(vi.fn(async (_request: AutoReviewRequest) => {
+ if (scenario === 'late-revoke') active = false;
+ if (scenario === 'late-scope') revision = 'scope-2';
+ return { verdict: scenario === 'block' ? 'block' as const : scenario === 'ask' ? 'ask' as const : 'allow' as const };
+ }), {
+ prepareRequest: vi.fn(async (request: AutoReviewRequest): Promise<AutoReviewRequest> => {
+ if (scenario === 'unavailable') throw new Error('storage unavailable');
+ if (scenario === 'ordinary') return request;
+ return active ? { ...request, delegatedTask: { source: 'approved-plugin', pluginId: 'eval', role: 'worker',
+ task: 'Run the approved evaluation only', workingDir: request.workspaceRoots[0], authorizationRevision: revision } }
+ : { ...request, authorizationError: 'Plugin authorization revoked' };
+ }),
+ });
+ const deny = (): InteractionDecision => ({ kind: 'permission', behavior: 'deny' });
+ const session = transport === 'local'
+ ? await startSession(() => 'auto-approve', { permissionMode: 'auto', mcpServerNames: ['cindy_scheduler'], reviewAutoPermissionAction: review, decide: deny })
+ : await startRemoteSession(() => 'auto-approve', { permissionMode: 'auto', mcpServerNames: ['cindy_scheduler'], reviewAutoPermissionAction: review, attachResolver: deny });
+ try {
+ await session.handle.send({ type: 'user', content: 'Run this evaluation; do not create schedules.' });
+ const toolName = 'mcp__cindy_scheduler__call_tool';
+ const input = { name: 'schedule_create', args: { prompt: 'outside task scope' } };
+ const result = 'canUseTool' in session
+ ? await session.canUseTool(toolName, input, { toolUseID: 'delegated-mcp' })
+ : await session.onApprovalRequest({ requestId: 'delegated-mcp', kind: 'permission', toolName, input });
+ expect(result.behavior).toBe(['ordinary', 'allow'].includes(scenario) ? 'allow' : 'deny');
+ expect(review.prepareRequest).toHaveBeenCalled();
+ expect(review).toHaveBeenCalledTimes(['ordinary', 'revoked', 'unavailable'].includes(scenario) ? 0 : 1);
+ expect(session.seen).toHaveLength(['ask', 'unavailable'].includes(scenario) ? 1 : 0);
+ if (review.mock.calls.length) {
+ const request = review.mock.calls[0][0];
+ expect(request.delegatedTask?.pluginId).toBe('eval');
+ expect(JSON.parse((request.action as { description: string }).description)).toMatchObject({ toolName, input });
+ }
+ } finally { await session.handle.close(); }
+ },
+ );
+ });
+
it.each(['http', 'sse'] as const)('forwards a selected custom %s MCP to a remote Bot without the host bridge', async (transport) => {
process.env.CLAUDE_CONFIG_DIR = await makeTempDir();
const workingDir = await makeTempDir();
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index d7a7423bba..39a81172ee 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -2399,7 +2399,7 @@ export class ClaudeCodeAgent extends BaseAgent {
: normalizedAction;
const directorySensitivePermission = builtinReviewAction?.kind === 'read'
|| builtinReviewAction?.kind === 'file-write';
- if (mutablePermissionMode === 'auto' && (mcpApprovalPolicy !== 'auto-approve' || turnPolicyForcePrompt)) {
+ if (mutablePermissionMode === 'auto') {
const workspaceRoots = [opts.workingDir, ...mutableExtraDirs, ...mutableWritableDirs].filter(
(d): d is string => typeof d === 'string' && d.length > 0,
);
@@ -2434,6 +2434,7 @@ export class ClaudeCodeAgent extends BaseAgent {
workspaceRoots,
writableRoots,
opts.remoteHostId ? 'linux' : process.platform,
+ mcpApprovalPolicy === 'auto-approve' && !turnPolicyForcePrompt,
);
// 热切换收口:reviewAutoAction 是 async,期间 setPermissionMode 可能收紧(Auto→Ask)
// 或放宽(→Full)。必须按**最新**档位决策,否则进入审查前的旧 auto 档 allow 会绕过用户
@@ -2718,6 +2719,7 @@ export class ClaudeCodeAgent extends BaseAgent {
workspaceRoots: string[],
writableRoots: string[],
platform: NodeJS.Platform,
+ hostAutoApprove = false,
): Promise<AutoReviewDecision> => {
const directoryGeneration = autoReviewDirectoryGeneration;
const request = {
@@ -2739,11 +2741,12 @@ export class ClaudeCodeAgent extends BaseAgent {
if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)) {
return Promise.resolve({ verdict: 'block', reason: 'User instructions changed; retry against the current request.' });
}
- key = JSON.stringify(prepared);
+ key = JSON.stringify([prepared, hostAutoApprove]);
const cached = autoReviewDecisionCache.get(key);
pending = cached ?? resolveAutoReviewDecision(
prepared,
this.deps.reviewAutoPermissionAction,
+ hostAutoApprove,
);
if (!cached) autoReviewDecisionCache.set(key, pending);
return pending;
@@ -3699,10 +3702,7 @@ export class ClaudeCodeAgent extends BaseAgent {
);
let remoteForcePrompt = mutablePermissionMode !== 'auto' && remoteTurnPolicyForcePrompt;
let remoteUnavailableHandoff = false;
- if (
- mutablePermissionMode === 'auto'
- && (remoteMcpPolicy !== 'auto-approve' || remoteTurnPolicyForcePrompt)
- ) {
+ if (mutablePermissionMode === 'auto') {
const normalizedAction = normalizeBuiltinToolForAutoReview(remoteToolName, params.input ?? {});
const action = normalizedAction.kind === 'other'
? toolAutoReviewAction(remoteToolName, params.input ?? {}, remoteHostApprovalPresentation?.description)
@@ -3721,6 +3721,7 @@ export class ClaudeCodeAgent extends BaseAgent {
(d): d is string => typeof d === 'string' && d.length > 0,
),
'linux',
+ remoteMcpPolicy === 'auto-approve' && !remoteTurnPolicyForcePrompt,
);
const modeAfterReview = mutablePermissionMode as PermissionMode;
if (isPlanToolBlocked(remoteToolName)) {
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 8fdd988fc4..98e066cf73 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -33,6 +33,7 @@ import {
AUTO_REVIEW_UNAVAILABLE_METADATA_KEY,
AUTO_REVIEW_UNAVAILABLE_PROMPT_TEXT,
type AutoReviewDelegate,
+ type AutoReviewRequest,
} from '../shared/auto-review-decision.js';
type AgentEvent = Omit<CoreAgentEvent, 'data'> & { data: any };
@@ -16979,6 +16980,58 @@ describe('CodexAgent MCP thread context hooks', () => {
await fullHandle.close();
});
+ describe.each(['mcp', 'dynamic'] as const)('delegated trusted MCP %s', (kind) => {
+ it.each(['ordinary', 'allow', 'block', 'ask', 'revoked', 'unavailable', 'late-revoke', 'late-scope'] as const)('keeps live authorization before the Host shortcut: %s', async (scenario) => {
+ let active = scenario !== 'revoked';
+ let revision = 'scope-1';
+ const reviewer = Object.assign(vi.fn(async (_request: AutoReviewRequest) => {
+ if (scenario === 'late-revoke') active = false;
+ if (scenario === 'late-scope') revision = 'scope-2';
+ return { verdict: scenario === 'block' ? 'block' as const : scenario === 'ask' ? 'ask' as const : 'allow' as const };
+ }), { prepareRequest: vi.fn(async (request: AutoReviewRequest): Promise<AutoReviewRequest> => {
+ if (scenario === 'unavailable') throw new Error('Host storage unavailable');
+ if (scenario === 'ordinary') return request;
+ return active ? { ...request, delegatedTask: { source: 'approved-plugin', pluginId: 'eval', role: 'worker',
+ task: 'Run the approved evaluation only', workingDir: '/repo', authorizationRevision: revision } }
+ : { ...request, authorizationError: 'Plugin authorization revoked' };
+ }) });
+ const callTool = vi.fn(async () => ({ contentItems: [], success: true }));
+ const agent = new CodexAgent(createDeps({}, {
+ reviewAutoPermissionAction: reviewer,
+ getMcpToolApprovalPolicy: () => 'auto-approve',
+ codexHostDynamicToolProvider: {
+ listTools: () => [{ type: 'function' as const, name: 'cindy_scheduler__call_tool', description: 'Scheduler', inputSchema: { type: 'object' }, deferLoading: false }],
+ callTool,
+ },
+ }));
+ const host = installFakeHost(agent, (method) => method === Method.TurnStart ? { turn: { id: 'delegated-turn' } } : undefined);
+ const handle = await agent.startSession({ sessionId: `delegated-mcp-${kind}-${scenario}`, model: 'gpt-5.5', providerId: 'openai', workingDir: '/repo', permissionMode: 'auto' });
+ try {
+ const resolver = vi.fn(async (): Promise<InteractionDecision> => ({ kind: 'permission', behavior: 'deny' }));
+ handle.setInteractionResolver(resolver);
+ await handle.send({ type: 'user', content: 'Run this evaluation; do not create schedules.' });
+ const h = host.getThreadHandlers();
+ if (!h?.mcpServerElicitation || !h.dynamicToolCall) throw new Error('missing MCP handlers');
+ h.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'delegated-turn' } });
+ const input = { name: 'schedule_create', args: { prompt: 'outside task scope' } };
+ const result = kind === 'mcp'
+ ? await h.mcpServerElicitation({ threadId: 'start-thread-id', turnId: 'delegated-turn', serverName: 'cindy_scheduler', mode: 'form', message: 'Allow tool call', requestedSchema: {},
+ _meta: { codex_approval_kind: 'mcp_tool_call', tool_name: 'call_tool', tool_params: input } })
+ : await h.dynamicToolCall({ threadId: 'start-thread-id', turnId: 'delegated-turn', callId: 'delegated-call', namespace: null, tool: 'cindy_scheduler__call_tool', arguments: input }, { requestId: 'delegated-dynamic' });
+ const allowed = scenario === 'ordinary' || scenario === 'allow';
+ expect(result).toMatchObject(kind === 'mcp' ? { action: allowed ? 'accept' : 'decline' } : { success: allowed });
+ expect(callTool).toHaveBeenCalledTimes(kind === 'dynamic' && allowed ? 1 : 0);
+ expect(reviewer.prepareRequest).toHaveBeenCalled();
+ expect(reviewer).toHaveBeenCalledTimes(['ordinary', 'revoked', 'unavailable'].includes(scenario) ? 0 : 1);
+ expect(resolver).toHaveBeenCalledTimes(['ask', 'unavailable'].includes(scenario) ? 1 : 0);
+ if (reviewer.mock.calls.length) {
+ expect(reviewer.mock.calls[0]![0].delegatedTask?.pluginId).toBe('eval');
+ expect(JSON.stringify(reviewer.mock.calls[0]![0].action)).toContain('schedule_create');
+ }
+ } finally { await handle.close(); }
+ });
+ });
+
it.each(['command', 'file', 'mcp', 'permissions', 'dynamic'] as const)('revalidates cancelled Auto waits across %s approval callbacks', async (kind) => {
for (const lifecycle of ['abort', 'graceful-stop', 'close', 'completed', 'failed', 'superseded', 'child-completed', 'child-root-stopped', 'child-root-completed', 'same-turn-started'] as const) {
for (const verdict of ['allow', 'ask'] as const) {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 5612a98ee9..85924b8182 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -5631,7 +5631,7 @@ assertRouteCurrent();
// 关掉抹平 → fail-closed(不把远端 /private/tmp 误当 /tmp 区内)。本地用真实 process.platform。
// 定义在此(startSession 作用域,opts=session)以避开 awaitApprovalDecision 内层 opts 的遮蔽。
const sessionReviewPlatform: NodeJS.Platform = opts.remoteHostId ? 'linux' : process.platform;
- const reviewAutoAction = (action: ReviewableAction): Promise<AutoReviewDecision> => {
+ const reviewAutoAction = (action: ReviewableAction, hostAutoApprove = false): Promise<AutoReviewDecision> => {
const directoryGeneration = autoReviewDirectoryGeneration;
const request = {
sessionId: opts.sessionId,
@@ -5659,11 +5659,12 @@ assertRouteCurrent();
if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)) {
return Promise.resolve({ verdict: 'block', reason: 'User instructions changed; retry against the current request.' });
}
- key = JSON.stringify(prepared);
+ key = JSON.stringify([prepared, hostAutoApprove]);
const cached = autoReviewDecisionCache.get(key);
pending = cached ?? resolveAutoReviewDecision(
prepared,
this.deps.reviewAutoPermissionAction,
+ hostAutoApprove,
);
if (!cached) autoReviewDecisionCache.set(key, pending);
return pending;
@@ -7792,6 +7793,7 @@ assertRouteCurrent();
opts?: {
forcePrompt?: boolean;
autoReviewAction?: ReviewableAction;
+ hostAutoApprove?: boolean;
itemId?: string;
},
): Promise<{ decision: ApprovalDecision; reason?: string }> {
@@ -7867,6 +7869,7 @@ assertRouteCurrent();
!opts?.autoReviewAction || (forcePrompt && opts.autoReviewAction.kind !== 'other')
? toolAutoReviewAction(req.toolName, req.input, req.description)
: opts.autoReviewAction,
+ opts?.hostAutoApprove === true && !forcePrompt,
);
} finally {
if (pendingApprovals.get(requestId) === reviewEntry) pendingApprovals.delete(requestId);
@@ -9286,7 +9289,7 @@ assertRouteCurrent();
`mcp:${params.serverName}`,
policyPermissionInput,
);
- if (approvalPolicy === 'auto-approve' && !turnPolicyForcePrompt) {
+ if (mutablePermissionMode !== 'auto' && approvalPolicy === 'auto-approve' && !turnPolicyForcePrompt) {
log.debug('mcp elicitation auto-approved by host policy', {
serverName: params.serverName,
mode: params.mode,
@@ -9325,6 +9328,7 @@ assertRouteCurrent();
{
forcePrompt:
turnPolicyForcePrompt || approvalPolicy === 'prompt-each-time',
+ hostAutoApprove: approvalPolicy === 'auto-approve',
// Display text is not execution evidence. An absent argument payload
// must hit the shared missing-evidence denial, never reach AI as a
// seemingly complete action made only of server/title/message fields.
@@ -9908,7 +9912,7 @@ assertRouteCurrent();
};
const approvalPolicy = classifyMcpToolApprovalPolicy(approvalContext);
const hostApprovalPresentation = mcpToolApprovalPresentation(approvalContext);
- if (approvalPolicy !== 'auto-approve') {
+ if (approvalPolicy !== 'auto-approve' || mutablePermissionMode === 'auto') {
const requestId = `dynamic-tool:${serverName}:${params.turnId}:${params.callId}`;
const decision = await awaitApprovalDecision(
params.threadId,
@@ -9928,6 +9932,7 @@ assertRouteCurrent();
},
{
forcePrompt: approvalPolicy === 'prompt-each-time',
+ hostAutoApprove: approvalPolicy === 'auto-approve',
...(toolUseId ? { itemId: toolUseId } : {}),
},
);
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
index 5333c96355..af116b4d27 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts
@@ -4667,6 +4667,38 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
});
});
+ it.each(['ordinary', 'allow', 'block', 'ask', 'revoked', 'unavailable', 'late-revoke', 'late-scope'] as const)('delegated trusted MCP main keeps live authorization: %s', async (scenario) => {
+ let active = scenario !== 'revoked';
+ let revision = 'scope-1';
+ const review = Object.assign(vi.fn(async (_request: AutoReviewRequest) => {
+ if (scenario === 'late-revoke') active = false;
+ if (scenario === 'late-scope') revision = 'scope-2';
+ return { verdict: scenario === 'block' ? 'block' as const : scenario === 'ask' ? 'ask' as const : 'allow' as const };
+ }), { prepareRequest: vi.fn(async (request: AutoReviewRequest): Promise<AutoReviewRequest> => {
+ if (scenario === 'unavailable') throw new Error('Host storage unavailable');
+ if (scenario === 'ordinary') return request;
+ return active ? { ...request, delegatedTask: { source: 'approved-plugin', pluginId: 'eval', role: 'worker',
+ task: 'Run the approved evaluation only', workingDir: cwd, authorizationRevision: revision } }
+ : { ...request, authorizationError: 'Plugin authorization revoked' };
+ }) });
+ const handle = await start('auto', review, false, { serverNames: ['cindy_scheduler'], policy: () => 'auto-approve' });
+ try {
+ const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'deny' }) as const);
+ handle.setInteractionResolver(resolver);
+ await handle.send({ type: 'user', content: 'Run this evaluation; do not create schedules.' });
+ firePermissionRequest('delegated-mcp', 'mcp__cindy_scheduler__call_tool', { name: 'schedule_create', args: { prompt: 'outside task scope' } });
+ await vi.waitFor(() => expect(captured.sent).toContainEqual(expect.objectContaining({ type: 'extension_ui_response', id: 'delegated-mcp' })));
+ expect(captured.sent).toContainEqual(expect.objectContaining({ id: 'delegated-mcp', confirmed: scenario === 'ordinary' || scenario === 'allow' }));
+ expect(review.prepareRequest).toHaveBeenCalled();
+ expect(review).toHaveBeenCalledTimes(['ordinary', 'revoked', 'unavailable'].includes(scenario) ? 0 : 1);
+ expect(resolver).toHaveBeenCalledTimes(['ask', 'unavailable'].includes(scenario) ? 1 : 0);
+ if (review.mock.calls.length) {
+ expect(review.mock.calls[0]![0].delegatedTask?.pluginId).toBe('eval');
+ expect(JSON.stringify(review.mock.calls[0]![0].action)).toContain('schedule_create');
+ }
+ } finally { await handle.close(); }
+ });
+
it('reviews actual operations for MCP servers the host policy does not trust', async () => {
const review = vi.fn(async () => ({ verdict: 'allow' as const }));
const handle = await start('auto', review, false, {
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 75382094cb..275a2d5f10 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -27,6 +27,7 @@ import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AutoReviewRequest } from '../../shared/auto-review-decision.js';
// hoisted 控制旋钮:vi.mock 工厂被提升到 import 之上,不能闭包引用普通 let。
const knobs = vi.hoisted(() => ({
@@ -1103,6 +1104,90 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(proxyDisposed).toBe(2);
});
+ it.each(['ordinary', 'allow', 'block', 'ask', 'revoked', 'unavailable', 'late-revoke', 'late-scope'] as const)('delegated trusted MCP child keeps live authorization: %s', async (scenario) => {
+ let active = scenario !== 'revoked';
+ let revision = 'scope-1';
+ const review = Object.assign(vi.fn(async (_request: AutoReviewRequest) => {
+ if (scenario === 'late-revoke') active = false;
+ if (scenario === 'late-scope') revision = 'scope-2';
+ return { verdict: scenario === 'block' ? 'block' as const : scenario === 'ask' ? 'ask' as const : 'allow' as const };
+ }), { prepareRequest: vi.fn(async (request: AutoReviewRequest): Promise<AutoReviewRequest> => {
+ if (scenario === 'unavailable') throw new Error('Host storage unavailable');
+ if (scenario === 'ordinary') return request;
+ return active ? { ...request, delegatedTask: { source: 'approved-plugin', pluginId: 'eval', role: 'worker',
+ task: 'Run the approved evaluation only', workingDir: cwd, authorizationRevision: revision } }
+ : { ...request, authorizationError: 'Plugin authorization revoked' };
+ }) });
+ const run = pendingSubagentRun({ toolName: 'mcp__cindy_scheduler__call_tool', input: { name: 'schedule_create', args: { prompt: 'outside task scope' } } }, {}, 'input');
+ const discovery = deferSubagentDiscovery(run);
+ const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockResolvedValue(1);
+ const deps = buildDeps({ reviewAutoPermissionAction: review, getMcpToolApprovalPolicy: () => 'auto-approve' });
+ const prepareSpawn = deps.preparePiExtraSpawnConfig!;
+ deps.preparePiExtraSpawnConfig = async (...args) => {
+ const prepared = await prepareSpawn(...args);
+ if (!prepared?.mcpBridge) throw new Error('missing MCP bridge fixture');
+ return { ...prepared, mcpBridge: { ...prepared.mcpBridge, servers: [{ name: 'cindy_scheduler', url: 'http://127.0.0.1:4567/mcp' }] } };
+ };
+ const handle = await new PiAgent(deps).startSession({ ...opts(), permissionMode: 'auto' });
+ try {
+ const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'deny' }) as const);
+ handle.setInteractionResolver(resolver);
+ await handle.send({ type: 'user', content: 'Run this evaluation; do not create schedules.' });
+ discovery.publish();
+ await vi.waitFor(() => expect(control).toHaveBeenCalled(), { timeout: 3_000 });
+ expect(control).toHaveBeenCalledWith(expect.any(String), run.taskId, 'approval', expect.objectContaining({ value:
+ scenario === 'ordinary' || scenario === 'allow' ? 'allow' : ['ask', 'unavailable'].includes(scenario) ? 'user-deny' : expect.stringMatching(/^auto-review-deny(?::|$)/) }));
+ expect(review.prepareRequest).toHaveBeenCalled();
+ expect(review).toHaveBeenCalledTimes(['ordinary', 'revoked', 'unavailable'].includes(scenario) ? 0 : 1);
+ expect(resolver).toHaveBeenCalledTimes(['ask', 'unavailable'].includes(scenario) ? 1 : 0);
+ if (review.mock.calls.length) {
+ expect(review.mock.calls[0]![0].delegatedTask?.pluginId).toBe('eval');
+ expect(JSON.stringify(review.mock.calls[0]![0].action)).toContain('schedule_create');
+ }
+ } finally { discovery.clear(); await handle.close(); }
+ });
+
+ it.each((['zero', 'throw'] as const).flatMap((failure) =>
+ (['allow-revoked', 'allow-current', 'ask', 'unavailable', 'control-plane'] as const).map((scenario) => ({ failure, scenario })),
+ ))('delegated trusted MCP child rechecks automatic delivery, preserves human confirmation: $failure/$scenario', async ({ failure, scenario }) => {
+ let active = true;
+ const review = Object.assign(vi.fn(async (_request: AutoReviewRequest) => ({ verdict: scenario === 'ask' ? 'ask' as const : 'allow' as const })), {
+ prepareRequest: vi.fn(async (request: AutoReviewRequest): Promise<AutoReviewRequest> => {
+ if (scenario === 'unavailable') throw new Error('Host storage unavailable');
+ return active ? { ...request, delegatedTask: { source: 'approved-plugin', pluginId: 'eval', role: 'worker',
+ task: 'Run the approved evaluation only', workingDir: cwd, authorizationRevision: 'scope-1' } }
+ : { ...request, authorizationError: 'Plugin authorization revoked' };
+ }),
+ });
+ const run = pendingSubagentRun({ toolName: 'mcp__cindy_scheduler__call_tool', input: { name: 'schedule_create', args: {} }, controlPlaneWrite: scenario === 'control-plane' }, {}, 'input');
+ const discovery = deferSubagentDiscovery(run);
+ const control = vi.spyOn(piSubagentRuns, 'controlPiSubagentRuns').mockImplementationOnce(async () => {
+ if (scenario === 'allow-revoked') active = false;
+ if (failure === 'throw') throw new Error('mailbox write failed');
+ return 0;
+ }).mockResolvedValue(1);
+ const deps = buildDeps({ reviewAutoPermissionAction: review, getMcpToolApprovalPolicy: () => 'auto-approve' });
+ const prepareSpawn = deps.preparePiExtraSpawnConfig!;
+ deps.preparePiExtraSpawnConfig = async (...args) => {
+ const prepared = await prepareSpawn(...args);
+ if (!prepared?.mcpBridge) throw new Error('missing MCP bridge fixture');
+ return { ...prepared, mcpBridge: { ...prepared.mcpBridge, servers: [{ name: 'cindy_scheduler', url: 'http://127.0.0.1:4567/mcp' }] } };
+ };
+ const handle = await new PiAgent(deps).startSession({ ...opts(), permissionMode: 'auto' });
+ try {
+ const resolver = vi.fn(async () => ({ kind: 'permission', behavior: 'allow' }) as const);
+ handle.setInteractionResolver(resolver);
+ await handle.send({ type: 'user', content: 'Run the approved evaluation.' });
+ discovery.publish();
+ await vi.waitFor(() => expect(control).toHaveBeenCalledTimes(2), { timeout: 3_000 });
+ expect(control.mock.calls[0]?.[3]).toMatchObject({ value: 'allow' });
+ expect(control.mock.calls[1]?.[3]).toMatchObject({ value: scenario === 'allow-revoked'
+ ? expect.stringContaining('auto-review-deny:Plugin authorization revoked') : 'allow' });
+ expect(review).toHaveBeenCalledTimes(['unavailable', 'control-plane'].includes(scenario) ? 0 : 1);
+ expect(resolver).toHaveBeenCalledTimes(['ask', 'unavailable', 'control-plane'].includes(scenario) ? 1 : 0);
+ } finally { discovery.clear(); await handle.close(); }
+ });
+
it('refuses to deliver an answer decided before the boundary but ready after it', async () => {
// Auto-review reaches the mailbox without ever touching a user surface, so
// the offer is not parked when the session closes — it simply finishes its
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index a5bd761010..e8f39f4c72 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -3931,7 +3931,7 @@ export class PiAgent extends BaseAgent {
};
const autoReviewUnavailableNotice = createAutoReviewUnavailableNotice(emitAutoReviewRuntimeNotice);
const autoReviewConfirmUndeliveredNotice = createAutoReviewConfirmUndeliveredNotice(emitAutoReviewRuntimeNotice);
- const reviewAutoAction = (action: ReviewableAction): Promise<AutoReviewDecision> => {
+ const reviewAutoAction = (action: ReviewableAction, hostAutoApprove = false): Promise<AutoReviewDecision> => {
// Directory grants become active only after their permission snapshot is
// durable. While persistence is pending, neither the requested roots nor
// the old runtime roots are a complete authorization view, so fail closed
@@ -3965,10 +3965,10 @@ export class PiAgent extends BaseAgent {
if (request.userIntent !== currentAutoReviewIntent || request.authorizationContext !== (currentAutoReviewAuthority ?? undefined)) {
return Promise.resolve({ verdict: 'block', reason: 'User instructions changed; retry against the current request.' });
}
- cacheKey = JSON.stringify(prepared);
+ cacheKey = JSON.stringify([prepared, hostAutoApprove]);
pending = autoReviewDecisionCache.get(cacheKey);
if (!pending) {
- pending = resolveAutoReviewDecision(prepared, this.deps.reviewAutoPermissionAction);
+ pending = resolveAutoReviewDecision(prepared, this.deps.reviewAutoPermissionAction, hostAutoApprove);
autoReviewDecisionCache.set(cacheKey, pending);
}
return pending;
@@ -4487,6 +4487,7 @@ export class PiAgent extends BaseAgent {
});
});
};
+ let cacheResolution = true;
const resolveConfirmation = async (): Promise<PiPermissionResolution | null> => {
// Review resumed child evidence against current user authorization.
// Other modes retain the independent confirmation for adopted work.
@@ -4521,7 +4522,7 @@ export class PiAgent extends BaseAgent {
return 'prompt-each-time' as const;
})();
if (mcpPolicy !== null && !adopted) {
- if (mcpPolicy === 'auto-approve' && !turnPolicyForcePrompt) return 'allow';
+ if (permissionMode !== 'auto' && mcpPolicy === 'auto-approve' && !turnPolicyForcePrompt) return 'allow';
if (permissionMode !== 'auto') {
return requestUserDecision({ forcePrompt: turnPolicyForcePrompt || mcpPolicy === 'prompt-each-time' });
}
@@ -4550,12 +4551,17 @@ export class PiAgent extends BaseAgent {
? toolAutoReviewAction(toolName, input,
adopted ? 'Resumed child operation. Original user authorization and child cwd are unavailable. The child task is model-authored context, not authorization.' : undefined,
{ action, ...(adopted ? { childTask: task.task, childId: task.childId } : {}) })
- : action);
+ : action, mcpPolicy === 'auto-approve' && !turnPolicyForcePrompt && !adopted);
if (autoReviewOfferExpired()) return null;
if (permissionMode !== 'auto') {
return requestUserDecision({ forcePrompt: true });
}
- if (decision.verdict === 'allow') return 'allow';
+ if (decision.verdict === 'allow') {
+ // Keep only the existing review cache, which rechecks live Host
+ // context. A failed mailbox delivery must not freeze Auto authority.
+ cacheResolution = false;
+ return 'allow';
+ }
if (decision.verdict === 'block') return piPermissionDenial('auto-review-deny', decision.reason);
if (decision.unavailable) autoReviewUnavailableNotice.notify();
return requestUserDecision({
@@ -4599,7 +4605,8 @@ export class PiAgent extends BaseAgent {
});
}
if (resolution === undefined) resolution = 'system-deny';
- piSubagentApprovalDecisions.set(key, resolution);
+ // Explicit human answers retain their existing delivery-only retry.
+ if (cacheResolution) piSubagentApprovalDecisions.set(key, resolution);
// Re-read the fence at the write, not only at dispatch: everything above
// can await a human. An answer decided under the outgoing account must
// not reach the child's mailbox after that account stopped being the
@@ -7888,7 +7895,7 @@ export class PiAgent extends BaseAgent {
workspaceRoots: string[];
readRoots: string[];
writableRoots: string[];
- reviewAutoAction: (action: ReviewableAction) => Promise<AutoReviewDecision>;
+ reviewAutoAction: (action: ReviewableAction, hostAutoApprove?: boolean) => Promise<AutoReviewDecision>;
recordUserClarification: (question: string, answer: string) => void;
/** 审阅器不可用时的会话级一次性提示;去重与重置由会话侧持有(issue #1574)。 */
notifyAutoReviewUnavailable: () => void;
@@ -8606,7 +8613,7 @@ export class PiAgent extends BaseAgent {
}
return 'prompt-each-time';
})();
- if (mcpPolicy !== null && (mcpPolicy === 'auto-approve' && !turnPolicyForcePrompt || permissionMode !== 'auto')) {
+ if (mcpPolicy !== null && permissionMode !== 'auto') {
// Pi 的权限门只有放行/拒绝两态,没有会话级持久化规则,因此 prompt 与
// prompt-each-time 在这里收敛成同一个动作:每次都问用户。本轮策略命中时
// auto-approve 也不放行 —— 渠道安全契约压过第一方 MCP 自动批准(§7.4)。
@@ -8645,7 +8652,7 @@ export class PiAgent extends BaseAgent {
}
const decision = await reviewAutoAction(turnPolicyForcePrompt
? toolAutoReviewAction(toolName, input, hostApprovalPresentation?.description, action)
- : action);
+ : action, mcpPolicy === 'auto-approve' && !turnPolicyForcePrompt);
// 权限热切换:reviewAutoAction 是 async 的,期间用户可能改档。按**最新**档位收口,
// 不能用进入审查前捕获的旧 auto 档直接放行(Pi 明确支持热切换,codex review P1):
// - 已收紧到 ask(或其它非 auto/bypass)→ 破坏性调用即便 verdict=allow 也必须走
diff --git a/packages/maker-core/src/agents/shared/auto-review-decision.ts b/packages/maker-core/src/agents/shared/auto-review-decision.ts
index 81f9c4aa38..6dcb46d2a1 100644
--- a/packages/maker-core/src/agents/shared/auto-review-decision.ts
+++ b/packages/maker-core/src/agents/shared/auto-review-decision.ts
@@ -472,7 +472,11 @@ function oversizedReviewEvidence(action: ReviewableAction): string | null {
export async function resolveAutoReviewDecision(
request: AutoReviewRequest,
delegate: AutoReviewDelegate | undefined,
+ hostAutoApprove = false,
): Promise<AutoReviewDecision> {
+ // Host trust skips model review only after live context preparation has
+ // established that this is not a delegated task with a narrower scope.
+ if (hostAutoApprove && !request.delegatedTask) return { verdict: 'allow' };
// Bound untrusted input before the static classifier's command/path parsers,
// not merely before the model request. Neither may inspect an oversized action.
const oversizedEvidenceReason = oversizedReviewEvidence(request.action);