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: 防止子 Agent 直接弹出用户问答卡 (#3316)

Dash17c9604c28f9
diff --git a/packages/maker-cc-manager/__tests__/protocol.test.ts b/packages/maker-cc-manager/__tests__/protocol.test.ts
index 91075c8c7e..46fdc518f7 100644
--- a/packages/maker-cc-manager/__tests__/protocol.test.ts
+++ b/packages/maker-cc-manager/__tests__/protocol.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ CC_MGR_BUNDLE_VERSION,
PROTOCOL_VERSION,
METHODS,
NOTIFICATIONS,
@@ -18,8 +19,12 @@ describe('protocol constants', () => {
expect(PROTOCOL_VERSION).toBeGreaterThan(0);
});
- it('requires v4 so old daemons cannot ignore subagent model preflight', () => {
- expect(PROTOCOL_VERSION).toBe(4);
+ it('requires v5 so old daemons cannot reject native root-only guards', () => {
+ expect(PROTOCOL_VERSION).toBe(5);
+ });
+
+ it('bumps the daemon bundle when the wire contract changes', () => {
+ expect(CC_MGR_BUNDLE_VERSION).toBe('0.0.10');
});
it('METHODS has expected method names', () => {
diff --git a/packages/maker-cc-manager/__tests__/sdk-handlers.test.ts b/packages/maker-cc-manager/__tests__/sdk-handlers.test.ts
index f321aa1ef5..b89781a6b7 100644
--- a/packages/maker-cc-manager/__tests__/sdk-handlers.test.ts
+++ b/packages/maker-cc-manager/__tests__/sdk-handlers.test.ts
@@ -427,6 +427,22 @@ describe('sdk-handlers end-to-end', () => {
expect(latestFactoryOptions?.hooks?.PreToolUse?.[0]?.hooks[0]).toBeDefined();
});
+ it('query/start accepts a root-only guard for the native AskUserQuestion tool', async () => {
+ await ctx!.client.request('query/start', {
+ sessionId: 's-root-only-ask-user-question',
+ cwd: '/a',
+ model: 'm',
+ env: {},
+ toolGuards: [{
+ toolNamePrefix: 'AskUserQuestion',
+ sourceServerId: 'claude-code',
+ invocation: 'root-only',
+ }],
+ });
+ await waitFor(() => ctx!.notifications.length >= 1);
+ expect(latestFactoryOptions?.hooks?.PreToolUse?.[0]?.hooks[0]).toBeDefined();
+ });
+
it('query/close ends consume loop → session.alive=false + closed notification', async () => {
await ctx!.client.request('query/start', { sessionId: 's1', cwd: '/a', model: 'm', env: {} });
await waitFor(() => ctx!.notifications.length >= 1);
diff --git a/packages/maker-cc-manager/__tests__/session-registry.test.ts b/packages/maker-cc-manager/__tests__/session-registry.test.ts
index c8f7281d4f..2faeff764b 100644
--- a/packages/maker-cc-manager/__tests__/session-registry.test.ts
+++ b/packages/maker-cc-manager/__tests__/session-registry.test.ts
@@ -330,6 +330,42 @@ describe('SessionRegistry', () => {
})).resolves.toEqual({ continue: true });
});
+ it('allows AskUserQuestion for the root and denies it for nested Claude agents', async () => {
+ const { factory: baseFactory } = buildFakeFactory();
+ let captured: SdkQueryFactoryOptions | undefined;
+ const registry = new SessionRegistry({
+ sdkQueryFactory: (opts) => {
+ captured = opts;
+ return baseFactory(opts);
+ },
+ });
+ registry.create({
+ sessionId: 's-ask-user-question-root-only',
+ cwd: '/x',
+ model: 'm',
+ env: {},
+ toolGuards: [{
+ toolNamePrefix: 'AskUserQuestion',
+ sourceServerId: 'claude-code',
+ invocation: 'root-only',
+ denialMessage: 'NATIVE_SUBAGENT_USER_INPUT_NOT_ALLOWED',
+ }],
+ });
+ const preToolUse = captured?.hooks?.PreToolUse?.[0]?.hooks[0];
+ expect(preToolUse).toBeDefined();
+ const call = {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'AskUserQuestion',
+ };
+ await expect(preToolUse!(call)).resolves.toEqual({ continue: true });
+ await expect(preToolUse!({ ...call, agent_id: 'child-1' })).resolves.toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'deny',
+ permissionDecisionReason: 'NATIVE_SUBAGENT_USER_INPUT_NOT_ALLOWED',
+ },
+ });
+ });
+
it('keeps explicit selection across accepted same-turn steering inputs', async () => {
let captured: SdkQueryFactoryOptions | undefined;
const factory: SdkQueryFactory = (opts) => {
diff --git a/packages/maker-cc-manager/src/protocol.ts b/packages/maker-cc-manager/src/protocol.ts
index 79e2d1e0e6..2339146aa8 100644
--- a/packages/maker-cc-manager/src/protocol.ts
+++ b/packages/maker-cc-manager/src/protocol.ts
@@ -30,12 +30,16 @@
* 之前执行 Agent/Task 实时模型准入预检。旧 daemon 没有该执行边界,
* 会继续发起无权限请求,因此必须升级协议。
*
+ * v5: root-only toolGuards now accept the native `AskUserQuestion` tool name.
+ * Older daemons reject that exact guard as an invalid root-only tool and must
+ * be upgraded before remote queries send it.
+ *
* v1 (redesign): 删除 dead-session drain/archive 握手,对齐 codex 模式。
* reattach 只接新 events (live-only subscription),不 replay 旧 ring buffer。
* ring buffer 降级为纯内存 fast-path(同一 daemon 进程生命周期内的 mid-turn 续流)。
* 断开期间跑完的输出暂不自动补回 chat(follow-up: jsonl recovery 统一 cc + codex)。
*/
-export const PROTOCOL_VERSION = 4 as const;
+export const PROTOCOL_VERSION = 5 as const;
/**
* cc-mgr bundle 版本号 — 手动 bump。
@@ -44,7 +48,7 @@ export const PROTOCOL_VERSION = 4 as const;
* 无关依赖变化而变。desktop 用这个(而非 bundle sha256)判断远端 daemon
* 是否需要 upgrade,避免无关的 pnpm install 触发全量远端重装。
*/
-export const CC_MGR_BUNDLE_VERSION = '0.0.9' as const;
+export const CC_MGR_BUNDLE_VERSION = '0.0.10' as const;
export type RpcId = number;
@@ -216,7 +220,7 @@ export interface QueryStartParams {
}
export interface QueryToolGuard {
- /** Exact SDK tool-name prefix, for example `mcp__plugin_x_server__`. */
+ /** Exact SDK tool name for root-only guards, or a tool-name prefix otherwise. */
toolNamePrefix: string;
/** Exact harness-owned MCP server id before Claude normalizes punctuation. */
sourceServerId?: string;
diff --git a/packages/maker-cc-manager/src/sdk-handlers.ts b/packages/maker-cc-manager/src/sdk-handlers.ts
index 11d9f97759..203c86fd5d 100644
--- a/packages/maker-cc-manager/src/sdk-handlers.ts
+++ b/packages/maker-cc-manager/src/sdk-handlers.ts
@@ -402,7 +402,8 @@ function validateToolGuards(value: unknown): QueryToolGuard[] | undefined {
const toolNamePrefix = guard.toolNamePrefix.trim();
const sourceServerId = guard.sourceServerId?.trim();
const validToolName = guard.invocation === 'root-only'
- ? /^mcp__[A-Za-z0-9_-]+__[A-Za-z0-9_-]+$/.test(toolNamePrefix)
+ ? toolNamePrefix === 'AskUserQuestion'
+ || /^mcp__[A-Za-z0-9_-]+__[A-Za-z0-9_-]+$/.test(toolNamePrefix)
: /^mcp__[A-Za-z0-9_-]+__$/.test(toolNamePrefix);
if (!validToolName) {
throwInvalid(
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/capability-routing.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/capability-routing.test.ts
index b384936a3e..d06ee5b8e8 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/capability-routing.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/capability-routing.test.ts
@@ -2,12 +2,16 @@ import { describe, expect, it } from 'vitest';
import type { CapabilityRoutingPolicy } from '../../../types/capability-routing.js';
import {
+ buildClaudeAskUserQuestionCallerProvenanceHooks,
buildClaudeOrcaCallerProvenanceHooks,
buildClaudeRemoteOrcaCallerGuards,
+ buildClaudeRemoteRootOnlyToolGuards,
buildClaudeLocalToolGuardHooks,
buildClaudeRemoteToolGuards,
buildClaudeSkillOverrides,
mergeClaudeHookSets,
+ CLAUDE_ASK_USER_QUESTION_TOOL_NAME,
+ CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,
ORCA_SEND_TO_LEAD_TOOL_NAME,
} from '../capability-routing.js';
@@ -44,6 +48,41 @@ describe('Claude Orca caller provenance', () => {
}]);
expect(buildClaudeRemoteOrcaCallerGuards(false)).toEqual([]);
});
+
+ it('allows the root but denies a native subagent from asking the user', async () => {
+ const hook = buildClaudeAskUserQuestionCallerProvenanceHooks().PreToolUse?.[0]?.hooks[0];
+ if (!hook) throw new Error('expected AskUserQuestion caller provenance hook');
+ const input = {
+ hook_event_name: 'PreToolUse' as const,
+ session_id: 'session-ask-user-question',
+ transcript_path: '/tmp/transcript',
+ cwd: '/repo',
+ tool_name: CLAUDE_ASK_USER_QUESTION_TOOL_NAME,
+ tool_input: { questions: [] },
+ tool_use_id: 'tool-ask-user-question',
+ };
+
+ await expect(hook(input, 'tool-ask-user-question', {
+ signal: new AbortController().signal,
+ })).resolves.toEqual({ continue: true });
+ await expect(hook({ ...input, agent_id: 'native-child-1' }, 'tool-ask-user-question', {
+ signal: new AbortController().signal,
+ })).resolves.toMatchObject({
+ hookSpecificOutput: {
+ permissionDecision: 'deny',
+ permissionDecisionReason: CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,
+ },
+ });
+ });
+
+ it('serializes the native AskUserQuestion root-only guard for remote Claude', () => {
+ expect(buildClaudeRemoteRootOnlyToolGuards()).toEqual([{
+ toolNamePrefix: CLAUDE_ASK_USER_QUESTION_TOOL_NAME,
+ sourceServerId: 'claude-code',
+ invocation: 'root-only',
+ denialMessage: CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,
+ }]);
+ });
});
describe('buildClaudeSkillOverrides', () => {
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 872559c3ce..c168c0679d 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
@@ -1377,6 +1377,13 @@ describe('remote sessions share the same permission semantics', () => {
denialMessage:
'This downstream source was not explicitly selected. Use Cindy capability xd-feishu.',
},
+ {
+ toolNamePrefix: 'AskUserQuestion',
+ sourceServerId: 'claude-code',
+ invocation: 'root-only',
+ denialMessage:
+ 'NATIVE_SUBAGENT_USER_INPUT_NOT_ALLOWED: report the question to the parent agent, which can decide whether to ask the user.',
+ },
]);
await expect(
natural.onApprovalRequest({
@@ -1486,7 +1493,7 @@ describe('remote sessions share the same permission semantics', () => {
mcpServerNames: [userServerId],
});
- expect(remote.remoteStartParams?.toolGuards).toHaveLength(1);
+ expect(remote.remoteStartParams?.toolGuards).toHaveLength(2);
await expect(
remote.onApprovalRequest({
requestId: 'r-user-mcp-collision',
@@ -1568,7 +1575,7 @@ describe('remote sessions share the same permission semantics', () => {
failedInitMcpServerNames: [userServerId],
});
await new Promise<void>((resolve) => setTimeout(resolve, 0));
- expect(failed.remoteStartParams?.toolGuards).toHaveLength(1);
+ expect(failed.remoteStartParams?.toolGuards).toHaveLength(2);
await expect(
failed.onApprovalRequest({
requestId: 'r-failed-settings-mcp-collision',
diff --git a/packages/maker-core/src/agents/claude-code/capability-routing.ts b/packages/maker-core/src/agents/claude-code/capability-routing.ts
index fd1add5e23..7d52c01327 100644
--- a/packages/maker-core/src/agents/claude-code/capability-routing.ts
+++ b/packages/maker-core/src/agents/claude-code/capability-routing.ts
@@ -20,6 +20,9 @@ import { ORCA_NESTED_REPORT_DENIAL_REASON } from '../shared/orca-report-policy.j
const CLAUDE_CODE_HARNESS_ID = 'claude-code';
export const ORCA_SEND_TO_LEAD_TOOL_NAME = 'mcp__orca_worker_bridge__send_to_lead';
+export const CLAUDE_ASK_USER_QUESTION_TOOL_NAME = 'AskUserQuestion';
+export const CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON =
+ 'NATIVE_SUBAGENT_USER_INPUT_NOT_ALLOWED: report the question to the parent agent, which can decide whether to ask the user.';
/** Claude root calls have no agent_id; native subagents always carry one. */
export function buildClaudeOrcaCallerProvenanceHooks(): Partial<Record<HookEvent, HookCallbackMatcher[]>> {
@@ -40,6 +43,25 @@ export function buildClaudeOrcaCallerProvenanceHooks(): Partial<Record<HookEvent
return { PreToolUse: [{ matcher: ORCA_SEND_TO_LEAD_TOOL_NAME, hooks: [guardTool] }] };
}
+/** Native Claude subagents must report questions to the root agent. */
+export function buildClaudeAskUserQuestionCallerProvenanceHooks(): Partial<Record<HookEvent, HookCallbackMatcher[]>> {
+ const guardTool: HookCallback = async (input) => {
+ if (input.hook_event_name !== 'PreToolUse') return { continue: true };
+ const pre = input as PreToolUseHookInput;
+ if (pre.tool_name !== CLAUDE_ASK_USER_QUESTION_TOOL_NAME) return { continue: true };
+ if (typeof pre.agent_id !== 'string' || pre.agent_id.length === 0) return { continue: true };
+ return {
+ continue: true,
+ hookSpecificOutput: {
+ hookEventName: 'PreToolUse',
+ permissionDecision: 'deny',
+ permissionDecisionReason: CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,
+ },
+ };
+ };
+ return { PreToolUse: [{ matcher: CLAUDE_ASK_USER_QUESTION_TOOL_NAME, hooks: [guardTool] }] };
+}
+
function isClaudeSkillDirective(directive: CapabilityRouteOverride): boolean {
return (
directive.source.surface === 'skill' &&
@@ -96,6 +118,16 @@ export function buildClaudeRemoteOrcaCallerGuards(isOrcaWorker: boolean): Claude
}];
}
+/** JSON-safe remote equivalent of the native subagent user-input guard. */
+export function buildClaudeRemoteRootOnlyToolGuards(): ClaudeRemoteToolGuard[] {
+ return [{
+ toolNamePrefix: CLAUDE_ASK_USER_QUESTION_TOOL_NAME,
+ sourceServerId: 'claude-code',
+ invocation: 'root-only',
+ denialMessage: CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,
+ }];
+}
+
/**
* Build the JSON-safe routing guards enforced by the remote cc-manager as
* daemon-side PreToolUse hooks. Local callback hooks cannot cross the RPC
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 00fe20d734..7221b94745 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -113,9 +113,11 @@ import {
} from './env-builder.js';
import { buildClaudeFlagSettings } from './flag-settings.js';
import {
+ buildClaudeAskUserQuestionCallerProvenanceHooks,
buildClaudeOrcaCallerProvenanceHooks,
buildClaudeLocalToolGuardHooks,
buildClaudeRemoteOrcaCallerGuards,
+ buildClaudeRemoteRootOnlyToolGuards,
buildClaudeRemoteToolGuards,
mergeClaudeHookSets,
} from './capability-routing.js';
@@ -1575,6 +1577,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// rely on their observable order. The exact-match Orca provenance guard
// still runs for send_to_lead after those hooks and denies descendants.
buildClaudeOrcaCallerProvenanceHooks(),
+ buildClaudeAskUserQuestionCallerProvenanceHooks(),
this.deps.claudeHooks,
);
const deniedCapabilityRoute = (toolName: string) => {
@@ -2871,6 +2874,7 @@ export class ClaudeCodeAgent extends BaseAgent {
sdkInPlanMode = remotePermissionMode === 'plan';
const remoteToolGuards = [
...buildClaudeRemoteToolGuards(this.deps.capabilityRouting),
+ ...buildClaudeRemoteRootOnlyToolGuards(),
...buildClaudeRemoteOrcaCallerGuards(vo.orcaRole === 'worker'),
];
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 868adcee1a..d607efae7b 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -16417,6 +16417,139 @@ describe('CodexAgent MCP thread context hooks', () => {
await handle.close();
});
+ it('rejects descendant dynamic ask_user_question calls without opening an interaction', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-dynamic-user-input-descendant',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.dynamicToolCall || !handlers.descendantThreadStarted) {
+ throw new Error('expected dynamic tool and descendant thread handlers');
+ }
+ handlers.descendantThreadStarted({
+ thread: { id: 'child-thread-user-input', parentThreadId: 'start-thread-id' },
+ });
+ const resolveInteraction = vi.fn(async () => ({
+ kind: 'ask_user_question' as const,
+ answers: { 'Should I continue?': 'yes' },
+ }));
+ handle.setInteractionResolver(resolveInteraction);
+
+ const result = await handlers.dynamicToolCall({
+ threadId: 'child-thread-user-input',
+ turnId: 'turn-1',
+ callId: 'dynamic-call-descendant',
+ namespace: null,
+ tool: 'cindy__ask_user_question',
+ arguments: {
+ questions: [{ header: 'Direction', question: 'Should I continue?' }],
+ },
+ }, { requestId: 'req-dynamic-descendant' });
+
+ expect(result).toEqual({
+ contentItems: [{
+ type: 'inputText',
+ text: 'User questions are only available to the root agent. Report the question to the parent agent, which can decide whether to ask the user.',
+ }],
+ success: false,
+ });
+ expect(resolveInteraction).not.toHaveBeenCalled();
+ await handle.close();
+ });
+
+ it('rejects descendant native ask_user_question requests without opening an interaction', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-native-user-input-descendant',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.requestUserInput || !handlers.descendantThreadStarted) {
+ throw new Error('expected requestUserInput and descendant thread handlers');
+ }
+ handlers.descendantThreadStarted({
+ thread: { id: 'child-thread-native-user-input', parentThreadId: 'start-thread-id' },
+ });
+ const resolveInteraction = vi.fn();
+ handle.setInteractionResolver(resolveInteraction);
+
+ const result = await handlers.requestUserInput({
+ threadId: 'child-thread-native-user-input',
+ turnId: 'turn-native-descendant',
+ itemId: 'native-input-descendant',
+ questions: [{
+ id: 'direction',
+ header: 'Direction',
+ question: 'Choose child direction?',
+ isOther: false,
+ isSecret: false,
+ options: [],
+ }],
+ }, { requestId: 'req-native-descendant' });
+
+ expect(result).toEqual({ answers: {} });
+ expect(resolveInteraction).not.toHaveBeenCalled();
+ await handle.close();
+ });
+
+ it('keeps descendant native permission input requests available', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-native-permission-input-descendant',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.requestUserInput || !handlers.descendantThreadStarted || !handlers.descendantNotification) {
+ throw new Error('expected requestUserInput and descendant notification handlers');
+ }
+ handlers.descendantThreadStarted({
+ thread: { id: 'child-thread-permission-input', parentThreadId: 'start-thread-id' },
+ });
+ handlers.descendantNotification('child-thread-permission-input', 'item/started', {
+ threadId: 'child-thread-permission-input',
+ turnId: 'turn-permission-descendant',
+ item: {
+ id: 'child-permission-input',
+ type: 'mcpToolCall',
+ server: 'third_party',
+ tool: 'needs_confirmation',
+ },
+ });
+ const resolveInteraction = vi.fn(async (request: InteractionRequest): Promise<InteractionDecision> => {
+ expect(request.kind).toBe('permission');
+ return { kind: 'permission', behavior: 'allow' };
+ });
+ handle.setInteractionResolver(resolveInteraction);
+
+ const result = await handlers.requestUserInput({
+ threadId: 'child-thread-permission-input',
+ turnId: 'turn-permission-descendant',
+ itemId: 'child-permission-input',
+ questions: [{
+ id: 'confirm',
+ header: 'Confirm',
+ question: 'Allow the child tool?',
+ isOther: false,
+ isSecret: false,
+ options: [
+ { label: 'Deny', description: '' },
+ { label: 'Allow', description: '' },
+ ],
+ }],
+ }, { requestId: 'req-permission-descendant' });
+
+ expect(result).toEqual({ answers: { confirm: { answers: ['Allow'] } } });
+ expect(resolveInteraction).toHaveBeenCalledTimes(1);
+ await handle.close();
+ });
+
it('preserves submitted answers from different concurrent user input prompts', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent);
@@ -19645,6 +19778,7 @@ describe('CodexAgent turn lifecycle', () => {
|| !handlers.mcpServerElicitation
|| !handlers.permissionsApproval
|| !handlers.requestUserInput
+ || !handlers.serverRequestResolved
|| !handlers.dynamicToolCall
) {
throw new Error('expected all descendant server request handlers');
@@ -19709,7 +19843,7 @@ describe('CodexAgent turn lifecycle', () => {
itemId: 'child-permissions',
permissions: { network: true },
})).resolves.toEqual({ permissions: { network: true }, scope: 'turn' });
- await expect(handlers.requestUserInput({
+ const childInputPromise = handlers.requestUserInput({
...child,
itemId: 'child-input',
questions: [{
@@ -19720,8 +19854,13 @@ describe('CodexAgent turn lifecycle', () => {
isSecret: false,
options: [],
}],
- }, { requestId: 'child-input-request' })).resolves.toEqual({
- answers: { continue: { answers: ['Continue'] } },
+ }, { requestId: 'child-input-request' });
+ handlers.serverRequestResolved({
+ threadId: child.threadId,
+ requestId: 'child-input-request',
+ });
+ await expect(childInputPromise).resolves.toEqual({
+ answers: {},
});
await expect(handlers.dynamicToolCall({
...child,
@@ -19735,11 +19874,17 @@ describe('CodexAgent turn lifecycle', () => {
question: 'Choose child direction?',
}],
},
- }, { requestId: 'child-dynamic-request' })).resolves.toMatchObject({
- success: true,
+ }, { requestId: 'child-dynamic-request' })).resolves.toEqual({
+ contentItems: [{
+ type: 'inputText',
+ text: 'User questions are only available to the root agent. Report the question to the parent agent, which can decide whether to ask the user.',
+ }],
+ success: false,
});
- expect(resolver).toHaveBeenCalledTimes(6);
+ // The root orphan gate remains bypassed for verified descendants, but both
+ // user-question channels are root-owned and therefore do not open UI.
+ expect(resolver).toHaveBeenCalledTimes(4);
expect(host.request.mock.calls.filter(
([method]) => method === Method.TurnInterrupt,
)).toHaveLength(interruptsBeforeRequests);
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 06df5ba3b9..2e02eb01ac 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -658,6 +658,8 @@ const LEGACY_ASK_USER_DYNAMIC_TOOL_NAMESPACE = 'xdt_maker';
const ASK_USER_DYNAMIC_TOOL_NAME = 'ask_user_question';
const ASK_USER_DYNAMIC_TOOL_CANONICAL_NAME =
`${ASK_USER_DYNAMIC_TOOL_NAMESPACE}__${ASK_USER_DYNAMIC_TOOL_NAME}`;
+const CODEX_SUBAGENT_ASK_USER_QUESTION_DENIAL_MESSAGE =
+ 'User questions are only available to the root agent. Report the question to the parent agent, which can decide whether to ask the user.';
const MAX_REQUEST_USER_INPUT_QUESTIONS = 3;
const MAX_REQUEST_USER_INPUT_OPTIONS = 10;
const MAX_REQUEST_USER_INPUT_TEXT_CHARS = 1_000;
@@ -7263,8 +7265,7 @@ export class CodexAgent extends BaseAgent {
}
}
- function classifyUserInputRequest(params: ToolRequestUserInputParams): 'ask_user_question' | 'permission' {
- const ctx = activeToolContexts.get(params.itemId);
+ function classifyToolContext(ctx: ActiveToolContext | undefined): 'ask_user_question' | 'permission' {
if (!ctx) return 'ask_user_question';
if (ctx.type === 'mcpToolCall') return 'permission';
if (ctx.type === 'dynamicToolCall') {
@@ -7493,8 +7494,22 @@ export class CodexAgent extends BaseAgent {
if (resolvedWhileBufferedRequestIds.delete(requestId)) return { answers: {} };
const questions = normalizeRequestUserInputQuestions(params.questions);
if (questions.length === 0) return { answers: {} };
- const kind = classifyUserInputRequest(params);
+ // Codex 0.145 emits an MCP tool's item/started notification before it
+ // requests fallback approval through requestUserInput. Therefore an
+ // unknown descendant item is not a permission race: fail closed instead
+ // of adding a timer that can either hang or reject a legitimate request.
const activeToolContext = activeToolContexts.get(params.itemId);
+ const kind = classifyToolContext(activeToolContext);
+ if (kind === 'ask_user_question' && params.threadId !== threadId) {
+ log.warn('native requestUserInput rejected for descendant user question', {
+ requestId,
+ threadId: params.threadId,
+ rootThreadId: threadId,
+ turnId: params.turnId,
+ itemId: params.itemId,
+ });
+ return { answers: {} };
+ }
const hasToolGenerationBoundary =
activeToolContext?.type === 'mcpToolCall'
|| activeToolContext?.type === 'dynamicToolCall';
@@ -7570,6 +7585,19 @@ export class CodexAgent extends BaseAgent {
}
const toolUseId = activeDynamicToolUseId(params);
if (isAskUserDynamicTool(params)) {
+ // Codex app-server keeps dynamic tools at the root thread and may make
+ // them callable from descendant threads. User interaction is a
+ // root-owned capability: a native subagent must report the question to
+ // its parent instead of opening a Cindy card of its own.
+ if (params.threadId !== threadId) {
+ return {
+ contentItems: [{
+ type: 'inputText',
+ text: CODEX_SUBAGENT_ASK_USER_QUESTION_DENIAL_MESSAGE,
+ }],
+ success: false,
+ };
+ }
const requestId = String(meta.requestId);
// 挂起期间服务端已取消本请求 (greptile R13 P1): 直接回失败响应, 不注册
// broker 不上 UI (与 resolved 的 cancel 响应同款文案)。