omk-agent-core 1.2.4 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/agent-loop.d.ts.map +1 -1
  3. package/dist/agent-loop.js +35 -47
  4. package/dist/agent-loop.js.map +1 -1
  5. package/dist/agent.d.ts +6 -1
  6. package/dist/agent.d.ts.map +1 -1
  7. package/dist/agent.js +9 -5
  8. package/dist/agent.js.map +1 -1
  9. package/dist/pending-message-queue.d.ts +1 -0
  10. package/dist/pending-message-queue.d.ts.map +1 -1
  11. package/dist/pending-message-queue.js +16 -5
  12. package/dist/pending-message-queue.js.map +1 -1
  13. package/dist/tool-dag-ecraf.d.ts.map +1 -1
  14. package/dist/tool-dag-ecraf.js +15 -8
  15. package/dist/tool-dag-ecraf.js.map +1 -1
  16. package/dist/tool-dag-index.d.ts +19 -0
  17. package/dist/tool-dag-index.d.ts.map +1 -0
  18. package/dist/tool-dag-index.js +175 -0
  19. package/dist/tool-dag-index.js.map +1 -0
  20. package/dist/tool-dag-memo.d.ts +13 -3
  21. package/dist/tool-dag-memo.d.ts.map +1 -1
  22. package/dist/tool-dag-memo.js +64 -25
  23. package/dist/tool-dag-memo.js.map +1 -1
  24. package/dist/tool-dag-own-number.d.ts +3 -0
  25. package/dist/tool-dag-own-number.d.ts.map +1 -0
  26. package/dist/tool-dag-own-number.js +5 -0
  27. package/dist/tool-dag-own-number.js.map +1 -0
  28. package/dist/tool-dag-owned-task.d.ts +15 -0
  29. package/dist/tool-dag-owned-task.d.ts.map +1 -0
  30. package/dist/tool-dag-owned-task.js +33 -0
  31. package/dist/tool-dag-owned-task.js.map +1 -0
  32. package/dist/tool-dag-plan-copy.d.ts +5 -0
  33. package/dist/tool-dag-plan-copy.d.ts.map +1 -0
  34. package/dist/tool-dag-plan-copy.js +18 -0
  35. package/dist/tool-dag-plan-copy.js.map +1 -0
  36. package/dist/tool-dag-read-aware.d.ts +11 -0
  37. package/dist/tool-dag-read-aware.d.ts.map +1 -0
  38. package/dist/tool-dag-read-aware.js +34 -0
  39. package/dist/tool-dag-read-aware.js.map +1 -0
  40. package/dist/tool-dag-reduce.d.ts +29 -0
  41. package/dist/tool-dag-reduce.d.ts.map +1 -0
  42. package/dist/tool-dag-reduce.js +146 -0
  43. package/dist/tool-dag-reduce.js.map +1 -0
  44. package/dist/tool-dag-scheduler.d.ts.map +1 -1
  45. package/dist/tool-dag-scheduler.js +3 -14
  46. package/dist/tool-dag-scheduler.js.map +1 -1
  47. package/dist/tool-terminal-index.d.ts +4 -0
  48. package/dist/tool-terminal-index.d.ts.map +1 -0
  49. package/dist/tool-terminal-index.js +12 -0
  50. package/dist/tool-terminal-index.js.map +1 -0
  51. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [1.3.0] - 2026-10-04
6
+
7
+ ### Added
8
+
9
+ - `Agent.prepareTools(tools, pending)` selects the tools a run sends to the provider, for example to fit a model's input window. It runs when a prompt or continuation snapshots its context, receives the prompt messages not yet in `state.messages`, and never changes `state.tools`.
10
+
11
+ ### Changed
12
+
13
+ - The live tool frontier releases ready calls along the conflict DAG's transitive reduction. `assignDagDependencies()` still returns every conflict edge. On a 512-writer same-path graph the ready queue tracks a 511-edge chain instead of 130,816 edges. The reduction keeps a triangular ancestor matrix of at most 16 MiB and switches to exact iterative traversal for larger graphs.
14
+
15
+ ### Fixed
16
+
17
+ - A DAG task's rejection is observed when the task is created, and leaving the frontier joins every started task and keeps both execution and settlement failures, so several failures surface as one `AggregateError`. Memo inserts and hits detach nested claim arrays and objects, and dependency construction skips only read/read pairs.
18
+ - Taking queued steering or follow-up messages one at a time no longer copies the rest of the queue on every take. Draining 4,096 messages made 8,386,560 element copies and now makes 3,072.
19
+ - The per-run tool-call schedule memo is bounded by bytes as well as by its 64 entries. Its keys carry whole call arguments, so 64 batches that each wrote 256 KiB kept 16 MiB of key text. Each memo now keeps at most 4 MiB of accounted text (two bytes per UTF-16 code unit of key and JSON value, plus 128 per entry), evicting the least recently used batch, and schedules a batch whose entry would exceed 512 KiB, which one 256 KiB write already does, without retaining it.
20
+
5
21
  ## [1.2.4] - 2026-09-23
6
22
 
7
23
  ### Changed
