import { progressStream } from './progressStream.js'; import type { LoopEvent, ToolCall } from '../types.js'; import type { RunQueryOptions } from './options.js'; import type { EffectiveToolSet } from '../tools/effectiveToolSet.js'; import { executionSegments } from '../tools/executionSegments.js'; import { orderedPool } from '../runtime/orderedPool.js'; import { conciseToolPath } from '../runtime/toolDisplay.js'; import { previewArgs, friendlyToolDescription } from './toolPresentation.js'; import type { createToolExecutor, WorkerOutcome } from './toolExecutor.js'; import { getToolGateDetails, getToolByName } from '../tools/index.js'; import type { Tool, ToolCallContext } from '../types.js'; /** New Agent defaults to required; resumed tasks inherit the saved contract. */ function mayCreateRequiredAgent(tc: ToolCall): boolean { // A followup may reopen an existing required task. Its optional status is // not available in the batch; do not infer it from untrusted arguments. if (tc.function.name === 'AgentFollowup') return true; if (tc.function.name !== 'Agent') return false; try { const args = JSON.parse(tc.function.arguments || '{}') as { required?: unknown; resume_agent_id?: unknown }; return Boolean(args.resume_agent_id) || args.required !== false; } catch { return true; } } /** Explicit dependencies narrow the scope, but a later restart invalidates their receipt. */ function hasFutureAdvisorDependency(tc: ToolCall, later: ToolCall[]): boolean { try { const args = JSON.parse(tc.function.arguments); if (Array.isArray(args?.depends_on) && args.depends_on.length && args.depends_on.every((id: unknown) => typeof id === 'string' && id.length > 0)) { const ids = new Set(args.depends_on); return later.some(call => { if (!['Agent', 'AgentFollowup'].includes(call.function.name)) return false; try { const next = JSON.parse(call.function.arguments); const id = call.function.name === 'Agent' ? next.resume_agent_id : next.agent_id; return id ? ids.has(id) : call.function.name === 'AgentFollowup'; } catch { return true; } }); } if (args?.purpose === 'independent' && (args.depends_on === undefined || (Array.isArray(args.depends_on) && !args.depends_on.length))) return false; } catch { /* Invalid arguments must never grant an independent bypass. */ } return later.some(mayCreateRequiredAgent); } /** This is a scheduling check, not authorization. Unknown effects fail closed. * Unlike advisor reminder accounting, builds/tests are not treated as read-only. */ function canInvestigateAfterDeferredAdvisor(tc: ToolCall, tool: Tool | undefined, ctx: ToolCallContext): boolean { // A targeted stop reduces ongoing effects. It still passes runOne's host gate. if (tool === getToolByName(tc.function.name) && ['TaskStop', 'AgentInterrupt'].includes(tc.function.name)) return true; if (!tool || ['Advisor', 'AskUserQuestion', 'PresentResult', 'AgentResolve', 'AgentReport', 'OptimizeConversation'].includes(tool.name)) return false; try { return (getToolGateDetails(tool, tc.function.arguments, ctx)?.isReadOnly ?? tool.isReadOnly) === true; } catch { return false; } } /** Live events follow completion order; history commits follow request order. */ export async function* executeToolBatch(input: { toolCallsByIndex: ToolCall[]; currentEffectiveToolSet: EffectiveToolSet; options: Pick; runOne: ReturnType['runOne']; commitOutcome: (outcome: WorkerOutcome) => AsyncGenerator; onDeferredAdvisorReads?: (calls: ToolCall[]) => void; context?: ToolCallContext; }): AsyncGenerator { const { toolCallsByIndex, currentEffectiveToolSet, options, runOne, commitOutcome } = input; // A formal submission in the same batch as a possibly-required Agent call is // deferred: executed first, it would pass the delivery gate before the new // responsibility is even written to the ledger. const batchMayCreateRequired = toolCallsByIndex.some(mayCreateRequiredAgent); const startEvent = (tc: ToolCall): Extract => ({ type: 'tool_start', toolCallId: tc.id, toolName: tc.function.name, argsPreview: previewArgs(tc.function.arguments), argsFriendly: friendlyToolDescription(tc.function.name, tc.function.arguments), argsConcise: friendlyToolDescription(tc.function.name, tc.function.arguments, conciseToolPath), }); const endEvent = (o: WorkerOutcome): Extract => ({ type: 'tool_end', toolCallId: o.tc.id, toolName: o.tc.function.name, ok: o.result.ok, executed: o.executed === true, content: o.result.ok ? o.result.content : o.result.error === 'aborted' ? '(已中断)' : `Error: ${o.result.error}`, metadata: o.result.metadata, }); const segments: ToolCall[][] = executionSegments(toolCallsByIndex, (tc) => { const tool = currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name); return ( ![ 'AskUserQuestion', 'Advisor', 'OptimizeConversation', 'AgentReport', 'AgentResolve', // Observers/control must see all preceding dispatch registrations. Agent // dispatches themselves remain parallel with other adjacent dispatches. 'AgentList', 'AgentWait', 'TaskOutput', 'TaskStop', 'AgentInterrupt', ].includes(tc.function.name) && tool?.isConcurrencySafe === true ); }); const settled: WorkerOutcome[] = []; // A stop of an already registered target has no dependency on a preceding // dispatch. Launch it promptly, but commit its receipt in original call order. // Never move a control across a human/consultation decision boundary. const urgent = new Map>(); const scheduleUrgent = async function* (calls: ToolCall[], afterDeferredAdvisor = false) { for (const tc of calls) { // Once advice is deferred the batch will not execute any further decision // calls. Those placeholders are not live human/consultation barriers. if (!afterDeferredAdvisor && ['AskUserQuestion', 'Advisor', 'AgentResolve', 'AgentReport', 'OptimizeConversation'].includes(tc.function.name)) break; if (urgent.has(tc) || !['TaskStop', 'AgentInterrupt'].includes(tc.function.name)) continue; const tool = currentEffectiveToolSet.tools.find(t => t.name === tc.function.name); if (!tool || tool !== getToolByName(tc.function.name)) continue; try { const parsed = tool.inputSchema.safeParse(JSON.parse(tc.function.arguments)); if (!parsed.success) continue; const args = parsed.data as { task_id?: string; agent_id?: string }; const id = args.task_id ?? args.agent_id; const state = input.context?.sessionState; if (!id || !(state?.agentTasks.tasks.has(id) || state?.backgroundTasks.tasks.has(id))) continue; const restarting = toolCallsByIndex.slice(0, toolCallsByIndex.indexOf(tc)).some(previous => { if (!['Agent', 'AgentFollowup'].includes(previous.function.name)) return false; try { const args = JSON.parse(previous.function.arguments); return (previous.function.name === 'Agent' ? args.resume_agent_id : args.agent_id) === id; } catch { return true; } }); if (restarting) continue; yield startEvent(tc); urgent.set(tc, runOne(tc, () => {}, batchMayCreateRequired).catch(error => ({ tc, result: { ok: false, error: `停止操作失败:${(error as Error).message}` }, }))); } catch { /* Invalid controls follow normal validation, never lookahead. */ } } }; yield* scheduleUrgent(toolCallsByIndex); const allowsDeferredInvestigation = (tc: ToolCall) => canInvestigateAfterDeferredAdvisor(tc, currentEffectiveToolSet.tools.find(tool => tool.name === tc.function.name), input.context ?? {}); const resumeAfterDeferredAdvisor = async function* (tc: ToolCall) { const rest = toolCallsByIndex.slice(toolCallsByIndex.indexOf(tc) + 1); // Later questions/consultations are themselves deferred, not executed barriers. // Share the remaining allowance across exactly the eligible suffix. input.onDeferredAdvisorReads?.(rest.filter(allowsDeferredInvestigation)); yield* scheduleUrgent(rest, true); }; let questionEncountered = false; let advisorEncountered = false; let advisorDeferred = false; for (const segment of segments) { if (!questionEncountered && !advisorEncountered && segment.length > 1 && (!advisorDeferred || segment.every(allowsDeferredInvestigation))) { // Only concurrency-safe segments run together; hosts may bound throughput. const outcomes = yield* progressStream((enqueue) => orderedPool(segment, options.toolConcurrency ?? segment.length, async (tc) => { enqueue(startEvent(tc)); const o = await runOne(tc, (message, detail) => enqueue({ type: 'tool_progress', toolCallId: tc.id, toolName: tc.function.name, message, detail, }), batchMayCreateRequired, ); enqueue(endEvent(o)); return o; }), ); settled.push(...outcomes); for (const outcome of outcomes) yield* commitOutcome(outcome); } else { // —— 串行:逐个执行(含写类工具,或只有一个工具)。保持实时进度,完成后才提交历史。 for (const tc of segment) { if (batchMayCreateRequired && tc.function.name === 'PresentResult') { const deferred: WorkerOutcome = { tc, result: { ok: false as const, disposition: 'deferred' as const, error: '同一批次还在派生可能必需的子任务,正式成果尚未提交。等这些任务运行并收口、状态明确后,再重新调用 PresentResult;不要先宣布结果已交付。', }, }; yield startEvent(tc); yield endEvent(deferred); settled.push(deferred); yield* commitOutcome(deferred); continue; } if (questionEncountered || advisorEncountered || (advisorDeferred && !allowsDeferredInvestigation(tc))) { const outcome = { tc, result: { ok: false as const, disposition: 'deferred' as const, error: questionEncountered ? '此调用在用户回答前已生成,尚未执行。请先阅读提问结果并重新规划;仅在仍必要时重新调用。' : advisorDeferred ? '顾问调用已暂缓;此调用可能写入、续接执行或改变决策,尚未执行。请先读回执,下一轮重新规划必要派发、续接或修改;不要把未咨询当成已复核。' : '此调用在顾问返回前已生成,尚未执行。请先阅读顾问结果,自主决定采纳、部分采纳或拒绝,再重新生成必要的工具调用。咨询失败则自行判断继续,不必重复咨询。', }, }; yield startEvent(tc); yield endEvent(outcome); settled.push(outcome); yield* commitOutcome(outcome); continue; } if (tc.function.name === 'Advisor' && (() => { const tool = currentEffectiveToolSet.tools.find(t => t.name === tc.function.name); try { return !!tool?.inputSchema.safeParse(JSON.parse(tc.function.arguments)).success; } catch { return false; } })() && hasFutureAdvisorDependency(tc, toolCallsByIndex.slice(toolCallsByIndex.indexOf(tc) + 1))) { const deferred: WorkerOutcome = { tc, executed: false, result: { ok: false, disposition: 'deferred', error: '顾问尚未调用:本批后面仍有相关子任务派发或续接,依赖尚未就绪。只读调查可继续;写入及未知副作用调用需下一轮重新规划。先派发、收取并验收依赖,再咨询;不依赖这些结果的独立问题才用 purpose=independent。', } }; yield startEvent(tc); yield endEvent(deferred); settled.push(deferred); yield* commitOutcome(deferred); advisorDeferred = true; yield* resumeAfterDeferredAdvisor(tc); continue; } questionEncountered = tc.function.name === 'AskUserQuestion'; if (!urgent.has(tc)) yield startEvent(tc); const o: WorkerOutcome = yield* progressStream((emit): Promise => urgent.get(tc) ?? runOne(tc, (message, detail) => emit({ type: 'tool_progress', toolCallId: tc.id, toolName: tc.function.name, message, detail, }), batchMayCreateRequired, ), ); // Every later call was planned without this second opinion, including // decision records and further consultations. Return control to the LLM. if (tc.function.name === 'Advisor') { advisorDeferred = !o.result.ok && o.result.disposition === 'deferred' && o.executed !== true; advisorEncountered = !advisorDeferred; } yield endEvent(o); settled.push(o); yield* commitOutcome(o); if (tc.function.name === 'Advisor' && advisorDeferred) yield* resumeAfterDeferredAdvisor(tc); } } } return settled; }