@vib-rato/agent-core 0.16.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.
- package/CHANGELOG.md +852 -0
- package/README.md +493 -0
- package/dist/types/agent-loop.d.ts +229 -0
- package/dist/types/agent.d.ts +533 -0
- package/dist/types/append-only-context.d.ts +141 -0
- package/dist/types/attempt-scope.d.ts +84 -0
- package/dist/types/compaction/adaptive.d.ts +31 -0
- package/dist/types/compaction/branch-summarization.d.ts +103 -0
- package/dist/types/compaction/compaction.d.ts +330 -0
- package/dist/types/compaction/entries.d.ts +124 -0
- package/dist/types/compaction/errors.d.ts +26 -0
- package/dist/types/compaction/index.d.ts +12 -0
- package/dist/types/compaction/messages.d.ts +61 -0
- package/dist/types/compaction/openai.d.ts +65 -0
- package/dist/types/compaction/pruning.d.ts +130 -0
- package/dist/types/compaction/utils.d.ts +32 -0
- package/dist/types/compaction.d.ts +1 -0
- package/dist/types/harmony-leak.d.ts +100 -0
- package/dist/types/heap-eviction-retainers.test.d.ts +1 -0
- package/dist/types/image-placeholder-guard.d.ts +4 -0
- package/dist/types/index.d.ts +13 -0
- package/dist/types/proxy.d.ts +95 -0
- package/dist/types/run-collector.d.ts +223 -0
- package/dist/types/run-resource-ledger.d.ts +2 -0
- package/dist/types/telemetry.d.ts +605 -0
- package/dist/types/thinking.d.ts +18 -0
- package/dist/types/tool-dispatch-identity.d.ts +27 -0
- package/dist/types/types.d.ts +790 -0
- package/package.json +72 -0
- package/src/agent-loop.ts +5632 -0
- package/src/agent.ts +2437 -0
- package/src/append-only-context.ts +496 -0
- package/src/attempt-scope.ts +195 -0
- package/src/compaction/adaptive.ts +92 -0
- package/src/compaction/branch-summarization.ts +358 -0
- package/src/compaction/compaction.ts +1569 -0
- package/src/compaction/entries.ts +158 -0
- package/src/compaction/errors.ts +31 -0
- package/src/compaction/index.ts +13 -0
- package/src/compaction/messages.ts +212 -0
- package/src/compaction/openai.ts +580 -0
- package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
- package/src/compaction/prompts/branch-summary-context.md +5 -0
- package/src/compaction/prompts/branch-summary-preamble.md +2 -0
- package/src/compaction/prompts/branch-summary.md +30 -0
- package/src/compaction/prompts/compaction-short-summary.md +9 -0
- package/src/compaction/prompts/compaction-summary-context.md +5 -0
- package/src/compaction/prompts/compaction-summary.md +38 -0
- package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
- package/src/compaction/prompts/compaction-update-summary.md +45 -0
- package/src/compaction/prompts/file-operations.md +10 -0
- package/src/compaction/prompts/handoff-document.md +56 -0
- package/src/compaction/prompts/summarization-system.md +3 -0
- package/src/compaction/pruning.ts +1026 -0
- package/src/compaction/utils.ts +189 -0
- package/src/compaction.ts +1 -0
- package/src/harmony-leak.ts +457 -0
- package/src/heap-eviction-retainers.test.ts +293 -0
- package/src/image-placeholder-guard.ts +20 -0
- package/src/index.ts +23 -0
- package/src/prompts/escaped-nonascii-recovery.md +3 -0
- package/src/prompts/repeated-tool-failure-recovery.md +1 -0
- package/src/proxy.ts +408 -0
- package/src/run-collector.ts +728 -0
- package/src/run-resource-ledger.ts +345 -0
- package/src/telemetry.ts +2161 -0
- package/src/thinking.ts +20 -0
- package/src/tool-dispatch-identity.ts +87 -0
- package/src/types.ts +882 -0
package/README.md
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
# @vib-rato/agent-core
|
|
2
|
+
|
|
3
|
+
Stateful agent with tool execution and event streaming. Built on `@vib-rato/ai`.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @vib-rato/agent-core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { Agent } from "@vib-rato/agent-core";
|
|
15
|
+
import { getModel } from "@vib-rato/ai";
|
|
16
|
+
|
|
17
|
+
const agent = new Agent({
|
|
18
|
+
initialState: {
|
|
19
|
+
systemPrompt: ["You are a helpful assistant."],
|
|
20
|
+
model: getModel("anthropic", "anthropic-model-sonnet-4-20250514"),
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
agent.subscribe((event) => {
|
|
25
|
+
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
26
|
+
// Stream just the new text chunk
|
|
27
|
+
process.stdout.write(event.assistantMessageEvent.delta);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
await agent.prompt("Hello!");
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Core Concepts
|
|
35
|
+
|
|
36
|
+
### AgentMessage vs LLM Message
|
|
37
|
+
|
|
38
|
+
The agent works with `AgentMessage`, a flexible type that can include:
|
|
39
|
+
|
|
40
|
+
- Standard LLM messages (`user`, `assistant`, `toolResult`)
|
|
41
|
+
- Custom app-specific message types via declaration merging
|
|
42
|
+
|
|
43
|
+
LLMs only understand `user`, `assistant`, and `toolResult`. The `convertToLlm` function bridges this gap by filtering and transforming messages before each LLM call.
|
|
44
|
+
|
|
45
|
+
### Message Flow
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
AgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM
|
|
49
|
+
(optional) (required)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
1. **transformContext**: Prune old messages, inject external context
|
|
53
|
+
2. **convertToLlm**: Filter out UI-only messages, convert custom types to LLM format
|
|
54
|
+
|
|
55
|
+
## Event Flow
|
|
56
|
+
|
|
57
|
+
The agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.
|
|
58
|
+
|
|
59
|
+
### prompt() Event Sequence
|
|
60
|
+
|
|
61
|
+
When you call `prompt("Hello")`:
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
prompt("Hello")
|
|
65
|
+
├─ agent_start
|
|
66
|
+
├─ turn_start
|
|
67
|
+
├─ message_start { message: userMessage } // Your prompt
|
|
68
|
+
├─ message_end { message: userMessage }
|
|
69
|
+
├─ message_start { message: assistantMessage } // LLM starts responding
|
|
70
|
+
├─ message_update { message: partial... } // Streaming chunks
|
|
71
|
+
├─ message_update { message: partial... }
|
|
72
|
+
├─ message_end { message: assistantMessage } // Complete response
|
|
73
|
+
├─ turn_end { message, toolResults: [] }
|
|
74
|
+
└─ agent_end { messages: [...] }
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
When a provider or local run failure occurs, the agent emits `agent_failed`
|
|
78
|
+
before the terminal `agent_end`:
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
{ type: "agent_failed", error, scope? }
|
|
82
|
+
// ...then
|
|
83
|
+
{ type: "agent_end", messages, stopReason: "error" }
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`agent_failed` is diagnostic and correlated to the same attempt; consumers must
|
|
87
|
+
not treat it as the terminal boundary or stop waiting for `agent_end`. The
|
|
88
|
+
failure event is additive, so existing `agent_end` handling remains required.
|
|
89
|
+
|
|
90
|
+
`agent_failed.error` is always a sanitized `{ code, message }` pair produced by
|
|
91
|
+
the runtime's failure sanitizer before emission — never the raw provider error.
|
|
92
|
+
Consumers must not depend on provider-specific detail, request bodies, or raw
|
|
93
|
+
error objects in this payload; the code is a stable classifier and the message
|
|
94
|
+
is a fixed human-readable description.
|
|
95
|
+
|
|
96
|
+
### With Tool Calls
|
|
97
|
+
|
|
98
|
+
If the assistant calls tools, the loop continues:
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
prompt("Read config.json")
|
|
102
|
+
├─ agent_start
|
|
103
|
+
├─ turn_start
|
|
104
|
+
├─ message_start/end { userMessage }
|
|
105
|
+
├─ message_start { assistantMessage with toolCall }
|
|
106
|
+
├─ message_update...
|
|
107
|
+
├─ message_end { assistantMessage }
|
|
108
|
+
├─ tool_execution_start { toolCallId, toolName, args }
|
|
109
|
+
├─ tool_execution_update { partialResult } // If tool streams
|
|
110
|
+
├─ tool_execution_end { toolCallId, result }
|
|
111
|
+
├─ message_start/end { toolResultMessage }
|
|
112
|
+
├─ turn_end { message, toolResults: [toolResult] }
|
|
113
|
+
│
|
|
114
|
+
├─ turn_start // Next turn
|
|
115
|
+
├─ message_start { assistantMessage } // LLM responds to tool result
|
|
116
|
+
├─ message_update...
|
|
117
|
+
├─ message_end
|
|
118
|
+
├─ turn_end
|
|
119
|
+
└─ agent_end
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### continue() Event Sequence
|
|
123
|
+
|
|
124
|
+
`continue()` resumes from existing context without adding a new message. Use it for retries after errors.
|
|
125
|
+
|
|
126
|
+
```typescript
|
|
127
|
+
// After an error, retry from current state
|
|
128
|
+
await agent.continue();
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
The last message in context must be `user` or `toolResult` (not `assistant`).
|
|
132
|
+
|
|
133
|
+
### Event Types
|
|
134
|
+
|
|
135
|
+
| Event | Description |
|
|
136
|
+
| ----------------------- | --------------------------------------------------------------- |
|
|
137
|
+
| `agent_start` | Agent begins processing |
|
|
138
|
+
| `agent_failed` | Provider/local failure diagnostic; emitted before terminal `agent_end` |
|
|
139
|
+
| `agent_end` | Agent completes with all new messages |
|
|
140
|
+
| `turn_start` | New turn begins (one LLM call + tool executions) |
|
|
141
|
+
| `turn_end` | Turn completes with assistant message and tool results |
|
|
142
|
+
| `message_start` | Any message begins (user, assistant, toolResult) |
|
|
143
|
+
| `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
|
|
144
|
+
| `message_end` | Message completes |
|
|
145
|
+
| `tool_execution_start` | Tool begins |
|
|
146
|
+
| `tool_execution_update` | Tool streams progress |
|
|
147
|
+
| `tool_execution_end` | Tool completes |
|
|
148
|
+
|
|
149
|
+
## Agent Options
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
const agent = new Agent({
|
|
153
|
+
// Initial state
|
|
154
|
+
initialState: {
|
|
155
|
+
systemPrompt: string[],
|
|
156
|
+
model: Model,
|
|
157
|
+
thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh",
|
|
158
|
+
tools: AgentTool<any>[],
|
|
159
|
+
messages: AgentMessage[],
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
// Convert AgentMessage[] to LLM Message[] (required for custom message types)
|
|
163
|
+
convertToLlm: (messages) => messages.filter(...),
|
|
164
|
+
|
|
165
|
+
// Transform context before convertToLlm (for pruning, compaction)
|
|
166
|
+
transformContext: async (messages, signal) => pruneOldMessages(messages),
|
|
167
|
+
|
|
168
|
+
// How to handle queued messages: "one-at-a-time" (default) or "all"
|
|
169
|
+
queueMode: "one-at-a-time",
|
|
170
|
+
|
|
171
|
+
// Custom stream function (for proxy backends)
|
|
172
|
+
streamFn: streamProxy,
|
|
173
|
+
|
|
174
|
+
// Dynamic API key resolution (for expiring OAuth tokens)
|
|
175
|
+
getApiKey: async (provider) => refreshToken(),
|
|
176
|
+
|
|
177
|
+
// Tool execution context (late-bound UI/session access)
|
|
178
|
+
getToolContext: () => ({ /* app-defined */ }),
|
|
179
|
+
});
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Agent State
|
|
183
|
+
|
|
184
|
+
```typescript
|
|
185
|
+
interface AgentState {
|
|
186
|
+
systemPrompt: string[];
|
|
187
|
+
model: Model;
|
|
188
|
+
thinkingLevel: ThinkingLevel;
|
|
189
|
+
tools: AgentTool<any>[];
|
|
190
|
+
messages: AgentMessage[];
|
|
191
|
+
isStreaming: boolean;
|
|
192
|
+
streamMessage: AgentMessage | null; // Current partial during streaming
|
|
193
|
+
pendingToolCalls: Set<string>;
|
|
194
|
+
error?: string;
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Access via `agent.state`. During streaming, `streamMessage` contains the partial assistant message.
|
|
199
|
+
|
|
200
|
+
## Methods
|
|
201
|
+
|
|
202
|
+
### Prompting
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
// Text prompt
|
|
206
|
+
await agent.prompt("Hello");
|
|
207
|
+
|
|
208
|
+
// With images
|
|
209
|
+
await agent.prompt("What's in this image?", [{ type: "image", data: base64Data, mimeType: "image/jpeg" }]);
|
|
210
|
+
|
|
211
|
+
// AgentMessage directly
|
|
212
|
+
await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
|
|
213
|
+
|
|
214
|
+
// Continue from current context (last message must be user or toolResult)
|
|
215
|
+
await agent.continue();
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### State Management
|
|
219
|
+
|
|
220
|
+
```typescript
|
|
221
|
+
agent.setSystemPrompt("New prompt");
|
|
222
|
+
agent.setModel(getModel("openai", "gpt-4o"));
|
|
223
|
+
agent.setThinkingLevel("medium");
|
|
224
|
+
agent.setTools([myTool]);
|
|
225
|
+
agent.replaceMessages(newMessages);
|
|
226
|
+
agent.appendMessage(message);
|
|
227
|
+
agent.clearMessages();
|
|
228
|
+
agent.reset(); // Clear everything
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### Control
|
|
232
|
+
|
|
233
|
+
```typescript
|
|
234
|
+
agent.abort(); // Cancel current operation
|
|
235
|
+
await agent.waitForIdle(); // Wait for completion
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
### Events
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
const unsubscribe = agent.subscribe((event) => {
|
|
242
|
+
console.log(event.type);
|
|
243
|
+
});
|
|
244
|
+
unsubscribe();
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
## Steering & Follow-up
|
|
248
|
+
|
|
249
|
+
Queue messages to inject during tool execution (steering) or after the agent would otherwise stop (follow-up):
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
agent.setSteeringMode("one-at-a-time");
|
|
253
|
+
agent.setInterruptMode("immediate");
|
|
254
|
+
|
|
255
|
+
// While agent is running tools
|
|
256
|
+
agent.steer({
|
|
257
|
+
role: "user",
|
|
258
|
+
content: "Stop! Do this instead.",
|
|
259
|
+
timestamp: Date.now(),
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// Queue a follow-up to run after the current turn completes
|
|
263
|
+
agent.followUp({
|
|
264
|
+
role: "user",
|
|
265
|
+
content: "After that, summarize the changes.",
|
|
266
|
+
timestamp: Date.now(),
|
|
267
|
+
});
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
Steering messages are checked after each tool call by default. Set `interruptMode` to `"wait"` to defer
|
|
271
|
+
steering until the current turn completes.
|
|
272
|
+
|
|
273
|
+
## Custom Message Types
|
|
274
|
+
|
|
275
|
+
Extend `AgentMessage` via declaration merging:
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
declare module "@vib-rato/agent-core" {
|
|
279
|
+
interface CustomAgentMessages {
|
|
280
|
+
notification: { role: "notification"; text: string; timestamp: number };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Now valid
|
|
285
|
+
const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Handle custom types in `convertToLlm`:
|
|
289
|
+
|
|
290
|
+
```typescript
|
|
291
|
+
const agent = new Agent({
|
|
292
|
+
convertToLlm: (messages) =>
|
|
293
|
+
messages.flatMap((m) => {
|
|
294
|
+
if (m.role === "notification") return []; // Filter out
|
|
295
|
+
return [m];
|
|
296
|
+
}),
|
|
297
|
+
});
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
## Tools
|
|
301
|
+
|
|
302
|
+
Define tools using `AgentTool` with a Zod parameter schema (via `z` from `@vib-rato/ai`).
|
|
303
|
+
|
|
304
|
+
```typescript
|
|
305
|
+
import { z } from "@vib-rato/ai";
|
|
306
|
+
|
|
307
|
+
const readFileTool: AgentTool = {
|
|
308
|
+
name: "read_file",
|
|
309
|
+
label: "Read File", // For UI display
|
|
310
|
+
description: "Read a file's contents",
|
|
311
|
+
parameters: z.object({
|
|
312
|
+
path: z.string().describe("File path"),
|
|
313
|
+
}),
|
|
314
|
+
execute: async (toolCallId, params, signal, onUpdate, context) => {
|
|
315
|
+
const content = await fs.readFile(params.path, "utf-8");
|
|
316
|
+
|
|
317
|
+
// Optional: stream progress
|
|
318
|
+
onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
content: [{ type: "text", text: content }],
|
|
322
|
+
details: { path: params.path, size: content.length },
|
|
323
|
+
};
|
|
324
|
+
},
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
agent.setTools([readFileTool]);
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
### Error Handling
|
|
331
|
+
|
|
332
|
+
**Throw an error** when a tool fails. Do not return error messages as content.
|
|
333
|
+
|
|
334
|
+
```typescript
|
|
335
|
+
execute: async (toolCallId, params, signal, onUpdate) => {
|
|
336
|
+
if (!fs.existsSync(params.path)) {
|
|
337
|
+
throw new Error(`File not found: ${params.path}`);
|
|
338
|
+
}
|
|
339
|
+
// Return content only on success
|
|
340
|
+
return { content: [{ type: "text", text: "..." }] };
|
|
341
|
+
};
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
Thrown errors are caught by the agent and reported to the LLM as tool errors with `isError: true`.
|
|
345
|
+
|
|
346
|
+
## Proxy Usage
|
|
347
|
+
|
|
348
|
+
For browser apps that proxy through a backend:
|
|
349
|
+
|
|
350
|
+
```typescript
|
|
351
|
+
import { Agent, streamProxy } from "@vib-rato/agent-core";
|
|
352
|
+
|
|
353
|
+
const agent = new Agent({
|
|
354
|
+
streamFn: (model, context, options) =>
|
|
355
|
+
streamProxy(model, context, {
|
|
356
|
+
...options,
|
|
357
|
+
authToken: "...",
|
|
358
|
+
proxyUrl: "https://your-server.com",
|
|
359
|
+
}),
|
|
360
|
+
});
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
## Low-Level API
|
|
364
|
+
|
|
365
|
+
For direct control without the Agent class:
|
|
366
|
+
|
|
367
|
+
```typescript
|
|
368
|
+
import { agentLoop, agentLoopContinue } from "@vib-rato/agent-core";
|
|
369
|
+
|
|
370
|
+
const context: AgentContext = {
|
|
371
|
+
systemPrompt: ["You are helpful."],
|
|
372
|
+
messages: [],
|
|
373
|
+
tools: [],
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
const config: AgentLoopConfig = {
|
|
377
|
+
model: getModel("openai", "gpt-4o"),
|
|
378
|
+
convertToLlm: (msgs) => msgs.filter((m) => ["user", "assistant", "toolResult"].includes(m.role)),
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
|
|
382
|
+
|
|
383
|
+
for await (const event of agentLoop([userMessage], context, config)) {
|
|
384
|
+
console.log(event.type);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Continue from existing context
|
|
388
|
+
for await (const event of agentLoopContinue(context, config)) {
|
|
389
|
+
console.log(event.type);
|
|
390
|
+
}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
## Run-level telemetry
|
|
394
|
+
Every `invoke_agent` produces two values alongside the OTEL spans:
|
|
395
|
+
|
|
396
|
+
- **`AgentRunSummary`** — chat / tool / usage / cost / error counters bucketed
|
|
397
|
+
by status, with per-tool-name breakdowns. Pure aggregation, safe to
|
|
398
|
+
persist, diff, or assert.
|
|
399
|
+
- **`AgentRunCoverage`** — sorted+deduped `toolsAvailable` / `toolsInvoked` /
|
|
400
|
+
`toolsUnused` / `modelsUsed` / `providersUsed` arrays. Stable for snapshot
|
|
401
|
+
tests.
|
|
402
|
+
|
|
403
|
+
Three delivery channels (use whichever fits):
|
|
404
|
+
|
|
405
|
+
### `agent_end` event (additive)
|
|
406
|
+
|
|
407
|
+
```typescript
|
|
408
|
+
for await (const event of agentLoop([userMessage], context, {
|
|
409
|
+
...config,
|
|
410
|
+
telemetry: {},
|
|
411
|
+
})) {
|
|
412
|
+
if (event.type === "agent_end" && event.telemetry) {
|
|
413
|
+
console.log("tokens:", event.telemetry.usage.totalTokens);
|
|
414
|
+
console.log("unused tools:", event.coverage?.toolsUnused);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
The `messages` field is unchanged. Consumers that ignore `telemetry`/
|
|
420
|
+
`coverage` continue to work.
|
|
421
|
+
|
|
422
|
+
### `onRunEnd` hook (non-fatal)
|
|
423
|
+
|
|
424
|
+
```typescript
|
|
425
|
+
const stream = agentLoop([userMessage], context, {
|
|
426
|
+
...config,
|
|
427
|
+
telemetry: {
|
|
428
|
+
onRunEnd: (summary, coverage) => {
|
|
429
|
+
await persistRunSummary(summary, coverage);
|
|
430
|
+
},
|
|
431
|
+
},
|
|
432
|
+
});
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
Exceptions thrown from `onRunEnd` are caught and logged via `console.warn`;
|
|
436
|
+
a misbehaving telemetry consumer can **never** turn a successful agent run
|
|
437
|
+
into a failed one.
|
|
438
|
+
|
|
439
|
+
### `agentLoopDetailed` (typed `detailed()` result)
|
|
440
|
+
|
|
441
|
+
Convenience wrapper that preserves the existing stream API and exposes the
|
|
442
|
+
rollup as a typed value:
|
|
443
|
+
|
|
444
|
+
```typescript
|
|
445
|
+
const { stream, detailed } = agentLoopDetailed([userMessage], context, {
|
|
446
|
+
...config,
|
|
447
|
+
telemetry: {}, // required to populate telemetry/coverage
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
for await (const event of stream) {
|
|
451
|
+
// existing event handling
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const { messages, telemetry, coverage } = await detailed();
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
`stream.result()` still resolves to `AgentMessage[]` — no breaking change.
|
|
458
|
+
|
|
459
|
+
### Multi-run aggregation
|
|
460
|
+
|
|
461
|
+
Callers that drive the loop multiple times (verify pass, benchmark harness)
|
|
462
|
+
fold N summaries with `aggregateAgentRunSummaries` / `aggregateAgentRunCoverage`:
|
|
463
|
+
|
|
464
|
+
```typescript
|
|
465
|
+
import {
|
|
466
|
+
aggregateAgentRunSummaries,
|
|
467
|
+
aggregateAgentRunCoverage,
|
|
468
|
+
} from "@vib-rato/agent-core";
|
|
469
|
+
|
|
470
|
+
const summaries: AgentRunSummary[] = [];
|
|
471
|
+
const coverages: AgentRunCoverage[] = [];
|
|
472
|
+
for (const target of targets) {
|
|
473
|
+
const { detailed } = agentLoopDetailed(/* ... */);
|
|
474
|
+
const result = await detailed();
|
|
475
|
+
if (result.telemetry) summaries.push(result.telemetry);
|
|
476
|
+
if (result.coverage) coverages.push(result.coverage);
|
|
477
|
+
}
|
|
478
|
+
const runSummary = aggregateAgentRunSummaries(summaries);
|
|
479
|
+
const runCoverage = aggregateAgentRunCoverage(coverages);
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
### Tool status reporting
|
|
483
|
+
|
|
484
|
+
`execute_tool` spans carry `pi.gen_ai.tool.status` ∈
|
|
485
|
+
`"ok" | "error" | "skipped" | "blocked" | "timeout" | "aborted"`.
|
|
486
|
+
`beforeToolCall` blocks throw a distinguishable `ToolCallBlockedError`
|
|
487
|
+
internally; the catch path reports `status: "blocked"` instead of conflating
|
|
488
|
+
with generic tool errors. Pre-run interrupts and tail-sweep skips are
|
|
489
|
+
recorded as `"skipped"` even though they never start a span.
|
|
490
|
+
|
|
491
|
+
## License
|
|
492
|
+
|
|
493
|
+
MIT
|