@@ -1 +1 @@
1
- {"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAKN,WAAW,EACX,KAAK,KAAK,EACV,KAAK,iBAAiB,EAEtB,MAAM,QAAQ,CAAC;AAKhB,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAwBhG,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,eAAe,EAEpB,KAAK,YAAY,EAKjB,KAAK,QAAQ,EAGb,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAWzE,MAAM,WAAW,sBAAsB;IACtC,kFAAkF;IAClF,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,4EAA4E;IAC5E,cAAc,EAAE,YAAY,GAAG,SAAS,CAAC;IACzC,0EAA0E;IAC1E,cAAc,EAAE,iBAAiB,EAAE,CAAC;CACpC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACrC,iBAAiB,EAAE,SAAS,YAAY,EAAE,EAC1C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,OAAO,GACd,sBAAsB,CAiCxB;AAqCD;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CA0BzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAoCzC;AAED,wBAAsB,YAAY,CACjC,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAezB;AAED,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAgBzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"omk-ai\";\nimport { bindToolIdentity } from \"./builtin-tool-resource-claims.ts\";\nimport { partitionToolBatchWaves } from \"./parallel-tool-batch.ts\";\nimport { pinProviderConfig, requestAssistantResponse } from \"./provider-request.ts\";\n\nexport { getVisionRouteModel, isVisionRouteModel, VISION_ROUTE_MODEL } from \"./vision-route.ts\";\n\nimport { type DeferredCall, deferredStillConflicts } from \"./tool-dag-deferred.ts\";\nimport { type DagScheduleCache, scheduleDagLevelsMemo as scheduleDagLevelsMemoFromModule } from \"./tool-dag-memo.ts\";\nimport { applyConcurrencyCap, assignDagDependencies } from \"./tool-dag-scheduler.ts\";\nimport {\n\tawaitWithAbort,\n\tcreateErrorToolResult,\n\tcreateImmutableJsonSnapshot,\n\tcreateImmutableSnapshot,\n\ttype ExecutedToolCallOutcome,\n\ttype FinalizedToolCallOutcome,\n\tfinalizeExecutedToolCall,\n\tparseJsonValue,\n\tstampToolResultEnvelope,\n} from \"./tool-execution-boundary.ts\";\nimport { type ClaimableToolCall, resolveToolClaimsForCall, type ToolClaimResolution } from \"./tool-resource-claims.ts\";\nimport { resolveToolTimeoutMs, runToolCallWithTimeout } from \"./tool-timeout.ts\";\nimport { hasUnsettledTimeout } from \"./tool-timeout-settlement.ts\";\nimport {\n\tcreateSyntheticToolResult,\n\tinspectTranscriptIntegrity,\n\trepairTranscriptIntegrity,\n} from \"./tool-transcript-integrity.ts\";\nimport {\n\ttype AgentContext,\n\ttype AgentEvent,\n\ttype AgentLoopConfig,\n\ttype AgentLoopTurnUpdate,\n\ttype AgentMessage,\n\ttype AgentTool,\n\ttype AgentToolCall,\n\ttype AgentToolResult,\n\tcreateToolResultEnvelope,\n\ttype StreamFn,\n\ttype ToolCallDisposition,\n\ttype ToolResultEnvelope,\n} from \"./types.ts\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nexport interface FailureTerminationPlan {\n\t/** Messages to publish as the run result (closure results + optional failure). */\n\tmessages: AgentMessage[];\n\t/** Synthetic assistant failure message, or `undefined` when fail-closed. */\n\tfailureMessage: AgentMessage | undefined;\n\t/** Synthetic tool results used to close an open turn, in source order. */\n\tclosureResults: ToolResultMessage[];\n}\n\n/**\n * Decide how to terminate a run after the underlying loop rejected.\n *\n * A synthetic assistant failure may only be appended on top of a transcript\n * whose tool turns are all closed. When `completedMessages` ends with an open\n * tool turn, a safe missing-only closure (synthetic results for the unambiguous\n * missing tail calls) is appended first so the failure assistant never creates\n * an `assistant(tool calls) -> assistant(failure)` interleaving.\n *\n * If the transcript is ambiguous (duplicate/orphan/interleave, or a\n * mid-transcript gap) it is never auto-repaired: the plan returns no failure\n * message so the caller ends the stream without fabricating a turn over\n * corruption. Pure apart from `Date.now()` on the failure message.\n */\nexport function planFailureTermination(\n\tcompletedMessages: readonly AgentMessage[],\n\tmodel: Model<any>,\n\terror: unknown,\n\taborted: boolean,\n): FailureTerminationPlan {\n\tconst messages = [...completedMessages];\n\tconst closureResults: ToolResultMessage[] = [];\n\n\tif (!inspectTranscriptIntegrity(messages).ok) {\n\t\ttry {\n\t\t\tconst repaired = repairTranscriptIntegrity(messages, \"Tool result missing; run terminated by error\");\n\t\t\t// repairTranscriptIntegrity appends synthetic results only for\n\t\t\t// unambiguous missing tail calls; anything ambiguous throws above.\n\t\t\tfor (let i = messages.length; i < repaired.length; i++) {\n\t\t\t\tconst result = createImmutableSnapshot(repaired[i] as ToolResultMessage);\n\t\t\t\tclosureResults.push(result);\n\t\t\t\tmessages.push(result);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ambiguous transcript: never auto-repair. Fail closed without a\n\t\t\t// synthetic assistant turn over a corrupt transcript.\n\t\t\treturn { messages, failureMessage: undefined, closureResults: [] };\n\t\t}\n\t}\n\n\tconst failureMessage: AgentMessage = createImmutableSnapshot({\n\t\trole: \"assistant\",\n\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: EMPTY_USAGE,\n\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t});\n\treturn { messages: [...messages, failureMessage], failureMessage, closureResults };\n}\n\n/**\n * Terminate the public event stream after the underlying loop rejected.\n *\n * Uses {@link planFailureTermination} so the disposition of any unresolved tool\n * calls matches transcript repair exactly: an unambiguous open turn is closed\n * with synthetic results before a coherent\n * message_start/message_end/turn_end/agent_end sequence for the failure\n * assistant, and an ambiguous transcript fails closed (agent_end only, no\n * fabricated assistant). The stream always settles for `for await` consumers\n * and `stream.result()`.\n */\nfunction endStreamWithFailure(\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tconfig: AgentLoopConfig,\n\tcompletedMessages: AgentMessage[],\n\terror: unknown,\n\tsignal?: AbortSignal,\n): void {\n\tconst plan = planFailureTermination(completedMessages, config.model, error, signal?.aborted ?? false);\n\n\tfor (const result of plan.closureResults) {\n\t\tstream.push({ type: \"message_start\", message: result });\n\t\tstream.push({ type: \"message_end\", message: result });\n\t}\n\n\tif (plan.failureMessage) {\n\t\tstream.push({ type: \"message_start\", message: plan.failureMessage });\n\t\tstream.push({ type: \"message_end\", message: plan.failureMessage });\n\t\tstream.push({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t}\n\n\tstream.push({ type: \"agent_end\", messages: plan.messages });\n\tstream.end(plan.messages);\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\tconst completedMessages: AgentMessage[] = [];\n\n\tvoid runAgentLoop(\n\t\tprompts,\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tif (event.type === \"message_end\") {\n\t\t\t\tcompletedMessages.push(event.message);\n\t\t\t}\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then(\n\t\t(messages) => {\n\t\t\tstream.end(messages);\n\t\t},\n\t\t(error: unknown) => {\n\t\t\tendStreamWithFailure(stream, config, completedMessages, error, signal);\n\t\t},\n\t);\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\t// Guard: the last message must be one the provider can build on. A plain\n\t// text/thinking assistant turn is acceptable (convertToLlm may merge or the\n\t// provider supports assistant pre-fill); only an assistant turn that still\n\t// carries unresolved tool calls is a hard error because the provider will\n\t// reject the request without matching tool results.\n\tassertContinuableTranscript(context.messages);\n\n\tconst stream = createAgentStream();\n\tconst completedMessages: AgentMessage[] = [];\n\n\tvoid runAgentLoopContinue(\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tif (event.type === \"message_end\") {\n\t\t\t\tcompletedMessages.push(event.message);\n\t\t\t}\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then(\n\t\t(messages) => {\n\t\t\tstream.end(messages);\n\t\t},\n\t\t(error: unknown) => {\n\t\t\tendStreamWithFailure(stream, config, completedMessages, error, signal);\n\t\t},\n\t);\n\n\treturn stream;\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = [...prompts];\n\tconst currentContext: AgentContext = { ...context, messages: [...context.messages, ...prompts] };\n\tconst publish: AgentEventSink = (event) => emit(createImmutableSnapshot(event));\n\tconst pinnedConfig = await pinProviderConfig(config, publish);\n\n\tawait publish({ type: \"agent_start\" });\n\tawait publish({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait publish({ type: \"message_start\", message: prompt });\n\t\tawait publish({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, pinnedConfig, signal, publish, streamFn);\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tassertContinuableTranscript(context.messages);\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context };\n\tconst publish: AgentEventSink = (event) => emit(createImmutableSnapshot(event));\n\tconst pinnedConfig = await pinProviderConfig(config, publish);\n\n\tawait publish({ type: \"agent_start\" });\n\tawait publish({ type: \"turn_start\" });\n\tawait runLoop(currentContext, newMessages, pinnedConfig, signal, publish, streamFn);\n\treturn newMessages;\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\n/**\n * Validate the full transcript before continuing. Replaces the earlier\n * last-message-only tail check: `assistant(A,B) -> result(A)` and any\n * duplicate/orphan/interleaved structure now fail before the first provider\n * request, not only a trailing assistant message that still carries tool calls.\n *\n * A trailing assistant turn with no tool calls (plain text/thinking) remains\n * continuable, so compaction, session resume, and explicit retries keep working.\n */\nfunction assertContinuableTranscript(messages: AgentMessage[]): void {\n\tconst report = inspectTranscriptIntegrity(messages);\n\tif (report.ok) {\n\t\treturn;\n\t}\n\tconst last = messages[messages.length - 1];\n\tif (last !== undefined && last.role === \"assistant\" && last.content.some((block) => block.type === \"toolCall\")) {\n\t\tthrow new Error(\n\t\t\t\"Cannot continue: the last assistant message has pending tool calls without matching results. \" +\n\t\t\t\t\"Add tool results or a new user message before continuing.\",\n\t\t);\n\t}\n\tconst summary = report.issues.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\tthrow new Error(\n\t\t`Cannot continue: invalid tool transcript (${summary}). ` +\n\t\t\t\"Append terminal tool results or repair the transcript before continuing.\",\n\t);\n}\n\n/** Throw when the tool transcript could not be accepted by a provider. */\nfunction assertValidToolTranscript(messages: AgentMessage[], describe: (summary: string) => string): void {\n\tconst integrityReport = inspectTranscriptIntegrity(messages);\n\tif (integrityReport.ok) {\n\t\treturn;\n\t}\n\tconst summary = integrityReport.issues.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\tthrow new Error(describe(summary));\n}\n\n/** Inject queued steering messages into the transcript before the next assistant turn. */\nasync function injectPendingMessages(\n\tpendingMessages: AgentMessage[],\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\temit: AgentEventSink,\n): Promise<void> {\n\tfor (const message of pendingMessages) {\n\t\tawait emit({ type: \"message_start\", message });\n\t\tawait emit({ type: \"message_end\", message });\n\t\tcurrentContext.messages.push(message);\n\t\tnewMessages.push(message);\n\t}\n}\n\n/** Close every emitted tool call with a synthetic terminal result and end the run. */\nasync function closeRunOnTerminalStop(\n\tcurrentContext: AgentContext,\n\tmessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tnewMessages: AgentMessage[],\n\temit: AgentEventSink,\n): Promise<void> {\n\tconst toolResults: ToolResultMessage[] = [];\n\tconst reason =\n\t\tmessage.stopReason === \"aborted\"\n\t\t\t? \"Operation aborted\"\n\t\t\t: \"Skipped because the provider terminated before tool execution\";\n\tconst disposition = message.stopReason === \"aborted\" ? \"aborted\" : \"skipped\";\n\tfor (const toolCall of toolCalls) {\n\t\tconst result = createImmutableSnapshot(\n\t\t\tcreateSyntheticToolResult(toolCall.id, toolCall.name, reason, Date.now(), disposition),\n\t\t);\n\t\tcurrentContext.messages.push(result);\n\t\tnewMessages.push(result);\n\t\ttoolResults.push(result);\n\t\tawait emitToolResultMessage(result, emit);\n\t}\n\tawait emit({ type: \"turn_end\", message, toolResults });\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\n/** Drain an optional message queue, normalizing absent queues to an empty list. */\nasync function drainMessageQueue(queue?: () => Promise<AgentMessage[]>): Promise<AgentMessage[]> {\n\treturn queue === undefined ? [] : await queue();\n}\n\n/** Validate an optional per-run provider-turn budget. */\nfunction validateMaxTurns(maxTurns: number | undefined): number | undefined {\n\tif (maxTurns === undefined) return undefined;\n\tif (!Number.isSafeInteger(maxTurns) || maxTurns < 1) {\n\t\tthrow new RangeError(\"maxTurns must be a positive safe integer\");\n\t}\n\treturn maxTurns;\n}\n\n/** Reject ambiguous provider-emitted tool transcripts before any tool executes. */\nfunction assertEmittedTranscriptUnambiguous(messages: AgentMessage[]): void {\n\tconst emittedAmbiguities = inspectTranscriptIntegrity(messages).issues.filter(\n\t\t(issue) => issue.kind !== \"missing_result\",\n\t);\n\tif (emittedAmbiguities.length === 0) {\n\t\treturn;\n\t}\n\tconst summary = emittedAmbiguities.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\tthrow new Error(`Refusing tool execution: invalid emitted tool transcript (${summary}).`);\n}\n\ntype ToolBatchTurnOutcome =\n\t| { kind: \"continue\"; toolResults: ToolResultMessage[]; hasMoreToolCalls: boolean; stopRun: boolean }\n\t| { kind: \"ended\" };\n\n/** Execute one assistant batch, closing unresolved calls and ending the run on abort. */\nasync function runToolBatchForTurn(\n\tcurrentContext: AgentContext,\n\tmessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tnewMessages: AgentMessage[],\n\tdagScheduleCache: DagScheduleCache,\n): Promise<ToolBatchTurnOutcome> {\n\tconst executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit, dagScheduleCache);\n\tconst toolResults = [...executedToolBatch.messages];\n\tif (signal?.aborted) {\n\t\t// Close only unresolved calls, preserving finalized results, then stop\n\t\t// before hooks, queues, or another provider request.\n\t\tconst synthesized = await closeUnresolvedToolBatch(currentContext, toolCalls, toolResults, emit);\n\t\ttoolResults.push(...synthesized);\n\t\tfor (const result of toolResults) newMessages.push(result);\n\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\treturn { kind: \"ended\" };\n\t}\n\tfor (const result of toolResults) newMessages.push(result);\n\treturn {\n\t\tkind: \"continue\",\n\t\ttoolResults,\n\t\thasMoreToolCalls: !executedToolBatch.terminate,\n\t\tstopRun: executedToolBatch.stopRun ?? false,\n\t};\n}\n\n/** Merge a prepareNextTurn snapshot into the active context and loop config. */\nfunction applyNextTurnSnapshot(\n\tcurrentContext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsnapshot: AgentLoopTurnUpdate,\n): { context: AgentContext; config: AgentLoopConfig } {\n\treturn {\n\t\tcontext: snapshot.context ?? currentContext,\n\t\tconfig: {\n\t\t\t...config,\n\t\t\tmodel: snapshot.model ?? config.model,\n\t\t\treasoning:\n\t\t\t\tsnapshot.thinkingLevel === undefined\n\t\t\t\t\t? config.reasoning\n\t\t\t\t\t: snapshot.thinkingLevel === \"off\"\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: snapshot.thinkingLevel,\n\t\t},\n\t};\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tinitialContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tinitialConfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tlet currentContext = initialContext;\n\tlet config = initialConfig;\n\tlet firstTurn = true;\n\tlet turnsStarted = 0;\n\tconst maxTurns = validateMaxTurns(initialConfig.maxTurns);\n\tconst dagScheduleCache: DagScheduleCache = new Map();\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages = await drainMessageQueue(config.getSteeringMessages);\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t}\n\t\t\tfirstTurn = false;\n\n\t\t\t// Process pending messages (inject before next assistant response)\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tawait injectPendingMessages(pendingMessages, currentContext, newMessages, emit);\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Stream assistant response\n\t\t\tturnsStarted++;\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tnewMessages.push(message);\n\n\t\t\t// Provider output is untrusted protocol input. Reject duplicate call IDs\n\t\t\t// and every other ambiguous turn before any tool can execute.\n\t\t\tassertEmittedTranscriptUnambiguous(currentContext.messages);\n\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait closeRunOnTerminalStop(currentContext, message, toolCalls, newMessages, emit);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tlet stopAfterToolBatch = false;\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tconst batchOutcome = await runToolBatchForTurn(\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolCalls,\n\t\t\t\t\tconfig,\n\t\t\t\t\tsignal,\n\t\t\t\t\temit,\n\t\t\t\t\tnewMessages,\n\t\t\t\t\tdagScheduleCache,\n\t\t\t\t);\n\t\t\t\tif (batchOutcome.kind === \"ended\") {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttoolResults.push(...batchOutcome.toolResults);\n\t\t\t\thasMoreToolCalls = batchOutcome.hasMoreToolCalls;\n\t\t\t\tstopAfterToolBatch = batchOutcome.stopRun;\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\t\t\tif (stopAfterToolBatch) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (maxTurns !== undefined && turnsStarted >= maxTurns) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst nextTurnContext = {\n\t\t\t\tmessage,\n\t\t\t\ttoolResults,\n\t\t\t\tcontext: currentContext,\n\t\t\t\tnewMessages,\n\t\t\t};\n\t\t\tconst nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);\n\t\t\tif (nextTurnSnapshot) {\n\t\t\t\tconst applied = applyNextTurnSnapshot(currentContext, config, nextTurnSnapshot);\n\t\t\t\tcurrentContext = applied.context;\n\t\t\t\tconfig = applied.config;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tawait config.shouldStopAfterTurn?.({\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolResults,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\tnewMessages,\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tpendingMessages = await drainMessageQueue(config.getSteeringMessages);\n\t\t}\n\n\t\t// Agent would stop here. Check for follow-up messages.\n\t\tconst followUpMessages = await drainMessageQueue(config.getFollowUpMessages);\n\t\tif (followUpMessages.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\t// Validate the full transcript before every provider request. This fails\n\t// fast for `assistant(A,B) -> result(A)` and any duplicate/orphan/interleaved\n\t// structure that the provider would otherwise reject opaquely.\n\tassertValidToolTranscript(\n\t\tcontext.messages,\n\t\t(summary) =>\n\t\t\t`Refusing provider request: invalid tool transcript (${summary}). ` +\n\t\t\t\"Append terminal tool results or repair the transcript before retrying.\",\n\t);\n\n\t// Pin request-affecting data before asynchronous context/auth hooks can mutate caller state.\n\tconst requestConfig = config.modelContract\n\t\t? { ...config, model: createImmutableSnapshot(config.model), headers: config.headers && { ...config.headers } }\n\t\t: config;\n\t// Apply context transform if configured (AgentMessage[] → AgentMessage[])\n\tlet messages = context.messages;\n\tif (config.transformContext) {\n\t\tmessages = await config.transformContext(messages, signal);\n\t\tassertValidToolTranscript(\n\t\t\tmessages,\n\t\t\t(summary) => `Refusing provider request: transformed context has an invalid tool transcript (${summary}).`,\n\t\t);\n\t}\n\n\t// Convert to LLM-compatible messages (AgentMessage[] → Message[])\n\tconst llmMessages = await config.convertToLlm(messages);\n\n\t// Build LLM context\n\tconst llmContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tsystemPromptCacheBoundary: context.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: context.systemPromptCacheBoundaryBypass,\n\t\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\treturn requestAssistantResponse(llmContext, requestConfig, {\n\t\tsignal,\n\t\temit,\n\t\tstreamFn,\n\t\tconsume: (response) => consumeAssistantStream(response, context, emit),\n\t});\n}\n\n/** Commit the final assistant message to the transcript and emit its lifecycle. */\nasync function commitFinalAssistantMessage(\n\tresponse: AssistantMessageEventStream,\n\tcontext: AgentContext,\n\taddedPartial: boolean,\n\temit: AgentEventSink,\n): Promise<AssistantMessage> {\n\tconst finalMessage = await response.result();\n\tif (addedPartial) {\n\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t} else {\n\t\tcontext.messages.push(finalMessage);\n\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t}\n\tawait emit({ type: \"message_end\", message: finalMessage });\n\treturn finalMessage;\n}\n\n/** Forward a partial assistant update into the transcript and event sink. */\nasync function forwardPartialUpdate(\n\tevent: Extract<AssistantMessageEvent, { partial: AssistantMessage }>,\n\tpartialMessage: AssistantMessage | null,\n\tcontext: AgentContext,\n\temit: AgentEventSink,\n): Promise<AssistantMessage | null> {\n\tif (!partialMessage) {\n\t\treturn partialMessage;\n\t}\n\tconst updated = event.partial;\n\tcontext.messages[context.messages.length - 1] = updated;\n\tawait emit({\n\t\ttype: \"message_update\",\n\t\tassistantMessageEvent: event,\n\t\tmessage: { ...updated },\n\t});\n\treturn updated;\n}\n\n/** Consume the assistant event stream, maintaining the partial message in the transcript. */\nasync function consumeAssistantStream(\n\tresponse: AssistantMessageEventStream,\n\tcontext: AgentContext,\n\temit: AgentEventSink,\n): Promise<AssistantMessage> {\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tfor await (const event of response) {\n\t\tswitch (event.type) {\n\t\t\tcase \"start\":\n\t\t\t\tpartialMessage = event.partial;\n\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\taddedPartial = true;\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\tbreak;\n\t\t\tcase \"done\":\n\t\t\tcase \"error\":\n\t\t\t\treturn commitFinalAssistantMessage(response, context, addedPartial, emit);\n\t\t\tdefault:\n\t\t\t\tpartialMessage = await forwardPartialUpdate(event, partialMessage, context, emit);\n\t\t}\n\t}\n\n\treturn commitFinalAssistantMessage(response, context, addedPartial, emit);\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tdagScheduleCache: DagScheduleCache,\n): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\t// dag-v2 is the safe default; waves-v1 remains an explicit rollback path.\n\tif ((config.toolScheduler ?? \"dag-v2\") === \"dag-v2\") {\n\t\treturn executeToolCallsDagLevels(\n\t\t\tcurrentContext,\n\t\t\tassistantMessage,\n\t\t\ttoolCalls,\n\t\t\tconfig,\n\t\t\tsignal,\n\t\t\temit,\n\t\t\tdagScheduleCache,\n\t\t);\n\t}\n\tconst hasSequentialToolCall = toolCalls.some(\n\t\t(tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === \"sequential\",\n\t);\n\tconst toolPolicies = new Map<string, \"sequential\" | \"parallel\">();\n\tfor (const tool of currentContext.tools ?? []) {\n\t\tif (tool.executionMode) {\n\t\t\ttoolPolicies.set(tool.name, tool.executionMode);\n\t\t}\n\t}\n\tconst batchWaves = applyConcurrencyCap(\n\t\tpartitionToolBatchWaves(\n\t\t\ttoolCalls.map((tc) => ({ name: tc.name, arguments: tc.arguments as Record<string, unknown> })),\n\t\t\t{\n\t\t\t\tcwd: config.cwd ?? process.cwd(),\n\t\t\t\ttoolPolicies,\n\t\t\t\tallowUnknownParallel: (toolName) => toolPolicies.get(toolName) === \"parallel\",\n\t\t\t},\n\t\t),\n\t\tconfig.maxToolConcurrency,\n\t);\n\tif (\n\t\tconfig.toolExecution === \"sequential\" ||\n\t\thasSequentialToolCall ||\n\t\tbatchWaves.every((wave) => wave.length === 1)\n\t) {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\tif (batchWaves.length === 1) {\n\t\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\treturn executeToolCallsInWaves(currentContext, assistantMessage, toolCalls, batchWaves, config, signal, emit);\n}\n\n/**\n * Execute a partitioned tool-call batch wave by wave: waves run in source\n * order, calls inside a multi-call wave run concurrently, and solo waves run\n * sequentially. Waves are contiguous index runs, so the returned tool result\n * messages keep the model's original tool-call order. An all-terminating wave\n * skips every later call with a synthesized \"skipped\" result and ends the\n * run, matching the dag-v2 level-termination contract.\n */\nasync function executeToolCallsInWaves(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\twaves: number[][],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst messages: ToolResultMessage[] = [];\n\tlet terminated = false;\n\tlet stopRun = false;\n\tfor (const wave of waves) {\n\t\tconst waveCalls = wave.map((index) => toolCalls[index]);\n\t\tconst executedWave =\n\t\t\twaveCalls.length === 1\n\t\t\t\t? await executeToolCallsSequential(currentContext, assistantMessage, waveCalls, config, signal, emit)\n\t\t\t\t: await executeToolCallsParallel(currentContext, assistantMessage, waveCalls, config, signal, emit);\n\t\tmessages.push(...executedWave.messages);\n\t\tif (executedWave.terminate || executedWave.stopRun) {\n\t\t\tterminated = true;\n\t\t\tstopRun = executedWave.stopRun ?? false;\n\t\t\tconst reason = stopRun\n\t\t\t\t? \"Skipped because the preceding tool wave timed out before settling\"\n\t\t\t\t: \"Skipped because the preceding tool wave requested termination\";\n\t\t\tconst skipped = await closeUnresolvedToolBatch(currentContext, toolCalls, messages, emit, {\n\t\t\t\treason,\n\t\t\t\tdisposition: \"skipped\",\n\t\t\t});\n\t\t\tmessages.push(...skipped);\n\t\t\tbreak;\n\t\t}\n\t\tif (signal?.aborted) break;\n\t}\n\treturn { messages, terminate: terminated, stopRun };\n}\n\n/**\n * Shared scheduling state for one DAG batch: the last known claim resolution\n * per source index, calls deferred because a post-hook claim change would\n * execute them before an unsettled earlier-source conflict, and calls that\n * have reached a terminal outcome. Mutated across candidate levels so the\n * final-claims contract is enforced globally, not per level.\n */\ninterface DagBatchScheduleState {\n\treadonly resolutions: Map<number, ToolClaimResolution>;\n\t/**\n\t * Calls deferred because their post-hook claims conflict with an unsettled\n\t * or running call. The stored resolution is only used to prove that conflict\n\t * — reusing it there skips an extension callback that cannot change the\n\t * conservative answer — while admission always re-resolves, because dynamic\n\t * resource identities may change across the wait.\n\t */\n\treadonly deferred: Map<number, DeferredCall<PreparedToolCall>>;\n\treadonly settled: Set<number>;\n}\n\n/**\n * Schedule planned calls into candidate DAG levels. Immediate plans fail\n * before any tool executes, so they carry no claims and fold into the first\n * level instead of degrading the whole batch to sequential singleton levels.\n * Unresolvable argument payloads stay in the schedule and fail closed into\n * exclusive barriers inside claim resolution.\n */\nasync function schedulePlannedDagLevels(\n\tplans: Array<PlannedToolCall | ImmediateToolCallOutcome>,\n\ttoolPolicies: ReadonlyMap<string, \"sequential\" | \"parallel\">,\n\tboundTools: AgentTool<any>[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\tdagScheduleCache: DagScheduleCache,\n): Promise<{\n\tlevels: number[][];\n\tresolutions: Map<number, ToolClaimResolution>;\n\t/** Conflicting predecessors per source index — the precedence graph the ready queue admits from. */\n\tdependencies: Map<number, number[]>;\n}> {\n\tconst schedulableSourceIndices: number[] = [];\n\tconst claimableCalls: ClaimableToolCall[] = [];\n\tconst immediateSourceIndices: number[] = [];\n\tplans.forEach((plan, sourceIndex) => {\n\t\tif (plan.kind === \"planned\") {\n\t\t\tschedulableSourceIndices.push(sourceIndex);\n\t\t\tclaimableCalls.push({ id: plan.toolCall.id, name: plan.toolCall.name, arguments: plan.args });\n\t\t} else {\n\t\t\timmediateSourceIndices.push(sourceIndex);\n\t\t}\n\t});\n\tconst scheduled = await scheduleDagLevelsMemoFromModule(\n\t\tclaimableCalls,\n\t\t{\n\t\t\tcwd: config.cwd ?? process.cwd(),\n\t\t\ttoolPolicies,\n\t\t\tregisteredTools: boundTools,\n\t\t\tstrictExtensionClaims: config.strictExtensionClaims,\n\t\t\tmaxConcurrency: config.maxToolConcurrency,\n\t\t\tresourceKeyResolver: config.resourceKeyResolver,\n\t\t},\n\t\tsignal,\n\t\tdagScheduleCache,\n\t);\n\tif (scheduled === null) {\n\t\treturn { levels: [], resolutions: new Map(), dependencies: new Map() };\n\t}\n\tconst resolutions = new Map<number, ToolClaimResolution>();\n\tscheduled.entries.forEach((entry, position) => {\n\t\tresolutions.set(schedulableSourceIndices[position], entry.resolution);\n\t});\n\t// Precedence graph in source-index space. Immediate plans carry no claims and\n\t// therefore no predecessors; they already fail before any tool executes.\n\tconst dependencies = new Map<number, number[]>();\n\tfor (const sourceIndex of immediateSourceIndices) dependencies.set(sourceIndex, []);\n\tassignDagDependencies(scheduled.entries).forEach((blockers, position) => {\n\t\tdependencies.set(\n\t\t\tschedulableSourceIndices[position],\n\t\t\tblockers.map((blocker) => schedulableSourceIndices[blocker]),\n\t\t);\n\t});\n\tconst levels = scheduled.levels.map((level) => level.map((position) => schedulableSourceIndices[position]));\n\tif (immediateSourceIndices.length === 0) {\n\t\treturn { levels, resolutions, dependencies };\n\t}\n\tif (levels.length === 0) {\n\t\treturn { levels: [[...immediateSourceIndices]], resolutions, dependencies };\n\t}\n\tlevels[0] = [...levels[0], ...immediateSourceIndices].sort((left, right) => left - right);\n\treturn { levels, resolutions, dependencies };\n}\n\n/**\n * Execute a tool-call batch using the dag-v2 scheduler.\n *\n * Schedule every planned call through the DAG: immediate plans fail before\n * any tool executes, so they carry no claims and fold into the first level\n * instead of degrading the whole batch to sequential singleton levels.\n * Unresolvable argument payloads stay in the schedule and fail closed into\n * exclusive barriers inside claim resolution. Each candidate level authorizes\n * calls, re-resolves claims from exact final args, and emits lifecycle starts\n * only when a final safe sublevel begins. Results remain globally buffered\n * and are emitted in source order.\n */\nasync function executeToolCallsDagLevels(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tdagScheduleCache: DagScheduleCache,\n): Promise<ExecutedToolCallBatch> {\n\tconst plans = toolCalls.map((toolCall) => planToolCall(currentContext, toolCall));\n\tconst boundTools = plans.flatMap((plan) => (plan.kind === \"planned\" ? [plan.tool] : []));\n\tconst toolPolicies = new Map<string, \"sequential\" | \"parallel\">();\n\tfor (const tool of boundTools) {\n\t\tconst mode = config.toolExecution ?? tool.executionMode;\n\t\tif (mode && !toolPolicies.has(tool.name)) toolPolicies.set(tool.name, mode);\n\t}\n\n\tconst schedule = await schedulePlannedDagLevels(plans, toolPolicies, boundTools, config, signal, dagScheduleCache);\n\tconst levels = schedule.levels;\n\tconst batchState: DagBatchScheduleState = {\n\t\tresolutions: schedule.resolutions,\n\t\tdeferred: new Map(),\n\t\tsettled: new Set(),\n\t};\n\n\tconst finalizedByIndex: Array<FinalizedToolCallOutcome | undefined> = new Array(toolCalls.length).fill(undefined);\n\tlet skippedReason: string | undefined;\n\tlet stoppedByUnsettledTimeout = false;\n\n\tconst frontier = await runDagFrontier(\n\t\tcurrentContext,\n\t\tassistantMessage,\n\t\tlevels.flat(),\n\t\tschedule.dependencies,\n\t\ttoolCalls,\n\t\tplans,\n\t\ttoolPolicies,\n\t\tconfig,\n\t\tsignal,\n\t\temit,\n\t\tbatchState,\n\t);\n\tfor (const outcome of frontier.outcomes) finalizedByIndex[outcome.sourceIndex] = outcome.finalized;\n\tif (frontier.stoppedByUnsettledTimeout) {\n\t\tskippedReason = \"Skipped because a preceding DAG tool timed out before its execution promise settled\";\n\t\tstoppedByUnsettledTimeout = true;\n\t} else if (frontier.terminated) {\n\t\tskippedReason = \"Skipped because the preceding DAG level requested termination\";\n\t}\n\n\tconst messages: ToolResultMessage[] = [];\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tfor (let index = 0; index < toolCalls.length; index++) {\n\t\tconst finalized = finalizedByIndex[index];\n\t\tif (finalized) {\n\t\t\tmessages.push(createToolResultMessage(finalized));\n\t\t\tfinalizedCalls.push(finalized);\n\t\t} else if (signal?.aborted) {\n\t\t\tconst toolCall = toolCalls[index];\n\t\t\tmessages.push(\n\t\t\t\tcreateImmutableSnapshot(createSyntheticToolResult(toolCall.id, toolCall.name, \"Operation aborted\")),\n\t\t\t);\n\t\t} else if (skippedReason !== undefined) {\n\t\t\tconst toolCall = toolCalls[index];\n\t\t\tmessages.push(\n\t\t\t\tcreateImmutableSnapshot(\n\t\t\t\t\tcreateSyntheticToolResult(toolCall.id, toolCall.name, skippedReason, Date.now(), \"skipped\"),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\t// Close the full source-ordered batch before result notification; calls not\n\t// reached by a candidate level receive no execution lifecycle.\n\tfor (const message of messages) {\n\t\tcurrentContext.messages.push(message);\n\t\ttry {\n\t\t\tawait emitToolResultMessage(message, emit);\n\t\t} finally {\n\t\t\tfinalizedCalls.find(({ toolCall }) => toolCall.id === message.toolCallId)?.commitTerminal?.();\n\t\t}\n\t}\n\n\treturn {\n\t\tmessages,\n\t\tterminate: skippedReason !== undefined || shouldTerminateToolBatch(finalizedCalls),\n\t\tstopRun: stoppedByUnsettledTimeout,\n\t};\n}\n\ntype DagLevelOutcome = { sourceIndex: number; finalized: FinalizedToolCallOutcome };\n\n// Re-resolve claims for a prepared call from its exact post-hook arguments.\n// Resolution failures fail closed as an immediate error rather than guessing\n// at a safe scope.\n//\n// The wait is bound to the run's abort signal exactly like the initial\n// scheduling pass (tool-dag-memo): an extension `resourceClaims()` that never\n// settles must not pin a cancelled run. Abandoning the wait does not stop the\n// callback — a plain Promise cannot be killed — but the aborted outcome settles\n// this call before any late value could admit it, and the frontier loop exits\n// on the same signal, so a late fulfilment or rejection lands in a finished\n// batch and admits nothing.\nasync function resolveFinalResolution(\n\tpreparation: PreparedToolCall,\n\ttoolPolicies: ReadonlyMap<string, \"sequential\" | \"parallel\">,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<ToolClaimResolution | ImmediateToolCallOutcome> {\n\t// awaitWithAbort short-circuits an already-aborted signal before invoking the callback.\n\tconst call = { id: preparation.toolCall.id, name: preparation.toolCall.name, arguments: preparation.args };\n\tconst options = {\n\t\tcwd: config.cwd ?? process.cwd(),\n\t\ttoolPolicies,\n\t\tregisteredTools: [preparation.tool],\n\t\tstrictExtensionClaims: config.strictExtensionClaims,\n\t\tresourceKeyResolver: config.resourceKeyResolver,\n\t};\n\ttry {\n\t\tconst bounded = await awaitWithAbort(() => resolveToolClaimsForCall(call, options), signal);\n\t\tif (bounded.kind === \"aborted\" || signal?.aborted) return immediateOutcome(\"aborted\", \"Operation aborted\");\n\t\treturn bounded.value;\n\t} catch (error) {\n\t\treturn immediateOutcome(\"failed\", error instanceof Error ? error.message : String(error));\n\t}\n}\n\n/**\n * Execute a planned batch as a dependency ready queue.\n *\n * States are `pending -> ready -> running -> settled`. A call is admitted once\n * every call it actually conflicts with has settled, rather than once its whole\n * barrier level has, so one slow unrelated call no longer delays independent\n * work queued behind it.\n *\n * Admission — authorize, re-resolve claims from exact post-hook arguments, and\n * enforce the final-claims contract — runs one call at a time in source order.\n * That keeps hook ordering and the conflict contract identical to the barrier\n * executor and leaves the shared batch state free of concurrent mutation; only\n * tool execution overlaps. Simultaneously-ready calls are admitted by source\n * index, so admission order stays deterministic even though completion order\n * is not.\n *\n * A call whose post-hook claims newly conflict with an earlier unsettled call\n * yields its turn and is retried after the next settle, which preserves the\n * source-order conflict contract without a separate drain pass.\n */\nasync function runDagFrontier(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\torder: readonly number[],\n\tdependencies: ReadonlyMap<number, number[]>,\n\ttoolCalls: AgentToolCall[],\n\tplans: Array<PlannedToolCall | ImmediateToolCallOutcome>,\n\ttoolPolicies: ReadonlyMap<string, \"sequential\" | \"parallel\">,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstate: DagBatchScheduleState,\n): Promise<{ outcomes: DagLevelOutcome[]; stoppedByUnsettledTimeout: boolean; terminated: boolean }> {\n\tconst outcomes: DagLevelOutcome[] = [];\n\tconst pending = [...order].sort((left, right) => left - right);\n\tconst running = new Map<number, Promise<DagLevelOutcome>>();\n\t// Mirrors applyConcurrencyCap: absent, non-finite, or non-positive is unbounded.\n\tconst cap =\n\t\ttypeof config.maxToolConcurrency === \"number\" &&\n\t\tNumber.isFinite(config.maxToolConcurrency) &&\n\t\tconfig.maxToolConcurrency > 0\n\t\t\t? Math.max(1, Math.floor(config.maxToolConcurrency))\n\t\t\t: Number.POSITIVE_INFINITY;\n\tlet stoppedByUnsettledTimeout = false;\n\tlet terminated = false;\n\n\t// Readiness bookkeeping: each pending call tracks how many of its\n\t// predecessors are still unsettled, and each settle decrements only its\n\t// successors — the per-settle cost is proportional to the out-degree of the\n\t// finished call, not to a full rescan of every pending dependency list.\n\tconst remainingPredecessors = new Map<number, number>();\n\tconst successors = new Map<number, number[]>();\n\tfor (const sourceIndex of pending) {\n\t\tconst blockers = dependencies.get(sourceIndex) ?? [];\n\t\tremainingPredecessors.set(sourceIndex, blockers.filter((blocker) => !state.settled.has(blocker)).length);\n\t\tfor (const blocker of blockers) {\n\t\t\tconst followers = successors.get(blocker);\n\t\t\tif (followers) followers.push(sourceIndex);\n\t\t\telse successors.set(blocker, [sourceIndex]);\n\t\t}\n\t}\n\n\tconst settle = async (outcome: DagLevelOutcome): Promise<void> => {\n\t\toutcomes.push(outcome);\n\t\tstate.settled.add(outcome.sourceIndex);\n\t\tfor (const follower of successors.get(outcome.sourceIndex) ?? []) {\n\t\t\tconst remaining = (remainingPredecessors.get(follower) ?? 0) - 1;\n\t\t\tremainingPredecessors.set(follower, Math.max(0, remaining));\n\t\t}\n\t\tif (await hasUnsettledTimeout([outcome.finalized])) stoppedByUnsettledTimeout = true;\n\t};\n\n\ttry {\n\t\twhile (!signal?.aborted && !stoppedByUnsettledTimeout && !terminated) {\n\t\t\t// Termination is a property of a settled group, not of one call:\n\t\t\t// shouldTerminateToolBatch requires every member to terminate. Evaluating it\n\t\t\t// only when nothing is in flight keeps the barrier executor's semantics,\n\t\t\t// where a call sharing a level with a non-terminating peer did not end the\n\t\t\t// batch. Judging a single outcome would terminate on the first terminating\n\t\t\t// call and strand its concurrent peers.\n\t\t\tif (running.size === 0 && shouldTerminateToolBatch(outcomes.map((outcome) => outcome.finalized))) {\n\t\t\t\tterminated = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlet admitted = false;\n\t\t\tfor (let position = 0; position < pending.length && running.size < cap; ) {\n\t\t\t\tif (signal?.aborted || stoppedByUnsettledTimeout) break;\n\t\t\t\tconst sourceIndex = pending[position];\n\t\t\t\tif ((remainingPredecessors.get(sourceIndex) ?? 0) > 0) {\n\t\t\t\t\tposition++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst runningSet = new Set(running.keys());\n\t\t\t\tconst cached = state.deferred.get(sourceIndex);\n\t\t\t\tlet preparation: PreparedToolCall;\n\t\t\t\tif (cached) {\n\t\t\t\t\t// A stale conflict answer only delays this call; admission below\n\t\t\t\t\t// re-resolves, so no tool executes from a cached scope.\n\t\t\t\t\tif (\n\t\t\t\t\t\tdeferredStillConflicts(sourceIndex, cached.resolution, state.settled, runningSet, state.resolutions)\n\t\t\t\t\t) {\n\t\t\t\t\t\tposition++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpreparation = cached.preparation;\n\t\t\t\t} else {\n\t\t\t\t\tconst plan = plans[sourceIndex];\n\t\t\t\t\tconst preparedOutcome =\n\t\t\t\t\t\tplan.kind === \"immediate\"\n\t\t\t\t\t\t\t? plan\n\t\t\t\t\t\t\t: await authorizePlannedToolCall(currentContext, assistantMessage, plan, config, signal);\n\t\t\t\t\tif (preparedOutcome.kind === \"immediate\") {\n\t\t\t\t\t\tpending.splice(position, 1);\n\t\t\t\t\t\tadmitted = true;\n\t\t\t\t\t\tawait settle({\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tfinalized: {\n\t\t\t\t\t\t\t\ttoolCall: toolCalls[sourceIndex],\n\t\t\t\t\t\t\t\tresult: preparedOutcome.result,\n\t\t\t\t\t\t\t\tisError: preparedOutcome.isError,\n\t\t\t\t\t\t\t\tenvelope: preparedOutcome.envelope,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpreparation = preparedOutcome;\n\t\t\t\t}\n\t\t\t\tconst resolved = await resolveFinalResolution(preparation, toolPolicies, config, signal);\n\t\t\t\tif (resolved.kind === \"immediate\") {\n\t\t\t\t\tstate.deferred.delete(sourceIndex);\n\t\t\t\t\tpending.splice(position, 1);\n\t\t\t\t\tadmitted = true;\n\t\t\t\t\tawait settle({\n\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\tfinalized: {\n\t\t\t\t\t\t\ttoolCall: preparation.toolCall,\n\t\t\t\t\t\t\tresult: resolved.result,\n\t\t\t\t\t\t\tisError: resolved.isError,\n\t\t\t\t\t\t\tenvelope: resolved.envelope,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.resolutions.set(sourceIndex, resolved);\n\t\t\t\tif (deferredStillConflicts(sourceIndex, resolved, state.settled, runningSet, state.resolutions)) {\n\t\t\t\t\t// Defer without losing the prepared call: a later scan retries\n\t\t\t\t\t// admission from this cache instead of re-invoking authorization.\n\t\t\t\t\tstate.deferred.set(sourceIndex, { preparation, resolution: resolved });\n\t\t\t\t\tposition++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.deferred.delete(sourceIndex);\n\t\t\t\tpending.splice(position, 1);\n\t\t\t\tadmitted = true;\n\t\t\t\tawait emitToolExecutionStart(preparation, emit);\n\t\t\t\trunning.set(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\t(async (): Promise<DagLevelOutcome> => {\n\t\t\t\t\t\tconst executed = await executePreparedToolCall(preparation, config, signal, emit);\n\t\t\t\t\t\tconst finalized = await finalizeExecutedToolCall({\n\t\t\t\t\t\t\tcurrentContext,\n\t\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\t\tprepared: preparation,\n\t\t\t\t\t\t\texecuted,\n\t\t\t\t\t\t\tafterToolCall: config.afterToolCall,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait emitToolExecutionEnd(finalized, emit);\n\t\t\t\t\t\treturn { sourceIndex, finalized };\n\t\t\t\t\t})(),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (running.size === 0) {\n\t\t\t\t// Nothing is in flight: either every call settled, or the remainder is\n\t\t\t\t// blocked with nothing left that could unblock it. A pending call that\n\t\t\t\t// can never become ready still gets an explicit terminal outcome rather\n\t\t\t\t// than vanishing from the batch.\n\t\t\t\tif (!admitted) {\n\t\t\t\t\tfor (const sourceIndex of pending.splice(0)) {\n\t\t\t\t\t\tawait settle({\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tfinalized: {\n\t\t\t\t\t\t\t\ttoolCall: toolCalls[sourceIndex],\n\t\t\t\t\t\t\t\tresult: createErrorToolResult(\n\t\t\t\t\t\t\t\t\t\"DAG dependency deadlock: call could not become ready and nothing is running to unblock it\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\tenvelope: createToolResultEnvelope({\n\t\t\t\t\t\t\t\t\tdisposition: \"failed\",\n\t\t\t\t\t\t\t\t\tsynthetic: true,\n\t\t\t\t\t\t\t\t\texecutionStarted: false,\n\t\t\t\t\t\t\t\t\treason: \"DAG dependency deadlock\",\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst finished = await Promise.race([...running.values()]);\n\t\t\trunning.delete(finished.sourceIndex);\n\t\t\tawait settle(finished);\n\t\t}\n\t} finally {\n\t\t// Join work already in flight: cancellation, termination, and propagation\n\t\t// of preparation/event errors all preserve ownership of started\n\t\t// executions rather than abandoning them mid-flight.\n\t\twhile (running.size > 0) {\n\t\t\tconst entries = [...running.entries()];\n\t\t\tconst drained = await Promise.allSettled(entries.map(([, task]) => task));\n\t\t\tfor (const [index, drainedResult] of drained.entries()) {\n\t\t\t\trunning.delete(entries[index][0]);\n\t\t\t\tif (drainedResult.status === \"fulfilled\") await settle(drainedResult.value);\n\t\t\t}\n\t\t}\n\t}\n\treturn { outcomes, stoppedByUnsettledTimeout, terminated };\n}\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\tterminate: boolean;\n\t/** End the run without another provider request after an unsettled timeout. */\n\tstopRun?: boolean;\n};\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tconst messages: ToolResultMessage[] = [];\n\n\tfor (const toolCall of toolCalls) {\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tlet finalized: FinalizedToolCallOutcome;\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tfinalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\tenvelope: preparation.envelope,\n\t\t\t};\n\t\t} else {\n\t\t\tawait emitToolExecutionStart(preparation, emit);\n\t\t\tconst executed = await executePreparedToolCall(preparation, config, signal, emit);\n\t\t\tfinalized = await finalizeExecutedToolCall({\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tprepared: preparation,\n\t\t\t\texecuted,\n\t\t\t\tafterToolCall: config.afterToolCall,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t}\n\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tcurrentContext.messages.push(toolResultMessage);\n\t\tif (preparation.kind === \"prepared\") await emitToolExecutionEnd(finalized, emit);\n\t\ttry {\n\t\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\t} finally {\n\t\t\tfinalized.commitTerminal?.();\n\t\t}\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(toolResultMessage);\n\n\t\tif (await hasUnsettledTimeout([finalized])) {\n\t\t\tconst skipped = await closeUnresolvedToolBatch(currentContext, toolCalls, messages, emit, {\n\t\t\t\treason: \"Skipped because a preceding tool timed out before settling\",\n\t\t\t\tdisposition: \"skipped\",\n\t\t\t});\n\t\t\tmessages.push(...skipped);\n\t\t\treturn { messages, terminate: true, stopRun: true };\n\t\t}\n\t\tif (signal?.aborted) break;\n\t}\n\n\treturn {\n\t\tmessages,\n\t\tterminate: shouldTerminateToolBatch(finalizedCalls),\n\t};\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallEntry[] = [];\n\n\tfor (const toolCall of toolCalls) {\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tconst finalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\tenvelope: preparation.envelope,\n\t\t\t} satisfies FinalizedToolCallOutcome;\n\t\t\tfinalizedCalls.push(finalized);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tfinalizedCalls.push(async () => {\n\t\t\tawait emitToolExecutionStart(preparation, emit);\n\t\t\tconst executed = await executePreparedToolCall(preparation, config, signal, emit);\n\t\t\tconst finalized = await finalizeExecutedToolCall({\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tprepared: preparation,\n\t\t\t\texecuted,\n\t\t\t\tafterToolCall: config.afterToolCall,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tawait emitToolExecutionEnd(finalized, emit);\n\t\t\treturn finalized;\n\t\t});\n\t\tif (signal?.aborted) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tconst orderedFinalizedCalls = await Promise.all(\n\t\tfinalizedCalls.map((entry) => (typeof entry === \"function\" ? entry() : Promise.resolve(entry))),\n\t);\n\tconst messages: ToolResultMessage[] = [];\n\tfor (const finalized of orderedFinalizedCalls) {\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tcurrentContext.messages.push(toolResultMessage);\n\t\ttry {\n\t\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\t} finally {\n\t\t\tfinalized.commitTerminal?.();\n\t\t}\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\tconst stopRun = await hasUnsettledTimeout(orderedFinalizedCalls);\n\treturn { messages, terminate: stopRun || shouldTerminateToolBatch(orderedFinalizedCalls), stopRun };\n}\n\ntype PlannedToolCall = {\n\tkind: \"planned\";\n\ttoolCall: AgentToolCall;\n\tpreparedToolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\t/** Immutable scheduler/executor arguments fixed after the authorization hook. */\n\targs: unknown;\n\t/** Separate immutable public-event snapshot. */\n\teventArgs: unknown;\n\t/** Effective per-call timeout in ms resolved by precedence; 0 disables it. */\n\ttimeoutMs: number;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\tenvelope: ToolResultEnvelope;\n};\n\ntype FinalizedToolCallEntry = FinalizedToolCallOutcome | (() => Promise<FinalizedToolCallOutcome>);\n\nfunction shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {\n\treturn finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);\n}\n\nfunction prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {\n\tif (!tool.prepareArguments) {\n\t\treturn toolCall;\n\t}\n\tconst preparedArguments = tool.prepareArguments(toolCall.arguments);\n\tif (preparedArguments === toolCall.arguments) {\n\t\treturn toolCall;\n\t}\n\treturn {\n\t\t...toolCall,\n\t\targuments: preparedArguments as Record<string, any>,\n\t};\n}\n\nfunction immediateOutcome(disposition: ToolCallDisposition, reason: string): ImmediateToolCallOutcome {\n\treturn {\n\t\tkind: \"immediate\",\n\t\tresult: createErrorToolResult(reason),\n\t\tisError: true,\n\t\tenvelope: createToolResultEnvelope({ disposition, synthetic: true, executionStarted: false, reason }),\n\t};\n}\n\nfunction planToolCall(\n\tcurrentContext: AgentContext,\n\tuntrustedToolCall: AgentToolCall,\n): PlannedToolCall | ImmediateToolCallOutcome {\n\ttry {\n\t\tconst toolCall = createImmutableJsonSnapshot(untrustedToolCall);\n\t\tif (toolCall.id.length === 0 || toolCall.name.length === 0) throw new TypeError(\"Invalid empty tool identity\");\n\t\tconst candidate = currentContext.tools?.find((tool) => tool.name === toolCall.name);\n\t\tif (!candidate) return immediateOutcome(\"failed\", `Tool ${toolCall.name} not found`);\n\t\tconst tool = bindToolIdentity(candidate, toolCall.name);\n\t\tconst prepared = prepareToolCallArguments(tool, toolCall);\n\t\tconst args = createImmutableJsonSnapshot(prepared.arguments);\n\t\tconst preparedToolCall = createImmutableSnapshot({ ...toolCall, arguments: args });\n\t\treturn { kind: \"planned\", toolCall, preparedToolCall, tool, args };\n\t} catch (error) {\n\t\treturn immediateOutcome(\"failed\", error instanceof Error ? error.message : String(error));\n\t}\n}\n\nasync function authorizePlannedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tplan: PlannedToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\ttry {\n\t\tconst hookArgs = parseJsonValue(validateToolArguments(plan.tool, plan.preparedToolCall));\n\t\tconst beforeToolCall = config.beforeToolCall;\n\t\tif (beforeToolCall) {\n\t\t\tconst bounded = await awaitWithAbort(\n\t\t\t\t() =>\n\t\t\t\t\tbeforeToolCall(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tassistantMessage: createImmutableSnapshot(assistantMessage),\n\t\t\t\t\t\t\ttoolCall: plan.toolCall,\n\t\t\t\t\t\t\targs: hookArgs,\n\t\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (bounded.kind === \"aborted\" || signal?.aborted) return immediateOutcome(\"aborted\", \"Operation aborted\");\n\t\t\tif (bounded.value?.block) {\n\t\t\t\treturn immediateOutcome(\"blocked\", bounded.value.reason || \"Tool execution was blocked\");\n\t\t\t}\n\t\t}\n\t\tif (signal?.aborted) return immediateOutcome(\"aborted\", \"Operation aborted\");\n\t\tconst args = createImmutableJsonSnapshot(hookArgs);\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall: plan.toolCall,\n\t\t\ttool: plan.tool,\n\t\t\targs,\n\t\t\teventArgs: createImmutableSnapshot(args),\n\t\t\ttimeoutMs: resolveToolTimeoutMs(plan.tool, config, plan.toolCall.name),\n\t\t};\n\t} catch (error) {\n\t\treturn immediateOutcome(\"failed\", error instanceof Error ? error.message : String(error));\n\t}\n}\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst plan = planToolCall(currentContext, toolCall);\n\treturn plan.kind === \"immediate\"\n\t\t? plan\n\t\t: authorizePlannedToolCall(currentContext, assistantMessage, plan, config, signal);\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tlet realPromiseSettled = false;\n\tlet commitTerminal = (): void => {};\n\tconst terminalCommitted = new Promise<void>((resolve) => {\n\t\tcommitTerminal = resolve;\n\t});\n\tconst executed = await runToolCallWithTimeout({\n\t\ttoolCallId: prepared.toolCall.id,\n\t\ttoolName: prepared.toolCall.name,\n\t\ttimeoutMs: prepared.timeoutMs,\n\t\tlateSettlement: config.toolExecutionPolicy?.lateSettlement,\n\t\tsignal,\n\t\tstart: async (childSignal, onUpdate) => {\n\t\t\ttry {\n\t\t\t\treturn await prepared.tool.execute(prepared.toolCall.id, prepared.args as never, childSignal, onUpdate);\n\t\t\t} finally {\n\t\t\t\trealPromiseSettled = true;\n\t\t\t}\n\t\t},\n\t\temitUpdate: (partialResult) =>\n\t\t\temit({\n\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\targs: prepared.eventArgs,\n\t\t\t\tpartialResult: createImmutableSnapshot(partialResult),\n\t\t\t}),\n\t\temitLateSettlement: async (settlement) => {\n\t\t\tawait terminalCommitted;\n\t\t\tawait emit({\n\t\t\t\ttype: \"tool_execution_late_settlement\",\n\t\t\t\ttoolCallId: settlement.toolCallId,\n\t\t\t\ttoolName: settlement.toolName,\n\t\t\t\tdisposition: settlement.disposition,\n\t\t\t\toutcome: settlement.outcome,\n\t\t\t});\n\t\t},\n\t\ttoErrorResult: (error) => createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t});\n\treturn { ...executed, isRealPromiseSettled: () => realPromiseSettled, commitTerminal };\n}\n\nasync function emitToolExecutionStart(prepared: PreparedToolCall, emit: AgentEventSink): Promise<void> {\n\tawait emit({\n\t\ttype: \"tool_execution_start\",\n\t\ttoolCallId: prepared.toolCall.id,\n\t\ttoolName: prepared.toolCall.name,\n\t\targs: prepared.eventArgs,\n\t});\n}\n\nasync function emitToolExecutionEnd(finalized: FinalizedToolCallOutcome, emit: AgentEventSink): Promise<void> {\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tresult: createImmutableSnapshot(finalized.result),\n\t\tisError: finalized.isError,\n\t});\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn createImmutableSnapshot({\n\t\trole: \"toolResult\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tcontent: finalized.result.content,\n\t\tdetails: stampToolResultEnvelope(finalized.result.details, finalized.envelope),\n\t\tisError: finalized.isError,\n\t\ttimestamp: Date.now(),\n\t});\n}\n\nasync function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n}\n\n/** Commit and notify one synthetic terminal for each unresolved, unstarted call. */\nasync function closeUnresolvedToolBatch(\n\tcurrentContext: AgentContext,\n\ttoolCalls: AgentToolCall[],\n\texistingResults: ToolResultMessage[],\n\temit: AgentEventSink,\n\tclosure?: { reason: string; disposition: \"aborted\" | \"skipped\" },\n): Promise<ToolResultMessage[]> {\n\tconst resolvedIds = new Set(existingResults.map((result) => result.toolCallId));\n\tconst synthesized: ToolResultMessage[] = [];\n\tfor (const toolCall of toolCalls) {\n\t\tif (resolvedIds.has(toolCall.id)) continue;\n\t\tconst result = createImmutableSnapshot(\n\t\t\tcreateSyntheticToolResult(\n\t\t\t\ttoolCall.id,\n\t\t\t\ttoolCall.name,\n\t\t\t\tclosure?.reason ?? \"Operation aborted\",\n\t\t\t\tDate.now(),\n\t\t\t\tclosure?.disposition ?? \"aborted\",\n\t\t\t),\n\t\t);\n\t\tcurrentContext.messages.push(result);\n\t\tawait emit({ type: \"message_start\", message: result });\n\t\tawait emit({ type: \"message_end\", message: result });\n\t\tsynthesized.push(result);\n\t\t// Guard against a duplicated call id within the same assistant message.\n\t\tresolvedIds.add(toolCall.id);\n\t}\n\treturn synthesized;\n}\n"]}
1
+ {"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAKN,WAAW,EACX,KAAK,KAAK,EACV,KAAK,iBAAiB,EAEtB,MAAM,QAAQ,CAAC;AAKhB,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AA2BhG,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,eAAe,EAEpB,KAAK,YAAY,EAKjB,KAAK,QAAQ,EAGb,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAWzE,MAAM,WAAW,sBAAsB;IACtC,kFAAkF;IAClF,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,4EAA4E;IAC5E,cAAc,EAAE,YAAY,GAAG,SAAS,CAAC;IACzC,0EAA0E;IAC1E,cAAc,EAAE,iBAAiB,EAAE,CAAC;CACpC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACrC,iBAAiB,EAAE,SAAS,YAAY,EAAE,EAC1C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,OAAO,GACd,sBAAsB,CAiCxB;AAqCD;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CA0BzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAoCzC;AAED,wBAAsB,YAAY,CACjC,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAezB;AAED,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAgBzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"omk-ai\";\nimport { bindToolIdentity } from \"./builtin-tool-resource-claims.ts\";\nimport { partitionToolBatchWaves } from \"./parallel-tool-batch.ts\";\nimport { pinProviderConfig, requestAssistantResponse } from \"./provider-request.ts\";\n\nexport { getVisionRouteModel, isVisionRouteModel, VISION_ROUTE_MODEL } from \"./vision-route.ts\";\n\nimport { type DeferredCall, deferredStillConflicts } from \"./tool-dag-deferred.ts\";\nimport { type DagFrontierScheduleCache, resolveDagFrontierMemo } from \"./tool-dag-memo.ts\";\nimport { finishDagTasks, type OwnedTaskResult, startDagTask } from \"./tool-dag-owned-task.ts\";\nimport { reduceDagDependencies } from \"./tool-dag-reduce.ts\";\nimport { applyConcurrencyCap, assignDagDependencies } from \"./tool-dag-scheduler.ts\";\nimport {\n\tawaitWithAbort,\n\tcreateErrorToolResult,\n\tcreateImmutableJsonSnapshot,\n\tcreateImmutableSnapshot,\n\ttype ExecutedToolCallOutcome,\n\ttype FinalizedToolCallOutcome,\n\tfinalizeExecutedToolCall,\n\tparseJsonValue,\n\tstampToolResultEnvelope,\n} from \"./tool-execution-boundary.ts\";\nimport { type ClaimableToolCall, resolveToolClaimsForCall, type ToolClaimResolution } from \"./tool-resource-claims.ts\";\nimport { indexFinalizedToolCalls } from \"./tool-terminal-index.ts\";\nimport { resolveToolTimeoutMs, runToolCallWithTimeout } from \"./tool-timeout.ts\";\nimport { hasUnsettledTimeout } from \"./tool-timeout-settlement.ts\";\nimport {\n\tcreateSyntheticToolResult,\n\tinspectTranscriptIntegrity,\n\trepairTranscriptIntegrity,\n} from \"./tool-transcript-integrity.ts\";\nimport {\n\ttype AgentContext,\n\ttype AgentEvent,\n\ttype AgentLoopConfig,\n\ttype AgentLoopTurnUpdate,\n\ttype AgentMessage,\n\ttype AgentTool,\n\ttype AgentToolCall,\n\ttype AgentToolResult,\n\tcreateToolResultEnvelope,\n\ttype StreamFn,\n\ttype ToolCallDisposition,\n\ttype ToolResultEnvelope,\n} from \"./types.ts\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nexport interface FailureTerminationPlan {\n\t/** Messages to publish as the run result (closure results + optional failure). */\n\tmessages: AgentMessage[];\n\t/** Synthetic assistant failure message, or `undefined` when fail-closed. */\n\tfailureMessage: AgentMessage | undefined;\n\t/** Synthetic tool results used to close an open turn, in source order. */\n\tclosureResults: ToolResultMessage[];\n}\n\n/**\n * Decide how to terminate a run after the underlying loop rejected.\n *\n * A synthetic assistant failure may only be appended on top of a transcript\n * whose tool turns are all closed. When `completedMessages` ends with an open\n * tool turn, a safe missing-only closure (synthetic results for the unambiguous\n * missing tail calls) is appended first so the failure assistant never creates\n * an `assistant(tool calls) -> assistant(failure)` interleaving.\n *\n * If the transcript is ambiguous (duplicate/orphan/interleave, or a\n * mid-transcript gap) it is never auto-repaired: the plan returns no failure\n * message so the caller ends the stream without fabricating a turn over\n * corruption. Pure apart from `Date.now()` on the failure message.\n */\nexport function planFailureTermination(\n\tcompletedMessages: readonly AgentMessage[],\n\tmodel: Model<any>,\n\terror: unknown,\n\taborted: boolean,\n): FailureTerminationPlan {\n\tconst messages = [...completedMessages];\n\tconst closureResults: ToolResultMessage[] = [];\n\n\tif (!inspectTranscriptIntegrity(messages).ok) {\n\t\ttry {\n\t\t\tconst repaired = repairTranscriptIntegrity(messages, \"Tool result missing; run terminated by error\");\n\t\t\t// repairTranscriptIntegrity appends synthetic results only for\n\t\t\t// unambiguous missing tail calls; anything ambiguous throws above.\n\t\t\tfor (let i = messages.length; i < repaired.length; i++) {\n\t\t\t\tconst result = createImmutableSnapshot(repaired[i] as ToolResultMessage);\n\t\t\t\tclosureResults.push(result);\n\t\t\t\tmessages.push(result);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ambiguous transcript: never auto-repair. Fail closed without a\n\t\t\t// synthetic assistant turn over a corrupt transcript.\n\t\t\treturn { messages, failureMessage: undefined, closureResults: [] };\n\t\t}\n\t}\n\n\tconst failureMessage: AgentMessage = createImmutableSnapshot({\n\t\trole: \"assistant\",\n\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: EMPTY_USAGE,\n\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t});\n\treturn { messages: [...messages, failureMessage], failureMessage, closureResults };\n}\n\n/**\n * Terminate the public event stream after the underlying loop rejected.\n *\n * Uses {@link planFailureTermination} so the disposition of any unresolved tool\n * calls matches transcript repair exactly: an unambiguous open turn is closed\n * with synthetic results before a coherent\n * message_start/message_end/turn_end/agent_end sequence for the failure\n * assistant, and an ambiguous transcript fails closed (agent_end only, no\n * fabricated assistant). The stream always settles for `for await` consumers\n * and `stream.result()`.\n */\nfunction endStreamWithFailure(\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tconfig: AgentLoopConfig,\n\tcompletedMessages: AgentMessage[],\n\terror: unknown,\n\tsignal?: AbortSignal,\n): void {\n\tconst plan = planFailureTermination(completedMessages, config.model, error, signal?.aborted ?? false);\n\n\tfor (const result of plan.closureResults) {\n\t\tstream.push({ type: \"message_start\", message: result });\n\t\tstream.push({ type: \"message_end\", message: result });\n\t}\n\n\tif (plan.failureMessage) {\n\t\tstream.push({ type: \"message_start\", message: plan.failureMessage });\n\t\tstream.push({ type: \"message_end\", message: plan.failureMessage });\n\t\tstream.push({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t}\n\n\tstream.push({ type: \"agent_end\", messages: plan.messages });\n\tstream.end(plan.messages);\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\tconst completedMessages: AgentMessage[] = [];\n\n\tvoid runAgentLoop(\n\t\tprompts,\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tif (event.type === \"message_end\") {\n\t\t\t\tcompletedMessages.push(event.message);\n\t\t\t}\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then(\n\t\t(messages) => {\n\t\t\tstream.end(messages);\n\t\t},\n\t\t(error: unknown) => {\n\t\t\tendStreamWithFailure(stream, config, completedMessages, error, signal);\n\t\t},\n\t);\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\t// Guard: the last message must be one the provider can build on. A plain\n\t// text/thinking assistant turn is acceptable (convertToLlm may merge or the\n\t// provider supports assistant pre-fill); only an assistant turn that still\n\t// carries unresolved tool calls is a hard error because the provider will\n\t// reject the request without matching tool results.\n\tassertContinuableTranscript(context.messages);\n\n\tconst stream = createAgentStream();\n\tconst completedMessages: AgentMessage[] = [];\n\n\tvoid runAgentLoopContinue(\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tif (event.type === \"message_end\") {\n\t\t\t\tcompletedMessages.push(event.message);\n\t\t\t}\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then(\n\t\t(messages) => {\n\t\t\tstream.end(messages);\n\t\t},\n\t\t(error: unknown) => {\n\t\t\tendStreamWithFailure(stream, config, completedMessages, error, signal);\n\t\t},\n\t);\n\n\treturn stream;\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = [...prompts];\n\tconst currentContext: AgentContext = { ...context, messages: [...context.messages, ...prompts] };\n\tconst publish: AgentEventSink = (event) => emit(createImmutableSnapshot(event));\n\tconst pinnedConfig = await pinProviderConfig(config, publish);\n\n\tawait publish({ type: \"agent_start\" });\n\tawait publish({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait publish({ type: \"message_start\", message: prompt });\n\t\tawait publish({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, pinnedConfig, signal, publish, streamFn);\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tassertContinuableTranscript(context.messages);\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context };\n\tconst publish: AgentEventSink = (event) => emit(createImmutableSnapshot(event));\n\tconst pinnedConfig = await pinProviderConfig(config, publish);\n\n\tawait publish({ type: \"agent_start\" });\n\tawait publish({ type: \"turn_start\" });\n\tawait runLoop(currentContext, newMessages, pinnedConfig, signal, publish, streamFn);\n\treturn newMessages;\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\n/**\n * Validate the full transcript before continuing. Replaces the earlier\n * last-message-only tail check: `assistant(A,B) -> result(A)` and any\n * duplicate/orphan/interleaved structure now fail before the first provider\n * request, not only a trailing assistant message that still carries tool calls.\n *\n * A trailing assistant turn with no tool calls (plain text/thinking) remains\n * continuable, so compaction, session resume, and explicit retries keep working.\n */\nfunction assertContinuableTranscript(messages: AgentMessage[]): void {\n\tconst report = inspectTranscriptIntegrity(messages);\n\tif (report.ok) {\n\t\treturn;\n\t}\n\tconst last = messages[messages.length - 1];\n\tif (last !== undefined && last.role === \"assistant\" && last.content.some((block) => block.type === \"toolCall\")) {\n\t\tthrow new Error(\n\t\t\t\"Cannot continue: the last assistant message has pending tool calls without matching results. \" +\n\t\t\t\t\"Add tool results or a new user message before continuing.\",\n\t\t);\n\t}\n\tconst summary = report.issues.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\tthrow new Error(\n\t\t`Cannot continue: invalid tool transcript (${summary}). ` +\n\t\t\t\"Append terminal tool results or repair the transcript before continuing.\",\n\t);\n}\n\n/** Throw when the tool transcript could not be accepted by a provider. */\nfunction assertValidToolTranscript(messages: AgentMessage[], describe: (summary: string) => string): void {\n\tconst integrityReport = inspectTranscriptIntegrity(messages);\n\tif (integrityReport.ok) {\n\t\treturn;\n\t}\n\tconst summary = integrityReport.issues.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\tthrow new Error(describe(summary));\n}\n\n/** Inject queued steering messages into the transcript before the next assistant turn. */\nasync function injectPendingMessages(\n\tpendingMessages: AgentMessage[],\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\temit: AgentEventSink,\n): Promise<void> {\n\tfor (const message of pendingMessages) {\n\t\tawait emit({ type: \"message_start\", message });\n\t\tawait emit({ type: \"message_end\", message });\n\t\tcurrentContext.messages.push(message);\n\t\tnewMessages.push(message);\n\t}\n}\n\n/** Close every emitted tool call with a synthetic terminal result and end the run. */\nasync function closeRunOnTerminalStop(\n\tcurrentContext: AgentContext,\n\tmessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tnewMessages: AgentMessage[],\n\temit: AgentEventSink,\n): Promise<void> {\n\tconst toolResults: ToolResultMessage[] = [];\n\tconst reason =\n\t\tmessage.stopReason === \"aborted\"\n\t\t\t? \"Operation aborted\"\n\t\t\t: \"Skipped because the provider terminated before tool execution\";\n\tconst disposition = message.stopReason === \"aborted\" ? \"aborted\" : \"skipped\";\n\tfor (const toolCall of toolCalls) {\n\t\tconst result = createImmutableSnapshot(\n\t\t\tcreateSyntheticToolResult(toolCall.id, toolCall.name, reason, Date.now(), disposition),\n\t\t);\n\t\tcurrentContext.messages.push(result);\n\t\tnewMessages.push(result);\n\t\ttoolResults.push(result);\n\t\tawait emitToolResultMessage(result, emit);\n\t}\n\tawait emit({ type: \"turn_end\", message, toolResults });\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\n/** Drain an optional message queue, normalizing absent queues to an empty list. */\nasync function drainMessageQueue(queue?: () => Promise<AgentMessage[]>): Promise<AgentMessage[]> {\n\treturn queue === undefined ? [] : await queue();\n}\n\n/** Validate an optional per-run provider-turn budget. */\nfunction validateMaxTurns(maxTurns: number | undefined): number | undefined {\n\tif (maxTurns === undefined) return undefined;\n\tif (!Number.isSafeInteger(maxTurns) || maxTurns < 1) {\n\t\tthrow new RangeError(\"maxTurns must be a positive safe integer\");\n\t}\n\treturn maxTurns;\n}\n\n/** Reject ambiguous provider-emitted tool transcripts before any tool executes. */\nfunction assertEmittedTranscriptUnambiguous(messages: AgentMessage[]): void {\n\tconst emittedAmbiguities = inspectTranscriptIntegrity(messages).issues.filter(\n\t\t(issue) => issue.kind !== \"missing_result\",\n\t);\n\tif (emittedAmbiguities.length === 0) {\n\t\treturn;\n\t}\n\tconst summary = emittedAmbiguities.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\tthrow new Error(`Refusing tool execution: invalid emitted tool transcript (${summary}).`);\n}\n\ntype ToolBatchTurnOutcome =\n\t| { kind: \"continue\"; toolResults: ToolResultMessage[]; hasMoreToolCalls: boolean; stopRun: boolean }\n\t| { kind: \"ended\" };\n\n/** Execute one assistant batch, closing unresolved calls and ending the run on abort. */\nasync function runToolBatchForTurn(\n\tcurrentContext: AgentContext,\n\tmessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tnewMessages: AgentMessage[],\n\tdagScheduleCache: DagFrontierScheduleCache,\n): Promise<ToolBatchTurnOutcome> {\n\tconst executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit, dagScheduleCache);\n\tconst toolResults = [...executedToolBatch.messages];\n\tif (signal?.aborted) {\n\t\t// Close only unresolved calls, preserving finalized results, then stop\n\t\t// before hooks, queues, or another provider request.\n\t\tconst synthesized = await closeUnresolvedToolBatch(currentContext, toolCalls, toolResults, emit);\n\t\ttoolResults.push(...synthesized);\n\t\tfor (const result of toolResults) newMessages.push(result);\n\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\treturn { kind: \"ended\" };\n\t}\n\tfor (const result of toolResults) newMessages.push(result);\n\treturn {\n\t\tkind: \"continue\",\n\t\ttoolResults,\n\t\thasMoreToolCalls: !executedToolBatch.terminate,\n\t\tstopRun: executedToolBatch.stopRun ?? false,\n\t};\n}\n\n/** Merge a prepareNextTurn snapshot into the active context and loop config. */\nfunction applyNextTurnSnapshot(\n\tcurrentContext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsnapshot: AgentLoopTurnUpdate,\n): { context: AgentContext; config: AgentLoopConfig } {\n\treturn {\n\t\tcontext: snapshot.context ?? currentContext,\n\t\tconfig: {\n\t\t\t...config,\n\t\t\tmodel: snapshot.model ?? config.model,\n\t\t\treasoning:\n\t\t\t\tsnapshot.thinkingLevel === undefined\n\t\t\t\t\t? config.reasoning\n\t\t\t\t\t: snapshot.thinkingLevel === \"off\"\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: snapshot.thinkingLevel,\n\t\t},\n\t};\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tinitialContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tinitialConfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tlet currentContext = initialContext;\n\tlet config = initialConfig;\n\tlet firstTurn = true;\n\tlet turnsStarted = 0;\n\tconst maxTurns = validateMaxTurns(initialConfig.maxTurns);\n\tconst dagScheduleCache: DagFrontierScheduleCache = new Map();\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages = await drainMessageQueue(config.getSteeringMessages);\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t}\n\t\t\tfirstTurn = false;\n\n\t\t\t// Process pending messages (inject before next assistant response)\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tawait injectPendingMessages(pendingMessages, currentContext, newMessages, emit);\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Stream assistant response\n\t\t\tturnsStarted++;\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tnewMessages.push(message);\n\n\t\t\t// Provider output is untrusted protocol input. Reject duplicate call IDs\n\t\t\t// and every other ambiguous turn before any tool can execute.\n\t\t\tassertEmittedTranscriptUnambiguous(currentContext.messages);\n\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait closeRunOnTerminalStop(currentContext, message, toolCalls, newMessages, emit);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tlet stopAfterToolBatch = false;\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tconst batchOutcome = await runToolBatchForTurn(\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolCalls,\n\t\t\t\t\tconfig,\n\t\t\t\t\tsignal,\n\t\t\t\t\temit,\n\t\t\t\t\tnewMessages,\n\t\t\t\t\tdagScheduleCache,\n\t\t\t\t);\n\t\t\t\tif (batchOutcome.kind === \"ended\") {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttoolResults.push(...batchOutcome.toolResults);\n\t\t\t\thasMoreToolCalls = batchOutcome.hasMoreToolCalls;\n\t\t\t\tstopAfterToolBatch = batchOutcome.stopRun;\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\t\t\tif (stopAfterToolBatch) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (maxTurns !== undefined && turnsStarted >= maxTurns) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst nextTurnContext = {\n\t\t\t\tmessage,\n\t\t\t\ttoolResults,\n\t\t\t\tcontext: currentContext,\n\t\t\t\tnewMessages,\n\t\t\t};\n\t\t\tconst nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);\n\t\t\tif (nextTurnSnapshot) {\n\t\t\t\tconst applied = applyNextTurnSnapshot(currentContext, config, nextTurnSnapshot);\n\t\t\t\tcurrentContext = applied.context;\n\t\t\t\tconfig = applied.config;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tawait config.shouldStopAfterTurn?.({\n\t\t\t\t\tmessage,\n\t\t\t\t\ttoolResults,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\tnewMessages,\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tpendingMessages = await drainMessageQueue(config.getSteeringMessages);\n\t\t}\n\n\t\t// Agent would stop here. Check for follow-up messages.\n\t\tconst followUpMessages = await drainMessageQueue(config.getFollowUpMessages);\n\t\tif (followUpMessages.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\t// Validate the full transcript before every provider request. This fails\n\t// fast for `assistant(A,B) -> result(A)` and any duplicate/orphan/interleaved\n\t// structure that the provider would otherwise reject opaquely.\n\tassertValidToolTranscript(\n\t\tcontext.messages,\n\t\t(summary) =>\n\t\t\t`Refusing provider request: invalid tool transcript (${summary}). ` +\n\t\t\t\"Append terminal tool results or repair the transcript before retrying.\",\n\t);\n\n\t// Pin request-affecting data before asynchronous context/auth hooks can mutate caller state.\n\tconst requestConfig = config.modelContract\n\t\t? { ...config, model: createImmutableSnapshot(config.model), headers: config.headers && { ...config.headers } }\n\t\t: config;\n\t// Apply context transform if configured (AgentMessage[] → AgentMessage[])\n\tlet messages = context.messages;\n\tif (config.transformContext) {\n\t\tmessages = await config.transformContext(messages, signal);\n\t\tassertValidToolTranscript(\n\t\t\tmessages,\n\t\t\t(summary) => `Refusing provider request: transformed context has an invalid tool transcript (${summary}).`,\n\t\t);\n\t}\n\n\t// Convert to LLM-compatible messages (AgentMessage[] → Message[])\n\tconst llmMessages = await config.convertToLlm(messages);\n\n\t// Build LLM context\n\tconst llmContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tsystemPromptCacheBoundary: context.systemPromptCacheBoundary,\n\t\tsystemPromptCacheBoundaryBypass: context.systemPromptCacheBoundaryBypass,\n\t\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\treturn requestAssistantResponse(llmContext, requestConfig, {\n\t\tsignal,\n\t\temit,\n\t\tstreamFn,\n\t\tconsume: (response) => consumeAssistantStream(response, context, emit),\n\t});\n}\n\n/** Commit the final assistant message to the transcript and emit its lifecycle. */\nasync function commitFinalAssistantMessage(\n\tresponse: AssistantMessageEventStream,\n\tcontext: AgentContext,\n\taddedPartial: boolean,\n\temit: AgentEventSink,\n): Promise<AssistantMessage> {\n\tconst finalMessage = await response.result();\n\tif (addedPartial) {\n\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t} else {\n\t\tcontext.messages.push(finalMessage);\n\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t}\n\tawait emit({ type: \"message_end\", message: finalMessage });\n\treturn finalMessage;\n}\n\n/** Forward a partial assistant update into the transcript and event sink. */\nasync function forwardPartialUpdate(\n\tevent: Extract<AssistantMessageEvent, { partial: AssistantMessage }>,\n\tpartialMessage: AssistantMessage | null,\n\tcontext: AgentContext,\n\temit: AgentEventSink,\n): Promise<AssistantMessage | null> {\n\tif (!partialMessage) {\n\t\treturn partialMessage;\n\t}\n\tconst updated = event.partial;\n\tcontext.messages[context.messages.length - 1] = updated;\n\tawait emit({\n\t\ttype: \"message_update\",\n\t\tassistantMessageEvent: event,\n\t\tmessage: { ...updated },\n\t});\n\treturn updated;\n}\n\n/** Consume the assistant event stream, maintaining the partial message in the transcript. */\nasync function consumeAssistantStream(\n\tresponse: AssistantMessageEventStream,\n\tcontext: AgentContext,\n\temit: AgentEventSink,\n): Promise<AssistantMessage> {\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tfor await (const event of response) {\n\t\tswitch (event.type) {\n\t\t\tcase \"start\":\n\t\t\t\tpartialMessage = event.partial;\n\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\taddedPartial = true;\n\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\tbreak;\n\t\t\tcase \"done\":\n\t\t\tcase \"error\":\n\t\t\t\treturn commitFinalAssistantMessage(response, context, addedPartial, emit);\n\t\t\tdefault:\n\t\t\t\tpartialMessage = await forwardPartialUpdate(event, partialMessage, context, emit);\n\t\t}\n\t}\n\n\treturn commitFinalAssistantMessage(response, context, addedPartial, emit);\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tdagScheduleCache: DagFrontierScheduleCache,\n): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\t// dag-v2 is the safe default; waves-v1 remains an explicit rollback path.\n\tif ((config.toolScheduler ?? \"dag-v2\") === \"dag-v2\") {\n\t\treturn executeToolCallsDagLevels(\n\t\t\tcurrentContext,\n\t\t\tassistantMessage,\n\t\t\ttoolCalls,\n\t\t\tconfig,\n\t\t\tsignal,\n\t\t\temit,\n\t\t\tdagScheduleCache,\n\t\t);\n\t}\n\tconst hasSequentialToolCall = toolCalls.some(\n\t\t(tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === \"sequential\",\n\t);\n\tconst toolPolicies = new Map<string, \"sequential\" | \"parallel\">();\n\tfor (const tool of currentContext.tools ?? []) {\n\t\tif (tool.executionMode) {\n\t\t\ttoolPolicies.set(tool.name, tool.executionMode);\n\t\t}\n\t}\n\tconst batchWaves = applyConcurrencyCap(\n\t\tpartitionToolBatchWaves(\n\t\t\ttoolCalls.map((tc) => ({ name: tc.name, arguments: tc.arguments as Record<string, unknown> })),\n\t\t\t{\n\t\t\t\tcwd: config.cwd ?? process.cwd(),\n\t\t\t\ttoolPolicies,\n\t\t\t\tallowUnknownParallel: (toolName) => toolPolicies.get(toolName) === \"parallel\",\n\t\t\t},\n\t\t),\n\t\tconfig.maxToolConcurrency,\n\t);\n\tif (\n\t\tconfig.toolExecution === \"sequential\" ||\n\t\thasSequentialToolCall ||\n\t\tbatchWaves.every((wave) => wave.length === 1)\n\t) {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\tif (batchWaves.length === 1) {\n\t\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\treturn executeToolCallsInWaves(currentContext, assistantMessage, toolCalls, batchWaves, config, signal, emit);\n}\n\n/**\n * Execute a partitioned tool-call batch wave by wave: waves run in source\n * order, calls inside a multi-call wave run concurrently, and solo waves run\n * sequentially. Waves are contiguous index runs, so the returned tool result\n * messages keep the model's original tool-call order. An all-terminating wave\n * skips every later call with a synthesized \"skipped\" result and ends the\n * run, matching the dag-v2 level-termination contract.\n */\nasync function executeToolCallsInWaves(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\twaves: number[][],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst messages: ToolResultMessage[] = [];\n\tlet terminated = false;\n\tlet stopRun = false;\n\tfor (const wave of waves) {\n\t\tconst waveCalls = wave.map((index) => toolCalls[index]);\n\t\tconst executedWave =\n\t\t\twaveCalls.length === 1\n\t\t\t\t? await executeToolCallsSequential(currentContext, assistantMessage, waveCalls, config, signal, emit)\n\t\t\t\t: await executeToolCallsParallel(currentContext, assistantMessage, waveCalls, config, signal, emit);\n\t\tmessages.push(...executedWave.messages);\n\t\tif (executedWave.terminate || executedWave.stopRun) {\n\t\t\tterminated = true;\n\t\t\tstopRun = executedWave.stopRun ?? false;\n\t\t\tconst reason = stopRun\n\t\t\t\t? \"Skipped because the preceding tool wave timed out before settling\"\n\t\t\t\t: \"Skipped because the preceding tool wave requested termination\";\n\t\t\tconst skipped = await closeUnresolvedToolBatch(currentContext, toolCalls, messages, emit, {\n\t\t\t\treason,\n\t\t\t\tdisposition: \"skipped\",\n\t\t\t});\n\t\t\tmessages.push(...skipped);\n\t\t\tbreak;\n\t\t}\n\t\tif (signal?.aborted) break;\n\t}\n\treturn { messages, terminate: terminated, stopRun };\n}\n\n/**\n * Shared scheduling state for one DAG batch: the last known claim resolution\n * per source index, calls deferred because a post-hook claim change would\n * execute them before an unsettled earlier-source conflict, and calls that\n * have reached a terminal outcome. Shared across the ready frontier so the\n * final-claims contract is enforced for the whole batch.\n */\ninterface DagBatchScheduleState {\n\treadonly resolutions: Map<number, ToolClaimResolution>;\n\t/**\n\t * Calls deferred because their post-hook claims conflict with an unsettled\n\t * or running call. The stored resolution is only used to prove that conflict\n\t * — reusing it there skips an extension callback that cannot change the\n\t * conservative answer — while admission always re-resolves, because dynamic\n\t * resource identities may change across the wait.\n\t */\n\treadonly deferred: Map<number, DeferredCall<PreparedToolCall>>;\n\treadonly settled: Set<number>;\n}\n\n/**\n * Resolve planned calls for the dependency ready frontier. Immediate outcomes\n * carry no claims; unresolvable arguments become exclusive claim barriers.\n * Barrier levels are a public compatibility schedule, not an admission input.\n */\nasync function schedulePlannedDagFrontier(\n\tplans: Array<PlannedToolCall | ImmediateToolCallOutcome>,\n\ttoolPolicies: ReadonlyMap<string, \"sequential\" | \"parallel\">,\n\tboundTools: AgentTool<any>[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\tdagScheduleCache: DagFrontierScheduleCache,\n): Promise<{\n\torder: number[];\n\tresolutions: Map<number, ToolClaimResolution>;\n\t/** Conflicting predecessors per source index — the precedence graph the ready queue admits from. */\n\tdependencies: Map<number, number[]>;\n}> {\n\tconst schedulableSourceIndices: number[] = [];\n\tconst claimableCalls: ClaimableToolCall[] = [];\n\tconst immediateSourceIndices: number[] = [];\n\tplans.forEach((plan, sourceIndex) => {\n\t\tif (plan.kind === \"planned\") {\n\t\t\tschedulableSourceIndices.push(sourceIndex);\n\t\t\tclaimableCalls.push({ id: plan.toolCall.id, name: plan.toolCall.name, arguments: plan.args });\n\t\t} else {\n\t\t\timmediateSourceIndices.push(sourceIndex);\n\t\t}\n\t});\n\tconst scheduled = await resolveDagFrontierMemo(\n\t\tclaimableCalls,\n\t\t{\n\t\t\tcwd: config.cwd ?? process.cwd(),\n\t\t\ttoolPolicies,\n\t\t\tregisteredTools: boundTools,\n\t\t\tstrictExtensionClaims: config.strictExtensionClaims,\n\t\t\tmaxConcurrency: config.maxToolConcurrency,\n\t\t\tresourceKeyResolver: config.resourceKeyResolver,\n\t\t},\n\t\tsignal,\n\t\tdagScheduleCache,\n\t);\n\tif (scheduled === null) {\n\t\treturn { order: [], resolutions: new Map(), dependencies: new Map() };\n\t}\n\tconst resolutions = new Map<number, ToolClaimResolution>();\n\tscheduled.forEach((entry, position) => {\n\t\tresolutions.set(schedulableSourceIndices[position], entry.resolution);\n\t});\n\t// Precedence graph in source-index space. Immediate plans carry no claims and\n\t// therefore no predecessors; they already fail before any tool executes.\n\tconst dependencies = new Map<number, number[]>();\n\tfor (const sourceIndex of immediateSourceIndices) dependencies.set(sourceIndex, []);\n\t// The public dependency graph retains every conflict edge. The live frontier\n\t// only needs ordering reachability, so discard transitive synchronization\n\t// without changing which conflicts must settle before a call can start.\n\tconst frontierDependencies = reduceDagDependencies(assignDagDependencies(scheduled));\n\tfrontierDependencies.forEach((blockers, position) => {\n\t\tdependencies.set(\n\t\t\tschedulableSourceIndices[position],\n\t\t\tblockers.map((blocker) => schedulableSourceIndices[blocker]),\n\t\t);\n\t});\n\treturn { order: plans.map((_, sourceIndex) => sourceIndex), resolutions, dependencies };\n}\n\n/**\n * Execute a tool-call batch using the dag-v2 scheduler.\n *\n * Planned calls resolve claims in source order, while immediate failures carry\n * no claims. The dependency frontier authorizes ready calls in source order,\n * re-resolves claims from exact post-hook arguments, and starts only safe work.\n * Results remain globally buffered and are emitted in source order.\n */\nasync function executeToolCallsDagLevels(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tdagScheduleCache: DagFrontierScheduleCache,\n): Promise<ExecutedToolCallBatch> {\n\tconst plans = toolCalls.map((toolCall) => planToolCall(currentContext, toolCall));\n\tconst boundTools = plans.flatMap((plan) => (plan.kind === \"planned\" ? [plan.tool] : []));\n\tconst toolPolicies = new Map<string, \"sequential\" | \"parallel\">();\n\tfor (const tool of boundTools) {\n\t\tconst mode = config.toolExecution ?? tool.executionMode;\n\t\tif (mode && !toolPolicies.has(tool.name)) toolPolicies.set(tool.name, mode);\n\t}\n\n\tconst schedule = await schedulePlannedDagFrontier(plans, toolPolicies, boundTools, config, signal, dagScheduleCache);\n\tconst batchState: DagBatchScheduleState = {\n\t\tresolutions: schedule.resolutions,\n\t\tdeferred: new Map(),\n\t\tsettled: new Set(),\n\t};\n\n\tconst finalizedByIndex: Array<FinalizedToolCallOutcome | undefined> = new Array(toolCalls.length).fill(undefined);\n\tlet skippedReason: string | undefined;\n\tlet stoppedByUnsettledTimeout = false;\n\n\tconst frontier = await runDagFrontier(\n\t\tcurrentContext,\n\t\tassistantMessage,\n\t\tschedule.order,\n\t\tschedule.dependencies,\n\t\ttoolCalls,\n\t\tplans,\n\t\ttoolPolicies,\n\t\tconfig,\n\t\tsignal,\n\t\temit,\n\t\tbatchState,\n\t);\n\tfor (const outcome of frontier.outcomes) finalizedByIndex[outcome.sourceIndex] = outcome.finalized;\n\tif (frontier.stoppedByUnsettledTimeout) {\n\t\tskippedReason = \"Skipped because a preceding DAG tool timed out before its execution promise settled\";\n\t\tstoppedByUnsettledTimeout = true;\n\t} else if (frontier.terminated) {\n\t\tskippedReason = \"Skipped because the preceding DAG level requested termination\";\n\t}\n\n\tconst messages: ToolResultMessage[] = [];\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tfor (let index = 0; index < toolCalls.length; index++) {\n\t\tconst finalized = finalizedByIndex[index];\n\t\tif (finalized) {\n\t\t\tmessages.push(createToolResultMessage(finalized));\n\t\t\tfinalizedCalls.push(finalized);\n\t\t} else if (signal?.aborted) {\n\t\t\tconst toolCall = toolCalls[index];\n\t\t\tmessages.push(\n\t\t\t\tcreateImmutableSnapshot(createSyntheticToolResult(toolCall.id, toolCall.name, \"Operation aborted\")),\n\t\t\t);\n\t\t} else if (skippedReason !== undefined) {\n\t\t\tconst toolCall = toolCalls[index];\n\t\t\tmessages.push(\n\t\t\t\tcreateImmutableSnapshot(\n\t\t\t\t\tcreateSyntheticToolResult(toolCall.id, toolCall.name, skippedReason, Date.now(), \"skipped\"),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\tconst finalizedById = indexFinalizedToolCalls(finalizedCalls);\n\t// Close the full source-ordered batch before result notification; calls not\n\t// reached by a candidate level receive no execution lifecycle.\n\tfor (const message of messages) {\n\t\tcurrentContext.messages.push(message);\n\t\ttry {\n\t\t\tawait emitToolResultMessage(message, emit);\n\t\t} finally {\n\t\t\tfinalizedById.get(message.toolCallId)?.commitTerminal?.();\n\t\t}\n\t}\n\n\treturn {\n\t\tmessages,\n\t\tterminate: skippedReason !== undefined || shouldTerminateToolBatch(finalizedCalls),\n\t\tstopRun: stoppedByUnsettledTimeout,\n\t};\n}\n\ntype DagLevelOutcome = { sourceIndex: number; finalized: FinalizedToolCallOutcome };\n\n// Re-resolve claims for a prepared call from its exact post-hook arguments.\n// Resolution failures fail closed as an immediate error rather than guessing\n// at a safe scope.\n//\n// The wait is bound to the run's abort signal exactly like the initial\n// scheduling pass (tool-dag-memo): an extension `resourceClaims()` that never\n// settles must not pin a cancelled run. Abandoning the wait does not stop the\n// callback — a plain Promise cannot be killed — but the aborted outcome settles\n// this call before any late value could admit it, and the frontier loop exits\n// on the same signal, so a late fulfilment or rejection lands in a finished\n// batch and admits nothing.\nasync function resolveFinalResolution(\n\tpreparation: PreparedToolCall,\n\ttoolPolicies: ReadonlyMap<string, \"sequential\" | \"parallel\">,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<ToolClaimResolution | ImmediateToolCallOutcome> {\n\t// awaitWithAbort short-circuits an already-aborted signal before invoking the callback.\n\tconst call = { id: preparation.toolCall.id, name: preparation.toolCall.name, arguments: preparation.args };\n\tconst options = {\n\t\tcwd: config.cwd ?? process.cwd(),\n\t\ttoolPolicies,\n\t\tregisteredTools: [preparation.tool],\n\t\tstrictExtensionClaims: config.strictExtensionClaims,\n\t\tresourceKeyResolver: config.resourceKeyResolver,\n\t};\n\ttry {\n\t\tconst bounded = await awaitWithAbort(() => resolveToolClaimsForCall(call, options), signal);\n\t\tif (bounded.kind === \"aborted\" || signal?.aborted) return immediateOutcome(\"aborted\", \"Operation aborted\");\n\t\treturn bounded.value;\n\t} catch (error) {\n\t\treturn immediateOutcome(\"failed\", error instanceof Error ? error.message : String(error));\n\t}\n}\n\n/**\n * Execute a planned batch as a dependency ready queue.\n *\n * States are `pending -> ready -> running -> settled`. A call is admitted once\n * every call it actually conflicts with has settled, rather than once its whole\n * barrier level has, so one slow unrelated call no longer delays independent\n * work queued behind it.\n *\n * Admission — authorize, re-resolve claims from exact post-hook arguments, and\n * enforce the final-claims contract — runs one call at a time in source order.\n * That keeps hook ordering and the conflict contract identical to the barrier\n * executor and leaves the shared batch state free of concurrent mutation; only\n * tool execution overlaps. Simultaneously-ready calls are admitted by source\n * index, so admission order stays deterministic even though completion order\n * is not.\n *\n * A call whose post-hook claims newly conflict with an earlier unsettled call\n * yields its turn and is retried after the next settle, which preserves the\n * source-order conflict contract without a separate drain pass.\n */\nasync function runDagFrontier(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\torder: readonly number[],\n\tdependencies: ReadonlyMap<number, number[]>,\n\ttoolCalls: AgentToolCall[],\n\tplans: Array<PlannedToolCall | ImmediateToolCallOutcome>,\n\ttoolPolicies: ReadonlyMap<string, \"sequential\" | \"parallel\">,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstate: DagBatchScheduleState,\n): Promise<{ outcomes: DagLevelOutcome[]; stoppedByUnsettledTimeout: boolean; terminated: boolean }> {\n\tconst outcomes: DagLevelOutcome[] = [];\n\tconst pending = [...order].sort((left, right) => left - right);\n\tconst running = new Map<number, Promise<OwnedTaskResult<DagLevelOutcome>>>();\n\tconst taskErrors: unknown[] = [];\n\t// Mirrors applyConcurrencyCap: absent, non-finite, or non-positive is unbounded.\n\tconst cap =\n\t\ttypeof config.maxToolConcurrency === \"number\" &&\n\t\tNumber.isFinite(config.maxToolConcurrency) &&\n\t\tconfig.maxToolConcurrency > 0\n\t\t\t? Math.max(1, Math.floor(config.maxToolConcurrency))\n\t\t\t: Number.POSITIVE_INFINITY;\n\tlet stoppedByUnsettledTimeout = false;\n\tlet terminated = false;\n\n\t// Readiness bookkeeping: each pending call tracks how many of its\n\t// predecessors are still unsettled, and each settle decrements only its\n\t// successors — the per-settle cost is proportional to the out-degree of the\n\t// finished call, not to a full rescan of every pending dependency list.\n\tconst remainingPredecessors = new Map<number, number>();\n\tconst successors = new Map<number, number[]>();\n\tfor (const sourceIndex of pending) {\n\t\tconst blockers = dependencies.get(sourceIndex) ?? [];\n\t\tremainingPredecessors.set(sourceIndex, blockers.filter((blocker) => !state.settled.has(blocker)).length);\n\t\tfor (const blocker of blockers) {\n\t\t\tconst followers = successors.get(blocker);\n\t\t\tif (followers) followers.push(sourceIndex);\n\t\t\telse successors.set(blocker, [sourceIndex]);\n\t\t}\n\t}\n\n\tconst settle = async (outcome: DagLevelOutcome): Promise<void> => {\n\t\toutcomes.push(outcome);\n\t\tstate.settled.add(outcome.sourceIndex);\n\t\tfor (const follower of successors.get(outcome.sourceIndex) ?? []) {\n\t\t\tconst remaining = (remainingPredecessors.get(follower) ?? 0) - 1;\n\t\t\tremainingPredecessors.set(follower, Math.max(0, remaining));\n\t\t}\n\t\tif (await hasUnsettledTimeout([outcome.finalized])) stoppedByUnsettledTimeout = true;\n\t};\n\n\ttry {\n\t\twhile (!signal?.aborted && !stoppedByUnsettledTimeout && !terminated) {\n\t\t\t// Termination is a property of a settled group, not of one call:\n\t\t\t// shouldTerminateToolBatch requires every member to terminate. Evaluating it\n\t\t\t// only when nothing is in flight keeps the barrier executor's semantics,\n\t\t\t// where a call sharing a level with a non-terminating peer did not end the\n\t\t\t// batch. Judging a single outcome would terminate on the first terminating\n\t\t\t// call and strand its concurrent peers.\n\t\t\tif (running.size === 0 && shouldTerminateToolBatch(outcomes.map((outcome) => outcome.finalized))) {\n\t\t\t\tterminated = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlet admitted = false;\n\t\t\tfor (let position = 0; position < pending.length && running.size < cap; ) {\n\t\t\t\tif (signal?.aborted || stoppedByUnsettledTimeout) break;\n\t\t\t\tconst sourceIndex = pending[position];\n\t\t\t\tif ((remainingPredecessors.get(sourceIndex) ?? 0) > 0) {\n\t\t\t\t\tposition++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst runningSet = new Set(running.keys());\n\t\t\t\tconst cached = state.deferred.get(sourceIndex);\n\t\t\t\tlet preparation: PreparedToolCall;\n\t\t\t\tif (cached) {\n\t\t\t\t\t// A stale conflict answer only delays this call; admission below\n\t\t\t\t\t// re-resolves, so no tool executes from a cached scope.\n\t\t\t\t\tif (\n\t\t\t\t\t\tdeferredStillConflicts(sourceIndex, cached.resolution, state.settled, runningSet, state.resolutions)\n\t\t\t\t\t) {\n\t\t\t\t\t\tposition++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpreparation = cached.preparation;\n\t\t\t\t} else {\n\t\t\t\t\tconst plan = plans[sourceIndex];\n\t\t\t\t\tconst preparedOutcome =\n\t\t\t\t\t\tplan.kind === \"immediate\"\n\t\t\t\t\t\t\t? plan\n\t\t\t\t\t\t\t: await authorizePlannedToolCall(currentContext, assistantMessage, plan, config, signal);\n\t\t\t\t\tif (preparedOutcome.kind === \"immediate\") {\n\t\t\t\t\t\tpending.splice(position, 1);\n\t\t\t\t\t\tadmitted = true;\n\t\t\t\t\t\tawait settle({\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tfinalized: {\n\t\t\t\t\t\t\t\ttoolCall: toolCalls[sourceIndex],\n\t\t\t\t\t\t\t\tresult: preparedOutcome.result,\n\t\t\t\t\t\t\t\tisError: preparedOutcome.isError,\n\t\t\t\t\t\t\t\tenvelope: preparedOutcome.envelope,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpreparation = preparedOutcome;\n\t\t\t\t}\n\t\t\t\tconst resolved = await resolveFinalResolution(preparation, toolPolicies, config, signal);\n\t\t\t\tif (resolved.kind === \"immediate\") {\n\t\t\t\t\tstate.deferred.delete(sourceIndex);\n\t\t\t\t\tpending.splice(position, 1);\n\t\t\t\t\tadmitted = true;\n\t\t\t\t\tawait settle({\n\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\tfinalized: {\n\t\t\t\t\t\t\ttoolCall: preparation.toolCall,\n\t\t\t\t\t\t\tresult: resolved.result,\n\t\t\t\t\t\t\tisError: resolved.isError,\n\t\t\t\t\t\t\tenvelope: resolved.envelope,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.resolutions.set(sourceIndex, resolved);\n\t\t\t\tif (deferredStillConflicts(sourceIndex, resolved, state.settled, runningSet, state.resolutions)) {\n\t\t\t\t\t// Defer without losing the prepared call: a later scan retries\n\t\t\t\t\t// admission from this cache instead of re-invoking authorization.\n\t\t\t\t\tstate.deferred.set(sourceIndex, { preparation, resolution: resolved });\n\t\t\t\t\tposition++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.deferred.delete(sourceIndex);\n\t\t\t\tpending.splice(position, 1);\n\t\t\t\tadmitted = true;\n\t\t\t\tawait emitToolExecutionStart(preparation, emit);\n\t\t\t\trunning.set(\n\t\t\t\t\tsourceIndex,\n\t\t\t\t\tstartDagTask(sourceIndex, async (): Promise<DagLevelOutcome> => {\n\t\t\t\t\t\tconst executed = await executePreparedToolCall(preparation, config, signal, emit);\n\t\t\t\t\t\tconst finalized = await finalizeExecutedToolCall({\n\t\t\t\t\t\t\tcurrentContext,\n\t\t\t\t\t\t\tassistantMessage,\n\t\t\t\t\t\t\tprepared: preparation,\n\t\t\t\t\t\t\texecuted,\n\t\t\t\t\t\t\tafterToolCall: config.afterToolCall,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait emitToolExecutionEnd(finalized, emit);\n\t\t\t\t\t\treturn { sourceIndex, finalized };\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (running.size === 0) {\n\t\t\t\t// Nothing is in flight: either every call settled, or the remainder is\n\t\t\t\t// blocked with nothing left that could unblock it. A pending call that\n\t\t\t\t// can never become ready still gets an explicit terminal outcome rather\n\t\t\t\t// than vanishing from the batch.\n\t\t\t\tif (!admitted) {\n\t\t\t\t\tfor (const sourceIndex of pending.splice(0)) {\n\t\t\t\t\t\tawait settle({\n\t\t\t\t\t\t\tsourceIndex,\n\t\t\t\t\t\t\tfinalized: {\n\t\t\t\t\t\t\t\ttoolCall: toolCalls[sourceIndex],\n\t\t\t\t\t\t\t\tresult: createErrorToolResult(\n\t\t\t\t\t\t\t\t\t\"DAG dependency deadlock: call could not become ready and nothing is running to unblock it\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\tenvelope: createToolResultEnvelope({\n\t\t\t\t\t\t\t\t\tdisposition: \"failed\",\n\t\t\t\t\t\t\t\t\tsynthetic: true,\n\t\t\t\t\t\t\t\t\texecutionStarted: false,\n\t\t\t\t\t\t\t\t\treason: \"DAG dependency deadlock\",\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst finished = await Promise.race([...running.values()]);\n\t\t\trunning.delete(finished.sourceIndex);\n\t\t\tif (finished.status === \"rejected\") throw finished.reason;\n\t\t\tawait settle(finished.value);\n\t\t}\n\t} catch (error) {\n\t\ttaskErrors.push(error);\n\t} finally {\n\t\tawait finishDagTasks(running, settle, taskErrors);\n\t}\n\treturn { outcomes, stoppedByUnsettledTimeout, terminated };\n}\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\tterminate: boolean;\n\t/** End the run without another provider request after an unsettled timeout. */\n\tstopRun?: boolean;\n};\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallOutcome[] = [];\n\tconst messages: ToolResultMessage[] = [];\n\n\tfor (const toolCall of toolCalls) {\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tlet finalized: FinalizedToolCallOutcome;\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tfinalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\tenvelope: preparation.envelope,\n\t\t\t};\n\t\t} else {\n\t\t\tawait emitToolExecutionStart(preparation, emit);\n\t\t\tconst executed = await executePreparedToolCall(preparation, config, signal, emit);\n\t\t\tfinalized = await finalizeExecutedToolCall({\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tprepared: preparation,\n\t\t\t\texecuted,\n\t\t\t\tafterToolCall: config.afterToolCall,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t}\n\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tcurrentContext.messages.push(toolResultMessage);\n\t\tif (preparation.kind === \"prepared\") await emitToolExecutionEnd(finalized, emit);\n\t\ttry {\n\t\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\t} finally {\n\t\t\tfinalized.commitTerminal?.();\n\t\t}\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(toolResultMessage);\n\n\t\tif (await hasUnsettledTimeout([finalized])) {\n\t\t\tconst skipped = await closeUnresolvedToolBatch(currentContext, toolCalls, messages, emit, {\n\t\t\t\treason: \"Skipped because a preceding tool timed out before settling\",\n\t\t\t\tdisposition: \"skipped\",\n\t\t\t});\n\t\t\tmessages.push(...skipped);\n\t\t\treturn { messages, terminate: true, stopRun: true };\n\t\t}\n\t\tif (signal?.aborted) break;\n\t}\n\n\treturn {\n\t\tmessages,\n\t\tterminate: shouldTerminateToolBatch(finalizedCalls),\n\t};\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst finalizedCalls: FinalizedToolCallEntry[] = [];\n\n\tfor (const toolCall of toolCalls) {\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tconst finalized = {\n\t\t\t\ttoolCall,\n\t\t\t\tresult: preparation.result,\n\t\t\t\tisError: preparation.isError,\n\t\t\t\tenvelope: preparation.envelope,\n\t\t\t} satisfies FinalizedToolCallOutcome;\n\t\t\tfinalizedCalls.push(finalized);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tfinalizedCalls.push(async () => {\n\t\t\tawait emitToolExecutionStart(preparation, emit);\n\t\t\tconst executed = await executePreparedToolCall(preparation, config, signal, emit);\n\t\t\tconst finalized = await finalizeExecutedToolCall({\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tprepared: preparation,\n\t\t\t\texecuted,\n\t\t\t\tafterToolCall: config.afterToolCall,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tawait emitToolExecutionEnd(finalized, emit);\n\t\t\treturn finalized;\n\t\t});\n\t\tif (signal?.aborted) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tconst orderedFinalizedCalls = await Promise.all(\n\t\tfinalizedCalls.map((entry) => (typeof entry === \"function\" ? entry() : Promise.resolve(entry))),\n\t);\n\tconst messages: ToolResultMessage[] = [];\n\tfor (const finalized of orderedFinalizedCalls) {\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tcurrentContext.messages.push(toolResultMessage);\n\t\ttry {\n\t\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\t} finally {\n\t\t\tfinalized.commitTerminal?.();\n\t\t}\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\tconst stopRun = await hasUnsettledTimeout(orderedFinalizedCalls);\n\treturn { messages, terminate: stopRun || shouldTerminateToolBatch(orderedFinalizedCalls), stopRun };\n}\n\ntype PlannedToolCall = {\n\tkind: \"planned\";\n\ttoolCall: AgentToolCall;\n\tpreparedToolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\t/** Immutable scheduler/executor arguments fixed after the authorization hook. */\n\targs: unknown;\n\t/** Separate immutable public-event snapshot. */\n\teventArgs: unknown;\n\t/** Effective per-call timeout in ms resolved by precedence; 0 disables it. */\n\ttimeoutMs: number;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n\tenvelope: ToolResultEnvelope;\n};\n\ntype FinalizedToolCallEntry = FinalizedToolCallOutcome | (() => Promise<FinalizedToolCallOutcome>);\n\nfunction shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {\n\treturn finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);\n}\n\nfunction prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {\n\tif (!tool.prepareArguments) {\n\t\treturn toolCall;\n\t}\n\tconst preparedArguments = tool.prepareArguments(toolCall.arguments);\n\tif (preparedArguments === toolCall.arguments) {\n\t\treturn toolCall;\n\t}\n\treturn {\n\t\t...toolCall,\n\t\targuments: preparedArguments as Record<string, any>,\n\t};\n}\n\nfunction immediateOutcome(disposition: ToolCallDisposition, reason: string): ImmediateToolCallOutcome {\n\treturn {\n\t\tkind: \"immediate\",\n\t\tresult: createErrorToolResult(reason),\n\t\tisError: true,\n\t\tenvelope: createToolResultEnvelope({ disposition, synthetic: true, executionStarted: false, reason }),\n\t};\n}\n\nfunction planToolCall(\n\tcurrentContext: AgentContext,\n\tuntrustedToolCall: AgentToolCall,\n): PlannedToolCall | ImmediateToolCallOutcome {\n\ttry {\n\t\tconst toolCall = createImmutableJsonSnapshot(untrustedToolCall);\n\t\tif (toolCall.id.length === 0 || toolCall.name.length === 0) throw new TypeError(\"Invalid empty tool identity\");\n\t\tconst candidate = currentContext.tools?.find((tool) => tool.name === toolCall.name);\n\t\tif (!candidate) return immediateOutcome(\"failed\", `Tool ${toolCall.name} not found`);\n\t\tconst tool = bindToolIdentity(candidate, toolCall.name);\n\t\tconst prepared = prepareToolCallArguments(tool, toolCall);\n\t\tconst args = createImmutableJsonSnapshot(prepared.arguments);\n\t\tconst preparedToolCall = createImmutableSnapshot({ ...toolCall, arguments: args });\n\t\treturn { kind: \"planned\", toolCall, preparedToolCall, tool, args };\n\t} catch (error) {\n\t\treturn immediateOutcome(\"failed\", error instanceof Error ? error.message : String(error));\n\t}\n}\n\nasync function authorizePlannedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tplan: PlannedToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\ttry {\n\t\tconst hookArgs = parseJsonValue(validateToolArguments(plan.tool, plan.preparedToolCall));\n\t\tconst beforeToolCall = config.beforeToolCall;\n\t\tif (beforeToolCall) {\n\t\t\tconst bounded = await awaitWithAbort(\n\t\t\t\t() =>\n\t\t\t\t\tbeforeToolCall(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tassistantMessage: createImmutableSnapshot(assistantMessage),\n\t\t\t\t\t\t\ttoolCall: plan.toolCall,\n\t\t\t\t\t\t\targs: hookArgs,\n\t\t\t\t\t\t\tcontext: currentContext,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (bounded.kind === \"aborted\" || signal?.aborted) return immediateOutcome(\"aborted\", \"Operation aborted\");\n\t\t\tif (bounded.value?.block) {\n\t\t\t\treturn immediateOutcome(\"blocked\", bounded.value.reason || \"Tool execution was blocked\");\n\t\t\t}\n\t\t}\n\t\tif (signal?.aborted) return immediateOutcome(\"aborted\", \"Operation aborted\");\n\t\tconst args = createImmutableJsonSnapshot(hookArgs);\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall: plan.toolCall,\n\t\t\ttool: plan.tool,\n\t\t\targs,\n\t\t\teventArgs: createImmutableSnapshot(args),\n\t\t\ttimeoutMs: resolveToolTimeoutMs(plan.tool, config, plan.toolCall.name),\n\t\t};\n\t} catch (error) {\n\t\treturn immediateOutcome(\"failed\", error instanceof Error ? error.message : String(error));\n\t}\n}\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst plan = planToolCall(currentContext, toolCall);\n\treturn plan.kind === \"immediate\"\n\t\t? plan\n\t\t: authorizePlannedToolCall(currentContext, assistantMessage, plan, config, signal);\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tlet realPromiseSettled = false;\n\tlet commitTerminal = (): void => {};\n\tconst terminalCommitted = new Promise<void>((resolve) => {\n\t\tcommitTerminal = resolve;\n\t});\n\tconst executed = await runToolCallWithTimeout({\n\t\ttoolCallId: prepared.toolCall.id,\n\t\ttoolName: prepared.toolCall.name,\n\t\ttimeoutMs: prepared.timeoutMs,\n\t\tlateSettlement: config.toolExecutionPolicy?.lateSettlement,\n\t\tsignal,\n\t\tstart: async (childSignal, onUpdate) => {\n\t\t\ttry {\n\t\t\t\treturn await prepared.tool.execute(prepared.toolCall.id, prepared.args as never, childSignal, onUpdate);\n\t\t\t} finally {\n\t\t\t\trealPromiseSettled = true;\n\t\t\t}\n\t\t},\n\t\temitUpdate: (partialResult) =>\n\t\t\temit({\n\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\targs: prepared.eventArgs,\n\t\t\t\tpartialResult: createImmutableSnapshot(partialResult),\n\t\t\t}),\n\t\temitLateSettlement: async (settlement) => {\n\t\t\tawait terminalCommitted;\n\t\t\tawait emit({\n\t\t\t\ttype: \"tool_execution_late_settlement\",\n\t\t\t\ttoolCallId: settlement.toolCallId,\n\t\t\t\ttoolName: settlement.toolName,\n\t\t\t\tdisposition: settlement.disposition,\n\t\t\t\toutcome: settlement.outcome,\n\t\t\t});\n\t\t},\n\t\ttoErrorResult: (error) => createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t});\n\treturn { ...executed, isRealPromiseSettled: () => realPromiseSettled, commitTerminal };\n}\n\nasync function emitToolExecutionStart(prepared: PreparedToolCall, emit: AgentEventSink): Promise<void> {\n\tawait emit({\n\t\ttype: \"tool_execution_start\",\n\t\ttoolCallId: prepared.toolCall.id,\n\t\ttoolName: prepared.toolCall.name,\n\t\targs: prepared.eventArgs,\n\t});\n}\n\nasync function emitToolExecutionEnd(finalized: FinalizedToolCallOutcome, emit: AgentEventSink): Promise<void> {\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tresult: createImmutableSnapshot(finalized.result),\n\t\tisError: finalized.isError,\n\t});\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn createImmutableSnapshot({\n\t\trole: \"toolResult\",\n\t\ttoolCallId: finalized.toolCall.id,\n\t\ttoolName: finalized.toolCall.name,\n\t\tcontent: finalized.result.content,\n\t\tdetails: stampToolResultEnvelope(finalized.result.details, finalized.envelope),\n\t\tisError: finalized.isError,\n\t\ttimestamp: Date.now(),\n\t});\n}\n\nasync function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n}\n\n/** Commit and notify one synthetic terminal for each unresolved, unstarted call. */\nasync function closeUnresolvedToolBatch(\n\tcurrentContext: AgentContext,\n\ttoolCalls: AgentToolCall[],\n\texistingResults: ToolResultMessage[],\n\temit: AgentEventSink,\n\tclosure?: { reason: string; disposition: \"aborted\" | \"skipped\" },\n): Promise<ToolResultMessage[]> {\n\tconst resolvedIds = new Set(existingResults.map((result) => result.toolCallId));\n\tconst synthesized: ToolResultMessage[] = [];\n\tfor (const toolCall of toolCalls) {\n\t\tif (resolvedIds.has(toolCall.id)) continue;\n\t\tconst result = createImmutableSnapshot(\n\t\t\tcreateSyntheticToolResult(\n\t\t\t\ttoolCall.id,\n\t\t\t\ttoolCall.name,\n\t\t\t\tclosure?.reason ?? \"Operation aborted\",\n\t\t\t\tDate.now(),\n\t\t\t\tclosure?.disposition ?? \"aborted\",\n\t\t\t),\n\t\t);\n\t\tcurrentContext.messages.push(result);\n\t\tawait emit({ type: \"message_start\", message: result });\n\t\tawait emit({ type: \"message_end\", message: result });\n\t\tsynthesized.push(result);\n\t\t// Guard against a duplicated call id within the same assistant message.\n\t\tresolvedIds.add(toolCall.id);\n\t}\n\treturn synthesized;\n}\n"]}
@@ -8,10 +8,13 @@ import { partitionToolBatchWaves } from "./parallel-tool-batch.js";
8
8
  import { pinProviderConfig, requestAssistantResponse } from "./provider-request.js";
