@handy_wote/pi-agent-core 0.81.1

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 (102) hide show
  1. package/README.md +507 -0
  2. package/dist/agent-loop.d.ts +24 -0
  3. package/dist/agent-loop.d.ts.map +1 -0
  4. package/dist/agent-loop.js +549 -0
  5. package/dist/agent-loop.js.map +1 -0
  6. package/dist/agent.d.ts +120 -0
  7. package/dist/agent.d.ts.map +1 -0
  8. package/dist/agent.js +413 -0
  9. package/dist/agent.js.map +1 -0
  10. package/dist/harness/agent-harness.d.ts +92 -0
  11. package/dist/harness/agent-harness.d.ts.map +1 -0
  12. package/dist/harness/agent-harness.js +952 -0
  13. package/dist/harness/agent-harness.js.map +1 -0
  14. package/dist/harness/compaction/branch-summarization.d.ts +55 -0
  15. package/dist/harness/compaction/branch-summarization.d.ts.map +1 -0
  16. package/dist/harness/compaction/branch-summarization.js +173 -0
  17. package/dist/harness/compaction/branch-summarization.js.map +1 -0
  18. package/dist/harness/compaction/compaction.d.ts +107 -0
  19. package/dist/harness/compaction/compaction.d.ts.map +1 -0
  20. package/dist/harness/compaction/compaction.js +577 -0
  21. package/dist/harness/compaction/compaction.js.map +1 -0
  22. package/dist/harness/compaction/utils.d.ts +25 -0
  23. package/dist/harness/compaction/utils.d.ts.map +1 -0
  24. package/dist/harness/compaction/utils.js +120 -0
  25. package/dist/harness/compaction/utils.js.map +1 -0
  26. package/dist/harness/env/nodejs.d.ts +51 -0
  27. package/dist/harness/env/nodejs.d.ts.map +1 -0
  28. package/dist/harness/env/nodejs.js +516 -0
  29. package/dist/harness/env/nodejs.js.map +1 -0
  30. package/dist/harness/messages.d.ts +51 -0
  31. package/dist/harness/messages.d.ts.map +1 -0
  32. package/dist/harness/messages.js +102 -0
  33. package/dist/harness/messages.js.map +1 -0
  34. package/dist/harness/prompt-templates.d.ts +48 -0
  35. package/dist/harness/prompt-templates.d.ts.map +1 -0
  36. package/dist/harness/prompt-templates.js +230 -0
  37. package/dist/harness/prompt-templates.js.map +1 -0
  38. package/dist/harness/session/jsonl-repo.d.ts +26 -0
  39. package/dist/harness/session/jsonl-repo.d.ts.map +1 -0
  40. package/dist/harness/session/jsonl-repo.js +103 -0
  41. package/dist/harness/session/jsonl-repo.js.map +1 -0
  42. package/dist/harness/session/jsonl-storage.d.ts +42 -0
  43. package/dist/harness/session/jsonl-storage.d.ts.map +1 -0
  44. package/dist/harness/session/jsonl-storage.js +293 -0
  45. package/dist/harness/session/jsonl-storage.js.map +1 -0
  46. package/dist/harness/session/memory-repo.d.ts +18 -0
  47. package/dist/harness/session/memory-repo.d.ts.map +1 -0
  48. package/dist/harness/session/memory-repo.js +42 -0
  49. package/dist/harness/session/memory-repo.js.map +1 -0
  50. package/dist/harness/session/memory-storage.d.ts +33 -0
  51. package/dist/harness/session/memory-storage.d.ts.map +1 -0
  52. package/dist/harness/session/memory-storage.js +168 -0
  53. package/dist/harness/session/memory-storage.js.map +1 -0
  54. package/dist/harness/session/repo-utils.d.ts +11 -0
  55. package/dist/harness/session/repo-utils.d.ts.map +1 -0
  56. package/dist/harness/session/repo-utils.js +39 -0
  57. package/dist/harness/session/repo-utils.js.map +1 -0
  58. package/dist/harness/session/session.d.ts +49 -0
  59. package/dist/harness/session/session.d.ts.map +1 -0
  60. package/dist/harness/session/session.js +263 -0
  61. package/dist/harness/session/session.js.map +1 -0
  62. package/dist/harness/skills.d.ts +44 -0
  63. package/dist/harness/skills.d.ts.map +1 -0
  64. package/dist/harness/skills.js +311 -0
  65. package/dist/harness/skills.js.map +1 -0
  66. package/dist/harness/system-prompt.d.ts +3 -0
  67. package/dist/harness/system-prompt.d.ts.map +1 -0
  68. package/dist/harness/system-prompt.js +30 -0
  69. package/dist/harness/system-prompt.js.map +1 -0
  70. package/dist/harness/types.d.ts +665 -0
  71. package/dist/harness/types.d.ts.map +1 -0
  72. package/dist/harness/types.js +94 -0
  73. package/dist/harness/types.js.map +1 -0
  74. package/dist/harness/utils/shell-output.d.ts +14 -0
  75. package/dist/harness/utils/shell-output.d.ts.map +1 -0
  76. package/dist/harness/utils/shell-output.js +126 -0
  77. package/dist/harness/utils/shell-output.js.map +1 -0
  78. package/dist/harness/utils/truncate.d.ts +70 -0
  79. package/dist/harness/utils/truncate.d.ts.map +1 -0
  80. package/dist/harness/utils/truncate.js +290 -0
  81. package/dist/harness/utils/truncate.js.map +1 -0
  82. package/dist/index.d.ts +23 -0
  83. package/dist/index.d.ts.map +1 -0
  84. package/dist/index.js +29 -0
  85. package/dist/index.js.map +1 -0
  86. package/dist/node.d.ts +3 -0
  87. package/dist/node.d.ts.map +1 -0
  88. package/dist/node.js +3 -0
  89. package/dist/node.js.map +1 -0
  90. package/dist/proxy.d.ts +69 -0
  91. package/dist/proxy.d.ts.map +1 -0
  92. package/dist/proxy.js +278 -0
  93. package/dist/proxy.js.map +1 -0
  94. package/dist/stream-fn.d.ts +10 -0
  95. package/dist/stream-fn.d.ts.map +1 -0
  96. package/dist/stream-fn.js +17 -0
  97. package/dist/stream-fn.js.map +1 -0
  98. package/dist/types.d.ts +407 -0
  99. package/dist/types.d.ts.map +1 -0
  100. package/dist/types.js +2 -0
  101. package/dist/types.js.map +1 -0
  102. package/package.json +60 -0
