@hansjm10/volt-agent-core 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +497 -2
  3. package/dist/agent-loop.d.ts +24 -0
  4. package/dist/agent-loop.d.ts.map +1 -0
  5. package/dist/agent-loop.js +524 -0
  6. package/dist/agent-loop.js.map +1 -0
  7. package/dist/agent.d.ts +127 -0
  8. package/dist/agent.d.ts.map +1 -0
  9. package/dist/agent.js +435 -0
  10. package/dist/agent.js.map +1 -0
  11. package/dist/harness/agent-harness.d.ts +95 -0
  12. package/dist/harness/agent-harness.d.ts.map +1 -0
  13. package/dist/harness/agent-harness.js +963 -0
  14. package/dist/harness/agent-harness.js.map +1 -0
  15. package/dist/harness/compaction/branch-summarization.d.ts +53 -0
  16. package/dist/harness/compaction/branch-summarization.d.ts.map +1 -0
  17. package/dist/harness/compaction/branch-summarization.js +175 -0
  18. package/dist/harness/compaction/branch-summarization.js.map +1 -0
  19. package/dist/harness/compaction/compaction.d.ts +95 -0
  20. package/dist/harness/compaction/compaction.d.ts.map +1 -0
  21. package/dist/harness/compaction/compaction.js +528 -0
  22. package/dist/harness/compaction/compaction.js.map +1 -0
  23. package/dist/harness/compaction/utils.d.ts +25 -0
  24. package/dist/harness/compaction/utils.d.ts.map +1 -0
  25. package/dist/harness/compaction/utils.js +131 -0
  26. package/dist/harness/compaction/utils.js.map +1 -0
  27. package/dist/harness/env/nodejs.d.ts +51 -0
  28. package/dist/harness/env/nodejs.d.ts.map +1 -0
  29. package/dist/harness/env/nodejs.js +490 -0
  30. package/dist/harness/env/nodejs.js.map +1 -0
  31. package/dist/harness/messages.d.ts +51 -0
  32. package/dist/harness/messages.d.ts.map +1 -0
  33. package/dist/harness/messages.js +102 -0
  34. package/dist/harness/messages.js.map +1 -0
  35. package/dist/harness/prompt-templates.d.ts +48 -0
  36. package/dist/harness/prompt-templates.d.ts.map +1 -0
  37. package/dist/harness/prompt-templates.js +230 -0
  38. package/dist/harness/prompt-templates.js.map +1 -0
  39. package/dist/harness/session/jsonl-repo.d.ts +26 -0
  40. package/dist/harness/session/jsonl-repo.d.ts.map +1 -0
  41. package/dist/harness/session/jsonl-repo.js +101 -0
  42. package/dist/harness/session/jsonl-repo.js.map +1 -0
  43. package/dist/harness/session/jsonl-storage.d.ts +33 -0
  44. package/dist/harness/session/jsonl-storage.d.ts.map +1 -0
  45. package/dist/harness/session/jsonl-storage.js +231 -0
  46. package/dist/harness/session/jsonl-storage.js.map +1 -0
  47. package/dist/harness/session/memory-repo.d.ts +18 -0
  48. package/dist/harness/session/memory-repo.d.ts.map +1 -0
  49. package/dist/harness/session/memory-repo.js +42 -0
  50. package/dist/harness/session/memory-repo.js.map +1 -0
  51. package/dist/harness/session/memory-storage.d.ts +25 -0
  52. package/dist/harness/session/memory-storage.d.ts.map +1 -0
  53. package/dist/harness/session/memory-storage.js +114 -0
  54. package/dist/harness/session/memory-storage.js.map +1 -0
  55. package/dist/harness/session/repo-utils.d.ts +11 -0
  56. package/dist/harness/session/repo-utils.d.ts.map +1 -0
  57. package/dist/harness/session/repo-utils.js +39 -0
  58. package/dist/harness/session/repo-utils.js.map +1 -0
  59. package/dist/harness/session/session.d.ts +33 -0
  60. package/dist/harness/session/session.d.ts.map +1 -0
  61. package/dist/harness/session/session.js +210 -0
  62. package/dist/harness/session/session.js.map +1 -0
  63. package/dist/harness/session/uuid.d.ts +2 -0
  64. package/dist/harness/session/uuid.d.ts.map +1 -0
  65. package/dist/harness/session/uuid.js +50 -0
  66. package/dist/harness/session/uuid.js.map +1 -0
  67. package/dist/harness/skills.d.ts +44 -0
  68. package/dist/harness/skills.d.ts.map +1 -0
  69. package/dist/harness/skills.js +314 -0
  70. package/dist/harness/skills.js.map +1 -0
  71. package/dist/harness/system-prompt.d.ts +3 -0
  72. package/dist/harness/system-prompt.d.ts.map +1 -0
  73. package/dist/harness/system-prompt.js +30 -0
  74. package/dist/harness/system-prompt.js.map +1 -0
  75. package/dist/harness/types.d.ts +615 -0
  76. package/dist/harness/types.d.ts.map +1 -0
  77. package/dist/harness/types.js +94 -0
  78. package/dist/harness/types.js.map +1 -0
  79. package/dist/harness/utils/shell-output.d.ts +14 -0
  80. package/dist/harness/utils/shell-output.d.ts.map +1 -0
  81. package/dist/harness/utils/shell-output.js +126 -0
  82. package/dist/harness/utils/shell-output.js.map +1 -0
  83. package/dist/harness/utils/truncate.d.ts +70 -0
  84. package/dist/harness/utils/truncate.d.ts.map +1 -0
  85. package/dist/harness/utils/truncate.js +290 -0
  86. package/dist/harness/utils/truncate.js.map +1 -0
  87. package/dist/index.d.ts +20 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +25 -0
  90. package/dist/index.js.map +1 -0
  91. package/dist/node.d.ts +3 -0
  92. package/dist/node.d.ts.map +1 -0
  93. package/dist/node.js +3 -0
  94. package/dist/node.js.map +1 -0
  95. package/dist/proxy.d.ts +69 -0
  96. package/dist/proxy.d.ts.map +1 -0
  97. package/dist/proxy.js +278 -0
  98. package/dist/proxy.js.map +1 -0
  99. package/dist/types.d.ts +410 -0
  100. package/dist/types.d.ts.map +1 -0
  101. package/dist/types.js +2 -0
  102. package/dist/types.js.map +1 -0
  103. package/package.json +70 -19