9
9
  export { getVisionRouteModel, isVisionRouteModel, VISION_ROUTE_MODEL } from "./vision-route.js";
10
10
  import { deferredStillConflicts } from "./tool-dag-deferred.js";
11
- import { scheduleDagLevelsMemo as scheduleDagLevelsMemoFromModule } from "./tool-dag-memo.js";
11
+ import { resolveDagFrontierMemo } from "./tool-dag-memo.js";
12
+ import { finishDagTasks, startDagTask } from "./tool-dag-owned-task.js";
13
+ import { reduceDagDependencies } from "./tool-dag-reduce.js";
12
14
  import { applyConcurrencyCap, assignDagDependencies } from "./tool-dag-scheduler.js";
13
15
  import { awaitWithAbort, createErrorToolResult, createImmutableJsonSnapshot, createImmutableSnapshot, finalizeExecutedToolCall, parseJsonValue, stampToolResultEnvelope, } from "./tool-execution-boundary.js";
14
16
  import { resolveToolClaimsForCall } from "./tool-resource-claims.js";
17
+ import { indexFinalizedToolCalls } from "./tool-terminal-index.js";
15
18
  import { resolveToolTimeoutMs, runToolCallWithTimeout } from "./tool-timeout.js";
16
19
  import { hasUnsettledTimeout } from "./tool-timeout-settlement.js";