package/README.md ADDED
@@ -0,0 +1,507 @@
1
+ # @handy_wote/pi-agent-core
2
+
3
+ Stateful agent with tool execution and event streaming. Built on `@handy_wote/pi-ai`.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @handy_wote/pi-agent-core
9
+ ```
10
+
11
+ ### SQLite session backends
12
+
13
+ The SQLite session backend and the `node:sqlite` adapter live in a separate package, `@handy_wote/pi-storage-sqlite-node`, so the core package does not pull in runtime builtins or native SQLite dependencies by default. The backend accepts a runtime-specific SQLite factory, allowing other storage backends to ship as their own packages in the future.
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { Agent } from "@handy_wote/pi-agent-core";
19
+ import { createModels } from "@handy_wote/pi-ai";
20
+ import { anthropicProvider } from "@handy_wote/pi-ai/providers/anthropic";
21
+
22
+ const models = createModels();
23
+ models.setProvider(anthropicProvider());
24
+ const model = models.getModel("anthropic", "claude-sonnet-4-6");
25
+ if (!model) throw new Error("Model not found");
26
+
27
+ const agent = new Agent({
28
+ initialState: {
29
+ systemPrompt: "You are a helpful assistant.",
30
+ model,
31
+ },
32
+ streamFn: models.streamSimple.bind(models),
33
+ });
34
+
35
+ agent.subscribe((event) => {
36
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
37
+ // Stream just the new text chunk
38
+ process.stdout.write(event.assistantMessageEvent.delta);
39
+ }
40
+ });
41
+
42
+ await agent.prompt("Hello!");
43
+ ```
44
+
45
+ ## Core Concepts
46
+
47
+ ### AgentMessage vs LLM Message
48
+
49
+ The agent works with `AgentMessage`, a flexible type that can include:
50
+ - Standard LLM messages (`user`, `assistant`, `toolResult`)
51
+ - Custom app-specific message types via declaration merging
52
+
53
+ LLMs only understand `user`, `assistant`, and `toolResult`. The `convertToLlm` function bridges this gap by filtering and transforming messages before each LLM call.
54
+
55
+ ### Message Flow
56
+
57
+ ```
58
+ AgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM
59
+ (optional) (required)
60
+ ```
61
+
62
+ 1. **transformContext**: Prune old messages, inject external context
63
+ 2. **convertToLlm**: Filter out UI-only messages, convert custom types to LLM format
64
+
65
+ ## Event Flow
66
+
67
+ The agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.
68
+
69
+ ### prompt() Event Sequence
70
+
71
+ When you call `prompt("Hello")`:
72
+
73
+ ```
74
+ prompt("Hello")
75
+ ├─ agent_start
76
+ ├─ turn_start
77
+ ├─ message_start { message: userMessage } // Your prompt
78
+ ├─ message_end { message: userMessage }
79
+ ├─ message_start { message: assistantMessage } // LLM starts responding
80
+ ├─ message_update { message: partial... } // Streaming chunks
81
+ ├─ message_update { message: partial... }
82
+ ├─ message_end { message: assistantMessage } // Complete response
83
+ ├─ turn_end { message, toolResults: [] }
84
+ └─ agent_end { messages: [...] }
85
+ ```
86
+
87
+ ### With Tool Calls
88
+
89
+ If the assistant calls tools, the loop continues:
90
+
91
+ ```
92
+ prompt("Read config.json")
93
+ ├─ agent_start
94
+ ├─ turn_start
95
+ ├─ message_start/end { userMessage }
96
+ ├─ message_start { assistantMessage with toolCall }
97
+ ├─ message_update...
98
+ ├─ message_end { assistantMessage }
99
+ ├─ tool_execution_start { toolCallId, toolName, args }
100
+ ├─ tool_execution_update { partialResult } // If tool streams
101
+ ├─ tool_execution_end { toolCallId, result }
102
+ ├─ message_start/end { toolResultMessage }
103
+ ├─ turn_end { message, toolResults: [toolResult] }
104
+
105
+ ├─ turn_start // Next turn
106
+ ├─ message_start { assistantMessage } // LLM responds to tool result
107
+ ├─ message_update...
108
+ ├─ message_end
109
+ ├─ turn_end
110
+ └─ agent_end
111
+ ```
112
+
113
+ Tool execution mode is configurable:
114
+
115
+ - `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
116
+ - `sequential`: execute tool calls one by one, matching the historical behavior
117
+
118
+ In parallel mode, tool completion events follow tool completion order, but persisted toolResult messages still follow assistant source order.
119
+
120
+ 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.
121
+
122
+ The `beforeToolCall` hook runs after `tool_execution_start` and validated argument parsing. It can block execution. The `afterToolCall` hook runs after tool execution finishes and before `tool_execution_end` and final tool result message events are emitted.
123
+
124
+ Tools can also return `terminate: true` to hint that the automatic follow-up LLM call should be skipped. The loop only stops early when every finalized tool result in that batch sets `terminate: true`. Mixed batches continue normally.
125
+
126
+ Low-level loop callers can set `shouldStopAfterTurn` to stop gracefully after the current turn completes:
127
+
128
+ ```typescript
129
+ const stream = agentLoop(
130
+ prompts,
131
+ context,
132
+ {
133
+ model,
134
+ convertToLlm,
135
+ shouldStopAfterTurn: async ({ message, toolResults, context, newMessages }) => {
136
+ return shouldCompactBeforeNextTurn(context.messages);
137
+ },
138
+ },
139
+ undefined,
140
+ models.streamSimple.bind(models),
141
+ );
142
+ ```
143
+
144
+ `shouldStopAfterTurn` runs after `turn_end` is emitted and after the assistant response and any tool executions have completed normally. If it returns `true`, the loop emits `agent_end` and exits before polling steering or follow-up queues, and before starting another LLM call. It does not abort the provider stream, does not cancel running tools, and does not alter the assistant message stop reason.
145
+
146
+ When you use the `Agent` class, assistant `message_end` processing is treated as a barrier before tool preflight begins. That means `beforeToolCall` sees agent state that already includes the assistant message that requested the tool call.
147
+
148
+ ### continue() Event Sequence
149
+
150
+ `continue()` resumes from existing context without adding a new message. Use it for retries after errors.
151
+
152
+ ```typescript
153
+ // After an error, retry from current state
154
+ await agent.continue();
155
+ ```
156
+
157
+ The last message in context must be `user` or `toolResult` (not `assistant`).
158
+
159
+ ### Event Types
160
+
161
+ | Event | Description |
162
+ |-------|-------------|
163
+ | `agent_start` | Agent begins processing |
164
+ | `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |
165
+ | `turn_start` | New turn begins (one LLM call + tool executions) |
166
+ | `turn_end` | Turn completes with assistant message and tool results |
167
+ | `message_start` | Any message begins (user, assistant, toolResult) |
168
+ | `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
169
+ | `message_end` | Message completes |
170
+ | `tool_execution_start` | Tool begins |
171
+ | `tool_execution_update` | Tool streams progress |
172
+ | `tool_execution_end` | Tool completes |
173
+
174
+ `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.
175
+
176
+ ## Agent Options
177
+
178
+ ```typescript
179
+ const agent = new Agent({
180
+ // Initial state
181
+ initialState: {
182
+ systemPrompt: string,
183
+ model: Model<any>,
184
+ thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max",
185
+ tools: AgentTool<any>[],
186
+ messages: AgentMessage[],
187
+ },
188
+
189
+ // Convert AgentMessage[] to LLM Message[] (required for custom message types)
190
+ convertToLlm: (messages) => messages.filter(...),
191
+
192
+ // Transform context before convertToLlm (for pruning, compaction)
193
+ transformContext: async (messages, signal) => pruneOldMessages(messages),
194
+
195
+ // Steering mode: "one-at-a-time" (default) or "all"
196
+ steeringMode: "one-at-a-time",
197
+
198
+ // Follow-up mode: "one-at-a-time" (default) or "all"
199
+ followUpMode: "one-at-a-time",
200
+
201
+ // Required stream function
202
+ streamFn: models.streamSimple.bind(models),
203
+
204
+ // Session ID for provider caching
205
+ sessionId: "session-123",
206
+
207
+ // Dynamic API key resolution (for expiring OAuth tokens)
208
+ getApiKey: async (provider) => refreshToken(),
209
+
210
+ // Tool execution mode: "parallel" (default) or "sequential"
211
+ toolExecution: "parallel",
212
+
213
+ // Preflight each tool call after args are validated. Can block execution.
214
+ beforeToolCall: async ({ toolCall, args, context }) => {
215
+ if (toolCall.name === "bash") {
216
+ return { block: true, reason: "bash is disabled" };
217
+ }
218
+ },
219
+
220
+ // Postprocess each tool result before final tool events are emitted.
221
+ afterToolCall: async ({ toolCall, result, isError, context }) => {
222
+ if (toolCall.name === "notify_done" && !isError) {
223
+ return { terminate: true };
224
+ }
225
+ if (!isError) {
226
+ return { details: { ...result.details, audited: true } };
227
+ }
228
+ },
229
+
230
+ // Custom thinking budgets for token-based providers
231
+ thinkingBudgets: {
232
+ minimal: 128,
233
+ low: 512,
234
+ medium: 1024,
235
+ high: 2048,
236
+ },
237
+ });
238
+ ```
239
+
240
+ ## Agent State
241
+
242
+ ```typescript
243
+ interface AgentState {
244
+ systemPrompt: string;
245
+ model: Model<any>;
246
+ thinkingLevel: ThinkingLevel;
247
+ tools: AgentTool<any>[];
248
+ messages: AgentMessage[];
249
+ readonly isStreaming: boolean;
250
+ readonly streamingMessage?: AgentMessage;
251
+ readonly pendingToolCalls: ReadonlySet<string>;
252
+ readonly errorMessage?: string;
253
+ }
254
+ ```
255
+
256
+ Access state via `agent.state`.
257
+
258
+ Assigning `agent.state.tools = [...]` or `agent.state.messages = [...]` copies the top-level array before storing it. Mutating the returned array mutates the current agent state.
259
+
260
+ During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
261
+
262
+ `agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
263
+
264
+ ## Methods
265
+
266
+ ### Prompting
267
+
268
+ ```typescript
269
+ // Text prompt
270
+ await agent.prompt("Hello");
271
+
272
+ // With images
273
+ await agent.prompt("What's in this image?", [
274
+ { type: "image", data: base64Data, mimeType: "image/jpeg" }
275
+ ]);
276
+
277
+ // AgentMessage directly
278
+ await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
279
+
280
+ // Continue from current context (last message must be user or toolResult)
281
+ await agent.continue();
282
+ ```
283
+
284
+ ### State Management
285
+
286
+ ```typescript
287
+ agent.state.systemPrompt = "New prompt";
288
+ agent.state.model = getModel("openai", "gpt-4o");
289
+ agent.state.thinkingLevel = "medium";
290
+ agent.state.tools = [myTool];
291
+ agent.toolExecution = "sequential";
292
+ agent.beforeToolCall = async ({ toolCall }) => undefined;
293
+ agent.afterToolCall = async ({ toolCall, result }) => undefined;
294
+ agent.state.messages = newMessages; // top-level array is copied
295
+ agent.state.messages.push(message);
296
+ agent.reset();
297
+ ```
298
+
299
+ ### Session and Thinking Budgets
300
+
301
+ ```typescript
302
+ agent.sessionId = "session-123";
303
+
304
+ agent.thinkingBudgets = {
305
+ minimal: 128,
306
+ low: 512,
307
+ medium: 1024,
308
+ high: 2048,
309
+ };
310
+ ```
311
+
312
+ ### Control
313
+
314
+ ```typescript
315
+ agent.abort(); // Cancel current operation
316
+ await agent.waitForIdle(); // Wait for completion
317
+ ```
318
+
319
+ ### Events
320
+
321
+ ```typescript
322
+ const unsubscribe = agent.subscribe(async (event, signal) => {
323
+ if (event.type === "agent_end") {
324
+ // Final barrier work for the run
325
+ await flushSessionState(signal);
326
+ }
327
+ });
328
+ unsubscribe();
329
+ ```
330
+
331
+ ## Steering and Follow-up
332
+
333
+ Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
334
+
335
+ ```typescript
336
+ agent.steeringMode = "one-at-a-time";
337
+ agent.followUpMode = "one-at-a-time";
338
+
339
+ // While agent is running tools
340
+ agent.steer({
341
+ role: "user",
342
+ content: "Stop! Do this instead.",
343
+ timestamp: Date.now(),
344
+ });
345
+
346
+ // After the agent finishes its current work
347
+ agent.followUp({
348
+ role: "user",
349
+ content: "Also summarize the result.",
350
+ timestamp: Date.now(),
351
+ });
352
+
353
+ const steeringMode = agent.steeringMode;
354
+ const followUpMode = agent.followUpMode;
355
+
356
+ agent.clearSteeringQueue();
357
+ agent.clearFollowUpQueue();
358
+ agent.clearAllQueues();
359
+ ```
360
+
361
+ Use clearSteeringQueue, clearFollowUpQueue, or clearAllQueues to drop queued messages.
362
+
363
+ When steering messages are detected after a turn completes:
364
+ 1. All tool calls from the current assistant message have already finished
365
+ 2. Steering messages are injected
366
+ 3. The LLM responds on the next turn
367
+
368
+ Follow-up messages are checked only when there are no more tool calls and no steering messages. If any are queued, they are injected and another turn runs.
369
+
370
+ ## Custom Message Types
371
+
372
+ Extend `AgentMessage` via declaration merging:
373
+
374
+ ```typescript
375
+ declare module "@handy_wote/pi-agent-core" {
376
+ interface CustomAgentMessages {
377
+ notification: { role: "notification"; text: string; timestamp: number };
378
+ }
379
+ }
380
+
381
+ // Now valid
382
+ const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
383
+ ```
384
+
385
+ Handle custom types in `convertToLlm`:
386
+
387
+ ```typescript
388
+ const agent = new Agent({
389
+ streamFn: models.streamSimple.bind(models),
390
+ convertToLlm: (messages) => messages.flatMap(m => {
391
+ if (m.role === "notification") return []; // Filter out
392
+ return [m];
393
+ }),
394
+ });
395
+ ```
396
+
397
+ ## Tools
398
+
399
+ Define tools using `AgentTool`:
400
+
401
+ ```typescript
402
+ import { Type } from "typebox";
403
+
404
+ const readFileTool: AgentTool = {
405
+ name: "read_file",
406
+ label: "Read File", // For UI display
407
+ description: "Read a file's contents",
408
+ parameters: Type.Object({
409
+ path: Type.String({ description: "File path" }),
410
+ }),
411
+ // Override execution mode for this tool (optional).
412
+ // "sequential" forces the entire batch to run one at a time.
413
+ // "parallel" allows concurrent execution with other tool calls.
414
+ // If omitted, the global toolExecution config applies.
415
+ executionMode: "sequential",
416
+ execute: async (toolCallId, params, signal, onUpdate) => {
417
+ const content = await fs.readFile(params.path, "utf-8");
418
+
419
+ // Optional: stream progress
420
+ onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
421
+
422
+ // Optional: add `terminate: true` here to skip the automatic follow-up LLM call
423
+ // when every finalized tool result in the batch does the same.
424
+ return {
425
+ content: [{ type: "text", text: content }],
426
+ details: { path: params.path, size: content.length },
427
+ };
428
+ },
429
+ };
430
+
431
+ agent.state.tools = [readFileTool];
432
+ ```
433
+
434
+ ### Error Handling
435
+
436
+ **Throw an error** when a tool fails. Do not return error messages as content.
437
+
438
+ ```typescript
439
+ execute: async (toolCallId, params, signal, onUpdate) => {
440
+ if (!fs.existsSync(params.path)) {
441
+ throw new Error(`File not found: ${params.path}`);
442
+ }
443
+ // Return content only on success
444
+ return { content: [{ type: "text", text: "..." }] };
445
+ }
446
+ ```
447
+
448
+ Thrown errors are caught by the agent and reported to the LLM as tool errors with `isError: true`.
449
+
450
+ 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.
451
+
452
+ ## Proxy Usage
453
+
454
+ For browser apps that proxy through a backend:
455
+
456
+ ```typescript
457
+ import { Agent, streamProxy } from "@handy_wote/pi-agent-core";
458
+
459
+ const agent = new Agent({
460
+ streamFn: (model, context, options) =>
461
+ streamProxy(model, context, {
462
+ ...options,
463
+ authToken: "...",
464
+ proxyUrl: "https://your-server.com",
465
+ }),
466
+ });
467
+ ```
468
+
469
+ ## Low-Level API
470
+
471
+ For direct control without the Agent class:
472
+
473
+ ```typescript
474
+ import { agentLoop, agentLoopContinue } from "@handy_wote/pi-agent-core";
475
+
476
+ const context: AgentContext = {
477
+ systemPrompt: "You are helpful.",
478
+ messages: [],
479
+ tools: [],
480
+ };
481
+
482
+ const config: AgentLoopConfig = {
483
+ model: getModel("openai", "gpt-4o"),
484
+ convertToLlm: (msgs) => msgs.filter(m => ["user", "assistant", "toolResult"].includes(m.role)),
485
+ toolExecution: "parallel", // overridden by per-tool executionMode if set
486
+ beforeToolCall: async ({ toolCall, args, context }) => undefined,
487
+ afterToolCall: async ({ toolCall, result, isError, context }) => undefined,
488
+ };
489
+
490
+ const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
491
+
492
+ const streamFn = models.streamSimple.bind(models);
493
+ for await (const event of agentLoop([userMessage], context, config, undefined, streamFn)) {
494
+ console.log(event.type);
495
+ }
496
+
497
+ // Continue from existing context
498
+ for await (const event of agentLoopContinue(context, config, undefined, streamFn)) {
499
+ console.log(event.type);
500
+ }
501
+ ```
502
+
503
+ These low-level streams are observational. They preserve event order, but they do not wait for your async event handling to settle before later producer phases continue. If you need message processing to act as a barrier before tool preflight, use the `Agent` class instead of raw `agentLoop()` or `agentLoopContinue()`.
504
+
505
+ ## License
506
+
507
+ MIT
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Agent loop that works with AgentMessage throughout.
3
+ * Transforms to Message[] only at the LLM call boundary.
4
+ */
5
+ import { EventStream } from "@handy_wote/pi-ai";
6
+ import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, StreamFn } from "./types.ts";
7
+ export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
8
+ /**
9
+ * Start an agent loop with a new prompt message.
10
+ * The prompt is added to the context and events are emitted for it.
11
+ */
12
+ export declare function agentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal: AbortSignal | undefined, streamFn: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
13
+ /**
14
+ * Continue an agent loop from the current context without adding a new message.
15
+ * Used for retries - context already has user message or tool results.
16
+ *
17
+ * **Important:** The last message in context must convert to a `user` or `toolResult` message
18
+ * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
19
+ * This cannot be validated here since `convertToLlm` is only called once per turn.
20
+ */
21
+ export declare function agentLoopContinue(context: AgentContext, config: AgentLoopConfig, signal: AbortSignal | undefined, streamFn: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
22
+ export declare function runAgentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal: AbortSignal | undefined, streamFn: StreamFn): Promise<AgentMessage[]>;
23
+ export declare function runAgentLoopContinue(context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal: AbortSignal | undefined, streamFn: StreamFn): Promise<AgentMessage[]>;
24
+ //# sourceMappingURL=agent-loop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAGN,WAAW,EAGX,MAAM,mBAAmB,CAAC;AAE3B,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;AAEzE;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,QAAQ,GAChB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAiBzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,QAAQ,GAChB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAwBzC;AAED,wBAAsB,YAAY,CACjC,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,QAAQ,GAChB,OAAO,CAAC,YAAY,EAAE,CAAC,CAgBzB;AAED,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,QAAQ,GAChB,OAAO,CAAC,YAAY,EAAE,CAAC,CAiBzB","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 ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@handy_wote/pi-ai\";\nimport { getDefaultStreamFn } from \"./stream-fn.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\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 | undefined,\n\tstreamFn: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoop(\n\t\tprompts,\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\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 | undefined,\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\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoopContinue(\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\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 | undefined,\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 ?? getDefaultStreamFn());\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal: AbortSignal | undefined,\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\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\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 ?? getDefaultStreamFn());\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 * 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\tstreamFunction: 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, streamFunction);\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\t// A \"length\" stop means the output was cut off by the token limit, so\n\t\t\t\t// every tool call in the message may carry truncated arguments. Fail\n\t\t\t\t// them all instead of executing potentially borked calls.\n\t\t\t\tconst executedToolBatch =\n\t\t\t\t\tmessage.stopReason === \"length\"\n\t\t\t\t\t\t? await failToolCallsFromTruncatedMessage(toolCalls, emit)\n\t\t\t\t\t\t: 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\tstreamFunction: 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\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 * Fail all tool calls from an assistant message that was truncated by the\n * output token limit. Streamed tool-call arguments are finalized with a\n * best-effort JSON salvage parser, so a truncated message can yield tool calls\n * whose arguments parse and validate but are silently incomplete. None of them\n * are safe to execute; report each as an error so the model can re-issue them.\n */\nasync function failToolCallsFromTruncatedMessage(\n\ttoolCalls: AgentToolCall[],\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallBatch> {\n\tconst messages: ToolResultMessage[] = [];\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\t\tconst finalized: FinalizedToolCallOutcome = {\n\t\t\ttoolCall,\n\t\t\tresult: createErrorToolResult(\n\t\t\t\t`Tool call \"${toolCall.name}\" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`,\n\t\t\t),\n\t\t\tisError: true,\n\t\t};\n\t\tawait emitToolExecutionEnd(finalized, emit);\n\t\tconst toolResultMessage = createToolResultMessage(finalized);\n\t\tawait emitToolResultMessage(toolResultMessage, emit);\n\t\tmessages.push(toolResultMessage);\n\t}\n\treturn { messages, terminate: false };\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\tif (config.toolExecution === \"sequential\" || hasSequentialToolCall) {\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\tlet acceptingUpdates = true;\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\tif (!acceptingUpdates) return;\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\tacceptingUpdates = false;\n\t\tawait Promise.all(updateEvents);\n\t\treturn { result, isError: false };\n\t} catch (error) {\n\t\tacceptingUpdates = false;\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} finally {\n\t\tacceptingUpdates = false;\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\t...result,\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\tusage: afterResult.usage ?? result.usage,\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\t// Untyped tools (JS extensions) can return results without content; normalize\n\t\t// so the null never enters session history or provider payloads.\n\t\tcontent: finalized.result.content ?? [],\n\t\tdetails: finalized.result.details,\n\t\tusage: finalized.result.usage,\n\t\t...(finalized.result.addedToolNames?.length ? { addedToolNames: finalized.result.addedToolNames } : {}),\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"]}