package/LICENSE CHANGED
@@ -19,4 +19,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
19
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
20
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
21
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,5 +1,500 @@
1
1
  # @hansjm10/volt-agent-core
2
2
 
3
- This package only reserves the npm name for [Volt](https://github.com/hansjm10/Volt).
3
+ Stateful agent with tool execution and event streaming. Built on `@hansjm10/volt-ai`.
4
4
 
5
- Installable releases begin at `0.1.0` and use the `beta` dist-tag.
5
+ Maintained and distributed as part of Volt by [Jordan Hans](https://github.com/hansjm10).
6
+ Volt is derived from [Mario Zechner's Pi project](https://github.com/badlogic/pi-mono)
7
+ under the MIT License.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @hansjm10/volt-agent-core@beta
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { Agent } from "@hansjm10/volt-agent-core";
19
+ import { getModel } from "@hansjm10/volt-ai";
20
+
21
+ const agent = new Agent({
22
+ initialState: {
23
+ systemPrompt: "You are a helpful assistant.",
24
+ model: getModel("anthropic", "claude-sonnet-4-20250514"),
25
+ },
26
+ });
27
+
28
+ agent.subscribe((event) => {
29
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
30
+ // Stream just the new text chunk
31
+ process.stdout.write(event.assistantMessageEvent.delta);
32
+ }
33
+ });
34
+
35
+ await agent.prompt("Hello!");
36
+ ```
37
+
38
+ ## Core Concepts
39
+
40
+ ### AgentMessage vs LLM Message
41
+
42
+ The agent works with `AgentMessage`, a flexible type that can include:
43
+ - Standard LLM messages (`user`, `assistant`, `toolResult`)
44
+ - Custom app-specific message types via declaration merging
45
+
46
+ LLMs only understand `user`, `assistant`, and `toolResult`. The `convertToLlm` function bridges this gap by filtering and transforming messages before each LLM call.
47
+
48
+ ### Message Flow
49
+
50
+ ```
51
+ AgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM
52
+ (optional) (required)
53
+ ```
54
+
55
+ 1. **transformContext**: Prune old messages, inject external context
56
+ 2. **convertToLlm**: Filter out UI-only messages, convert custom types to LLM format
57
+
58
+ ## Event Flow
59
+
60
+ The agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.
61
+
62
+ ### prompt() Event Sequence
63
+
64
+ When you call `prompt("Hello")`:
65
+
66
+ ```
67
+ prompt("Hello")
68
+ ├─ agent_start
69
+ ├─ turn_start
70
+ ├─ message_start { message: userMessage } // Your prompt
71
+ ├─ message_end { message: userMessage }
72
+ ├─ message_start { message: assistantMessage } // LLM starts responding
73
+ ├─ message_update { message: partial... } // Streaming chunks
74
+ ├─ message_update { message: partial... }
75
+ ├─ message_end { message: assistantMessage } // Complete response
76
+ ├─ turn_end { message, toolResults: [] }
77
+ └─ agent_end { messages: [...] }
78
+ ```
79
+
80
+ ### With Tool Calls
81
+
82
+ If the assistant calls tools, the loop continues:
83
+
84
+ ```
85
+ prompt("Read config.json")
86
+ ├─ agent_start
87
+ ├─ turn_start
88
+ ├─ message_start/end { userMessage }
89
+ ├─ message_start { assistantMessage with toolCall }
90
+ ├─ message_update...
91
+ ├─ message_end { assistantMessage }
92
+ ├─ tool_execution_start { toolCallId, toolName, args }
93
+ ├─ tool_execution_update { partialResult } // If tool streams
94
+ ├─ tool_execution_end { toolCallId, result }
95
+ ├─ message_start/end { toolResultMessage }
96
+ ├─ turn_end { message, toolResults: [toolResult] }
97
+
98
+ ├─ turn_start // Next turn
99
+ ├─ message_start { assistantMessage } // LLM responds to tool result
100
+ ├─ message_update...
101
+ ├─ message_end
102
+ ├─ turn_end
103
+ └─ agent_end
104
+ ```
105
+
106
+ Tool execution mode is configurable:
107
+
108
+ - `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
109
+ - `sequential`: execute tool calls one by one, matching the historical behavior
110
+
111
+ In parallel mode, tool completion events follow tool completion order, but persisted toolResult messages still follow assistant source order.
112
+
113
+ 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.
114
+
115
+ 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.
116
+
117
+ 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.
118
+
119
+ Low-level loop callers can set `shouldStopAfterTurn` to stop gracefully after the current turn completes:
120
+
121
+ ```typescript
122
+ const stream = agentLoop(prompts, context, {
123
+ model,
124
+ convertToLlm,
125
+ shouldStopAfterTurn: async ({ message, toolResults, context, newMessages }) => {
126
+ return shouldCompactBeforeNextTurn(context.messages);
127
+ },
128
+ });
129
+ ```
130
+
131
+ `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.
132
+
133
+ 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.
134
+
135
+ ### continue() Event Sequence
136
+
137
+ `continue()` resumes from existing context without adding a new message. Use it for retries after errors.
138
+
139
+ ```typescript
140
+ // After an error, retry from current state
141
+ await agent.continue();
142
+ ```
143
+
144
+ The last message in context must be `user` or `toolResult` (not `assistant`).
145
+
146
+ ### Event Types
147
+
148
+ | Event | Description |
149
+ |-------|-------------|
150
+ | `agent_start` | Agent begins processing |
151
+ | `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |
152
+ | `turn_start` | New turn begins (one LLM call + tool executions) |
153
+ | `turn_end` | Turn completes with assistant message and tool results |
154
+ | `message_start` | Any message begins (user, assistant, toolResult) |
155
+ | `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
156
+ | `message_end` | Message completes |
157
+ | `tool_execution_start` | Tool begins |
158
+ | `tool_execution_update` | Tool streams progress |
159
+ | `tool_execution_end` | Tool completes |
160
+
161
+ `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.
162
+
163
+ ## Agent Options
164
+
165
+ ```typescript
166
+ const agent = new Agent({
167
+ // Initial state
168
+ initialState: {
169
+ systemPrompt: string,
170
+ model: Model<any>,
171
+ thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max",
172
+ tools: AgentTool<any>[],
173
+ messages: AgentMessage[],
174
+ },
175
+
176
+ // Convert AgentMessage[] to LLM Message[] (required for custom message types)
177
+ convertToLlm: (messages) => messages.filter(...),
178
+
179
+ // Transform context before convertToLlm (for pruning, compaction)
180
+ transformContext: async (messages, signal) => pruneOldMessages(messages),
181
+
182
+ // Steering mode: "one-at-a-time" (default) or "all"
183
+ steeringMode: "one-at-a-time",
184
+
185
+ // Follow-up mode: "one-at-a-time" (default) or "all"
186
+ followUpMode: "one-at-a-time",
187
+
188
+ // Custom stream function (for proxy backends)
189
+ streamFn: streamProxy,
190
+
191
+ // Session ID for provider caching
192
+ sessionId: "session-123",
193
+
194
+ // Dynamic API key resolution (for expiring OAuth tokens)
195
+ getApiKey: async (provider) => refreshToken(),
196
+
197
+ // Tool execution mode: "parallel" (default) or "sequential"
198
+ toolExecution: "parallel",
199
+
200
+ // Preflight each tool call after args are validated. Can block execution.
201
+ beforeToolCall: async ({ toolCall, args, context }) => {
202
+ if (toolCall.name === "bash") {
203
+ return { block: true, reason: "bash is disabled" };
204
+ }
205
+ },
206
+
207
+ // Postprocess each tool result before final tool events are emitted.
208
+ afterToolCall: async ({ toolCall, result, isError, context }) => {
209
+ if (toolCall.name === "notify_done" && !isError) {
210
+ return { terminate: true };
211
+ }
212
+ if (!isError) {
213
+ return { details: { ...result.details, audited: true } };
214
+ }
215
+ },
216
+
217
+ // Stop gracefully after a completed turn, before queue polling or another model call.
218
+ shouldStopAfterTurn: async ({ context }) => shouldCompactBeforeNextTurn(context.messages),
219
+
220
+ // Custom thinking budgets for token-based providers
221
+ thinkingBudgets: {
222
+ minimal: 128,
223
+ low: 512,
224
+ medium: 1024,
225
+ high: 2048,
226
+ },
227
+ });
228
+ ```
229
+
230
+ ## Agent State
231
+
232
+ ```typescript
233
+ interface AgentState {
234
+ systemPrompt: string;
235
+ model: Model<any>;
236
+ thinkingLevel: ThinkingLevel;
237
+ tools: AgentTool<any>[];
238
+ messages: AgentMessage[];
239
+ readonly isStreaming: boolean;
240
+ readonly streamingMessage?: AgentMessage;
241
+ readonly pendingToolCalls: ReadonlySet<string>;
242
+ readonly errorMessage?: string;
243
+ }
244
+ ```
245
+
246
+ Access state via `agent.state`.
247
+
248
+ 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.
249
+
250
+ During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
251
+
252
+ `agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
253
+
254
+ ## Methods
255
+
256
+ ### Prompting
257
+
258
+ ```typescript
259
+ // Text prompt
260
+ await agent.prompt("Hello");
261
+
262
+ // With images
263
+ await agent.prompt("What's in this image?", [
264
+ { type: "image", data: base64Data, mimeType: "image/jpeg" }
265
+ ]);
266
+
267
+ // AgentMessage directly
268
+ await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
269
+
270
+ // Continue from current context (last message must normally be user or toolResult)
271
+ await agent.continue();
272
+
273
+ // If the transcript ends with an assistant message, explicitly drain one/all queued
274
+ // follow-ups (according to followUpMode) as the continuation input.
275
+ await agent.continue({ drainFollowUps: true });
276
+ ```
277
+
278
+ ### State Management
279
+
280
+ ```typescript
281
+ agent.state.systemPrompt = "New prompt";
282
+ agent.state.model = getModel("openai", "gpt-4o");
283
+ agent.state.thinkingLevel = "medium";
284
+ agent.state.tools = [myTool];
285
+ agent.toolExecution = "sequential";
286
+ agent.beforeToolCall = async ({ toolCall }) => undefined;
287
+ agent.afterToolCall = async ({ toolCall, result }) => undefined;
288
+ agent.shouldStopAfterTurn = async ({ context }) => shouldCompactBeforeNextTurn(context.messages);
289
+ agent.state.messages = newMessages; // top-level array is copied
290
+ agent.state.messages.push(message);
291
+ agent.reset();
292
+ ```
293
+
294
+ ### Session and Thinking Budgets
295
+
296
+ ```typescript
297
+ agent.sessionId = "session-123";
298
+
299
+ agent.thinkingBudgets = {
300
+ minimal: 128,
301
+ low: 512,
302
+ medium: 1024,
303
+ high: 2048,
304
+ };
305
+ ```
306
+
307
+ ### Control
308
+
309
+ ```typescript
310
+ agent.abort(); // Cancel current operation
311
+ await agent.waitForIdle(); // Wait for completion
312
+ ```
313
+
314
+ ### Events
315
+
316
+ ```typescript
317
+ const unsubscribe = agent.subscribe(async (event, signal) => {
318
+ if (event.type === "agent_end") {
319
+ // Final barrier work for the run
320
+ await flushSessionState(signal);
321
+ }
322
+ });
323
+ unsubscribe();
324
+ ```
325
+
326
+ ## Steering and Follow-up
327
+
328
+ Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
329
+
330
+ ```typescript
331
+ agent.steeringMode = "one-at-a-time";
332
+ agent.followUpMode = "one-at-a-time";
333
+
334
+ // While agent is running tools
335
+ agent.steer({
336
+ role: "user",
337
+ content: "Stop! Do this instead.",
338
+ timestamp: Date.now(),
339
+ });
340
+
341
+ // After the agent finishes its current work
342
+ agent.followUp({
343
+ role: "user",
344
+ content: "Also summarize the result.",
345
+ timestamp: Date.now(),
346
+ });
347
+
348
+ const steeringMode = agent.steeringMode;
349
+ const followUpMode = agent.followUpMode;
350
+
351
+ agent.clearSteeringQueue();
352
+ agent.clearFollowUpQueue();
353
+ agent.clearAllQueues();
354
+ ```
355
+
356
+ Use clearSteeringQueue, clearFollowUpQueue, or clearAllQueues to drop queued messages.
357
+
358
+ When steering messages are detected after a turn completes:
359
+ 1. All tool calls from the current assistant message have already finished
360
+ 2. Steering messages are injected
361
+ 3. The LLM responds on the next turn
362
+
363
+ 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.
364
+
365
+ ## Custom Message Types
366
+
367
+ Extend `AgentMessage` via declaration merging:
368
+
369
+ ```typescript
370
+ declare module "@hansjm10/volt-agent-core" {
371
+ interface CustomAgentMessages {
372
+ notification: { role: "notification"; text: string; timestamp: number };
373
+ }
374
+ }
375
+
376
+ // Now valid
377
+ const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
378
+ ```
379
+
380
+ Handle custom types in `convertToLlm`:
381
+
382
+ ```typescript
383
+ const agent = new Agent({
384
+ convertToLlm: (messages) => messages.flatMap(m => {
385
+ if (m.role === "notification") return []; // Filter out
386
+ return [m];
387
+ }),
388
+ });
389
+ ```
390
+
391
+ ## Tools
392
+
393
+ Define tools using `AgentTool`:
394
+
395
+ ```typescript
396
+ import { Type } from "typebox";
397
+
398
+ const readFileTool: AgentTool = {
399
+ name: "read_file",
400
+ label: "Read File", // For UI display
401
+ description: "Read a file's contents",
402
+ parameters: Type.Object({
403
+ path: Type.String({ description: "File path" }),
404
+ }),
405
+ // Override execution mode for this tool (optional).
406
+ // "sequential" forces the entire batch to run one at a time.
407
+ // "parallel" allows concurrent execution with other tool calls.
408
+ // If omitted, the global toolExecution config applies.
409
+ executionMode: "sequential",
410
+ execute: async (toolCallId, params, signal, onUpdate) => {
411
+ const content = await fs.readFile(params.path, "utf-8");
412
+
413
+ // Optional: stream progress
414
+ onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
415
+
416
+ // Optional: add `terminate: true` here to skip the automatic follow-up LLM call
417
+ // when every finalized tool result in the batch does the same.
418
+ return {
419
+ content: [{ type: "text", text: content }],
420
+ details: { path: params.path, size: content.length },
421
+ };
422
+ },
423
+ };
424
+
425
+ agent.state.tools = [readFileTool];
426
+ ```
427
+
428
+ ### Error Handling
429
+
430
+ **Throw an error** when a tool fails. Do not return error messages as content.
431
+
432
+ ```typescript
433
+ execute: async (toolCallId, params, signal, onUpdate) => {
434
+ if (!fs.existsSync(params.path)) {
435
+ throw new Error(`File not found: ${params.path}`);
436
+ }
437
+ // Return content only on success
438
+ return { content: [{ type: "text", text: "..." }] };
439
+ }
440
+ ```
441
+
442
+ Thrown errors are caught by the agent and reported to the LLM as tool errors with `isError: true`.
443
+
444
+ 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.
445
+
446
+ ## Proxy Usage
447
+
448
+ For browser apps that proxy through a backend:
449
+
450
+ ```typescript
451
+ import { Agent, streamProxy } from "@hansjm10/volt-agent-core";
452
+
453
+ const agent = new Agent({
454
+ streamFn: (model, context, options) =>
455
+ streamProxy(model, context, {
456
+ ...options,
457
+ authToken: "...",
458
+ proxyUrl: "https://your-server.com",
459
+ }),
460
+ });
461
+ ```
462
+
463
+ ## Low-Level API
464
+
465
+ For direct control without the Agent class:
466
+
467
+ ```typescript
468
+ import { agentLoop, agentLoopContinue } from "@hansjm10/volt-agent-core";
469
+
470
+ const context: AgentContext = {
471
+ systemPrompt: "You are helpful.",
472
+ messages: [],
473
+ tools: [],
474
+ };
475
+
476
+ const config: AgentLoopConfig = {
477
+ model: getModel("openai", "gpt-4o"),
478
+ convertToLlm: (msgs) => msgs.filter(m => ["user", "assistant", "toolResult"].includes(m.role)),
479
+ toolExecution: "parallel", // overridden by per-tool executionMode if set
480
+ beforeToolCall: async ({ toolCall, args, context }) => undefined,
481
+ afterToolCall: async ({ toolCall, result, isError, context }) => undefined,
482
+ };
483
+
484
+ const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
485
+
486
+ for await (const event of agentLoop([userMessage], context, config)) {
487
+ console.log(event.type);
488
+ }
489
+
490
+ // Continue from existing context
491
+ for await (const event of agentLoopContinue(context, config)) {
492
+ console.log(event.type);
493
+ }
494
+ ```
495
+
496
+ 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()`.
497
+
498
+ ## License
499
+
500
+ 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 "@hansjm10/volt-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, 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, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
22
+ export declare function runAgentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn): Promise<AgentMessage[]>;
23
+ export declare function runAgentLoopContinue(context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, 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,EAIX,MAAM,mBAAmB,CAAC;AAC3B,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,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAiBzC;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,CAwBzC;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,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\tstreamSimple,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@hansjm10/volt-ai\";\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,\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,\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,\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\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);\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\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\t// An aborted run must not silently start another turn: without this\n\t\t\t// guard the loop would call transformContext/streamFn (a fresh provider\n\t\t\t// request) after abort() — e.g. when a tool finished after the run was\n\t\t\t// aborted. Pending (steering) messages still get delivered: queued user\n\t\t\t// input survives abort by contract, and the provider stream itself\n\t\t\t// observes the aborted signal.\n\t\t\tif (signal?.aborted && pendingMessages.length === 0) {\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\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\tlet toolBatchTerminated = 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\ttoolBatchTerminated = executedToolBatch.terminate;\n\t\t\t\thasMoreToolCalls = !toolBatchTerminated;\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\ttoolBatchTerminated,\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\ttoolBatchTerminated,\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\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\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"]}