17
20
  import { createSyntheticToolResult, inspectTranscriptIntegrity, repairTranscriptIntegrity, } from "./tool-transcript-integrity.js";
@@ -540,13 +543,11 @@ async function executeToolCallsInWaves(currentContext, assistantMessage, toolCal
540
543
  return { messages, terminate: terminated, stopRun };
541
544
  }
542
545
  /**
543
- * Schedule planned calls into candidate DAG levels. Immediate plans fail
544
- * before any tool executes, so they carry no claims and fold into the first
545
- * level instead of degrading the whole batch to sequential singleton levels.
546
- * Unresolvable argument payloads stay in the schedule and fail closed into
547
- * exclusive barriers inside claim resolution.
546
+ * Resolve planned calls for the dependency ready frontier. Immediate outcomes
547
+ * carry no claims; unresolvable arguments become exclusive claim barriers.
548
+ * Barrier levels are a public compatibility schedule, not an admission input.
548
549
  */
549
- async function schedulePlannedDagLevels(plans, toolPolicies, boundTools, config, signal, dagScheduleCache) {
550
+ async function schedulePlannedDagFrontier(plans, toolPolicies, boundTools, config, signal, dagScheduleCache) {
550
551
  const schedulableSourceIndices = [];
551
552
  const claimableCalls = [];
552
553
  const immediateSourceIndices = [];
@@ -559,7 +560,7 @@ async function schedulePlannedDagLevels(plans, toolPolicies, boundTools, config,
559
560
  immediateSourceIndices.push(sourceIndex);
560
561
  }
561
562
  });
