Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(agent): 统一 Codex、Claude Code 和 Pi 的异步提问流程 (#5658)
Dashebf0c1604eb3
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 1c0eaf1220..c645f9210f 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -1011,6 +1011,16 @@ export function getMaker(): Maker {return Boolean(session && session.instanceId === sessionInstanceId&& session.getStatus() === 'active' && !isAppSessionBoundaryPending());},+ askUserQuestionAsync: (+ context: import('@cindy/mcps').LiziMcpSessionContext,+ questions: Parameters<import('@cindy/maker-core').Session['askUserQuestionAsync']>[0],+ ) => {+ const session = context.sessionId ? _maker?.getSession(context.sessionId) : undefined;+ if (!session || session.instanceId !== context.sessionInstanceId || isAppSessionBoundaryPending()) {+ throw new Error('Question caller is no longer active');+ }+ return session.askUserQuestionAsync(questions);+ },// 只读活跃 Session 的运行时真相。权限切换是 runtime-first、DB-second,// 因此插件过户自动放行不得回退 sessions.permission_mode;会话不再 active// 时同样 fail closed。闭包在 MCP tool-call 时执行,此时 _maker 已装配完成。diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 03d3dfe180..2fa59a8912 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -105,6 +105,7 @@ import { createSkillhubAgentTools } from '../skillhub/agentTools.js';import { startGrokDeviceLogin, grokDeviceLoginStatus, cancelGrokDeviceLogin } from '../maker-host/grok-device-login-service.js';export interface DesktopMcpProvidersDeps {+ askUserQuestionAsync?: XdtHelperMcpDeps['askUserQuestionAsync'];runtimeCapabilities?: XdtHelperMcpDeps['runtimeCapabilities'];botCapabilities: Pick<ReturnType<typeof createBotCapabilityService>, 'list' | 'select'>;createMediaDownloadContext?: CindyGhostsHostDeps['createMediaDownloadContext'];@@ -625,6 +626,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcreturn { ok: false, errorCode: 'INTERNAL', message };}},+ askUserQuestionAsync: deps.askUserQuestionAsync,renameSessions: async ({ changes, dryRun }) => {if (!tryGetDbClient()) {return { ok: false, errorCode: 'HOST_NOT_READY', message: 'localDb not ready' };diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 9b690f1dd0..b3c7d18753 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -307,13 +307,50 @@ sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计`goal-ownership.native.test.ts` 用隔离的原生运行时验证旧目标恢复后不再自行续跑。- **产品 turn 未结算不得结束。** provider `turn/completed` 可以立刻给 SDK turn 落墓碑并结算 usage;只有原子挂在该终态边界上的显式 continuation claim 才能挡住产品结束。- Codex 提问/计划审阅尚待用户确认时同样保留产品边界:底层可继续独立工作并结束+ Codex 同步提问/计划审阅尚待用户确认时同样保留产品边界:底层可继续独立工作并结束SDK turn,但不能触发完成通知、队列收口或协作任务完成。人工等待使用独立 claim,复用 `turnContinuationId`,不能塞进 yield claim 造成回答续跑等待自身。计划审阅必须在发布边界前登记;回答/批准后沿原意图续跑,取消/Stop 单次结束且不重复结算 usage。起跑回执之前到达的终态先缓冲再核对归属;失败只能走失败终态,不能先以取消回调触发定时任务的成功收口。回归见 `agents/codex/index.test.ts` 的 pending confirmation与 human continuation 用例,以及 Desktop `sessionEventPipeline.test.ts`。+ Codex 异步提问使用 `agentMessage.delivery=async` 与结构化 `questions` 接入同一提问+ 流程,不把回退正文当成最终回答。未回答的异步问题不保留产品边界,原轮次结束时自动+ 收起卡片、不代选答案,迟到回答不得续跑。结束前已提交的回答优先通过 `turn/steer`+ 送入原轮次;发送与结束竞态导致原轮次明确拒绝接收时复用人工续跑,发送结果不确定时+ 提示错误且不自动重发。Stop、失败、关闭及被替换问题的迟到回答不得续跑。+ 协议与前缀稳定性实测见 `agents/codex/async-user-input.native.test.ts`,+ 卡片、回传、去重及取消回归见 `agents/codex/index.test.ts`。+ Claude Code/Pi 通过 `cindy_helper.ask_user_question_async` 复用现有卡片;工具立即返回+ pending 回执。Codex 只保留原生入口,MCP 按请求时的 harness 隐藏并拒绝这条工具;+ `Session` 也按实际引擎拒绝 Codex 调用共享入口,防止陈旧上下文创建第二套待回答状态。+ Claude Code/Pi 的 `Session` 共用 `agents/shared/async-user-questions.ts` 管理问题寿命,+ 不登记阻塞交互或人工续跑。回答只走原执行的 steer,结束/Stop/关闭/替换后作废,+ 发送失败不重投新 turn。Claude 会把已排队的答案合并为下一 SDK 段:仅在答案已被接收+ 时复用现有 continuation claim 保留产品边界,避免提前完成或重复完成;未回答不建 claim。+ Pi 在原生 RPC 排队后再核对执行代次与取消信号,防止答案串到+ 下一次执行。Claude 的本机 hook 与远端 root-only guard 禁止原生子代理直接提问;工具+ 入口只接受宿主标明 `mcpCallerKind=root` 且 `mcpCallerAttested=true` 的请求,身份未知、+ 缺失或未证实均拒绝;不提供通用 call_tool 别名,避免绕过该判据。+ SSH、手机沿用既有 MCP/交互传输通道。+ 回归见 `session.async-user-questions.test.ts`、MCP `asyncUserQuestionTool.test.ts`;+ 两种真实 harness 配本地假模型的投递与稳定前缀实测见+ `agents/shared/async-user-questions.native.test.ts`。+ 同步与异步问题共用卡片时,同步问题优先:已有同步问题等待时不再显示异步卡片,+ 同步问题后到时收起未回答的异步卡片,避免遮住阻塞执行的问题。三个 harness 均只保留+ 最新一张待回答的异步卡片:显示新卡片前先将旧卡片标为被替换,旧答案即使在原轮次+ 结束前到达也不得投递或清除新卡片。Codex 的同步工具结果+ 仅在同步协议别名间按内容去重;异步只按 item id 去重事件,不共用 pending/submitted+ 答案缓存,同轮同文案的新 item 也必须重新询问。答案被接收后,卡片不再属于待回答+ 集合;即使投递尚未完成时遇到结束/Stop/替换,也只能取消投递,不能把已回答卡片+ 再标成过期。异步问题被跳过、取消或没有对应问题的非空答案时,只结算卡片,不更新+ 审查意图、不投递占位答案、不建立 continuation;同批问题至少一个有效答案仍可投递。+ Codex 复用规范化答案与 `hasSubmittedUserInput` 判据,同步提问的 Skip 行为保持不变。+ 交错回归见上述 Session 与 Codex 测试。+ 原生与共享异步请求均携带 `InteractionRequest.delivery=async`;Session 不把它们计入+ 阻塞交互或生命周期等待,未回答也不能暂停工具循环检测/零事件看门狗。字段缺省仍按+ 同步等待处理;Codex 本机/SSH 共用同一 adapter,手机卡片仍走既有宿主交互通道。+ 回归见 `session.tool-loop.test.ts`、`session.turn-stall.test.ts`。Codex `functions.exec` yield 没有协议级 execution handle(cell / wait 活在`codex-rs` daemon),近期检测只能是 adapter 内、用真实 rollout fixture 锁死的启发式,用来铸造有界 claim,再由宿主确定性开续段让模型 wait 同一 cell。diff --git a/packages/lizi-mcps/src/__tests__/asyncUserQuestionTool.test.ts b/packages/lizi-mcps/src/__tests__/asyncUserQuestionTool.test.tsnew file mode 100644index 0000000000..98fe11c077--- /dev/null+++ b/packages/lizi-mcps/src/__tests__/asyncUserQuestionTool.test.ts@@ -0,0 +1,90 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { describe, expect, it, vi } from 'vitest';+import { createXdtHelperMcpServer } from '../lizi_xdtHelperMcpServer.js';+import type { LiziMcpSessionContext } from '../types.js';++describe.each(['claude-code', 'pi'] as const)('%s async question MCP', (agentKind) => {+ it('discovers and calls the same tool with request-time identity and a pending-only receipt', async () => {+ let context: LiziMcpSessionContext | undefined = {+ agentKind, workingDir: '/repo', sessionId: 'task-1', sessionInstanceId: 'instance-1',+ mcpCallerKind: 'root', mcpCallerAttested: true, remoteHostId: 'ssh-host',+ };+ const ask = vi.fn(() => 'question-1');+ const server = createXdtHelperMcpServer({ askUserQuestionAsync: ask }, {+ agentKind, workingDir: '', getSessionContext: () => context,+ });+ const client = new Client({ name: 'question-test', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(st), client.connect(ct)]);+ const parse = (result: unknown) => JSON.parse((result as { content: Array<{ text: string }> }).content[0].text);+ const call = (args: Record<string, unknown>) => client.callTool({ name: 'ask_user_question_async', arguments: args });+ const questions = [{ question: 'Which scope?', options: [{ label: 'Personal' }, { label: 'Both' }] }];+ try {+ const prefix = await client.listTools();+ expect(prefix.tools.some((tool) => tool.name === 'ask_user_question_async')).toBe(true);+ const bypass = await client.callTool({ name: 'call_tool', arguments: { name: 'ask_user_question_async', args: { questions } } });+ expect(bypass.isError).toBe(true);+ expect(parse(await call({ questions }))).toEqual({ ok: true, request_id: 'question-1', status: 'pending' });+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'task-1', remoteHostId: 'ssh-host' }), questions);+ context = { ...context!, sessionId: 'task-2', sessionInstanceId: 'instance-2' };+ await call({ questions });+ expect(ask).toHaveBeenLastCalledWith(expect.objectContaining({ sessionId: 'task-2' }), questions);+ context = undefined;+ expect(parse(await call({ questions })).errorCode).toBe('NO_SESSION_CONTEXT');+ expect(ask).toHaveBeenCalledTimes(2);+ for (const [mcpCallerKind, mcpCallerAttested] of [+ ['descendant', true], ['unknown', true], [undefined, true],+ ['root', false], ['root', undefined], [undefined, undefined],+ ] as const) {+ context = { agentKind, workingDir: '/repo', sessionId: 'task-2', sessionInstanceId: 'instance-2',+ mcpCallerKind, mcpCallerAttested };+ expect(parse(await call({ questions })).errorCode).toBe('ROOT_REQUIRED');+ expect(ask).toHaveBeenCalledTimes(2);+ }+ // Tool arguments cannot supply the missing host provenance.+ expect((await call({ questions, mcpCallerKind: 'root', mcpCallerAttested: true })).isError).toBe(true);+ context = { ...context!, mcpCallerKind: 'root', mcpCallerAttested: true };+ expect((await call({ questions: [...questions, ...questions] })).isError).toBe(true);+ expect((await call({ questions, sessionId: 'spoofed' })).isError).toBe(true);+ expect(ask).toHaveBeenCalledTimes(2);+ ask.mockImplementationOnce(() => { throw new Error('stale instance'); });+ expect(parse(await call({ questions })).errorCode).toBe('QUESTION_UNAVAILABLE');+ expect(await client.listTools()).toEqual(prefix);+ } finally { await client.close(); await server.close(); }+ });+});++// The HTTP helper factory can serve different harnesses; its captured kind is+// not the authority for a tools/list or tools/call request.+it.each(['codex', 'claude-code'] as const)('keeps one async entry per harness with a %s factory', async (factoryKind) => {+ let context: LiziMcpSessionContext = {+ agentKind: 'claude-code', workingDir: '/repo', sessionId: 'task', sessionInstanceId: 'instance',+ mcpCallerKind: 'root', mcpCallerAttested: true,+ };+ const ask = vi.fn(() => 'question');+ const server = createXdtHelperMcpServer({ askUserQuestionAsync: ask }, {+ agentKind: factoryKind, workingDir: '', getSessionContext: () => context,+ });+ const client = new Client({ name: 'shared-question-test', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await Promise.all([server.connect(st), client.connect(ct)]);+ const questions = [{ question: 'Which scope?' }];+ try {+ const claudePrefix = await client.listTools();+ for (const agentKind of ['codex', 'pi', 'unknown', 'claude-code', 'codex']) {+ context = { ...context, agentKind };+ const supported = agentKind === 'claude-code' || agentKind === 'pi';+ expect((await client.listTools()).tools.some((t) => t.name === 'ask_user_question_async')).toBe(supported);+ ask.mockClear();+ // A cached tool name must not open a second card through direct invocation.+ const result = await client.callTool({ name: 'ask_user_question_async', arguments: { questions } });+ expect(result.isError === true).toBe(!supported);+ expect(ask).toHaveBeenCalledTimes(supported ? 1 : 0);+ const alias = await client.callTool({ name: 'call_tool', arguments: { name: 'ask_user_question_async', args: { questions } } });+ expect(alias.isError).toBe(true);+ }+ context = { ...context, agentKind: 'claude-code' };+ expect(await client.listTools()).toEqual(claudePrefix);+ } finally { await client.close(); await server.close(); }+});diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 658b874f7e..4f5343c013 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -6,7 +6,8 @@ import { registerSessionTagTools, type SessionTagsCallback } from './xdt-helper/** 设计:* - server name = `cindy_helper`,essential(常开,不可被用户关闭)- * - 所有工具走 `list_tools` / `call_tool` 两个入口,渐进式发现:+ * - 通用工具走 `list_tools` / `call_tool` 两个入口,渐进式发现:+ * 异步提问使用独立的 ask_user_question_async 入口,以便 harness 验证根代理身份。* - 'cindy' : 只读自省 (get_capabilities / get_current_session_id)* - 'auth' : 由 Host 保存凭证的供应商授权* - 'history' : 只读查询本地数据库聊天历史与输入队列 (list_workdirs /@@ -35,6 +36,7 @@ import { z } from 'zod';import { registerBotRoutineTools, type BotRoutineCallbacks } from './xdt-helper/botRoutineTools.js';import { registerGrokLoginTools, type GrokLoginCallbacks } from './xdt-helper/grok_login.js';import { jsonObjectArg } from './json-object-arg.js';+import { registerAsyncQuestionTool, supportsAsyncQuestionTool, type AskUserQuestionAsyncCallback } from './xdt-helper/ask_user_question_async.js';import { XdtHelperToolRegistry } from './lizi_xdtHelperToolRegistry.js';import { registerCreateProjectTool, type CreateProjectCallback } from './xdt-helper/create_project.js';@@ -801,6 +803,7 @@ export interface XdtHelperMcpDeps {* set_current_session_title 会被注册; 不注入则不出现在 list_tools 里。*/setCurrentSessionTitle?: SetCurrentSessionTitleDeps['setCurrentSessionTitle'];+ askUserQuestionAsync?: AskUserQuestionAsyncCallback;/*** 批量 session 标题更新回调。host 注入后, control 类工具 rename_sessions 会被注册。* 工具层负责 dry-run token 护栏; host 负责读取当前标题、校验前置条件和写库。@@ -1025,6 +1028,24 @@ export function createXdtHelperMcpServer(...(deps.authorizeCall ? { authorizeCall: deps.authorizeCall } : {}),}, allowedSurface);+ // A dedicated tool identity lets native Claude enforce root-only provenance+ // before MCP dispatch. Do not expose an alias through the generic call_tool.+ const questionTools: Tool[] = [];+ if (deps.askUserQuestionAsync) {+ const questions = new XdtHelperToolRegistry();+ registerAsyncQuestionTool(questions, () => resolveLiziMcpSessionContext(sessionCtx), deps.askUserQuestionAsync);+ const definition = questions.get('ask_user_question_async')!;+ const inputSchema = z.strictObject(definition.inputShape);+ server.registerTool(definition.name, { description: definition.description, inputSchema }, async (args) => {+ if (!(await allowedSurface()).categories?.has('cindy')) {+ return errorPayload('CAPABILITY_NOT_AVAILABLE', 'Question UI is unavailable for this task.');+ }+ return questions.call(definition.name, args);+ });+ questionTools.push({ name: definition.name, description: definition.description,+ inputSchema: z.toJSONSchema(inputSchema) as Tool['inputSchema'] });+ }+// Pi already provides direct Bot tools through its native bridge. CC and Codex// consume MCP tools/list instead; expose the same registered definitions there.// Resolve identity per request: Codex's HTTP server is shared across sessions.@@ -1062,11 +1083,16 @@ export function createXdtHelperMcpServer(}));// Codex/remote Claude share one helper factory; rewrite ghost guidance from// the request-time session, not the empty factory ctx.- server.server.setRequestHandler(ListToolsRequestSchema, async () => ({- tools: (await allowedSurface()).categories?.has('bots')- ? [...entryTools, ...withCindyGatedBotToolDescriptions(botTools, cindyAvailableForSession(sessionCtx))]- : entryTools,- }));+ server.server.setRequestHandler(ListToolsRequestSchema, async () => {+ const allowed = await allowedSurface();+ return { tools: [+ ...entryTools,+ ...(allowed.categories?.has('cindy') && supportsAsyncQuestionTool(resolveLiziMcpSessionContext(sessionCtx))+ ? questionTools : []),+ ...(allowed.categories?.has('bots')+ ? withCindyGatedBotToolDescriptions(botTools, cindyAvailableForSession(sessionCtx)) : []),+ ] };+ });}return server;}diff --git a/packages/lizi-mcps/src/xdt-helper/ask_user_question_async.ts b/packages/lizi-mcps/src/xdt-helper/ask_user_question_async.tsnew file mode 100644index 0000000000..fc33d20ee6--- /dev/null+++ b/packages/lizi-mcps/src/xdt-helper/ask_user_question_async.ts@@ -0,0 +1,61 @@+import type { Session } from '@cindy/maker-core';+import { z } from 'zod';+import type { LiziMcpSessionContext } from '../types.js';+import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';+import { errorPayload, okPayload } from './_payload.js';++export type AskUserQuestionAsyncCallback = (+ context: LiziMcpSessionContext,+ questions: Parameters<Session['askUserQuestionAsync']>[0],+) => string;++// Codex owns async questions through its native protocol. Exposing this second+// path there would give the same card two independent lifecycle owners.+export function supportsAsyncQuestionTool(context: LiziMcpSessionContext): boolean {+ return context.agentKind === 'claude-code' || context.agentKind === 'pi';+}++export function registerAsyncQuestionTool(+ registry: XdtHelperToolRegistry,+ getContext: () => LiziMcpSessionContext,+ ask: AskUserQuestionAsyncCallback,+): void {+ registry.register({+ name: 'ask_user_question_async',+ category: 'cindy',+ description: 'Ask optional questions in Cindy cards and immediately continue independent work. '+ + 'This returns a pending receipt, not an answer. User answers arrive as same-turn input. '+ + 'Unanswered questions expire when execution ends; never infer a choice. '+ + 'Use your synchronous question tool when work must wait for the answer. Not for permissions or approvals.',+ inputShape: {+ questions: z.array(z.object({+ question: z.string().trim().min(1).max(2000),+ options: z.array(z.object({+ label: z.string().trim().min(1).max(256),+ description: z.string().max(1000).optional(),+ }).strict()).min(2).max(6).optional(),+ }).strict()).min(1).max(3).refine(+ (questions) => new Set(questions.map((q) => q.question)).size === questions.length,+ 'Questions must be distinct',+ ),+ },+ handler: async ({ questions }) => {+ const context = getContext();+ if (!context.sessionId || !context.sessionInstanceId) {+ return errorPayload('NO_SESSION_CONTEXT', 'No current task instance for this question.');+ }+ if (!supportsAsyncQuestionTool(context)) {+ return errorPayload('CAPABILITY_NOT_AVAILABLE', 'Use your native question tool.');+ }+ if (context.mcpCallerKind !== 'root' || context.mcpCallerAttested !== true) {+ return errorPayload('ROOT_REQUIRED', 'Ask the parent agent to relay the question.');+ }+ try {+ const requestId = ask(context, questions);+ return okPayload({ request_id: requestId, status: 'pending' });+ } catch {+ return errorPayload('QUESTION_UNAVAILABLE', 'No active task with question UI and same-turn input support.');+ }+ },+ });+}diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 01f79fd0c0..9fec92ab53 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -1983,6 +1983,8 @@ export interface StartSessionOptions {* this proof. Main dispatchers attach it only after authenticating the source.*/export const MAIN_OWNED_SEND_CONTEXT = Symbol('cindy.main-owned-send-context');+/** Optional question replies must never be queued for a later execution. */+export const ASYNC_QUESTION_ANSWER = Symbol('cindy.async-question-answer');/** Call-local user content before Session replaces images with generated descriptions. */export const AUTO_REVIEW_SOURCE_CONTENT = Symbol('cindy.auto-review-source-content');@@ -2024,6 +2026,7 @@ export interface MainOwnedSendContext {* 缺省 / 不识别字段必须安全忽略。*/export interface SendOptions {+ readonly [ASYNC_QUESTION_ANSWER]?: true;readonly [AUTO_REVIEW_SOURCE_CONTENT]?: UserMessage['content'];readonly [AUTO_REVIEW_USER_INTENT]?: AutoReviewUserIntent;readonly [AUTO_REVIEW_DELEGATED_CONTINUATION]?: true;diff --git a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.tsindex a585b3a106..2cf2c667c2 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts@@ -22,6 +22,7 @@ import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import type { AgentDeps, AgentSessionHandle } from '../../base-agent.js';+import { ASYNC_QUESTION_ANSWER } from '../../base-agent.js';import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';import type { AgentEvent } from '../../../types/events.js';import type { Logger } from '../../../interfaces/logger.js';@@ -525,6 +526,44 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await handle.close();});+ it.each([1, 2])('retains the product for a batch of %i submitted async answers without adding a wake task', async (count) => {+ const { handle, stream, events } = await startSessionWithStream();+ try {+ await handle.send({ type: 'user', content: 'independent work' });+ for (let i = 0; i < count; i++) {+ await handle.steer({ type: 'user', content: `answer ${i}` }, { [ASYNC_QUESTION_ANSWER]: true });+ }+ stream.emit(turnResult('original work complete'));+ await waitFor(() => events.some((e) => e.type === 'done'), 'original SDK boundary');+ const boundary = events.find((e) => e.type === 'done')!;+ expect(boundary.turnContinuationId).toBeTypeOf('number');+ expect(handle.isTurnRunning?.()).toBe(true);+ expect(handle.listBackgroundTasks?.()).toEqual([]);+ expect(events.filter(isProductTerminal)).toHaveLength(0);+ stream.emit(assistantText('using the answers'));+ stream.emit(turnResult('answer work complete'));+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'one product terminal');+ expect(handle.isTurnRunning?.()).toBe(false);+ } finally { await handle.close(); }+ });++ it.each(['abort', 'requestGracefulStop'] as const)('cancels accepted-answer continuation on %s without reviving it', async (action) => {+ const { handle, stream, streams, events } = await startSessionWithStream();+ try {+ await handle.send({ type: 'user', content: 'work' });+ await handle.steer({ type: 'user', content: 'answer' }, { [ASYNC_QUESTION_ANSWER]: true });+ stream.emit(turnResult());+ await waitFor(() => events.some((e) => e.type === 'done'), 'claimed SDK boundary');+ await handle[action]?.();+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'cancelled product');+ streams[0].emit(assistantText('late answer processing'));+ streams[0].emit(turnResult());+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(events.filter(isProductTerminal)).toHaveLength(1);+ expect(handle.isTurnRunning?.()).toBe(false);+ } finally { await handle.close(); }+ });+it('graceful stop cancels an awaiting wake continuation and rebuilds before the next send', async () => {const { handle, stream, streams, events, fakeQuery, fakeQueries } =await startSessionWithStream();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.tsindex d06ee5b8e8..c07b414dc9 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@@ -11,6 +11,7 @@ import {buildClaudeSkillOverrides,mergeClaudeHookSets,CLAUDE_ASK_USER_QUESTION_TOOL_NAME,+ CINDY_ASYNC_QUESTION_TOOL_NAME,CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,ORCA_SEND_TO_LEAD_TOOL_NAME,} from '../capability-routing.js';@@ -49,15 +50,15 @@ 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];+ it.each([CLAUDE_ASK_USER_QUESTION_TOOL_NAME, CINDY_ASYNC_QUESTION_TOOL_NAME])('allows only the root to ask using %s', async (toolName) => {+ const hook = buildClaudeAskUserQuestionCallerProvenanceHooks().PreToolUse?.find((entry) => entry.matcher === toolName)?.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_name: toolName,tool_input: { questions: [] },tool_use_id: 'tool-ask-user-question',};@@ -81,6 +82,11 @@ describe('Claude Orca caller provenance', () => {sourceServerId: 'claude-code',invocation: 'root-only',denialMessage: CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,+ }, {+ toolNamePrefix: CINDY_ASYNC_QUESTION_TOOL_NAME,+ sourceServerId: 'cindy_helper',+ invocation: 'root-only',+ denialMessage: CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,}]);});});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 b6dd904441..8d550cee35 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@@ -1781,6 +1781,13 @@ describe('remote sessions share the same permission semantics', () => {denialMessage:'NATIVE_SUBAGENT_USER_INPUT_NOT_ALLOWED: report the question to the parent agent, which can decide whether to ask the user.',},+ {+ toolNamePrefix: 'mcp__cindy_helper__ask_user_question_async',+ sourceServerId: 'cindy_helper',+ 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({@@ -1890,7 +1897,10 @@ describe('remote sessions share the same permission semantics', () => {mcpServerNames: [userServerId],});- expect(remote.remoteStartParams?.toolGuards).toHaveLength(2);+ expect(remote.remoteStartParams?.toolGuards).toHaveLength(3);+ expect(remote.remoteStartParams?.toolGuards).toContainEqual(expect.objectContaining({+ toolNamePrefix: 'mcp__cindy_helper__ask_user_question_async', invocation: 'root-only',+ }));await expect(remote.onApprovalRequest({requestId: 'r-user-mcp-collision',@@ -1972,7 +1982,10 @@ describe('remote sessions share the same permission semantics', () => {failedInitMcpServerNames: [userServerId],});await new Promise<void>((resolve) => setTimeout(resolve, 0));- expect(failed.remoteStartParams?.toolGuards).toHaveLength(2);+ expect(failed.remoteStartParams?.toolGuards).toHaveLength(3);+ expect(failed.remoteStartParams?.toolGuards).toContainEqual(expect.objectContaining({+ toolNamePrefix: 'mcp__cindy_helper__ask_user_question_async', invocation: 'root-only',+ }));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.tsindex 7d52c01327..e05e7e67c6 100644--- a/packages/maker-core/src/agents/claude-code/capability-routing.ts+++ b/packages/maker-core/src/agents/claude-code/capability-routing.ts@@ -21,6 +21,8 @@ import { ORCA_NESTED_REPORT_DENIAL_REASON } from '../shared/orca-report-policy.jconst 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 CINDY_ASYNC_QUESTION_TOOL_NAME = 'mcp__cindy_helper__ask_user_question_async';+const USER_QUESTION_TOOLS = [CLAUDE_ASK_USER_QUESTION_TOOL_NAME, CINDY_ASYNC_QUESTION_TOOL_NAME];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.';@@ -48,7 +50,7 @@ export function buildClaudeAskUserQuestionCallerProvenanceHooks(): Partial<Recorconst 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 (!USER_QUESTION_TOOLS.includes(pre.tool_name)) return { continue: true };if (typeof pre.agent_id !== 'string' || pre.agent_id.length === 0) return { continue: true };return {continue: true,@@ -59,7 +61,7 @@ export function buildClaudeAskUserQuestionCallerProvenanceHooks(): Partial<Recor},};};- return { PreToolUse: [{ matcher: CLAUDE_ASK_USER_QUESTION_TOOL_NAME, hooks: [guardTool] }] };+ return { PreToolUse: USER_QUESTION_TOOLS.map((matcher) => ({ matcher, hooks: [guardTool] })) };}function isClaudeSkillDirective(directive: CapabilityRouteOverride): boolean {@@ -120,12 +122,12 @@ 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',+ return USER_QUESTION_TOOLS.map((toolNamePrefix) => ({+ toolNamePrefix,+ sourceServerId: toolNamePrefix === CLAUDE_ASK_USER_QUESTION_TOOL_NAME ? 'claude-code' : 'cindy_helper',+ invocation: 'root-only' as const,denialMessage: CLAUDE_SUBAGENT_ASK_USER_QUESTION_DENIAL_REASON,- }];+ }));}/**diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 6928a38d35..f3253cd4c8 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -65,6 +65,7 @@ import {AgentStartupCleanupPendingError,TurnPermissionPolicyUnsupportedError,PINNED_SKILL_INVOCATION,+ ASYNC_QUESTION_ANSWER,DEVICE_HOSTED_GUEST_ROUTE_HEADER,type AgentSessionHandle,type AgentDeps,@@ -4624,11 +4625,15 @@ export class ClaudeCodeAgent extends BaseAgent {pendingBoundaryEvents: number;/** A later natural/synthetic done has closed the product turn. */settled: boolean;+ /** A submitted async answer already accepted by the SDK input queue. */+ asyncAnswer?: boolean;};// Claims are created synchronously when the provider enqueues a `done`.// The id is attached to that exact event, so a fast task_notification or// result-only continuation cannot change what the host later observes.let nextContinuationId = 1;+ // Claude coalesces input queued before the next SDK segment into one turn.+ let queuedAsyncAnswer = false;let activeContinuationId: number | null = null;// User Stop can close an awaiting product continuation while the provider// still has buffered activity. Suppress that cancelled tail until its@@ -4688,6 +4693,7 @@ export class ClaudeCodeAgent extends BaseAgent {}};const cancelActiveContinuation = (reason: string): ContinuationClaim | null => {+ queuedAsyncAnswer = false;const claim = activeContinuationClaim();if (!claim || claim.state !== 'awaiting') return null;claim.state = 'cancelled';@@ -4712,6 +4718,7 @@ export class ClaudeCodeAgent extends BaseAgent {releaseSettledContinuationClaim(claim);};const discardActiveContinuation = (reason: string, forceRelease = false): void => {+ queuedAsyncAnswer = false;clearWakeContractReconciliation();if (continuationClaims.size > 0) {log.debug('discarding turn continuation claims', {@@ -4783,6 +4790,7 @@ export class ClaudeCodeAgent extends BaseAgent {interruptedGeneration ||continuationCancellationGeneration === turnState.generation) {+ queuedAsyncAnswer = false;if (interruptedGeneration && existing) retireContinuationTasks(existing);return wasActiveContinuation;}@@ -4790,13 +4798,16 @@ export class ClaudeCodeAgent extends BaseAgent {for (const [taskId] of wakeTasks) {if (!carriedTasks.has(taskId)) carriedTasks.set(taskId, 'running');}- if (carriedTasks.size === 0) return wasActiveContinuation;+ const asyncAnswer = queuedAsyncAnswer;+ queuedAsyncAnswer = false;+ if (carriedTasks.size === 0 && !asyncAnswer) return wasActiveContinuation;const claim: ContinuationClaim = {id: nextContinuationId++,state: 'awaiting',tasks: carriedTasks,pendingBoundaryEvents: 1,settled: false,+ ...(asyncAnswer ? { asyncAnswer: true } : {}),};continuationClaims.set(claim.id, claim);activeContinuationId = claim.id;@@ -4833,6 +4844,7 @@ export class ClaudeCodeAgent extends BaseAgent {// concurrent interrupt resolving or rejecting; waiting for that control// result would leak the claim when no further provider event can exist.if (+ !claim.asyncAnswer &&states.length > 0 &&states.every((state) => state === 'stopped')) {@@ -4954,7 +4966,7 @@ export class ClaudeCodeAgent extends BaseAgent {}};const claimTasksAllTerminal = (claim: ContinuationClaim): boolean => {- if (claim.tasks.size === 0) return false;+ if (claim.tasks.size === 0) return claim.asyncAnswer === true;for (const state of claim.tasks.values()) {if (state === 'running') return false;}@@ -5197,6 +5209,7 @@ export class ClaudeCodeAgent extends BaseAgent {// 后台任务表旁路观察(O(1) type check,task 事件低频,不碰热路径逻辑)。const cancelledContinuation = noteBackgroundTaskEvent(e);if (ignoredLateTerminalTaskEvents.delete(e)) return true;+ if (e.type === 'error' && isTerminalAgentErrorEvent(e)) queuedAsyncAnswer = false;if (queuedBridgeTurns > 0) {if (e.type === 'done') {rememberBridgeSuppressedDoneData(e.data);@@ -6775,6 +6788,7 @@ export class ClaudeCodeAgent extends BaseAgent {// received it.throw new Error('No active Claude turn to steer: input queue is closed');}+ if (sendOpts?.[ASYNC_QUESTION_ANSWER]) queuedAsyncAnswer = true;appendActiveCapabilitySelectionText(userMessageTextForCapabilityRouting(message.content),);diff --git a/packages/maker-core/src/agents/codex/async-user-input.native.test.ts b/packages/maker-core/src/agents/codex/async-user-input.native.test.tsnew file mode 100644index 0000000000..ce4fcbcf22--- /dev/null+++ b/packages/maker-core/src/agents/codex/async-user-input.native.test.ts@@ -0,0 +1,140 @@+/** Opt-in protocol check; uses a private home and a local fake model, no account or API spend. */+import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { createServer, type ServerResponse } from 'node:http';+import { expect, it, vi } from 'vitest';+import { AppServerHost } from './app-server/host.js';+import { createStdioTransport } from './app-server/stdioTransport.js';+import { Method, type ItemEnvelope, type ThreadStartResponse, type TurnStartResponse } from './app-server/protocol.js';+import { asyncUserInputQuestions } from './async-user-input.js';+import type { Logger } from '../../interfaces/logger.js';++const binaryPath = process.env.CINDY_CODEX_TEST_BINARY;+const logger: Logger = {+ trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger,+};++it.skipIf(!binaryPath).each(['during', 'after', 'unanswered'] as const)(+ 'native async question lifecycle with answer=%s', async (answerTiming) => {+ const root = await mkdtemp(path.join(tmpdir(), 'cindy-async-question-'));+ const codexHome = path.join(root, 'codex-home');+ const workingDir = path.join(root, 'workdir');+ await mkdir(codexHome);+ await mkdir(workingDir);+ const requests: Array<{ instructions?: string; input: Array<Record<string, unknown>> }> = [];+ let continueResponse: ServerResponse | undefined;+ const send = (res: ServerResponse, item: unknown, number: number) => {+ const id = `response-${number}`;+ const events = [+ { type: 'response.created', response: { id } },+ { type: 'response.output_item.done', item },+ { type: 'response.completed', response: { id, usage: {+ input_tokens: 100, input_tokens_details: { cached_tokens: 80 }, output_tokens: 10, total_tokens: 110,+ } } },+ ];+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });+ res.end(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(''));+ };+ const answer = { type: 'message', role: 'assistant', id: 'answer',+ content: [{ type: 'output_text', text: 'Independent work completed.' }] };+ const server = createServer(async (req, res) => {+ if (req.method !== 'POST' || !req.url?.endsWith('/responses')) {+ res.writeHead(404).end();+ return;+ }+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8')));+ if (requests.length === 1) {+ send(res, { type: 'function_call', name: 'request_user_input_async', call_id: 'ask-async-1',+ arguments: JSON.stringify({ questions: [{ title: 'Which bot?', options: ['Personal', 'Both'] }] }),+ }, 1);+ } else if (requests.length === 2) {+ continueResponse = res;+ } else {+ send(res, answer, requests.length);+ }+ });+ let host: AppServerHost | undefined;+ try {+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('missing local address');+ await writeFile(path.join(codexHome, 'config.toml'), `+model = "gpt-6-astra"+model_provider = "mock"+approval_policy = "never"+sandbox_mode = "read-only"+[model_providers.mock]+name = "Local async question test"+base_url = "http://127.0.0.1:${address.port}/v1"+wire_api = "responses"+request_max_retries = 0+stream_max_retries = 0+`);+ host = new AppServerHost({+ createTransport: () => createStdioTransport({ binaryPath: binaryPath!, cwd: workingDir,+ env: { ...process.env, CODEX_HOME: codexHome, OPENAI_API_KEY: 'invalid-test-key' } }),+ logger, clientInfo: { name: 'cindy-async-question-test', version: '0.0.0' },+ });+ const thread = await host.request<ThreadStartResponse>(Method.ThreadStart, {+ model: 'gpt-6-astra', modelProvider: 'mock', cwd: workingDir,+ approvalPolicy: 'never', sandbox: 'read-only',+ }, { timeoutMs: 10_000 });+ const items: ItemEnvelope[] = [];+ let completed = false;+ const completedStatuses: string[] = [];+ const blockingQuestions = vi.fn(async () => ({ answers: {} }));+ const subscription = host.subscribeThread(thread.thread.id, {+ itemCompleted: (params) => { items.push(params.item); },+ requestUserInput: blockingQuestions,+ turnCompleted: (params) => { completedStatuses.push(params.turn.status); completed = true; },+ });+ const turn = await host.request<TurnStartResponse>(Method.TurnStart, {+ threadId: thread.thread.id, input: [{ type: 'text', text: 'Ask which bot and continue independent work.' }],+ }, { timeoutMs: 10_000 });+ await vi.waitFor(() => expect(continueResponse).toBeDefined(), { timeout: 10_000 });+ const question = items.find((item) => item.delivery === 'async');+ expect(question).toMatchObject({ type: 'agentMessage', id: 'ask-async-1',+ questions: [{ title: 'Which bot?', options: ['Personal', 'Both'] }] });+ expect(asyncUserInputQuestions(question!)?.[0]?.question).toBe('Which bot?');+ const answerInput = [{ type: 'text', text: 'Q: Which bot?\nA: Both' }];+ if (answerTiming === 'during') {+ await host.request(Method.TurnSteer, { threadId: thread.thread.id, expectedTurnId: turn.turn.id,+ input: answerInput,+ }, { timeoutMs: 10_000 });+ }+ send(continueResponse!, answer, 2);+ await vi.waitFor(() => expect(completed).toBe(true), { timeout: 10_000 });+ if (answerTiming !== 'during') {+ // There is no outstanding request holding the native turn open.+ expect(requests).toHaveLength(2);+ await expect(host.request(Method.TurnSteer, {+ threadId: thread.thread.id, expectedTurnId: turn.turn.id, input: answerInput,+ }, { timeoutMs: 10_000 })).rejects.toThrow(/no active turn/i);+ }+ if (answerTiming === 'after') {+ completed = false;+ await host.request(Method.TurnStart, { threadId: thread.thread.id, input: answerInput }, { timeoutMs: 10_000 });+ await vi.waitFor(() => expect(completed).toBe(true), { timeout: 10_000 });+ }+ await subscription.release();+ expect(blockingQuestions).not.toHaveBeenCalled();+ expect(completedStatuses).toEqual(answerTiming === 'after' ? ['completed', 'completed'] : ['completed']);+ expect(requests).toHaveLength(answerTiming === 'unanswered' ? 2 : 3);+ if (answerTiming !== 'unanswered') expect(JSON.stringify(requests[2].input)).toContain('A: Both');+ // The event bridge and answer must not change the stable prompt prefix.+ expect(requests.at(-1)?.instructions).toEqual(requests[0].instructions);+ const prefix = (request: typeof requests[number]) => request.input+ .filter((item) => item.role === 'system' || item.role === 'developer')+ .map(({ id: _id, ...item }) => item);+ expect(prefix(requests.at(-1)!)).toEqual(prefix(requests[0]));+ } finally {+ continueResponse?.destroy();+ await host?.shutdown();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ }+}, 25_000);diff --git a/packages/maker-core/src/agents/codex/async-user-input.test.ts b/packages/maker-core/src/agents/codex/async-user-input.test.tsnew file mode 100644index 0000000000..4c20ccccfd--- /dev/null+++ b/packages/maker-core/src/agents/codex/async-user-input.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';+import { asyncUserInputQuestions } from './async-user-input.js';++describe('Codex async user input message', () => {+ const message = { type: 'agentMessage', id: 'call-1', delivery: 'async', text: 'Fallback text' };++ it('keeps choices and free-form questions in order with stable distinct answer ids', () => {+ const questions = asyncUserInputQuestions({ ...message, questions: [+ { title: 'Which bot?', options: ['Personal', 'Official', 'Both'] },+ { title: 'Any constraints?', options: null },+ ] });+ expect(questions).toEqual([+ { id: 'call-1-question-1', header: '', question: 'Which bot?', isOther: true, isSecret: false,+ options: ['Personal', 'Official', 'Both'].map((label) => ({ label, description: null })) },+ { id: 'call-1-question-2', header: '', question: 'Any constraints?', isOther: true, isSecret: false, options: null },+ ]);+ });++ it.each([+ {}, { delivery: null }, { id: '' }, { questions: [] },+ { questions: [{ title: '' }] }, { questions: [{ title: 'Question', options: [42] }] },+ { questions: [{ title: 'Question' }, null] },+ ])('leaves ordinary or malformed messages on the existing text path: %j', (override) => {+ expect(asyncUserInputQuestions({ ...message, ...override })).toBeNull();+ });+});diff --git a/packages/maker-core/src/agents/codex/async-user-input.ts b/packages/maker-core/src/agents/codex/async-user-input.tsnew file mode 100644index 0000000000..b1d35b47e9--- /dev/null+++ b/packages/maker-core/src/agents/codex/async-user-input.ts@@ -0,0 +1,22 @@+import type { ItemEnvelope, ToolRequestUserInputQuestion } from './app-server/protocol.js';++/** Codex 0.159 async questions arrive as messages, not server requests. */+export function asyncUserInputQuestions(item: ItemEnvelope): ToolRequestUserInputQuestion[] | null {+ if (item.type !== 'agentMessage' || item.delivery !== 'async' || !item.id?.trim()+ || !Array.isArray(item.questions) || item.questions.length === 0) return null;+ const questions: ToolRequestUserInputQuestion[] = [];+ for (const raw of item.questions) {+ if (!raw || typeof raw !== 'object' || typeof raw.title !== 'string' || !raw.title.trim()+ || (raw.options != null && (!Array.isArray(raw.options)+ || raw.options.some((option: unknown) => typeof option !== 'string')))) return null;+ questions.push({+ id: `${item.id}-question-${questions.length + 1}`,+ header: '',+ question: raw.title,+ isOther: true,+ isSecret: false,+ options: raw.options?.map((label: string) => ({ label, description: null })) ?? null,+ });+ }+ return questions;+}diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 65b585ee84..a0d5509a16 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -19885,6 +19885,310 @@ describe('CodexAgent MCP thread context hooks', () => {return events;}+ const asyncQuestionItem = {+ type: 'agentMessage', id: 'async-question-1', phase: 'final_answer', delivery: 'async',+ text: 'Proceed?\n- Yes\n- No', questions: [{ title: 'Proceed?', options: ['Yes', 'No'] }],+ };++ async function runningAsyncQuestion(steer?: () => Promise<unknown>) {+ const agent = new CodexAgent(createDeps());+ let turnSeq = 0;+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) return { turn: { id: `async-turn-${++turnSeq}` } };+ if (method === Method.TurnSteer) return steer ? steer() : {};+ if (method === Method.TurnInterrupt) return {};+ return undefined;+ });+ const handle = await agent.startSession({ sessionId: 'async-question', model: 'gpt-5.4', workingDir: '/repo' });+ const decision = deferred<InteractionDecision>();+ const resolver = vi.fn(async (_request: InteractionRequest) => decision.promise);+ handle.setInteractionResolver(resolver);+ const events = await collectAgentEvents(handle);+ await handle.send({ type: 'user', content: 'Make the change' });+ const handlers = host.getThreadHandlers()!;+ const params = { threadId: 'start-thread-id', turnId: 'async-turn-1', item: asyncQuestionItem };+ handlers.itemStarted?.(params);+ handlers.itemUpdated?.(params);+ expect(resolver).not.toHaveBeenCalled();+ handlers.itemCompleted?.(params);+ expect(resolver).toHaveBeenCalledOnce();+ return { host, handle, handlers, params, decision, resolver, events };+ }++ it.each([+ { label: 'skip', answers: {} },+ { label: 'empty text', answers: { 'Proceed?': '' } },+ { label: 'whitespace', answers: { 'Proceed?': ' \n\t' } },+ { label: 'empty selections', answers: { 'Proceed?': '[]' } },+ { label: 'blank selections', answers: { 'Proceed?': '[" "]' } },+ { label: 'unrelated answer', answers: { 'Another question?': 'Yes' } },+ { label: 'dismissed answer', answers: { 'Proceed?': 'Yes' }, dismissed: true },+ { label: 'resolver failure', answers: {}, reject: true },+ ] as Array<{ label: string; answers: Record<string, string>; dismissed?: boolean; reject?: boolean }>)('does not deliver or retain an async continuation for $label', async ({ answers, dismissed, reject }) => {+ const s = await runningAsyncQuestion();+ try {+ if (reject) s.decision.reject(new Error('resolver unavailable'));+ else s.decision.resolve({ kind: 'ask_user_question', answers, ...(dismissed ? { dismissed } : {}) });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(s.host.request.mock.calls.filter(([method]) => method === Method.TurnSteer)).toHaveLength(0);+ expect(s.handle.isTurnRunning?.()).toBe(true);+ expect(s.events.filter((event) => event.type === 'done')).toHaveLength(0);+ s.handlers.turnCompleted?.({ threadId: s.params.threadId,+ turn: { id: s.params.turnId, status: 'completed' } });+ await vi.waitFor(() => expect(s.handle.isTurnRunning?.()).toBe(false));+ await vi.waitFor(() => expect(s.events.filter((event) => event.type === 'done')).toHaveLength(1));+ expect(s.events.find((event) => event.type === 'done')?.turnContinuationId).toBeUndefined();+ expect(s.events.filter((event) => event.type === 'interaction_dismissed')).toHaveLength(0);+ expect(askUserTurnStartCalls(s.host)).toHaveLength(1);+ } finally { await s.handle.close(); }+ });++ it('delivers a partially answered async batch once', async () => {+ const s = await runningAsyncQuestion();+ const partial = deferred<InteractionDecision>();+ try {+ s.resolver.mockImplementationOnce(async () => partial.promise);+ const next = { ...s.params, item: { ...asyncQuestionItem, id: 'partial-question',+ questions: [{ title: 'Optional detail?' }, { title: 'Next action?' }] } };+ s.handlers.itemCompleted?.(next);+ partial.resolve({ kind: 'ask_user_question', answers: { 'Optional detail?': '', 'Next action?': 'Run tests' } });+ await vi.waitFor(() => expect(s.host.request.mock.calls.filter(([method]) => method === Method.TurnSteer)).toHaveLength(1));+ expect(s.host.request.mock.calls.find(([method]) => method === Method.TurnSteer)?.[1]).toMatchObject({+ expectedTurnId: s.params.turnId, input: [{ text: expect.stringContaining('A: Run tests') }],+ });+ s.handlers.itemCompleted?.(next);+ expect(s.resolver).toHaveBeenCalledTimes(2);+ s.handlers.turnCompleted?.({ threadId: s.params.threadId,+ turn: { id: s.params.turnId, status: 'completed' } });+ await vi.waitFor(() => expect(s.handle.isTurnRunning?.()).toBe(false));+ expect(askUserTurnStartCalls(s.host)).toHaveLength(1);+ } finally { await s.handle.close(); }+ });++ it.each((['pending', 'answered', 'dismissed'] as const).flatMap((state) =>+ ['Proceed?', 'Continue testing?'].map((question) => ({ state, question })),+ ))('keeps only the latest async card for "$question" when the first is $state', async ({ state, question }) => {+ const s = await runningAsyncQuestion();+ const second = deferred<InteractionDecision>();+ const steerCalls = () => s.host.request.mock.calls.filter(([method]) => method === Method.TurnSteer);+ try {+ if (state !== 'pending') {+ s.decision.resolve({ kind: 'ask_user_question', answers: state === 'answered' ? { 'Proceed?': 'Yes' } : {},+ ...(state === 'dismissed' ? { dismissed: true } : {}) });+ if (state === 'answered') await vi.waitFor(() => expect(steerCalls()).toHaveLength(1));+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ s.resolver.mockImplementationOnce(async () => second.promise);+ const next = { ...s.params, item: { ...asyncQuestionItem, id: 'async-question-2',+ questions: [{ title: question, options: ['Yes', 'No'] }] } };+ s.handlers.itemCompleted?.(next);+ s.handlers.itemCompleted?.(next);+ s.handlers.itemCompleted?.(s.params);+ expect(s.resolver).toHaveBeenCalledTimes(2);+ expect(s.resolver.mock.calls[1][0].requestId).not.toBe(s.resolver.mock.calls[0][0].requestId);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(s.events.filter((event) => event.type === 'interaction_dismissed')).toEqual(state === 'pending' ? [{+ type: 'interaction_dismissed', source: 'codex',+ data: { requestId: s.resolver.mock.calls[0][0].requestId, reason: 'superseded', resolvedAs: 'deny' },+ }] : []);+ // Even before the turn ends, a late response to the replaced card cannot+ // steer the model or remove the current card.+ s.decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(steerCalls()).toHaveLength(state === 'answered' ? 1 : 0);+ second.resolve({ kind: 'ask_user_question', answers: { [question]: 'No' } });+ await vi.waitFor(() => expect(steerCalls()).toHaveLength(state === 'answered' ? 2 : 1));+ expect(steerCalls().at(-1)?.[1]).toMatchObject({ input: [{ text: expect.stringContaining('A: No') }] });+ s.handlers.turnCompleted?.({ threadId: s.params.threadId,+ turn: { id: s.params.turnId, status: 'completed' } });+ await vi.waitFor(() => expect(s.handle.isTurnRunning?.()).toBe(false));+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(s.events.filter((event) => event.type === 'interaction_dismissed')).toHaveLength(state === 'pending' ? 1 : 0);+ expect(steerCalls()).toHaveLength(state === 'answered' ? 2 : 1);+ expect(askUserTurnStartCalls(s.host)).toHaveLength(1);+ } finally { await s.handle.close(); }+ });++ it.each(['completed', 'failed', 'stop', 'close'] as const)('expires only the latest unanswered async card on %s after replacement', async (outcome) => {+ const s = await runningAsyncQuestion();+ const second = deferred<InteractionDecision>();+ try {+ s.resolver.mockImplementationOnce(async () => second.promise);+ const next = { ...s.params, item: { ...asyncQuestionItem, id: 'async-question-2' } };+ s.handlers.itemCompleted?.(next);+ // Replayed lifecycle events cannot bring the replaced card back.+ s.handlers.itemCompleted?.(s.params);+ expect(s.resolver).toHaveBeenCalledTimes(2);+ if (outcome === 'stop') await s.handle.abort();+ else if (outcome === 'close') await s.handle.close();+ else s.handlers.turnCompleted?.({ threadId: s.params.threadId,+ turn: { id: s.params.turnId, status: outcome } });+ await vi.waitFor(() => expect(s.events.filter((event) => event.type === 'interaction_dismissed')).toHaveLength(2));+ expect(s.events.filter((event) => event.type === 'interaction_dismissed').map((event) => event.data)).toEqual([+ { requestId: s.resolver.mock.calls[0][0].requestId, reason: 'superseded', resolvedAs: 'deny' },+ { requestId: s.resolver.mock.calls[1][0].requestId, reason: expect.any(String), resolvedAs: 'deny' },+ ]);+ s.decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ second.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'No' } });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(s.host.request.mock.calls.filter(([method]) => method === Method.TurnSteer)).toHaveLength(0);+ expect(askUserTurnStartCalls(s.host)).toHaveLength(1);+ } finally { await s.handle.close(); }+ });++ it.each(['completed', 'failed', 'stop'] as const)('does not expire an answered async card when %s occurs inside steer dispatch', async (outcome) => {+ let terminate!: () => void;+ const s = await runningAsyncQuestion(async () => { terminate(); return {}; });+ try {+ terminate = () => {+ if (outcome === 'stop') void s.handle.abort();+ else s.handlers.turnCompleted?.({ threadId: s.params.threadId,+ turn: { id: s.params.turnId, status: outcome } });+ };+ s.decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await vi.waitFor(() => expect(s.host.request.mock.calls.some(([method]) => method === Method.TurnSteer)).toBe(true));+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(s.events.filter((event) => event.type === 'interaction_dismissed')).toEqual([]);+ } finally { await s.handle.close(); }+ });++ it.each(['pending', 'answered'] as const)('does not join a synchronous tool to a %s async answer', async (state) => {+ const s = await runningAsyncQuestion();+ const syncDecision = deferred<InteractionDecision>();+ const syncResolver = vi.fn(async () => syncDecision.promise);+ try {+ if (state === 'answered') {+ s.decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await vi.waitFor(() => expect(s.host.request.mock.calls.filter(([method]) => method === Method.TurnSteer)).toHaveLength(1));+ }+ s.handle.setInteractionResolver(syncResolver);+ const sync = s.handlers.requestUserInput!({+ threadId: s.params.threadId, turnId: s.params.turnId, itemId: 'sync-item',+ questions: [{ id: 'sync-choice', header: '', question: 'Proceed?', isOther: true,+ options: [{ label: 'Yes', description: null }, { label: 'No', description: null }] }],+ }, { requestId: 561 });+ await vi.waitFor(() => expect(syncResolver).toHaveBeenCalledOnce());+ // Another optional question cannot cover the blocking card.+ s.handlers.itemCompleted?.({ ...s.params, item: { ...asyncQuestionItem, id: 'async-later' } });+ expect(syncResolver).toHaveBeenCalledOnce();+ s.decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ syncDecision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'No' } });+ await expect(sync).resolves.toEqual({ answers: { 'sync-choice': { answers: ['No'] } } });+ expect(s.host.request.mock.calls.filter(([method]) => method === Method.TurnSteer)).toHaveLength(state === 'answered' ? 1 : 0);+ s.handlers.turnCompleted?.({ threadId: s.params.threadId,+ turn: { id: s.params.turnId, status: 'completed' } });+ await vi.waitFor(() => expect(s.handle.isTurnRunning?.()).toBe(false));+ } finally { await s.handle.close(); }+ });++ it('shows an async question once through the existing card and steers its answer without waiting for turn completion', async () => {+ const { host, handle, handlers, params, decision, resolver, events } = await runningAsyncQuestion();+ expect(resolver.mock.calls[0]?.[0]).toMatchObject({ kind: 'ask_user_question', delivery: 'async', questions: [{+ question: 'Proceed?', options: [{ label: 'Yes' }, { label: 'No' }],+ }] });+ handlers.itemCompleted?.(params);+ expect(resolver).toHaveBeenCalledOnce();+ decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await vi.waitFor(() => expect(host.request.mock.calls.filter(([method]) => method === Method.TurnSteer)).toHaveLength(1));+ const [, input] = host.request.mock.calls.find(([method]) => method === Method.TurnSteer)!;+ expect(input).toMatchObject({ expectedTurnId: 'async-turn-1', input: [{ text: expect.stringContaining('A: Yes') }] });+ handlers.itemCompleted?.(params);+ expect(resolver).toHaveBeenCalledOnce();+ expect(events.filter((event) => event.type === 'text')).toHaveLength(0);+ expect(askUserTurnStartCalls(host)).toHaveLength(1);+ handlers.turnCompleted?.({ threadId: params.threadId, turn: { id: params.turnId, status: 'completed' } });+ await waitForExpectation(() => expect(handle.isTurnRunning?.()).toBe(false));+ await waitForExpectation(() => expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(1));+ await handle.close();+ });++ it.each(['accepted', 'rejected'] as const)('handles an async answer whose steer is %s after the original turn finishes', async (outcome) => {+ const ack = deferred<unknown>();+ const { host, handle, handlers, params, decision, events } = await runningAsyncQuestion(() => ack.promise);+ decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await vi.waitFor(() => expect(host.request.mock.calls.some(([method]) => method === Method.TurnSteer)).toBe(true));+ handlers.turnCompleted?.({ threadId: params.threadId, turn: { id: params.turnId, status: 'completed' } });+ expect(handle.isTurnRunning?.()).toBe(true);+ if (outcome === 'accepted') ack.resolve({});+ else ack.reject(Object.assign(new Error('codex app-server turn/steer error -32602: no active turn to steer'), { code: -32602 }));+ if (outcome === 'rejected') {+ await vi.waitFor(() => expect(askUserTurnStartCalls(host)).toHaveLength(2));+ handlers.turnCompleted?.({ threadId: params.threadId, turn: { id: 'async-turn-2', status: 'completed' } });+ }+ await waitForExpectation(() => expect(handle.isTurnRunning?.()).toBe(false));+ expect(askUserTurnStartCalls(host)).toHaveLength(outcome === 'accepted' ? 1 : 2);+ await waitForExpectation(() => expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(1));+ await handle.close();+ });++ it('does not replay an async answer when steer delivery is uncertain', async () => {+ const { host, handle, handlers, params, decision, events } = await runningAsyncQuestion(async () => {+ throw new Error('connection lost after dispatch');+ });+ decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await waitForExpectation(() => expect(events.some((event) => event.type === 'error' && event.data.isTerminal === false)).toBe(true));+ expect(handle.isTurnRunning?.()).toBe(true);+ expect(events.filter((event) => event.type === 'done')).toHaveLength(0);+ handlers.turnCompleted?.({ threadId: params.threadId, turn: { id: params.turnId, status: 'completed' } });+ await waitForExpectation(() => expect(handle.isTurnRunning?.()).toBe(false));+ expect(askUserTurnStartCalls(host)).toHaveLength(1);+ await handle.close();+ });++ it.each(['stop', 'failed', 'close'] as const)('ignores an async answer after %s', async (action) => {+ const { host, handle, handlers, params, decision } = await runningAsyncQuestion();+ if (action === 'stop') await handle.abort();+ if (action === 'close') await handle.close();+ if (action === 'failed') handlers.turnCompleted?.({ threadId: params.threadId, turn: { id: params.turnId, status: 'failed' } });+ decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnSteer)).toHaveLength(0);+ expect(askUserTurnStartCalls(host)).toHaveLength(1);+ await handle.close();+ });++ it.each([1, 2])('expires all %i unanswered async cards before completing the task and ignores late answers', async (count) => {+ const { host, handle, handlers, params, decision, resolver, events } = await runningAsyncQuestion();+ const lastDecision = deferred<InteractionDecision>();+ if (count === 2) {+ handle.setInteractionResolver(async () => lastDecision.promise);+ handlers.itemCompleted?.({ ...params, item: { ...asyncQuestionItem, id: 'async-question-2',+ questions: [{ title: 'Last question?', options: null }] } });+ }+ handlers.itemCompleted?.({ ...params, item: { type: 'agentMessage', id: 'final',+ phase: 'final_answer', text: 'Independent work completed.' } });+ handlers.turnCompleted?.({ threadId: params.threadId, turn: { id: params.turnId, status: 'completed' } });+ await waitForExpectation(() => expect(events.filter((event) => event.type === 'done')).toHaveLength(1));+ const doneIndex = events.findIndex((event) => event.type === 'done');+ expect(events[doneIndex]?.turnContinuationId).toBeUndefined();+ expect(handle.isTurnRunning?.()).toBe(false);+ const dismissed = events.filter((event) => event.type === 'interaction_dismissed');+ expect(dismissed).toHaveLength(count);+ expect(dismissed.map((event) => event.data.reason)).toEqual(+ count === 2 ? ['superseded', 'turn_completed'] : ['turn_completed'],+ );+ for (const event of dismissed) {+ expect(events.indexOf(event)).toBeLessThan(doneIndex);+ }+ expect(events.some((event) => event.type === 'text'+ && JSON.stringify(event.data).includes('Independent work completed.'))).toBe(true);+ expect(events.some((event) => event.type === 'error')).toBe(false);+ // Neither a repeated completion nor a late item may revive an expired card.+ handlers.turnCompleted?.({ threadId: params.threadId, turn: { id: params.turnId, status: 'completed' } });+ handlers.itemCompleted?.(params);+ expect(resolver).toHaveBeenCalledOnce();+ decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'stale' } });+ lastDecision.resolve({ kind: 'ask_user_question', answers: { 'Last question?': 'free-form answer' } });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnSteer)).toHaveLength(0);+ expect(askUserTurnStartCalls(host)).toHaveLength(1);+ expect(events.filter((event) => event.type === 'done')).toHaveLength(1);+ // The user can still start ordinary new work after the expired questions.+ await handle.send({ type: 'user', content: 'A new task' });+ expect(askUserTurnStartCalls(host)).toHaveLength(2);+ await handle.close();+ });+async function pendingHumanProduct(kind: 'native' | 'dynamic' | 'plan', followupStart?: () => Promise<unknown>) {const agent = new CodexAgent(createDeps());let turnSeq = 0;@@ -19953,7 +20257,7 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});- it.each(['abort', 'graceful', 'close'] as const)('supports %s while only a confirmation remains and ignores late approval', async (action) => {+ it.each(['abort', 'graceful', 'close'] as const)('supports %s while only a plan confirmation remains and ignores late approval', async (action) => {const { handle, host, decision, events } = await pendingHumanProduct('plan');if (action === 'abort') await handle.abort();else if (action === 'graceful') await handle.requestGracefulStop?.();diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 756700735d..4038e338cb 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -152,6 +152,7 @@ import {} from './capability-routing.js';import { scanCodexCustomizations } from './customization-scanner.js';import { commandExecutionDisplayInput } from './command-display.js';+import { asyncUserInputQuestions } from './async-user-input.js';import {dedupeCells,extractAliveYieldCellsFromCodexItem,@@ -250,6 +251,7 @@ import {type DynamicToolCallParams,type DynamicToolCallResponse,type DynamicToolSpec,+ type ItemEnvelope,type FileChangeRequestApprovalParams,type FileChangeRequestApprovalResponse,type McpServerElicitationRequestParams,@@ -1070,6 +1072,7 @@ interface LiveAskUserRequest {questions: ToolRequestUserInputQuestion[];detached: boolean;continuationStarted: boolean;+ delivery?: 'async';permissionPolicy: TurnPermissionPolicy | null;capabilitySelectionText: string;autoReviewIntent: AutoReviewUserIntent;@@ -3892,12 +3895,31 @@ assertRouteCurrent();async function sendInteractionContinuation(requestId: string, message: UserMessage, options: CodexInternalSendOptions,failureContext: string,+ steerTurnId?: string | null,): Promise<void> {const claim = interactionContinuation;if (!claim || !claim.requestIds.delete(requestId) || claim.settled) return;claim.pendingSends += 1;claim.sendTail = claim.sendTail.then(async () => {- if (claim.settled || closed || await waitForYieldContinuationIdle()) return;+ if (claim.settled || closed) return;+ if (steerTurnId && isTurnInFlight && currentTurnId === steerTurnId) {+ try {+ await handle.steer!(message, { ...options, signal: claim.abort.signal });+ return;+ } catch (error) {+ if (claim.settled || closed) return;+ // Only a definite pre-accept rejection can become a fresh turn.+ // A timeout/transport failure may already have delivered the answer.+ const message = error instanceof Error ? error.message : String(error);+ if (!/\bno active (?:Codex )?turn to steer\b/i.test(message)) {+ eventQueue.push({ type: 'error', data: {+ message: `Async question answer delivery failed: ${message}`, isTerminal: false,+ }, source: 'codex' });+ return;+ }+ }+ }+ if (await waitForYieldContinuationIdle()) return;while (!claim.settled && (isTurnInFlight || isTurnStartPending)) {await new Promise<void>((resolve) => {const wake = () => {@@ -7654,6 +7676,7 @@ assertRouteCurrent();pendingInteraction: PendingUserInputInteraction;}>();const liveAskUserByRequestId = new Map<string, LiveAskUserRequest>();+ const asyncQuestionItemsByTurn = new Map<string, Set<string>>();registerRootCodexMcpContext();let mcpElicitationSeq = 0;@@ -8104,6 +8127,16 @@ assertRouteCurrent();success: false,});+ function dismissLiveAskUser(requestId: string, reason: string): void {+ liveAskUserByRequestId.delete(requestId);+ forgetPendingUserInputRequest(requestId);+ eventQueue.push({+ type: 'interaction_dismissed',+ data: { requestId, reason, resolvedAs: 'deny' },+ source: 'codex',+ });+ }+function dismissPendingUserInput(reason: string,predicate: (meta: { threadId?: string; turnId?: string | null }) => boolean,@@ -8121,25 +8154,13 @@ assertRouteCurrent();const requestId = serverInteractionId(meta.requestId);if (dismissed.has(requestId)) continue;dismissed.add(requestId);- liveAskUserByRequestId.delete(requestId);- forgetPendingUserInputRequest(requestId);- eventQueue.push({- type: 'interaction_dismissed',- data: { requestId, reason, resolvedAs: 'deny' },- source: 'codex',- });+ dismissLiveAskUser(requestId, reason);}for (const [requestId, live] of liveAskUserByRequestId) {if (!predicate({ threadId, turnId: live.turnId })) continue;- liveAskUserByRequestId.delete(requestId);if (dismissed.has(requestId)) continue;dismissed.add(requestId);- forgetPendingUserInputRequest(requestId);- eventQueue.push({- type: 'interaction_dismissed',- data: { requestId, reason, resolvedAs: 'deny' },- source: 'codex',- });+ dismissLiveAskUser(requestId, reason);}}@@ -8156,10 +8177,11 @@ assertRouteCurrent();(meta) => meta.turnId === turnId,cancelledDynamicToolResponse('turn_completed'),);- // Desktop 只有一个 pendingAskUser。同 turn 多个提问只留最后一张,- // 否则被盖住的 resolver 会一直占着 hasPendingAgentInteraction。+ // Desktop 只有一个 pendingAskUser,只保留最后一张同步提问。+ // 异步提问不阻塞结束:未回答的卡片随原 turn 到期,不代选或续跑。const lives = [...liveAskUserByRequestId.values()].filter((live) => live.turnId === turnId);- const keep = lives.at(-1) ?? null;+ const latest = lives.at(-1);+ const keep = latest?.delivery === 'async' ? null : latest ?? null;if (keep) {keep.detached = true;retainInteractionContinuation(turnId, keep.requestId);@@ -8169,17 +8191,11 @@ assertRouteCurrent();const dismiss = (requestId: string, reason: string): void => {if (keepUiRequestIds.has(requestId) || dismissed.has(requestId)) return;dismissed.add(requestId);- liveAskUserByRequestId.delete(requestId);- forgetPendingUserInputRequest(requestId);- eventQueue.push({- type: 'interaction_dismissed',- data: { requestId, reason, resolvedAs: 'deny' },- source: 'codex',- });+ dismissLiveAskUser(requestId, reason);};for (const live of lives) {if (keep && live.requestId === keep.requestId) continue;- dismiss(live.requestId, 'superseded');+ dismiss(live.requestId, live.delivery === 'async' ? 'turn_completed' : 'superseded');}for (const meta of [...cancelledUserInput, ...cancelledDynamicTools]) {dismiss(serverInteractionId(meta.requestId), 'turn_completed');@@ -8209,7 +8225,7 @@ assertRouteCurrent();autoReviewIntent?: AutoReviewUserIntent,): Promise<void> {if (closed) return;- if (await waitForYieldContinuationIdle()) return;+ if (live.delivery !== 'async' && await waitForYieldContinuationIdle()) return;if (closed) return;const message = formatAskUserContinuationMessage(live.questions, answers);const sendOptions: CodexInternalSendOptions = {@@ -8222,7 +8238,7 @@ assertRouteCurrent();};try {await sendInteractionContinuation(live.requestId, { type: 'user', content: message }, sendOptions,- 'ask_user continuation turn failed to start');+ 'ask_user continuation turn failed to start', live.delivery === 'async' ? live.turnId : null);} catch (error) {emitAskUserContinuationStartFailure(error);}@@ -9536,6 +9552,7 @@ assertRouteCurrent();turnId?: string | null,isRequestPending: () => boolean = () => true,toolUseId?: string,+ delivery?: 'async',): Promise<ToolRequestUserInputResponse> {if (questions.some((q) => q.isSecret)) {log.warn('requestUserInput secret question refused', {@@ -9544,7 +9561,21 @@ assertRouteCurrent();});return emptyUserInputResponse(questions);}- const fingerprint = turnId ? userInputQuestionsFingerprint(questions) : null;+ // A blocking tool must remain answerable; optional cards may not cover it.+ if (delivery === 'async') {+ if ([...liveAskUserByRequestId.values()].some((live) => live.delivery !== 'async')) {+ return emptyUserInputResponse(questions);+ }+ }+ // The shared card has one slot: either kind of new question replaces an+ // unanswered async card. Answered cards have already left this map.+ for (const live of liveAskUserByRequestId.values()) {+ if (live.delivery === 'async') dismissLiveAskUser(live.requestId, 'superseded');+ }+ // Async items already deduplicate lifecycle notifications by item id.+ // Only synchronous protocol aliases may share pending/submitted answers+ // by content: distinct async items must always own their own decisions.+ const fingerprint = turnId && delivery !== 'async' ? userInputQuestionsFingerprint(questions) : null;const submittedForTurn = turnId ? submittedUserInputByTurn.get(turnId) : undefined;const replay = fingerprint ? submittedForTurn?.get(fingerprint) : undefined;if (replay) {@@ -9577,7 +9608,7 @@ assertRouteCurrent();turnId,});return isRequestPending()- ? askUserViaInteraction(requestId, questions, turnId, isRequestPending, toolUseId)+ ? askUserViaInteraction(requestId, questions, turnId, isRequestPending, toolUseId, delivery): emptyUserInputResponse(questions);}return responseFromUserInputAnswersByPosition(questions, joined.answersByPosition);@@ -9590,6 +9621,7 @@ assertRouteCurrent();questions,detached: false,continuationStarted: false,+ delivery,permissionPolicy: activeTurnPermissionPolicy,capabilitySelectionText: ((turnId ? capabilitySelectionTextByTurnId.get(turnId) : undefined)@@ -9602,6 +9634,7 @@ assertRouteCurrent();kind: 'ask_user_question',requestId,...(toolUseId ? { toolUseId } : {}),+ ...(delivery ? { delivery } : {}),questions: questionsToAskUserItems(questions),});if (decision.kind !== 'ask_user_question') {@@ -9610,6 +9643,21 @@ assertRouteCurrent();return questions.map(() => []);}const live = liveAskUserByRequestId.get(requestId);+ // Stop/supersession may win while the UI response is already in flight.+ if (!live) return questions.map(() => []);+ // The host has resolved the card. A synchronous completion during steer+ // must not mark it expired while the outer promise is still unwinding.+ liveAskUserByRequestId.delete(requestId);+ const answersByPosition = userInputAnswersByPosition(+ questions,+ responseFromAskUserAnswers(questions, decision.answers),+ );+ // Optional skips/cancellations settle the card without changing intent,+ // claiming a continuation, or sending synthetic "no answer" input.+ if (live.delivery === 'async'+ && (decision.dismissed === true || !hasSubmittedUserInput(answersByPosition))) {+ return answersByPosition;+ }// 澄清必须锚在发起提问那一轮的审查意图上。卡片挂起期间后续 turn 可能改写// currentAutoReviewIntent;plan_review 已用 planRequestAutoReviewIntent 防漂。const continuationAutoReviewIntent = composeAutoReviewIntentWithClarification(@@ -9617,17 +9665,16 @@ assertRouteCurrent();Object.entries(decision.answers ?? {}).map(([question, answer]) => ({ question, answer })),);setAutoReviewIntent(continuationAutoReviewIntent);- const answersByPosition = userInputAnswersByPosition(- questions,- responseFromAskUserAnswers(questions, decision.answers),- );if (live- && live.detached+ && (live.detached || live.delivery === 'async')&& !live.continuationStarted&& decision.dismissed !== true) {live.continuationStarted = true;+ if (live.delivery === 'async' && live.turnId) {+ retainInteractionContinuation(live.turnId, requestId);+ }// Pass the applied, normalized snapshot so send can reuse this transition.void startAskUserContinuation(live, decision.answers ?? {}, currentAutoReviewIntent);} else if (live?.detached && decision.dismissed === true) {@@ -9695,6 +9742,25 @@ assertRouteCurrent();}}+ function interceptAsyncUserInput(+ params: { threadId: string; turnId: string; item: ItemEnvelope },+ phase: 'started' | 'updated' | 'completed',+ ): boolean {+ const rawQuestions = asyncUserInputQuestions(params.item);+ if (!rawQuestions) return false;+ // Do not render the fallback prose as a final answer or open child-agent cards.+ if (phase !== 'completed' || reviewMode || params.threadId !== threadId) return true;+ let seen = asyncQuestionItemsByTurn.get(params.turnId);+ if (seen?.has(params.item.id)) return true;+ if (!seen) asyncQuestionItemsByTurn.set(params.turnId, seen = new Set());+ seen.add(params.item.id);+ const requestId = serverInteractionId(`async:${params.turnId}:${params.item.id}`);+ void askUserViaInteraction(requestId, normalizeRequestUserInputQuestions(rawQuestions),+ params.turnId, () => !closed && !completedTurnIds.has(params.turnId), undefined, 'async')+ .catch((error: unknown) => log.warn('async user input interaction failed', { requestId, error: String(error) }));+ return true;+ }+async function requestUserInputAsPermission(requestId: string,params: ToolRequestUserInputParams,@@ -10756,6 +10822,7 @@ assertRouteCurrent();// 同一个墓碑也负责拦截该 turn 随后迟到的 item / reasoning / started 事件。if (completedTurnIds.has(turn.id)) return;completedTurnIds.add(turn.id);+ asyncQuestionItemsByTurn.delete(turn.id);compactingTurnIds.delete(turn.id);normalModelWorkTurnIds.delete(turn.id);completedSummaryRecoveryTurnIds.delete(turn.id);@@ -12231,6 +12298,7 @@ assertRouteCurrent();}noteActiveToolContext(params.item, params.turnId);noteToolItemLifecycle(params.item, 'started');+ if (interceptAsyncUserInput(params, 'started')) return;// 先登记再翻译:子线程通知可能紧随 spawn item 到达,映射就位才不丢首帧。const translatedItem = withFrozenSubagentSpawnIdentity(params.item, params.turnId);const translatedParams = translatedItem === params.item@@ -12272,6 +12340,7 @@ assertRouteCurrent();}noteActiveToolContext(params.item, params.turnId);rememberYieldedExecCells(params.turnId, params.item, 'updated');+ if (interceptAsyncUserInput(params, 'updated')) return;// updated 也要登记映射,顺序与 started / completed 一致(先登记 → 翻译 → 后发重放帧)。// V1 的 spawn 是长跑 item(started → updated* → completed):started 那帧若没到我们手里// (turn 缓冲、stale turn 丢弃、上游省略),映射就要一直等到 completed 才建立 —— 期间@@ -12339,6 +12408,7 @@ assertRouteCurrent();producedOutputTurnIds.add(params.turnId);noteRecoveryModelWork(params.turnId, params.item);}+ if (interceptAsyncUserInput(params, 'completed')) return;noteAssistantReplyCandidate(params.turnId, params.item);completeActiveToolContext(params.item, params.turnId);rememberYieldedExecCells(params.turnId, params.item, 'completed');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.tsindex cfe02aac60..aec52f5bd3 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@@ -201,6 +201,7 @@ vi.mock('../rpc-client.js', () => ({import {AUTO_REVIEW_SOURCE_CONTENT,+ ASYNC_QUESTION_ANSWER,MAIN_OWNED_SEND_CONTEXT,PiManagedPackageMutationCancelledError,PiManagedPackageMutationFailedError,@@ -464,6 +465,26 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {}) as Promise<PiTestSessionHandle>;}+ it.each(['settled', 'replaced', 'aborted'] as const)('does not enqueue an async answer after its Pi execution is %s', async (action) => {+ const handle = await start('bypassPermissions');+ const controller = new AbortController();+ try {+ captured.onEvent?.({ type: 'agent_start' });+ const send = handle.steer({ type: 'user', content: 'Async answer' }, {+ signal: controller.signal, [ASYNC_QUESTION_ANSWER]: true,+ });+ // Interrupt while steer is awaiting prompt preparation / the RPC queue.+ if (action === 'aborted') controller.abort();+ else {+ captured.onEvent?.({ type: 'agent_end', messages: [] });+ captured.onEvent?.({ type: 'agent_settled' });+ if (action === 'replaced') captured.onEvent?.({ type: 'agent_start' });+ }+ await expect(send).rejects.toThrow(/cancelled|No active Pi turn/);+ expect(captured.requests.filter((request) => request.type === 'steer')).toHaveLength(0);+ } finally { await handle.close(); }+ });+it('toggles welcome policy without filesystem writes or extra prompt RPCs', async () => {const handle = await start('bypassPermissions');const token = captured.env.CINDY_PI_TURN_TOOL_POLICY;diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 80d3530cd4..75b0a5c87d 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -66,6 +66,7 @@ import {AgentStartupStoppedError,BaseAgent,MAIN_OWNED_SEND_CONTEXT,+ ASYNC_QUESTION_ANSWER,PINNED_SKILL_INVOCATION,PI_REQUEST_BODY_RECOVERY_EXHAUSTED,PiManagedPackageMutationCancelledError,@@ -7303,6 +7304,7 @@ export class PiAgent extends BaseAgent {},async steer(message: UserMessage, sendOpts?: SendOptions): Promise<void> {+ const answerLifecycle = piAgentLifecycleSequence;rejectIfCancelled(sendOpts, 'steer');if (sendOpts) handle.validateSendOptions?.(sendOpts);if (reviewMode) {@@ -7355,7 +7357,15 @@ export class PiAgent extends BaseAgent {doctorCommandActivity.enter(isDoctorCommand);let resp: Awaited<ReturnType<typeof proc.request>>;try {- resp = await runExclusivePiRpc(() => proc.request(command));+ resp = await runExclusivePiRpc(() => {+ if (sendOpts?.[ASYNC_QUESTION_ANSWER]) {+ rejectIfCancelled(sendOpts, 'steer');+ if (!ctx.isStreaming || piAgentLifecycleSequence !== answerLifecycle) {+ throw new Error('No active Pi turn for the async question answer');+ }+ }+ return proc.request(command);+ });} finally {doctorCommandActivity.leave(isDoctorCommand);}diff --git a/packages/maker-core/src/agents/shared/async-user-questions.native.test.ts b/packages/maker-core/src/agents/shared/async-user-questions.native.test.tsnew file mode 100644index 0000000000..4ef3c92d49--- /dev/null+++ b/packages/maker-core/src/agents/shared/async-user-questions.native.test.ts@@ -0,0 +1,125 @@+/** Opt-in: real harnesses, isolated homes and a loopback fake model; no account or API spend. */+import { mkdtemp, mkdir, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { createServer, type ServerResponse } from 'node:http';+import { expect, it, vi } from 'vitest';+import { ClaudeCodeAgent } from '../claude-code/index.js';+import { PiAgent } from '../pi/index.js';+import { Session } from '../../session.js';+import type { AgentDeps } from '../base-agent.js';+import type { AgentEvent, InteractionDecision } from '../../types/events.js';+import type { Logger } from '../../interfaces/logger.js';++const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger };++function reply(res: ServerResponse, model: string, text = 'Independent work completed.') {+ const events = [+ { type: 'message_start', message: { id: 'test-message', type: 'message', role: 'assistant', model,+ content: [], stop_reason: null, usage: { input_tokens: 42, output_tokens: 0 } } },+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } },+ { type: 'content_block_stop', index: 0 },+ { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 7 } },+ { type: 'message_stop' },+ ];+ res.writeHead(200, { 'content-type': 'text/event-stream' });+ res.end(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(''));+}++for (const agentKind of ['claude-code', 'pi'] as const) {+ const binary = agentKind === 'pi' ? process.env.CINDY_TEST_PI_BINARY : process.env.CINDY_TEST_CLAUDE_BINARY;+ it.skipIf(!binary).each(['during', 'twice', 'unanswered'] as const)(`${agentKind} native async question: %s`, async (timing) => {+ const root = await mkdtemp(path.join(tmpdir(), 'cindy-async-harness-'));+ const home = path.join(root, 'home');+ const cwd = path.join(root, 'work');+ await Promise.all([mkdir(home), mkdir(cwd)]);+ const model = agentKind === 'pi' ? 'pi-test-model' : 'claude-opus-4-6';+ const bodies: Array<Record<string, unknown>> = [];+ let held: ServerResponse | undefined;+ const server = createServer(async (req, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ if (req.url?.includes('/count_tokens')) {+ res.writeHead(200, { 'content-type': 'application/json' }).end('{"input_tokens":100}');+ return;+ }+ if (!req.url?.includes('/messages')) { res.writeHead(404).end(); return; }+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));+ // Claude also performs a separate title query; it is not an agent turn.+ if (!Array.isArray(body.tools) || body.tools.length === 0) { reply(res, model); return; }+ bodies.push(body);+ if (bodies.length === 1) held = res;+ else reply(res, model, 'Answer received.');+ });+ let session: Session | undefined;+ try {+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('missing loopback address');+ const endpoint = `http://127.0.0.1:${address.port}`;+ const deps: AgentDeps = {+ binaryPath: binary!, logger, runtimeConfig: { endpoint },+ auth: {+ getState: async () => ({ authenticated: true, authSource: 'api-key' as const }),+ triggerLogin: async () => ({ authenticated: true }), logout: async () => {},+ getAuthEnv: async () => ({ ANTHROPIC_API_KEY: 'invalid-test-key', CINDY_PI_API_KEY: 'invalid-test-key',+ CLAUDE_CONFIG_DIR: home, ANTHROPIC_BASE_URL: endpoint }),+ },+ resolvePiAgentHome: () => home, resolvePiGlobalContextHome: () => home,+ resolvePiGatewayModelApi: () => 'anthropic-messages',+ capabilityAdditions: { availableModels: [{ id: model, displayName: 'Test', contextWindow: 200_000,+ efforts: [], defaultEffort: null }] },+ };+ const agent = agentKind === 'pi' ? new PiAgent(deps) : new ClaudeCodeAgent(deps);+ const handle = await agent.startSession({ sessionId: 'async-native-test', workingDir: cwd, model });+ const steer = vi.spyOn(handle, 'steer');+ session = new Session({ id: 'async-native-test', agentKind, workDir: cwd, handle, logger,+ capabilities: { sameTurnSteer: { supported: true } } as never, turnStallMs: 0 });+ let answer!: (decision: InteractionDecision) => void;+ session.setInteractionListener(() => new Promise((resolve) => { answer = resolve; }));+ const events: AgentEvent[] = [];+ session.onEvent((event) => events.push(event));+ await session.send('Do independent work.');+ await vi.waitFor(() => expect(held).toBeDefined(), { timeout: 20_000 });+ const id = session.askUserQuestionAsync([{ question: 'Which scope?' }]);+ expect(session.getTurnControlSnapshot().pendingInteractionCount).toBe(0);+ if (timing !== 'unanswered') {+ answer({ kind: 'ask_user_question', answers: { 'Which scope?': 'BOTH_BOTS_CANARY' } });+ await vi.waitFor(() => expect(steer).toHaveBeenCalledOnce());+ await steer.mock.results[0].value;+ if (timing === 'twice') {+ session.askUserQuestionAsync([{ question: 'Which style?' }]);+ answer({ kind: 'ask_user_question', answers: { 'Which style?': 'SECOND_ANSWER_CANARY' } });+ await vi.waitFor(() => expect(steer).toHaveBeenCalledTimes(2));+ await steer.mock.results[1].value;+ }+ }+ reply(held!, model);+ await vi.waitFor(() => expect(events.some((event) => event.type === 'done')).toBe(true), { timeout: 20_000 });+ if (timing !== 'unanswered') {+ await vi.waitFor(() => expect(bodies.some((body) => JSON.stringify(body.messages).includes('BOTH_BOTS_CANARY'))).toBe(true), { timeout: 10_000 });+ expect(bodies.at(-1)?.system).toEqual(bodies[0].system);+ expect(bodies.at(-1)?.tools).toEqual(bodies[0].tools);+ await vi.waitFor(() => expect(events.some((event) => event.type === 'text'+ && JSON.stringify(event.data).includes('Answer received.'))).toBe(true));+ await vi.waitFor(() => expect(handle.isTurnRunning?.()).toBe(false));+ if (timing === 'twice') expect(JSON.stringify(bodies.at(-1)?.messages)).toContain('SECOND_ANSWER_CANARY');+ expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(1);+ } else {+ expect(events.some((event) => event.type === 'interaction_dismissed' && (event.data as { requestId?: string }).requestId === id)).toBe(true);+ answer({ kind: 'ask_user_question', answers: { 'Which scope?': 'BOTH_BOTS_CANARY' } });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(steer).not.toHaveBeenCalled();+ expect(bodies).toHaveLength(1);+ }+ expect(events.filter((event) => event.type === 'error')).toEqual([]);+ } finally {+ held?.destroy();+ await session?.close();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ }+ }, 45_000);+}diff --git a/packages/maker-core/src/agents/shared/async-user-questions.ts b/packages/maker-core/src/agents/shared/async-user-questions.tsnew file mode 100644index 0000000000..d73c1869e5--- /dev/null+++ b/packages/maker-core/src/agents/shared/async-user-questions.ts@@ -0,0 +1,73 @@+import { randomUUID } from 'node:crypto';+import type { AskUserQuestionItem, InteractionDecision, InteractionRequest } from '../../types/events.js';++interface PendingQuestion {+ generation: number;+ abort: AbortController;+ answered: boolean;+}++/** Optional questions never own a continuation or a blocking interaction. */+export class AsyncUserQuestions {+ private readonly pending = new Map<string, PendingQuestion>();++ constructor(private readonly deps: {+ isActive(generation: number): boolean;+ resolve(request: InteractionRequest): Promise<InteractionDecision>;+ deliver(text: string, signal: AbortSignal): Promise<void>;+ dismiss(requestId: string, reason: string): void;+ reportError(error: unknown): void;+ }) {}++ ask(questions: AskUserQuestionItem[], generation: number): string {+ if (!this.deps.isActive(generation)) throw new Error('No active turn for an async question');+ // The existing question UI has one active card per task.+ this.expire('superseded');+ const requestId = `async-question:${randomUUID()}`;+ const entry = { generation, abort: new AbortController(), answered: false };+ this.pending.set(requestId, entry);+ void this.waitForAnswer(requestId, entry, questions);+ return requestId;+ }++ expire(reason: string, generation?: number): void {+ for (const [requestId, entry] of this.pending) {+ if (generation !== undefined && entry.generation !== generation) continue;+ this.pending.delete(requestId);+ entry.abort.abort();+ if (!entry.answered) this.deps.dismiss(requestId, reason);+ }+ }++ private async waitForAnswer(requestId: string, entry: PendingQuestion, questions: AskUserQuestionItem[]): Promise<void> {+ let onAbort!: () => void;+ const cancelled = new Promise<null>((resolve) => {+ onAbort = () => resolve(null);+ entry.abort.signal.addEventListener('abort', onAbort, { once: true });+ });+ try {+ const answer = await Promise.race([+ this.deps.resolve({ kind: 'ask_user_question', requestId, questions, delivery: 'async' }), cancelled,+ ]);+ if (!answer || answer.kind !== 'ask_user_question' || answer.dismissed+ || entry.abort.signal.aborted || !this.deps.isActive(entry.generation)) return;+ // Keep delivery cancellable without expiring the card already resolved by the host.+ entry.answered = true;+ const answered = questions.flatMap(({ question, header }) => {+ const value = answer.answers[question] ?? (header ? answer.answers[header] : undefined);+ return typeof value === 'string' && value.trim() ? [{ question, answer: value }] : [];+ });+ if (answered.length === 0) return;+ // A user reply is ordinary same-turn input, never a new send or an inferred choice.+ await this.deps.deliver(+ `The user answered the asynchronous question:\n${JSON.stringify(answered)}`,+ entry.abort.signal,+ );+ } catch (error) {+ if (!entry.abort.signal.aborted && this.deps.isActive(entry.generation)) this.deps.reportError(error);+ } finally {+ entry.abort.signal.removeEventListener('abort', onAbort);+ this.pending.delete(requestId);+ }+ }+}diff --git a/packages/maker-core/src/session.async-user-questions.test.ts b/packages/maker-core/src/session.async-user-questions.test.tsnew file mode 100644index 0000000000..cda3927748--- /dev/null+++ b/packages/maker-core/src/session.async-user-questions.test.ts@@ -0,0 +1,189 @@+import { describe, expect, it, vi } from 'vitest';+import { Session } from './session.js';+import type { AgentSessionHandle } from './agents/base-agent.js';+import { createAsyncQueue } from './agents/shared/async-queue.js';+import type { AgentEvent, InteractionDecision, InteractionRequest } from './types/events.js';+import type { Logger } from './interfaces/logger.js';++const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger };+const questions = [{ question: 'Which scope?', options: [{ label: 'Personal' }, { label: 'Both' }] }];+const answer: InteractionDecision = { kind: 'ask_user_question', answers: { 'Which scope?': 'Both' } };+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++async function setup(agentKind: 'claude-code' | 'pi' | 'codex') {+ const queue = createAsyncQueue<AgentEvent>();+ let running = false;+ const requests: InteractionRequest[] = [];+ const resolvers: Array<(decision: InteractionDecision) => void> = [];+ let resolveNative!: (request: InteractionRequest) => Promise<InteractionDecision>;+ const handle = {+ id: 'thread', agentKind, model: 'test-model', events: () => queue,+ send: vi.fn(async () => { running = true; }), steer: vi.fn(async () => {}),+ abort: vi.fn(async () => { running = false; }),+ close: vi.fn(async () => { running = false; queue.end(); }),+ isTurnRunning: () => running, setInteractionResolver(resolve: typeof resolveNative) { resolveNative = resolve; },+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),+ } as unknown as AgentSessionHandle;+ const session = new Session({ id: 'task', agentKind, workDir: '/repo', handle, logger,+ capabilities: { sameTurnSteer: { supported: true } } as never, turnStallMs: 0 });+ session.setInteractionListener((request) => {+ requests.push(request);+ return new Promise((resolve) => { resolvers.push(resolve); });+ });+ const events: AgentEvent[] = [];+ session.onEvent((event) => events.push(event));+ await session.send('Start independent work');+ return { session, handle, requests, resolvers, events,+ askSync() { return resolveNative({ kind: 'ask_user_question', requestId: 'sync', questions }); },+ end(type: 'done' | 'error' = 'done') {+ running = false;+ queue.push({ type, source: agentKind, data: type === 'error' ? { isTerminal: true, message: 'failed' } : {} });+ },+ backgroundDone() { queue.push({ type: 'done', turnScope: 'background', data: {}, source: agentKind }); },+ };+}++describe.each(['claude-code', 'pi'] as const)('%s async questions', (agentKind) => {+ it.each(['sync-first', 'async-first'] as const)('keeps the blocking question answerable with %s arrival', async (order) => {+ const s = await setup(agentKind);+ try {+ const oldId = order === 'async-first' ? s.session.askUserQuestionAsync(questions) : null;+ const sync = s.askSync();+ expect(() => s.session.askUserQuestionAsync(questions)).toThrow('blocking user question');+ expect(s.requests.at(-1)?.requestId).toBe('sync');+ if (oldId) {+ expect(s.events.some((e) => e.type === 'interaction_dismissed'+ && (e.data as { requestId?: string }).requestId === oldId)).toBe(true);+ s.resolvers[0](answer);+ }+ s.resolvers.at(-1)!(answer);+ await expect(sync).resolves.toEqual(answer);+ await flush();+ expect(s.handle.steer).not.toHaveBeenCalled();+ // Settling the blocking request releases the card slot.+ expect(s.session.askUserQuestionAsync(questions)).toBeTypeOf('string');+ } finally { await s.session.close(); }+ });++ it.each(['done', 'error', 'abort', 'close', 'replace'] as const)('cancels in-flight answer delivery on %s without expiring the answered card', async (action) => {+ const s = await setup(agentKind);+ let settle!: () => void;+ vi.mocked(s.handle.steer).mockImplementationOnce(async () => new Promise<void>((resolve) => { settle = resolve; }));+ try {+ const id = s.session.askUserQuestionAsync(questions);+ s.resolvers[0](answer);+ await vi.waitFor(() => expect(s.handle.steer).toHaveBeenCalledOnce());+ const signal = vi.mocked(s.handle.steer).mock.calls[0][1]?.signal;+ if (action === 'done' || action === 'error') s.end(action);+ else if (action === 'replace') s.session.askUserQuestionAsync([{ question: 'Another question?' }]);+ else await s.session[action]();+ await vi.waitFor(() => expect(signal?.aborted).toBe(true));+ expect(s.events.filter((e) => e.type === 'interaction_dismissed'+ && (e.data as { requestId?: string }).requestId === id)).toEqual([]);+ settle();+ await flush();+ } finally { settle?.(); await s.session.close(); }+ });++ it('returns immediately, uses the existing card and sends a same-turn answer only once', async () => {+ const s = await setup(agentKind);+ try {+ const id = s.session.askUserQuestionAsync(questions);+ expect(s.requests).toEqual([{ kind: 'ask_user_question', requestId: id, questions, delivery: 'async' }]);+ expect(s.session.getTurnControlSnapshot().pendingInteractionCount).toBe(0);+ expect(s.handle.steer).not.toHaveBeenCalled();+ s.resolvers[0](answer);+ await vi.waitFor(() => expect(s.handle.steer).toHaveBeenCalledOnce());+ expect(s.handle.steer).toHaveBeenCalledWith(expect.objectContaining({+ content: expect.stringContaining('"answer":"Both"'),+ }), expect.objectContaining({ signal: expect.any(AbortSignal) }));+ expect(s.handle.send).toHaveBeenCalledOnce();+ s.resolvers[0](answer);+ await flush();+ expect(s.handle.steer).toHaveBeenCalledOnce();+ } finally { await s.session.close(); }+ });++ it.each(['done', 'error', 'abort', 'close', 'detach'] as const)('expires unanswered questions on %s and ignores a late answer', async (action) => {+ const s = await setup(agentKind);+ try {+ const id = s.session.askUserQuestionAsync(questions);+ if (action === 'done' || action === 'error') s.end(action);+ else await s.session[action]();+ await vi.waitFor(() => expect(s.events.some((e) => e.type === 'interaction_dismissed' && (e.data as { requestId?: string }).requestId === id)).toBe(true));+ if (action === 'done') {+ await vi.waitFor(() => expect(s.events.some((e) => e.type === 'done')).toBe(true));+ expect(s.events.findIndex((e) => e.type === 'interaction_dismissed')).toBeLessThan(s.events.findIndex((e) => e.type === 'done'));+ // A completed card may not answer a later execution of the same Session.+ await s.session.send('Next independent task');+ }+ s.resolvers[0](answer);+ await flush();+ expect(s.handle.steer).not.toHaveBeenCalled();+ expect(s.handle.send).toHaveBeenCalledTimes(action === 'done' ? 2 : 1);+ } finally { await s.session.close(); }+ });++ it('expires the replaced question and keeps background completion from dismissing the new card', async () => {+ const s = await setup(agentKind);+ try {+ const oldId = s.session.askUserQuestionAsync(questions);+ const newId = s.session.askUserQuestionAsync([{ question: 'New question?' }]);+ s.backgroundDone();+ await flush();+ expect(s.events.filter((e) => e.type === 'interaction_dismissed').map((e) => (e.data as { requestId?: string }).requestId)).toEqual([oldId]);+ s.resolvers[0](answer);+ s.resolvers[1]({ kind: 'ask_user_question', answers: { 'New question?': 'Free text' } });+ await vi.waitFor(() => expect(s.handle.steer).toHaveBeenCalledOnce());+ expect(s.requests[1].requestId).toBe(newId);+ } finally { await s.session.close(); }+ });++ it.each([{}, { dismissed: true }] as const)('does not invent a choice for an empty or dismissed answer %j', async (extra) => {+ const s = await setup(agentKind);+ try {+ s.session.askUserQuestionAsync(questions);+ s.resolvers[0]({ kind: 'ask_user_question', answers: {}, ...extra });+ await flush();+ expect(s.handle.steer).not.toHaveBeenCalled();+ expect(s.handle.send).toHaveBeenCalledOnce();+ } finally { await s.session.close(); }+ });++ it('never replays a failed answer as a fresh task', async () => {+ const s = await setup(agentKind);+ try {+ vi.mocked(s.handle.steer).mockRejectedValueOnce(new Error('transport closed after write'));+ s.session.askUserQuestionAsync(questions);+ s.resolvers[0](answer);+ await vi.waitFor(() => expect(s.events.some((e) => e.type === 'error' && (e.data as { isTerminal?: boolean }).isTerminal === false)).toBe(true));+ expect(s.handle.send).toHaveBeenCalledOnce();+ expect(s.handle.steer).toHaveBeenCalledOnce();+ } finally { await s.session.close(); }+ });+});++// Even a stale/misattributed MCP context cannot create a shared question in a+// Codex Session: the live Session owns the harness identity.+it('rejects shared questions around a native Codex card without disturbing it', async () => {+ const s = await setup('codex');+ try {+ expect(() => s.session.askUserQuestionAsync(questions)).toThrow('native');+ const nativeRequest: InteractionRequest = {+ kind: 'ask_user_question', requestId: 'native', questions, delivery: 'async',+ };+ const native = s.session.runHostInteraction(nativeRequest, () => new Promise((resolve) => {+ s.requests.push(nativeRequest);+ s.resolvers.push(resolve);+ }));+ expect(() => s.session.askUserQuestionAsync(questions)).toThrow('native');+ expect(s.requests).toEqual([nativeRequest]);+ expect(s.session.getTurnControlSnapshot().pendingInteractionCount).toBe(0);+ expect(s.events.filter((e) => e.type === 'interaction_dismissed')).toEqual([]);+ s.resolvers[0](answer);+ await expect(native).resolves.toEqual(answer);+ expect(() => s.session.askUserQuestionAsync(questions)).toThrow('native');+ await flush();+ expect(s.handle.steer).not.toHaveBeenCalled();+ } finally { await s.session.close(); }+});diff --git a/packages/maker-core/src/session.tool-loop.test.ts b/packages/maker-core/src/session.tool-loop.test.tsindex 60f1f14249..3f5f972d4b 100644--- a/packages/maker-core/src/session.tool-loop.test.ts+++ b/packages/maker-core/src/session.tool-loop.test.ts@@ -4,7 +4,7 @@ import { createAsyncQueue } from './agents/shared/async-queue.js';import { createPiTranslateContext, translatePiEvent } from './agents/pi/translator.js';import { newCodexRuntimeState, translateItemNotification } from './agents/codex/translator.js';import type { AgentSessionHandle } from './agents/base-agent.js';-import type { AgentEvent, InteractionDecision } from './types/events.js';+import type { AgentEvent, InteractionDecision, InteractionResolver } from './types/events.js';import type { Logger } from './interfaces/logger.js';import type { ToolLoopReviewer } from './agents/shared/tool-loop-review.js';@@ -18,6 +18,7 @@ function setup(agentKind: 'pi' | 'codex', hangAbort = false, toolLoopReviewer?:vi.useFakeTimers();const queue = createAsyncQueue<AgentEvent>();let running = false;+ let resolveInteraction!: InteractionResolver;const handle = {id: 'native-session', agentKind, model: 'test-model',events: () => queue,@@ -29,7 +30,7 @@ function setup(agentKind: 'pi' | 'codex', hangAbort = false, toolLoopReviewer?:}),close: vi.fn(async () => { running = false; queue.end(); }),isTurnRunning: () => running,- setInteractionResolver() {},+ setInteractionResolver(resolve: InteractionResolver) { resolveInteraction = resolve; },} as unknown as AgentSessionHandle;const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };const session = new Session({@@ -45,14 +46,35 @@ function setup(agentKind: 'pi' | 'codex', hangAbort = false, toolLoopReviewer?:await vi.advanceTimersByTimeAsync(0);};const errors = () => seen.filter((event) => event.type === 'error');- return { queue, session, seen, handle, tool, errors, end: async () => {- running = false;- queue.push({ type: 'done', data: {}, source: agentKind });- await vi.advanceTimersByTimeAsync(0);- } };+ return { queue, session, seen, handle, tool, errors,+ ask: (delivery?: 'async') => resolveInteraction({ kind: 'ask_user_question', requestId: 'question',+ questions: [{ question: 'Scope?' }], ...(delivery ? { delivery } : {}) }),+ end: async () => {+ running = false;+ queue.push({ type: 'done', data: {}, source: agentKind });+ await vi.advanceTimersByTimeAsync(0);+ } };}describe.each(['pi', 'codex'] as const)('%s Session tool loop coverage', (agentKind) => {+ it.each(['sync', 'async'] as const)('only suspends loop detection for a blocking question: %s', async (delivery) => {+ const t = setup(agentKind);+ let answer!: (decision: InteractionDecision) => void;+ t.session.setInteractionListener(() => new Promise((resolve) => { answer = resolve; }));+ await t.session.send('investigate');+ const pending = t.ask(delivery === 'async' ? delivery : undefined);+ for (let i = 0; i < 4; i++) await t.tool(`pending-${i}`);+ expect(t.handle.abort).toHaveBeenCalledTimes(delivery === 'async' ? 1 : 0);+ answer({ kind: 'ask_user_question', answers: {} });+ await pending;+ if (delivery === 'sync') {+ for (let i = 0; i < 4; i++) await t.tool(`resumed-${i}`);+ expect(t.handle.abort).toHaveBeenCalledOnce();+ }+ expect(t.errors()).toHaveLength(1);+ expect(t.errors()[0]).toMatchObject({ data: { reason: 'tool_use_loop_detected' } });+ });+it('does not interpret one parallel batch of distinct contract failures as retries', async () => {const t = setup(agentKind);await t.session.send('investigate');diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 8bf5700ca3..a76969392c 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -13,6 +13,7 @@import type { AutoReviewUserIntent } from './agents/shared/auto-review-decision.js';import { randomUUID } from 'node:crypto';import { ToolLoopGuard } from './agents/shared/loop-guard.js';+import { AsyncUserQuestions } from './agents/shared/async-user-questions.js';import {ToolLoopMonitor,type HardToolLoopVerdict,@@ -44,6 +45,7 @@ import { NotSupportedError } from './types/capabilities.js';import type { VisionBridgeHook } from './types/vision-bridge.js';import type {AgentEvent,+ AskUserQuestionItem,InteractionRequest,InteractionDecision,RewindCommitOptions,@@ -66,6 +68,7 @@ import type {} from './agents/base-agent.js';import {AUTO_REVIEW_SOURCE_CONTENT,+ ASYNC_QUESTION_ANSWER,AUTO_REVIEW_USER_INTENT,TurnDispatchRejectedError,TurnDispatchUnconfirmedError,@@ -532,6 +535,8 @@ export class Session {private turnStallSliceStartedAt = 0;/** 正在等用户回应的交互数;>0 期间不计 stall 额度(没事件是正常的)。 */private pendingInteractions = 0;+ /** Blocking question cards take precedence over optional async cards. */+ private pendingUserQuestions = 0;/** 最近一次 fan-out 事件的时刻,仅用于日志诊断。 */private lastEventAt = 0;/**@@ -550,6 +555,7 @@ export class Session {private lastEventType: string | null = null;/** 优雅停止所需的 turn 控制事实;不承担 UI/MCP 会话状态投影。 */private turnControlState: TurnControlState | null = null;+ private readonly asyncUserQuestions: AsyncUserQuestions;constructor(opts: SessionOptions) {this.hostStartupPreferences = opts.hostStartupPreferences@@ -570,6 +576,17 @@ export class Session {opts.turnStallMs ?? parseTurnStallMs(process.env.XDT_SESSION_TURN_STALL_MS);this.visionBridge = opts.visionBridge;this.toolLoopReviewer = opts.toolLoopReviewer;+ this.asyncUserQuestions = new AsyncUserQuestions({+ isActive: (generation) => this.status === 'active' && !this.terminationStarted+ && generation === this.turnGeneration && this.handle.isTurnRunning?.() === true,+ resolve: (request) => this.interactionListener!(request),+ deliver: (text, signal) => this.steer(text, { signal, [ASYNC_QUESTION_ANSWER]: true }),+ dismiss: (requestId, reason) => this.fanOutEvent({+ type: 'interaction_dismissed', data: { requestId, reason, resolvedAs: 'deny' }, source: this.agentKind,+ }),+ reportError: () => this.fanOutEvent({ type: 'error', source: this.agentKind,+ data: { message: 'Async question answer delivery failed.', isTerminal: false } }),+ });// 注入 InteractionResolver 到底层 handle, 转发到 host 维护的 listener。// 没接 listener 时按 kind 给出安全默认: 都视作 deny(host 必须接 listener 才能交互)。@@ -1143,6 +1160,7 @@ export class Session {async abort(): Promise<void> {if (this.status === 'closed') return;if (this.status === 'error') return;+ this.asyncUserQuestions.expire('session_aborted');const abortGeneration = this.turnGeneration;this.cancelSendReservation(this.sendReservation);// 中断已在进行:不再计 stall 额度(下一个 turn 的 send 会重新起表)。@@ -1195,6 +1213,7 @@ export class Session {}async requestGracefulStop(): Promise<SessionGracefulStopResult> {+ this.asyncUserQuestions.expire('session_stopping');const reservation = this.sendReservation;if (reservation) return this.requestGracefulStopForReservation(reservation);const control = this.turnControlState;@@ -1372,6 +1391,7 @@ export class Session {if (this.status === 'closed') return Promise.resolve();this.terminationStarted = true;+ this.asyncUserQuestions.expire('session_closed');// 拆除开始即作废进行中的工具循环复核,迟到结论不得再中断。this.turnControlState?.toolLoopMonitor?.dispose();// Reserve before synchronous terminal listeners run, but begin transport@@ -1522,6 +1542,7 @@ export class Session {const teardown: AgentSessionTeardownOptions = opts ?? { reason: 'account-boundary' };if (this.status === 'closed') return;this.terminationStarted = true;+ this.asyncUserQuestions.expire('session_closed');// 拆除开始即作废进行中的工具循环复核,迟到结论不得再中断。this.turnControlState?.toolLoopMonitor?.dispose();// 与 performClose() 对齐:进入拆离立即 abort 未完成的 pre-dispatch reservation@@ -2139,12 +2160,21 @@ export class Session {request: InteractionRequest,resolve: () => Promise<InteractionDecision>,): Promise<InteractionDecision> {+ // Native async questions use the same card resolver, but never suspend turn+ // protection or register a waiting interaction with the lifecycle observer.+ if (request.kind === 'ask_user_question' && request.delivery === 'async') return resolve();+ const isQuestion = request.kind === 'ask_user_question';+ if (isQuestion) {+ this.pendingUserQuestions += 1;+ this.asyncUserQuestions.expire('superseded');+ }this.pendingInteractions += 1;const runtime = this.observeInteractionStarted(request);this.armTurnStallWatchdog();try {return await resolve();} finally {+ if (isQuestion) this.pendingUserQuestions -= 1;this.pendingInteractions = Math.max(0, this.pendingInteractions - 1);this.observeInteractionSettled(runtime);this.armTurnStallWatchdog();@@ -2155,6 +2185,20 @@ export class Session {this.interactionListener = listener;}+ /** Display an optional question and return immediately; answers steer only this execution. */+ askUserQuestionAsync(questions: AskUserQuestionItem[]): string {+ // Use the live Session identity, even if a stale MCP context claims another+ // harness. Codex's native adapter is its sole async question owner.+ if (this.agentKind === 'codex') throw new Error('Codex uses native async questions');+ this.ensureActive();+ if (!this.interactionListener) throw new Error('Question UI is unavailable');+ if (this.pendingUserQuestions > 0) throw new Error('A blocking user question is already pending');+ if (!this.capabilities.sameTurnSteer.supported) {+ throw new NotSupportedError('sameTurnSteer', this.capabilities.sameTurnSteer);+ }+ return this.asyncUserQuestions.ask(questions, this.turnGeneration);+ }+setTurnLifecycleObserver(observer: SessionTurnLifecycleObserver | null): void {if (this.turnLifecycleObserver !== observer) this.settleHostTurnContinuation(this.turnGeneration);this.turnLifecycleObserver = observer;@@ -2189,6 +2233,7 @@ export class Session {}private beginTurnControl(generation: number): void {+ this.asyncUserQuestions.expire('superseded');this.turnControlState?.toolLoopMonitor?.dispose();this.turnControlState = {generation,@@ -2630,6 +2675,9 @@ export class Session {const hasPendingContinuation = continuationState !== null;const isTerminal =(event.type === 'done' && !hasPendingContinuation) || isTerminalAgentErrorEvent(event);+ if (isTerminal && !isBackgroundEvent) {+ this.asyncUserQuestions.expire(event.type === 'error' ? 'turn_failed' : 'turn_completed', resolvedGeneration);+ }// A dispatching send is not enough evidence that a terminal event belongs// to it: Codex can enqueue the previous turn's terminal error after flipping// its handle idle. Only runEventLoop's generation adoption may transferdiff --git a/packages/maker-core/src/session.turn-stall.test.ts b/packages/maker-core/src/session.turn-stall.test.tsindex 3856adcf1c..55b890fdac 100644--- a/packages/maker-core/src/session.turn-stall.test.ts+++ b/packages/maker-core/src/session.turn-stall.test.ts@@ -13,7 +13,7 @@ import {STALL_ABORT_RECOVERY_GRACE_MS,Session,} from './session.js';-import type { AgentEvent, InteractionDecision, SendOrigin } from './types/events.js';+import type { AgentEvent, InteractionDecision, InteractionRequest, SendOrigin } from './types/events.js';import type { AgentSessionHandle, BackgroundTaskSnapshot } from './agents/base-agent.js';type LoggedError = { msg: string; meta?: Record<string, unknown> };@@ -104,9 +104,11 @@ function createStubHandle(opts?: StubOptions) {endTurn() {turnRunning = false;},- callInteraction(): Promise<unknown> {+ callInteraction(request: InteractionRequest = {+ kind: 'permission', requestId: 'req-1', toolUseId: 'tool-1', toolName: 'test', input: {},+ }): Promise<unknown> {if (!interactionResolver) throw new Error('no interaction resolver installed');- return interactionResolver({ kind: 'permission', requestId: 'req-1' });+ return interactionResolver(request);},};}@@ -435,6 +437,51 @@ describe('Session turn stall watchdog', () => {}});+ it.each(['sync', 'async'] as const)('only suspends stall protection for a blocking question: %s', async (delivery) => {+ vi.useFakeTimers();+ const stub = createStubHandle();+ const session = createSession(stub);+ try {+ let answer!: (decision: InteractionDecision) => void;+ session.setInteractionListener(() => new Promise((resolve) => { answer = resolve; }));+ await session.send('work');+ const pending = stub.callInteraction({ kind: 'ask_user_question', requestId: 'question', toolUseId: 'question-item',+ questions: [{ question: 'Optional scope?' }], ...(delivery === 'async' ? { delivery } : {}) });+ expect(session.getTurnControlSnapshot().pendingInteractionCount).toBe(delivery === 'async' ? 0 : 1);+ await vi.advanceTimersByTimeAsync(STALL_MS + 1);+ expect(stub.abort).toHaveBeenCalledTimes(delivery === 'async' ? 1 : 0);+ answer({ kind: 'ask_user_question', answers: {} });+ await pending;+ if (delivery === 'sync') {+ await vi.advanceTimersByTimeAsync(STALL_MS + 1);+ expect(stub.abort).toHaveBeenCalledOnce();+ }+ } finally { await session.close(); vi.useRealTimers(); }+ });++ it('settling an async question does not release a concurrent blocking interaction', async () => {+ vi.useFakeTimers();+ const stub = createStubHandle();+ const session = createSession(stub);+ try {+ const answers: Array<(decision: InteractionDecision) => void> = [];+ session.setInteractionListener(() => new Promise((resolve) => { answers.push(resolve); }));+ await session.send('work');+ const optional = stub.callInteraction({ kind: 'ask_user_question', requestId: 'optional', toolUseId: 'optional-item',+ delivery: 'async', questions: [{ question: 'Optional scope?' }] });+ const blocking = stub.callInteraction();+ answers[0]({ kind: 'ask_user_question', answers: {} });+ await optional;+ expect(session.getTurnControlSnapshot().pendingInteractionCount).toBe(1);+ await vi.advanceTimersByTimeAsync(STALL_MS * 2);+ expect(stub.abort).not.toHaveBeenCalled();+ answers[1]({ kind: 'permission', behavior: 'allow' });+ await blocking;+ await vi.advanceTimersByTimeAsync(STALL_MS + 1);+ expect(stub.abort).toHaveBeenCalledOnce();+ } finally { await session.close(); vi.useRealTimers(); }+ });+it('交互回应之后重新起表(排除项不能变成永久豁免)', async () => {vi.useFakeTimers();try {diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.tsindex bb07e997f3..d2df179d45 100644--- a/packages/maker-core/src/types/events.ts+++ b/packages/maker-core/src/types/events.ts@@ -317,6 +317,8 @@ export type InteractionRequest =| (InteractionRequestBase & {kind: 'ask_user_question';questions: AskUserQuestionItem[];+ /** Optional question: the provider keeps running; absence means a blocking question. */+ delivery?: 'async';})| (InteractionRequestBase & {kind: 'plan_review';