/** * ============================================================ * src/askBridge.ts —— 「向人提问」的宿主交互桥(host interaction channel) * ------------------------------------------------------------ * 动态工作流的地基:让一个**工具**(AskUserQuestion)能在执行中途停下来问用户, * 拿到选择再继续。对齐上游 Claude Code 的 AskUserQuestion —— 交互不是给工作流引擎 * 特制的「双向生成器通道」,而是**骑在既有 tool_call → tool_result 回路上**: * 「等用户」只不过是这个工具返回得慢而已。所以同一座桥同时服务于: * - 主循环 TAOR(模型自己决定何时 AskUserQuestion) * - workflow 的 `tool: AskUserQuestion` 步骤 * - agent: 节点 miniReAct 把 AskUserQuestion 纳入工具白名单 * → 这就是「交互 + TAOR = 动态工作流」。 * * 为什么放在 src 根(而非 ui/ 或 tools/):它是工具(产出问题)与宿主/UI(回答) * 之间的中介,两边都要 import。放在中立位置,避免 tools → ui 的反向层级耦合。 * * 两种宿主: * - TUI:useChat mount 时 setAskHandler() 注册一个会弹出选择界面的处理器。 * - 非交互(`-p` / gateway / webchat 子进程):没有 handler → * requestUserChoice() 自动选**推荐项(每题首项)**并在 stderr 注记, * 绝不挂起(保 `-p` 单行 JSON 契约 + 子进程不卡死)。 * ============================================================ */ import { AsyncLocalStorage } from 'node:async_hooks'; /** 一个选项。约定:把推荐项放在第一个,并在 label 末尾标「(推荐)」。 */ export interface AskOption { label: string; description?: string; } /** 一道问题。 */ export interface AskQuestionSpec { /** 完整问题文本 */ question: string; /** 短标签(≤12 字),如「交互底座」,给 UI 当 chip 显示 */ header: string; /** 是否允许多选;默认 false */ multiSelect?: boolean; /** 2-4 个互斥选项;第一个应为推荐项 */ options: AskOption[]; } /** 一道问题的回答。 */ export interface AskAnswer { header: string; question: string; /** 选中的 label(多选可多个);选「其他」自由输入时是用户输入的文本 */ selected: string[]; } /** 提问来源只描述产品归属,不携带 cwd、Session 历史或其他本机隐私。 */ export interface AskSource { kind: 'main' | 'subagent'; parentToolCallId?: string; description?: string; ownerUserId?: string; } export type AskQueueState = 'queued' | 'waiting' | 'answered' | 'cancelled'; export interface AskQueueStatus { source: AskSource; state: AskQueueState; queuePosition?: number; queuedCount?: number; } /** 宿主侧控制当前提问所属执行单元;不进入协议或模型上下文。 */ export interface AskControl { /** 取消提问所属的主回合或子任务。 */ cancelSource: () => void; } /** UI 注册的处理器:弹界面、等用户选完、resolve 答案;中断则 reject。 */ export type AskHandler = ( questions: AskQuestionSpec[], signal?: AbortSignal, source?: AskSource, control?: AskControl, ) => Promise; let handler: AskHandler | null = null; const askHandlerScope = new AsyncLocalStorage(); interface AskSourceScope { source: AskSource; onWaitStart?: () => void; onWaitEnd?: () => void; onCancel?: () => void; } const askSourceScope = new AsyncLocalStorage(); /** * 注册 / 注销 UI 处理器。 * TUI 的 useChat 在 mount 时注册、unmount 时传 null 注销。 * 单进程单 UI,模块级单例即可;HTTP 多租户场景以后再按 session 隔离(留 TODO)。 */ export function setAskHandler(h: AskHandler | null): void { handler = h; } /** 在某个异步调用链里临时覆盖 Ask handler(Web/Gateway 多 turn 并发宿主用)。 */ export function withAskHandler(h: AskHandler, fn: () => T): T { return askHandlerScope.run(h, fn); } /** 给嵌套 Agent 的提问附上来源,并允许执行器暂停/恢复自身超时预算。 */ export function withAskSource( source: AskSource, lifecycle: { onWaitStart?: () => void; onWaitEnd?: () => void; onCancel?: () => void }, fn: () => T, ): T { return askSourceScope.run({ source, ...lifecycle }, fn); } /** * 把任意宿主 handler 包装为单活跃 FIFO 队列。队列实例必须按顶层回合创建, * 不能做模块级单例,否则不同用户/Session 会互相阻塞。 */ export function createAskCoordinator( base: AskHandler, onStatus?: (status: AskQueueStatus) => void, ): AskHandler { type Entry = { questions: AskQuestionSpec[]; signal?: AbortSignal; source: AskSource; control?: AskControl; resolve: (answers: AskAnswer[]) => void; reject: (error: Error) => void; abort?: () => void; }; const queue: Entry[] = []; let active = false; const refreshQueuedPositions = (): void => { queue.forEach((entry, index) => onStatus?.({ source: entry.source, state: 'queued', queuePosition: index + 1, queuedCount: queue.length, })); }; const pump = (): void => { if (active) return; const entry = queue.shift(); if (!entry) return; active = true; entry.abort?.(); onStatus?.({ source: entry.source, state: 'waiting', queuedCount: queue.length }); refreshQueuedPositions(); void base(entry.questions, entry.signal, entry.source, entry.control).then( (answers) => { onStatus?.({ source: entry.source, state: 'answered', queuedCount: queue.length }); entry.resolve(answers); }, (error) => { onStatus?.({ source: entry.source, state: 'cancelled', queuedCount: queue.length }); entry.reject(error instanceof Error ? error : new Error(String(error))); }, ).finally(() => { active = false; pump(); }); }; return (questions, signal, source = { kind: 'main' }, control) => new Promise((resolve, reject) => { if (signal?.aborted) { reject(new DOMException('aborted', 'AbortError')); return; } const entry: Entry = { questions, signal, source, control, resolve, reject }; const onAbort = (): void => { const index = queue.indexOf(entry); if (index < 0) return; // active entry is cancelled by the base handler's signal queue.splice(index, 1); onStatus?.({ source, state: 'cancelled', queuedCount: queue.length }); reject(new DOMException('aborted', 'AbortError')); refreshQueuedPositions(); }; if (signal) { signal.addEventListener('abort', onAbort, { once: true }); entry.abort = () => signal.removeEventListener('abort', onAbort); } queue.push(entry); if (active) { onStatus?.({ source, state: 'queued', queuePosition: queue.length, queuedCount: queue.length }); } pump(); }); } /** 是否有交互 UI 在场(测试 / 诊断用)。 */ export function hasAskHandler(): boolean { return askHandlerScope.getStore() !== undefined || handler !== null; } /** * 向用户提问,返回答案。 * * - 有 handler(TUI)→ 交给它弹界面、等用户。 * - 无 handler(非交互宿主)→ 自动选每题首项(约定=推荐),stderr 注记,不挂起。 */ export async function requestUserChoice( questions: AskQuestionSpec[], signal?: AbortSignal, ): Promise { const scope = askSourceScope.getStore(); const scoped = askHandlerScope.getStore(); if (scoped || handler) { scope?.onWaitStart?.(); try { return await (scoped ?? handler!)(questions, signal, scope?.source, { cancelSource: () => scope?.onCancel?.(), }); } finally { scope?.onWaitEnd?.(); } } // 非交互兜底 return questions.map((q) => { const pick = q.options[0]?.label ?? ''; // 约定校验:askBridge.ts:25 JSDoc 说"把推荐项放在第一个,并在 label 末尾标「(推荐)」。 // 若首项 label 不含 "(推荐)",stderr 注记一下——上游作者违反约定 // (用户被自动套上非推荐路径是糟糕的体验) const firstOpt = q.options[0]; if (firstOpt && !firstOpt.label.includes('(推荐)')) { try { process.stderr.write( `[AskUserQuestion·非交互] "${q.header}" 首项 label "${firstOpt.label}" 不含「(推荐)」标记——非交互宿主会按首项兜底,违反 promptAssembly 里的提问克制约定\n`, ); } catch { /* ignore */ } } try { process.stderr.write( `[AskUserQuestion·非交互] "${q.header}" 无 UI,自动选推荐项:"${pick}"\n`, ); } catch { /* stderr 不可用也不阻断 */ } return { header: q.header, question: q.question, selected: pick ? [pick] : [], }; }); }