562
- const scheduled = await scheduleDagLevelsMemoFromModule(claimableCalls, {
563
+ const scheduled = await resolveDagFrontierMemo(claimableCalls, {
563
564
  cwd: config.cwd ?? process.cwd(),
564
565
  toolPolicies,
565
566
  registeredTools: boundTools,
@@ -568,10 +569,10 @@ async function schedulePlannedDagLevels(plans, toolPolicies, boundTools, config,
568
569
  resourceKeyResolver: config.resourceKeyResolver,
569
570
  }, signal, dagScheduleCache);
570
571
  if (scheduled === null) {
571
- return { levels: [], resolutions: new Map(), dependencies: new Map() };
572
+ return { order: [], resolutions: new Map(), dependencies: new Map() };
572
573
  }
573
574
  const resolutions = new Map();
574
- scheduled.entries.forEach((entry, position) => {
575
+ scheduled.forEach((entry, position) => {
575
576
  resolutions.set(schedulableSourceIndices[position], entry.resolution);
576
577
  });
577
578
  // Precedence graph in source-index space. Immediate plans carry no claims and
@@ -579,30 +580,22 @@ async function schedulePlannedDagLevels(plans, toolPolicies, boundTools, config,
579
580
  const dependencies = new Map();
580
581
  for (const sourceIndex of immediateSourceIndices)
581
582
  dependencies.set(sourceIndex, []);
582
- assignDagDependencies(scheduled.entries).forEach((blockers, position) => {
583
+ // The public dependency graph retains every conflict edge. The live frontier
584
+ // only needs ordering reachability, so discard transitive synchronization
585
+ // without changing which conflicts must settle before a call can start.
586
+ const frontierDependencies = reduceDagDependencies(assignDagDependencies(scheduled));
587
+ frontierDependencies.forEach((blockers, position) => {
583
588
  dependencies.set(schedulableSourceIndices[position], blockers.map((blocker) => schedulableSourceIndices[blocker]));
584
589
  });
585
- const levels = scheduled.levels.map((level) => level.map((position) => schedulableSourceIndices[position]));
586
- if (immediateSourceIndices.length === 0) {
587
- return { levels, resolutions, dependencies };
588
- }
589
- if (levels.length === 0) {
590
- return { levels: [[...immediateSourceIndices]], resolutions, dependencies };
591
- }
592
- levels[0] = [...levels[0], ...immediateSourceIndices].sort((left, right) => left - right);
593
- return { levels, resolutions, dependencies };
590
+ return { order: plans.map((_, sourceIndex) => sourceIndex), resolutions, dependencies };
594
591
  }
595
592
  /**
596
593
  * Execute a tool-call batch using the dag-v2 scheduler.
597
594
  *
598
- * Schedule every planned call through the DAG: immediate plans fail before
599
- * any tool executes, so they carry no claims and fold into the first level
600
- * instead of degrading the whole batch to sequential singleton levels.
601
- * Unresolvable argument payloads stay in the schedule and fail closed into
602
- * exclusive barriers inside claim resolution. Each candidate level authorizes
603
- * calls, re-resolves claims from exact final args, and emits lifecycle starts
604
- * only when a final safe sublevel begins. Results remain globally buffered
605
- * and are emitted in source order.
595
+ * Planned calls resolve claims in source order, while immediate failures carry
596
+ * no claims. The dependency frontier authorizes ready calls in source order,
597
+ * re-resolves claims from exact post-hook arguments, and starts only safe work.
598
+ * Results remain globally buffered and are emitted in source order.
606
599
  */
607
600
  async function executeToolCallsDagLevels(currentContext, assistantMessage, toolCalls, config, signal, emit, dagScheduleCache) {
608
601
  const plans = toolCalls.map((toolCall) => planToolCall(currentContext, toolCall));
@@ -613,8 +606,7 @@ async function executeToolCallsDagLevels(currentContext, assistantMessage, toolC
613
606
  if (mode && !toolPolicies.has(tool.name))
614
607
  toolPolicies.set(tool.name, mode);
615
608
  }
616
- const schedule = await schedulePlannedDagLevels(plans, toolPolicies, boundTools, config, signal, dagScheduleCache);
617
- const levels = schedule.levels;
609
+ const schedule = await schedulePlannedDagFrontier(plans, toolPolicies, boundTools, config, signal, dagScheduleCache);
618
610
  const batchState = {
619
611
  resolutions: schedule.resolutions,
620
612
  deferred: new Map(),
@@ -623,7 +615,7 @@ async function executeToolCallsDagLevels(currentContext, assistantMessage, toolC
623
615
  const finalizedByIndex = new Array(toolCalls.length).fill(undefined);
624
616
  let skippedReason;
625
617
  let stoppedByUnsettledTimeout = false;
626
- const frontier = await runDagFrontier(currentContext, assistantMessage, levels.flat(), schedule.dependencies, toolCalls, plans, toolPolicies, config, signal, emit, batchState);
618
+ const frontier = await runDagFrontier(currentContext, assistantMessage, schedule.order, schedule.dependencies, toolCalls, plans, toolPolicies, config, signal, emit, batchState);
627
619
  for (const outcome of frontier.outcomes)
628
620
  finalizedByIndex[outcome.sourceIndex] = outcome.finalized;
629
621
  if (frontier.stoppedByUnsettledTimeout) {
@@ -650,6 +642,7 @@ async function executeToolCallsDagLevels(currentContext, assistantMessage, toolC
650
642
  messages.push(createImmutableSnapshot(createSyntheticToolResult(toolCall.id, toolCall.name, skippedReason, Date.now(), "skipped")));
651
643
  }
652
644
  }
645
+ const finalizedById = indexFinalizedToolCalls(finalizedCalls);
653
646
  // Close the full source-ordered batch before result notification; calls not
654
647
  // reached by a candidate level receive no execution lifecycle.
655
648
  for (const message of messages) {
@@ -658,7 +651,7 @@ async function executeToolCallsDagLevels(currentContext, assistantMessage, toolC
658
651
  await emitToolResultMessage(message, emit);
659
652
  }
660
653
  finally {
661
- finalizedCalls.find(({ toolCall }) => toolCall.id === message.toolCallId)?.commitTerminal?.();
654
+ finalizedById.get(message.toolCallId)?.commitTerminal?.();
662
655
  }
663
656
  }
664
657
  return {
@@ -722,6 +715,7 @@ async function runDagFrontier(currentContext, assistantMessage, order, dependenc
722
715
  const outcomes = [];
723
716
  const pending = [...order].sort((left, right) => left - right);
724
717
  const running = new Map();
718
+ const taskErrors = [];
725
719
  // Mirrors applyConcurrencyCap: absent, non-finite, or non-positive is unbounded.
726
720
  const cap = typeof config.maxToolConcurrency === "number" &&
727
721
  Number.isFinite(config.maxToolConcurrency) &&
@@ -839,7 +833,7 @@ async function runDagFrontier(currentContext, assistantMessage, order, dependenc
839
833
  pending.splice(position, 1);
840
834
  admitted = true;
841
835
  await emitToolExecutionStart(preparation, emit);
842
- running.set(sourceIndex, (async () => {
836
+ running.set(sourceIndex, startDagTask(sourceIndex, async () => {
843
837
  const executed = await executePreparedToolCall(preparation, config, signal, emit);
844
838
  const finalized = await finalizeExecutedToolCall({
845
839
  currentContext,
@@ -851,7 +845,7 @@ async function runDagFrontier(currentContext, assistantMessage, order, dependenc
851
845
  });
852
846
  await emitToolExecutionEnd(finalized, emit);
853
847
  return { sourceIndex, finalized };
854
- })());
848
+ }));
855
849
  }
856
850
  if (running.size === 0) {
857
851
  // Nothing is in flight: either every call settled, or the remainder is
@@ -881,22 +875,16 @@ async function runDagFrontier(currentContext, assistantMessage, order, dependenc
881
875
  }
882
876
  const finished = await Promise.race([...running.values()]);
883
877
  running.delete(finished.sourceIndex);
884
- await settle(finished);
878
+ if (finished.status === "rejected")
879
+ throw finished.reason;
880
+ await settle(finished.value);
885
881
  }
886
882
  }
883
+ catch (error) {
884
+ taskErrors.push(error);
885
+ }
887
886
  finally {
888
- // Join work already in flight: cancellation, termination, and propagation
889
- // of preparation/event errors all preserve ownership of started
890
- // executions rather than abandoning them mid-flight.
891
- while (running.size > 0) {
892
- const entries = [...running.entries()];
893
- const drained = await Promise.allSettled(entries.map(([, task]) => task));
894
- for (const [index, drainedResult] of drained.entries()) {
895
- running.delete(entries[index][0]);
896
- if (drainedResult.status === "fulfilled")
897
- await settle(drainedResult.value);
898
- }
899
- }
887
+ await finishDagTasks(running, settle, taskErrors);
900
888
  }
901
889
  return { outcomes, stoppedByUnsettledTimeout, terminated };
902
890
  }