omk-agent-core 0.90.7 → 0.90.9
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.
- package/README.md +97 -1
- package/dist/agent-loop.d.ts +25 -2
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +524 -189
- package/dist/agent-loop.js.map +1 -1
- package/dist/agent.d.ts +29 -7
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +81 -46
- package/dist/agent.js.map +1 -1
- package/dist/builtin-tool-resource-claims.d.ts +19 -0
- package/dist/builtin-tool-resource-claims.d.ts.map +1 -0
- package/dist/builtin-tool-resource-claims.js +200 -0
- package/dist/builtin-tool-resource-claims.js.map +1 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/dist/node-resource-resolver.d.ts +42 -0
- package/dist/node-resource-resolver.d.ts.map +1 -0
- package/dist/node-resource-resolver.js +149 -0
- package/dist/node-resource-resolver.js.map +1 -0
- package/dist/node.d.ts +1 -0
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +2 -0
- package/dist/node.js.map +1 -1
- package/dist/parallel-tool-batch.d.ts +12 -1
- package/dist/parallel-tool-batch.d.ts.map +1 -1
- package/dist/parallel-tool-batch.js +71 -49
- package/dist/parallel-tool-batch.js.map +1 -1
- package/dist/path-segments.d.ts +21 -1
- package/dist/path-segments.d.ts.map +1 -1
- package/dist/path-segments.js +91 -9
- package/dist/path-segments.js.map +1 -1
- package/dist/plain-data.d.ts +7 -0
- package/dist/plain-data.d.ts.map +1 -0
- package/dist/plain-data.js +70 -0
- package/dist/plain-data.js.map +1 -0
- package/dist/tool-dag-scheduler.d.ts +86 -0
- package/dist/tool-dag-scheduler.d.ts.map +1 -0
- package/dist/tool-dag-scheduler.js +171 -0
- package/dist/tool-dag-scheduler.js.map +1 -0
- package/dist/tool-execution-boundary.d.ts +52 -0
- package/dist/tool-execution-boundary.d.ts.map +1 -0
- package/dist/tool-execution-boundary.js +185 -0
- package/dist/tool-execution-boundary.js.map +1 -0
- package/dist/tool-resource-claims.d.ts +31 -0
- package/dist/tool-resource-claims.d.ts.map +1 -0
- package/dist/tool-resource-claims.js +128 -0
- package/dist/tool-resource-claims.js.map +1 -0
- package/dist/tool-timeout.d.ts +96 -0
- package/dist/tool-timeout.d.ts.map +1 -0
- package/dist/tool-timeout.js +173 -0
- package/dist/tool-timeout.js.map +1 -0
- package/dist/tool-transcript-integrity.d.ts +65 -0
- package/dist/tool-transcript-integrity.d.ts.map +1 -0
- package/dist/tool-transcript-integrity.js +223 -0
- package/dist/tool-transcript-integrity.js.map +1 -0
- package/dist/types.d.ts +219 -10
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +50 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -104,7 +104,12 @@ Tool execution mode is configurable:
|
|
|
104
104
|
- `parallel` (default): preflight tool calls sequentially, execute allowed tools concurrently, emit `tool_execution_end` as soon as each tool is finalized, then emit toolResult messages and `turn_end.toolResults` in assistant source order
|
|
105
105
|
- `sequential`: execute tool calls one by one, matching the historical behavior
|
|
106
106
|
|
|
107
|
-
In parallel mode
|
|
107
|
+
In parallel mode the batch can be scheduled with one of two schedulers:
|
|
108
|
+
|
|
109
|
+
- `waves-v1` (historical): partitions the batch into ordered waves using `partitionToolBatchWaves`. Calls in the same wave run concurrently, and waves run one after another in source order. A fully safe batch is a single concurrent wave; bash, `clarify`, sequential-policy tools, unknown tools, and file tools with overlapping target paths become their own waves, so one conflicting call no longer serializes the independent rest of the batch.
|
|
110
|
+
- `dag-v2` (opt-in): builds a deterministic resource-claim DAG per call. Tools declare `resourceClaims` and an access mode (`read` or `write`); the scheduler runs independent calls in source-directed levels, keeps `bash`, unknown tools, and unclaimed extension tools exclusive, and still preserves source-order result artifacts. Set `toolScheduler: "dag-v2"` in `Agent` options to enable it. `OMK_TOOL_SCHEDULER=dag-v2` is also honored in the OMK CLI.
|
|
111
|
+
|
|
112
|
+
Tool completion events follow tool completion order, but persisted toolResult messages still follow assistant source order.
|
|
108
113
|
|
|
109
114
|
The mode can be set globally via `toolExecution` in the agent config, or per-tool via `executionMode` on `AgentTool`. If any tool call in a batch targets a tool with `executionMode: "sequential"`, the entire batch executes sequentially regardless of the global setting.
|
|
110
115
|
|
|
@@ -153,6 +158,7 @@ The last message in context must be `user` or `toolResult` (not `assistant`).
|
|
|
153
158
|
| `tool_execution_start` | Tool begins |
|
|
154
159
|
| `tool_execution_update` | Tool streams progress |
|
|
155
160
|
| `tool_execution_end` | Tool completes |
|
|
161
|
+
| `tool_execution_late_settlement` | Tool promise settled after a terminal result was already committed (audit only) |
|
|
156
162
|
|
|
157
163
|
`Agent.subscribe()` listeners are awaited in registration order. `agent_end` means no more loop events will be emitted, but `await agent.waitForIdle()` and `await agent.prompt(...)` only settle after awaited `agent_end` listeners finish.
|
|
158
164
|
|
|
@@ -191,8 +197,45 @@ const agent = new Agent({
|
|
|
191
197
|
getApiKey: async (provider) => refreshToken(),
|
|
192
198
|
|
|
193
199
|
// Tool execution mode: "parallel" (default) or "sequential"
|
|
200
|
+
// Also "toolExecution: 'sequential'" forces waves/dag schedulers to run serially.
|
|
194
201
|
toolExecution: "parallel",
|
|
195
202
|
|
|
203
|
+
// Tool scheduler: "waves-v1" (default) or "dag-v2" (resource-claim DAG)
|
|
204
|
+
toolScheduler: "waves-v1",
|
|
205
|
+
|
|
206
|
+
// Maximum concurrent tool calls in one DAG level when using "dag-v2".
|
|
207
|
+
// 0 removes the cap. Default in the OMK CLI is 4.
|
|
208
|
+
maxToolConcurrency: 4,
|
|
209
|
+
|
|
210
|
+
// Require extension tools to declare resource claims when using "dag-v2".
|
|
211
|
+
// When true, unclaimed extension tools are treated as exclusive.
|
|
212
|
+
strictExtensionClaims: false,
|
|
213
|
+
|
|
214
|
+
// Working directory used for claim resolution and local tool backends.
|
|
215
|
+
cwd: process.cwd(),
|
|
216
|
+
|
|
217
|
+
// Custom resource-key resolver for dag-v2. The default Node resolver uses
|
|
218
|
+
// cwd-relative paths and common OMK namespaces. Import it from
|
|
219
|
+
// `omk-agent-core/node` if you need to customize it.
|
|
220
|
+
// resourceKeyResolver: createNodeResourceKeyResolver({ cwd: process.cwd() }),
|
|
221
|
+
|
|
222
|
+
// Fallback tool timeout in milliseconds. 0 disables the fallback timer.
|
|
223
|
+
// Individual tools can also set timeoutMs; toolTimeouts[name] overrides this.
|
|
224
|
+
toolTimeoutMs: 0,
|
|
225
|
+
|
|
226
|
+
// Per-tool timeout overrides in milliseconds. 0 disables that tool's timer.
|
|
227
|
+
toolTimeouts: {
|
|
228
|
+
read: 30_000,
|
|
229
|
+
bash: 300_000,
|
|
230
|
+
},
|
|
231
|
+
|
|
232
|
+
// What to do when a tool promise settles after timeout/abort has already
|
|
233
|
+
// committed a synthetic result. "audit" (default) emits a
|
|
234
|
+
// tool_execution_late_settlement event; "ignore" silently drops it.
|
|
235
|
+
toolExecutionPolicy: {
|
|
236
|
+
lateSettlement: "audit",
|
|
237
|
+
},
|
|
238
|
+
|
|
196
239
|
// Preflight each tool call after args are validated. Can block execution.
|
|
197
240
|
beforeToolCall: async ({ toolCall, args, context }) => {
|
|
198
241
|
if (toolCall.name === "bash") {
|
|
@@ -395,6 +438,17 @@ const readFileTool: AgentTool = {
|
|
|
395
438
|
// "parallel" allows concurrent execution with other tool calls.
|
|
396
439
|
// If omitted, the global toolExecution config applies.
|
|
397
440
|
executionMode: "sequential",
|
|
441
|
+
|
|
442
|
+
// Resource claims for dag-v2 scheduling. Return "exclusive" to run alone,
|
|
443
|
+
// or a claim list. Omit to let the tool run exclusively (or as an unclaimed
|
|
444
|
+
// extension tool when strictExtensionClaims is false).
|
|
445
|
+
resourceClaims: (args, context) => [
|
|
446
|
+
{ kind: "path", path: args.path, access: "read" },
|
|
447
|
+
],
|
|
448
|
+
|
|
449
|
+
// Per-tool timeout in milliseconds. 0 disables the timer for this tool.
|
|
450
|
+
timeoutMs: 30_000,
|
|
451
|
+
|
|
398
452
|
execute: async (toolCallId, params, signal, onUpdate) => {
|
|
399
453
|
const content = await fs.readFile(params.path, "utf-8");
|
|
400
454
|
|
|
@@ -431,6 +485,48 @@ Thrown errors are caught by the agent and reported to the LLM as tool errors wit
|
|
|
431
485
|
|
|
432
486
|
Return `terminate: true` from `execute()` or `afterToolCall` to hint that the agent should stop after the current tool batch. This only takes effect when every finalized tool result in the batch is terminating. The hint is runtime-only; emitted `toolResult` transcript messages remain standard LLM tool results.
|
|
433
487
|
|
|
488
|
+
### Tool Timeouts and Late Settlement
|
|
489
|
+
|
|
490
|
+
Every tool call is guarded by a timeout. The effective timeout for a call is resolved in order:
|
|
491
|
+
|
|
492
|
+
1. `AgentTool.timeoutMs` (per tool)
|
|
493
|
+
2. `AgentLoopConfig.toolTimeouts[name]` (per-name override)
|
|
494
|
+
3. `AgentLoopConfig.toolTimeoutMs` (fallback)
|
|
495
|
+
4. No timer when all of the above are `0` or unset
|
|
496
|
+
|
|
497
|
+
When a timeout wins the race, the agent closes the tool call and commits a synthetic terminal result with a `timeout` disposition. The same happens for `abort` or blocked calls. The LLM still sees the tool result, but the terminal envelope records why the call ended.
|
|
498
|
+
|
|
499
|
+
If the real tool promise settles after the terminal result has already been committed, the agent emits a `tool_execution_late_settlement` event (when `toolExecutionPolicy.lateSettlement` is `"audit"`, the default). The event is advisory: it does not change the transcript that the LLM sees.
|
|
500
|
+
|
|
501
|
+
```typescript
|
|
502
|
+
agent.subscribe((event) => {
|
|
503
|
+
if (event.type === "tool_execution_late_settlement") {
|
|
504
|
+
console.log("Late settlement:", event.toolCallId, event.toolName);
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
### Tool Result Dispositions and Transcript Integrity
|
|
510
|
+
|
|
511
|
+
Every terminal tool result carries a `details.omk` envelope with a `ToolCallDisposition`:
|
|
512
|
+
|
|
513
|
+
- `completed` - Normal success
|
|
514
|
+
- `failed` - Tool threw an error
|
|
515
|
+
- `blocked` - `beforeToolCall` blocked execution
|
|
516
|
+
- `aborted` - Caller aborted the run
|
|
517
|
+
- `timeout` - Tool exceeded its timeout
|
|
518
|
+
- `skipped` - Tool was skipped (e.g. duplicate call after transcript repair)
|
|
519
|
+
|
|
520
|
+
The loop enforces transcript integrity on every continuation and provider request. It checks for:
|
|
521
|
+
|
|
522
|
+
- Duplicate tool-call IDs
|
|
523
|
+
- Orphan tool results (no matching call)
|
|
524
|
+
- Duplicate results for the same call
|
|
525
|
+
- Interleaved non-result messages between a call and its result
|
|
526
|
+
- Missing results for finalized tool calls
|
|
527
|
+
|
|
528
|
+
Unambiguous missing-only tail results are repaired by synthesizing skipped/error results. Corrupt or ambiguous transcripts fail closed with an error rather than fabricating an assistant message. This is why thrown errors should be real errors, not strings returned as content.
|
|
529
|
+
|
|
434
530
|
## Proxy Usage
|
|
435
531
|
|
|
436
532
|
For browser apps that proxy through a backend:
|
package/dist/agent-loop.d.ts
CHANGED
|
@@ -2,9 +2,32 @@
|
|
|
2
2
|
* Agent loop that works with AgentMessage throughout.
|
|
3
3
|
* Transforms to Message[] only at the LLM call boundary.
|
|
4
4
|
*/
|
|
5
|
-
import { EventStream } from "omk-ai";
|
|
6
|
-
import type
|
|
5
|
+
import { EventStream, type Model, type ToolResultMessage } from "omk-ai";
|
|
6
|
+
import { type AgentContext, type AgentEvent, type AgentLoopConfig, type AgentMessage, type StreamFn } from "./types.ts";
|
|
7
7
|
export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
|
|
8
|
+
export interface FailureTerminationPlan {
|
|
9
|
+
/** Messages to publish as the run result (closure results + optional failure). */
|
|
10
|
+
messages: AgentMessage[];
|
|
11
|
+
/** Synthetic assistant failure message, or `undefined` when fail-closed. */
|
|
12
|
+
failureMessage: AgentMessage | undefined;
|
|
13
|
+
/** Synthetic tool results used to close an open turn, in source order. */
|
|
14
|
+
closureResults: ToolResultMessage[];
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Decide how to terminate a run after the underlying loop rejected.
|
|
18
|
+
*
|
|
19
|
+
* A synthetic assistant failure may only be appended on top of a transcript
|
|
20
|
+
* whose tool turns are all closed. When `completedMessages` ends with an open
|
|
21
|
+
* tool turn, a safe missing-only closure (synthetic results for the unambiguous
|
|
22
|
+
* missing tail calls) is appended first so the failure assistant never creates
|
|
23
|
+
* an `assistant(tool calls) -> assistant(failure)` interleaving.
|
|
24
|
+
*
|
|
25
|
+
* If the transcript is ambiguous (duplicate/orphan/interleave, or a
|
|
26
|
+
* mid-transcript gap) it is never auto-repaired: the plan returns no failure
|
|
27
|
+
* message so the caller ends the stream without fabricating a turn over
|
|
28
|
+
* corruption. Pure apart from `Date.now()` on the failure message.
|
|
29
|
+
*/
|
|
30
|
+
export declare function planFailureTermination(completedMessages: readonly AgentMessage[], model: Model<any>, error: unknown, aborted: boolean): FailureTerminationPlan;
|
|
8
31
|
/**
|
|
9
32
|
* Start an agent loop with a new prompt message.
|
|
10
33
|
* The prompt is added to the context and events are emitted for it.
|
package/dist/agent-loop.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAGN,WAAW,EAIX,MAAM,QAAQ,CAAC;AAEhB,OAAO,KAAK,EACX,YAAY,EACZ,UAAU,EACV,eAAe,EACf,YAAY,EAIZ,QAAQ,EACR,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAiDzE;;;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,CAgBzB;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,CAezB","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 Context,\n\tEventStream,\n\tstreamSimple,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"omk-ai\";\nimport { shouldParallelizeToolBatch } from \"./parallel-tool-batch.ts\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tStreamFn,\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\n/**\n * Terminate the public event stream after the underlying loop rejected.\n *\n * Mirrors `Agent.handleRunFailure`: synthesizes an assistant failure message\n * so consumers observe a coherent message_start/message_end/turn_end/agent_end\n * sequence, then ends the stream so `for await` consumers and `stream.result()`\n * always settle.\n *\n * Invariant: non-abort failures keep stopReason \"error\" and the same event\n * sequence; when the loop signal was aborted, the synthetic message reports\n * stopReason \"aborted\".\n */\nfunction endStreamWithFailure(\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tconfig: AgentLoopConfig,\n\tcompletedMessages: AgentMessage[],\n\terror: unknown,\n\tsignal?: AbortSignal,\n): void {\n\tconst failureMessage = {\n\t\trole: \"assistant\",\n\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\tapi: config.model.api,\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\tusage: EMPTY_USAGE,\n\t\tstopReason: signal?.aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t} satisfies AgentMessage;\n\tconst messages = [...completedMessages, failureMessage];\n\tstream.push({ type: \"message_start\", message: failureMessage });\n\tstream.push({ type: \"message_end\", message: failureMessage });\n\tstream.push({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\tstream.push({ type: \"agent_end\", messages });\n\tstream.end(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\tassertContinuableTail(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 = {\n\t\t...context,\n\t\tmessages: [...context.messages, ...prompts],\n\t};\n\n\tawait emit({ type: \"agent_start\" });\n\tawait emit({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\tawait emit({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, 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\tassertContinuableTail(context.messages);\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context };\n\n\tawait emit({ type: \"agent_start\" });\n\tawait emit({ type: \"turn_start\" });\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, 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 that the final message in `messages` is one a provider can continue\n * from without an opaque rejection.\n *\n * - A trailing user/toolResult message is always fine.\n * - A trailing assistant turn is fine ONLY when it carries no unresolved tool\n * calls. If it does carry tool calls, there is no matching toolResult to send\n * and every provider (OpenAI/Anthropic/Google) rejects the request, so we\n * fail fast with a clear, actionable error.\n *\n * This intentionally does NOT inspect `convertToLlm` output: that transform is\n * provider-specific and runs once per turn. The conservative check here keeps\n * the common \"continue after a finished text answer\" path working (compaction,\n * session resume, explicit retries) while still protecting the broken tool-call\n * case.\n */\nfunction assertContinuableTail(messages: AgentMessage[]): void {\n\tconst last = messages[messages.length - 1];\n\tif (last.role !== \"assistant\") {\n\t\treturn;\n\t}\n\tconst hasPendingToolCalls = last.content.some((c) => c.type === \"toolCall\");\n\tif (hasPendingToolCalls) {\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}\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\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await 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} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Process pending messages (inject before next assistant response)\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tnewMessages.push(message);\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Stream assistant response\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tnewMessages.push(message);\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\thasMoreToolCalls = false;\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tconst executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit);\n\t\t\t\ttoolResults.push(...executedToolBatch.messages);\n\t\t\t\thasMoreToolCalls = !executedToolBatch.terminate;\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\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\tcurrentContext = nextTurnSnapshot.context ?? currentContext;\n\t\t\t\tconfig = {\n\t\t\t\t\t...config,\n\t\t\t\t\tmodel: nextTurnSnapshot.model ?? config.model,\n\t\t\t\t\treasoning:\n\t\t\t\t\t\tnextTurnSnapshot.thinkingLevel === undefined\n\t\t\t\t\t\t\t? config.reasoning\n\t\t\t\t\t\t\t: nextTurnSnapshot.thinkingLevel === \"off\"\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: nextTurnSnapshot.thinkingLevel,\n\t\t\t\t};\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 config.getSteeringMessages?.()) || [];\n\t\t}\n\n\t\t// Agent would stop here. Check for follow-up messages.\n\t\tconst followUpMessages = (await 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\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\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// 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}\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\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\tconst streamFunction = streamFn || streamSimple;\n\n\t// Resolve API key (important for expiring tokens)\n\tconst resolvedApiKey =\n\t\t(config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;\n\n\tconst response = await streamFunction(config.model, llmContext, {\n\t\t...config,\n\t\tapiKey: resolvedApiKey,\n\t\tsignal,\n\t});\n\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\n\t\t\tcase \"text_start\":\n\t\t\tcase \"text_delta\":\n\t\t\tcase \"text_end\":\n\t\t\tcase \"thinking_start\":\n\t\t\tcase \"thinking_delta\":\n\t\t\tcase \"thinking_end\":\n\t\t\tcase \"toolcall_start\":\n\t\t\tcase \"toolcall_delta\":\n\t\t\tcase \"toolcall_end\":\n\t\t\t\tif (partialMessage) {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\tawait emit({\n\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"done\":\n\t\t\tcase \"error\": {\n\t\t\t\tconst finalMessage = await response.result();\n\t\t\t\tif (addedPartial) {\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t} else {\n\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t}\n\t\t\t\tif (!addedPartial) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t\t}\n\t\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\t\treturn finalMessage;\n\t\t\t}\n\t\t}\n\t}\n\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/**\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): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\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 batchParallelizable = shouldParallelizeToolBatch(\n\t\ttoolCalls.map((tc) => ({ name: tc.name, arguments: tc.arguments as Record<string, unknown> })),\n\t\t{\n\t\t\tcwd: config.cwd ?? process.cwd(),\n\t\t\ttoolPolicies,\n\t\t\tallowUnknownParallel: (toolName) => toolPolicies.get(toolName) === \"parallel\",\n\t\t},\n\t);\n\tif (config.toolExecution === \"sequential\" || hasSequentialToolCall || !batchParallelizable) {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\tterminate: 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\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\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};\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, signal, emit);\n\t\t\tfinalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t);\n\t\t}\n\n\t\tawait emitToolExecutionEnd(finalized, emit);\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\tfinalizedCalls.push(finalized);\n\t\tmessages.push(toolResultMessage);\n\n\t\tif (signal?.aborted) {\n\t\t\tbreak;\n\t\t}\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\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\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} satisfies FinalizedToolCallOutcome;\n\t\t\tawait emitToolExecutionEnd(finalized, emit);\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\tconst executed = await executePreparedToolCall(preparation, signal, emit);\n\t\t\tconst finalized = await finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\tpreparation,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\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\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\tmessages.push(toolResultMessage);\n\t}\n\n\treturn {\n\t\tmessages,\n\t\tterminate: shouldTerminateToolBatch(orderedFinalizedCalls),\n\t};\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype FinalizedToolCallOutcome = {\n\ttoolCall: AgentToolCall;\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\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\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 tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst preparedToolCall = prepareToolCallArguments(tool, toolCall);\n\t\tconst validatedArgs = validateToolArguments(tool, preparedToolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await config.beforeToolCall(\n\t\t\t\t{\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall,\n\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (signal?.aborted) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(\"Operation aborted\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (signal?.aborted) {\n\t\t\treturn {\n\t\t\t\tkind: \"immediate\",\n\t\t\t\tresult: createErrorToolResult(\"Operation aborted\"),\n\t\t\t\tisError: true,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst updateEvents: Promise<void>[] = [];\n\n\ttry {\n\t\tconst result = await prepared.tool.execute(\n\t\t\tprepared.toolCall.id,\n\t\t\tprepared.args as never,\n\t\t\tsignal,\n\t\t\t(partialResult) => {\n\t\t\t\tupdateEvents.push(\n\t\t\t\t\tPromise.resolve(\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t\tawait Promise.all(updateEvents);\n\t\treturn { result, isError: false };\n\t} catch (error) {\n\t\tawait Promise.all(updateEvents);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<FinalizedToolCallOutcome> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\ttry {\n\t\t\tconst afterResult = await config.afterToolCall(\n\t\t\t\t{\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\t\targs: prepared.args,\n\t\t\t\t\tresult,\n\t\t\t\t\tisError,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (afterResult) {\n\t\t\t\tresult = {\n\t\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t\t\tterminate: afterResult.terminate ?? result.terminate,\n\t\t\t\t};\n\t\t\t\tisError = afterResult.isError ?? isError;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tresult = createErrorToolResult(error instanceof Error ? error.message : String(error));\n\t\t\tisError = true;\n\t\t}\n\t}\n\n\treturn {\n\t\ttoolCall: prepared.toolCall,\n\t\tresult,\n\t\tisError,\n\t};\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\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: finalized.result,\n\t\tisError: finalized.isError,\n\t});\n}\n\nfunction createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {\n\treturn {\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: finalized.result.details,\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"]}
|
|
1
|
+
{"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAGN,WAAW,EACX,KAAK,KAAK,EAEV,KAAK,iBAAiB,EAEtB,MAAM,QAAQ,CAAC;AAqBhB,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,eAAe,EACpB,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,CAczB;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,CAezB","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 Context,\n\tEventStream,\n\ttype Model,\n\tstreamSimple,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"omk-ai\";\nimport { bindToolIdentity, isPlainArguments } from \"./builtin-tool-resource-claims.ts\";\nimport { partitionToolBatchWaves } from \"./parallel-tool-batch.ts\";\nimport { scheduleDagLevels } 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 { resolveToolTimeoutMs, runToolCallWithTimeout } from \"./tool-timeout.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 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\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, config, 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\n\tawait publish({ type: \"agent_start\" });\n\tawait publish({ type: \"turn_start\" });\n\tawait runLoop(currentContext, newMessages, config, 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/**\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\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await 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} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Process pending messages (inject before next assistant response)\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tnewMessages.push(message);\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Stream assistant response\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\tconst emittedIntegrity = inspectTranscriptIntegrity(currentContext.messages);\n\t\t\tconst emittedAmbiguities = emittedIntegrity.issues.filter((issue) => issue.kind !== \"missing_result\");\n\t\t\tif (emittedAmbiguities.length > 0) {\n\t\t\t\tconst summary = emittedAmbiguities.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\t\t\t\tthrow new Error(`Refusing tool execution: invalid emitted tool transcript (${summary}).`);\n\t\t\t}\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\tconst toolResults: ToolResultMessage[] = [];\n\t\t\t\tconst reason =\n\t\t\t\t\tmessage.stopReason === \"aborted\"\n\t\t\t\t\t\t? \"Operation aborted\"\n\t\t\t\t\t\t: \"Skipped because the provider terminated before tool execution\";\n\t\t\t\tconst disposition = message.stopReason === \"aborted\" ? \"aborted\" : \"skipped\";\n\t\t\t\tfor (const toolCall of toolCalls) {\n\t\t\t\t\tconst result = createImmutableSnapshot(\n\t\t\t\t\t\tcreateSyntheticToolResult(toolCall.id, toolCall.name, reason, Date.now(), disposition),\n\t\t\t\t\t);\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t\ttoolResults.push(result);\n\t\t\t\t\tawait emitToolResultMessage(result, emit);\n\t\t\t\t}\n\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\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 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 executedToolBatch = await executeToolCalls(currentContext, message, config, signal, emit);\n\t\t\t\ttoolResults.push(...executedToolBatch.messages);\n\t\t\t\thasMoreToolCalls = !executedToolBatch.terminate;\n\t\t\t\tstopAfterToolBatch = executedToolBatch.stopRun ?? false;\n\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t// Close only unresolved calls, preserving finalized results, then stop\n\t\t\t\t\t// before hooks, queues, or another provider request.\n\t\t\t\t\tconst synthesized = await closeAbortedToolBatch(currentContext, toolCalls, toolResults, emit);\n\t\t\t\t\ttoolResults.push(...synthesized);\n\t\t\t\t\tfor (const result of toolResults) newMessages.push(result);\n\t\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\t\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tfor (const result of toolResults) newMessages.push(result);\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\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\tcurrentContext = nextTurnSnapshot.context ?? currentContext;\n\t\t\t\tconfig = {\n\t\t\t\t\t...config,\n\t\t\t\t\tmodel: nextTurnSnapshot.model ?? config.model,\n\t\t\t\t\treasoning:\n\t\t\t\t\t\tnextTurnSnapshot.thinkingLevel === undefined\n\t\t\t\t\t\t\t? config.reasoning\n\t\t\t\t\t\t\t: nextTurnSnapshot.thinkingLevel === \"off\"\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: nextTurnSnapshot.thinkingLevel,\n\t\t\t\t};\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 config.getSteeringMessages?.()) || [];\n\t\t}\n\n\t\t// Agent would stop here. Check for follow-up messages.\n\t\tconst followUpMessages = (await 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\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\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\tconst integrityReport = inspectTranscriptIntegrity(context.messages);\n\tif (!integrityReport.ok) {\n\t\tconst summary = integrityReport.issues.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\t\tthrow new Error(\n\t\t\t`Refusing provider request: invalid tool transcript (${summary}). ` +\n\t\t\t\t\"Append terminal tool results or repair the transcript before retrying.\",\n\t\t);\n\t}\n\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\tconst transformedIntegrity = inspectTranscriptIntegrity(messages);\n\t\tif (!transformedIntegrity.ok) {\n\t\t\tconst summary = transformedIntegrity.issues.map((issue) => `${issue.kind}:${issue.toolCallId}`).join(\", \");\n\t\t\tthrow new Error(`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\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\tconst streamFunction = streamFn || streamSimple;\n\n\t// Resolve API key (important for expiring tokens)\n\tconst resolvedApiKey =\n\t\t(config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;\n\n\tconst response = await streamFunction(config.model, llmContext, {\n\t\t...config,\n\t\tapiKey: resolvedApiKey,\n\t\tsignal,\n\t});\n\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\n\t\t\tcase \"text_start\":\n\t\t\tcase \"text_delta\":\n\t\t\tcase \"text_end\":\n\t\t\tcase \"thinking_start\":\n\t\t\tcase \"thinking_delta\":\n\t\t\tcase \"thinking_end\":\n\t\t\tcase \"toolcall_start\":\n\t\t\tcase \"toolcall_delta\":\n\t\t\tcase \"toolcall_end\":\n\t\t\t\tif (partialMessage) {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\tawait emit({\n\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"done\":\n\t\t\tcase \"error\": {\n\t\t\t\tconst finalMessage = await response.result();\n\t\t\t\tif (addedPartial) {\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t} else {\n\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t}\n\t\t\t\tif (!addedPartial) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t\t}\n\t\t\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\t\t\treturn finalMessage;\n\t\t\t}\n\t\t}\n\t}\n\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/**\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): Promise<ExecutedToolCallBatch> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\t// dag-v2 is opt-in only. An explicit sequential execution mode takes\n\t// precedence and continues through the established waves-v1 path below.\n\tif (config.toolScheduler === \"dag-v2\" && config.toolExecution !== \"sequential\") {\n\t\treturn executeToolCallsDagLevels(currentContext, assistantMessage, toolCalls, config, signal, emit);\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 = partitionToolBatchWaves(\n\t\ttoolCalls.map((tc) => ({ name: tc.name, arguments: tc.arguments as Record<string, unknown> })),\n\t\t{\n\t\t\tcwd: config.cwd ?? process.cwd(),\n\t\t\ttoolPolicies,\n\t\t\tallowUnknownParallel: (toolName) => toolPolicies.get(toolName) === \"parallel\",\n\t\t},\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.\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\tconst waveTerminates: boolean[] = [];\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\twaveTerminates.push(executedWave.terminate);\n\t\tif (signal?.aborted) break;\n\t}\n\treturn {\n\t\tmessages,\n\t\tterminate: waveTerminates.length > 0 && waveTerminates.every(Boolean),\n\t};\n}\n\n/**\n * Execute a tool-call batch using the dag-v2 scheduler.\n *\n * Initial planning applies only the pure argument compatibility shim. Each\n * candidate level authorizes calls, re-resolves claims from exact final args,\n * and emits lifecycle starts only when a final safe sublevel begins. Results\n * 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): 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\tif (tool.executionMode && !toolPolicies.has(tool.name)) toolPolicies.set(tool.name, tool.executionMode);\n\t}\n\n\tconst claimableCalls: Array<{ id: string; name: string; arguments: Record<string, unknown> }> = [];\n\tfor (const plan of plans) {\n\t\tif (plan.kind === \"immediate\" || !isPlainArguments(plan.args)) {\n\t\t\tclaimableCalls.length = 0;\n\t\t\tbreak;\n\t\t}\n\t\tclaimableCalls.push({ id: plan.toolCall.id, name: plan.toolCall.name, arguments: plan.args });\n\t}\n\tlet levels: number[][];\n\tif (claimableCalls.length === toolCalls.length) {\n\t\tconst scheduled = await awaitWithAbort(\n\t\t\t() =>\n\t\t\t\tscheduleDagLevels(claimableCalls, {\n\t\t\t\t\tcwd: config.cwd ?? process.cwd(),\n\t\t\t\t\ttoolPolicies,\n\t\t\t\t\tregisteredTools: boundTools,\n\t\t\t\t\tstrictExtensionClaims: config.strictExtensionClaims,\n\t\t\t\t\tmaxConcurrency: config.maxToolConcurrency,\n\t\t\t\t\tresourceKeyResolver: config.resourceKeyResolver,\n\t\t\t\t}),\n\t\t\tsignal,\n\t\t);\n\t\tlevels = scheduled.kind === \"aborted\" ? [] : scheduled.value.levels;\n\t} else {\n\t\tlevels = toolCalls.map((_toolCall, sourceIndex) => [sourceIndex]);\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\tfor (const level of levels) {\n\t\tif (signal?.aborted) break;\n\t\tconst executedLevel = await runDagLevelCalls(\n\t\t\tcurrentContext,\n\t\t\tassistantMessage,\n\t\t\tlevel,\n\t\t\ttoolCalls,\n\t\t\tplans,\n\t\t\ttoolPolicies,\n\t\t\tconfig,\n\t\t\tsignal,\n\t\t\temit,\n\t\t);\n\t\tfor (const outcome of executedLevel.outcomes) finalizedByIndex[outcome.sourceIndex] = outcome.finalized;\n\t\tif (signal?.aborted) break;\n\t\tif (executedLevel.stoppedByUnsettledTimeout) {\n\t\t\tskippedReason = \"Skipped because a preceding DAG tool timed out before its execution promise settled\";\n\t\t\tstoppedByUnsettledTimeout = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (shouldTerminateToolBatch(executedLevel.outcomes.map((outcome) => outcome.finalized))) {\n\t\t\tskippedReason = \"Skipped because the preceding DAG level requested termination\";\n\t\t\tbreak;\n\t\t}\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/** Authorize one candidate DAG level, re-plan final claims, and run its safe sublevels. */\nasync function runDagLevelCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tlevelIndices: readonly 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): Promise<{ outcomes: DagLevelOutcome[]; stoppedByUnsettledTimeout: boolean }> {\n\tconst outcomes: DagLevelOutcome[] = [];\n\tconst runnable: Array<{ sourceIndex: number; preparation: PreparedToolCall }> = [];\n\n\tfor (const sourceIndex of levelIndices) {\n\t\tconst toolCall = toolCalls[sourceIndex];\n\t\tconst plan = plans[sourceIndex];\n\t\tconst preparation =\n\t\t\tplan.kind === \"immediate\"\n\t\t\t\t? plan\n\t\t\t\t: await authorizePlannedToolCall(currentContext, assistantMessage, plan, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\toutcomes.push({\n\t\t\t\tsourceIndex,\n\t\t\t\tfinalized: {\n\t\t\t\t\ttoolCall,\n\t\t\t\t\tresult: preparation.result,\n\t\t\t\t\tisError: preparation.isError,\n\t\t\t\t\tenvelope: preparation.envelope,\n\t\t\t\t},\n\t\t\t});\n\t\t} else {\n\t\t\trunnable.push({ sourceIndex, preparation });\n\t\t}\n\t\tif (signal?.aborted) return { outcomes, stoppedByUnsettledTimeout: false };\n\t}\n\n\tconst finalClaimableCalls: Array<{ id: string; name: string; arguments: Record<string, unknown> }> = [];\n\tfor (const { preparation } of runnable) {\n\t\tif (!isPlainArguments(preparation.args)) {\n\t\t\tfinalClaimableCalls.length = 0;\n\t\t\tbreak;\n\t\t}\n\t\tfinalClaimableCalls.push({\n\t\t\tid: preparation.toolCall.id,\n\t\t\tname: preparation.toolCall.name,\n\t\t\targuments: preparation.args,\n\t\t});\n\t}\n\n\tlet executionLevels: number[][];\n\tif (finalClaimableCalls.length === runnable.length) {\n\t\tconst scheduled = await awaitWithAbort(\n\t\t\t() =>\n\t\t\t\tscheduleDagLevels(finalClaimableCalls, {\n\t\t\t\t\tcwd: config.cwd ?? process.cwd(),\n\t\t\t\t\ttoolPolicies,\n\t\t\t\t\tregisteredTools: runnable.map(({ preparation }) => preparation.tool),\n\t\t\t\t\tstrictExtensionClaims: config.strictExtensionClaims,\n\t\t\t\t\tmaxConcurrency: config.maxToolConcurrency,\n\t\t\t\t\tresourceKeyResolver: config.resourceKeyResolver,\n\t\t\t\t}),\n\t\t\tsignal,\n\t\t);\n\t\tif (scheduled.kind === \"aborted\") return { outcomes, stoppedByUnsettledTimeout: false };\n\t\texecutionLevels = scheduled.value.levels;\n\t} else {\n\t\texecutionLevels = runnable.map((_entry, index) => [index]);\n\t}\n\n\tfor (const executionLevel of executionLevels) {\n\t\tif (signal?.aborted) break;\n\t\tfor (const entryIndex of executionLevel) {\n\t\t\tawait emitToolExecutionStart(runnable[entryIndex].preparation, emit);\n\t\t}\n\t\tconst finalizedLevel = await Promise.all(\n\t\t\texecutionLevel.map(async (entryIndex): Promise<DagLevelOutcome> => {\n\t\t\t\tconst entry = runnable[entryIndex];\n\t\t\t\tconst executed = await executePreparedToolCall(entry.preparation, config, signal, emit);\n\t\t\t\tconst finalized = await finalizeExecutedToolCall({\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\tprepared: entry.preparation,\n\t\t\t\t\texecuted,\n\t\t\t\t\tafterToolCall: config.afterToolCall,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\t\t\t\tawait emitToolExecutionEnd(finalized, emit);\n\t\t\t\treturn { sourceIndex: entry.sourceIndex, finalized };\n\t\t\t}),\n\t\t);\n\t\toutcomes.push(...finalizedLevel);\n\t\tif (signal?.aborted) break;\n\t\tif (\n\t\t\tfinalizedLevel.some(\n\t\t\t\t({ finalized }) =>\n\t\t\t\t\tfinalized.envelope.disposition === \"timeout\" && finalized.isRealPromiseSettled?.() === false,\n\t\t\t)\n\t\t) {\n\t\t\treturn { outcomes, stoppedByUnsettledTimeout: true };\n\t\t}\n\t}\n\treturn { outcomes, stoppedByUnsettledTimeout: false };\n}\n\ntype ExecutedToolCallBatch = {\n\tmessages: ToolResultMessage[];\n\tterminate: boolean;\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 (signal?.aborted) {\n\t\t\tbreak;\n\t\t}\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\treturn {\n\t\tmessages,\n\t\tterminate: shouldTerminateToolBatch(orderedFinalizedCalls),\n\t};\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 aborted terminal for each unresolved, unstarted call. */\nasync function closeAbortedToolBatch(\n\tcurrentContext: AgentContext,\n\ttoolCalls: AgentToolCall[],\n\texistingResults: ToolResultMessage[],\n\temit: AgentEventSink,\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)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = createImmutableSnapshot(\n\t\t\tcreateSyntheticToolResult(toolCall.id, toolCall.name, \"Operation aborted\"),\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"]}
|