@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.
Files changed (69) hide show
  1. package/CHANGELOG.md +852 -0
  2. package/README.md +493 -0
  3. package/dist/types/agent-loop.d.ts +229 -0
  4. package/dist/types/agent.d.ts +533 -0
  5. package/dist/types/append-only-context.d.ts +141 -0
  6. package/dist/types/attempt-scope.d.ts +84 -0
  7. package/dist/types/compaction/adaptive.d.ts +31 -0
  8. package/dist/types/compaction/branch-summarization.d.ts +103 -0
  9. package/dist/types/compaction/compaction.d.ts +330 -0
  10. package/dist/types/compaction/entries.d.ts +124 -0
  11. package/dist/types/compaction/errors.d.ts +26 -0
  12. package/dist/types/compaction/index.d.ts +12 -0
  13. package/dist/types/compaction/messages.d.ts +61 -0
  14. package/dist/types/compaction/openai.d.ts +65 -0
  15. package/dist/types/compaction/pruning.d.ts +130 -0
  16. package/dist/types/compaction/utils.d.ts +32 -0
  17. package/dist/types/compaction.d.ts +1 -0
  18. package/dist/types/harmony-leak.d.ts +100 -0
  19. package/dist/types/heap-eviction-retainers.test.d.ts +1 -0
  20. package/dist/types/image-placeholder-guard.d.ts +4 -0
  21. package/dist/types/index.d.ts +13 -0
  22. package/dist/types/proxy.d.ts +95 -0
  23. package/dist/types/run-collector.d.ts +223 -0
  24. package/dist/types/run-resource-ledger.d.ts +2 -0
  25. package/dist/types/telemetry.d.ts +605 -0
  26. package/dist/types/thinking.d.ts +18 -0
  27. package/dist/types/tool-dispatch-identity.d.ts +27 -0
  28. package/dist/types/types.d.ts +790 -0
  29. package/package.json +72 -0
  30. package/src/agent-loop.ts +5632 -0
  31. package/src/agent.ts +2437 -0
  32. package/src/append-only-context.ts +496 -0
  33. package/src/attempt-scope.ts +195 -0
  34. package/src/compaction/adaptive.ts +92 -0
  35. package/src/compaction/branch-summarization.ts +358 -0
  36. package/src/compaction/compaction.ts +1569 -0
  37. package/src/compaction/entries.ts +158 -0
  38. package/src/compaction/errors.ts +31 -0
  39. package/src/compaction/index.ts +13 -0
  40. package/src/compaction/messages.ts +212 -0
  41. package/src/compaction/openai.ts +580 -0
  42. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  43. package/src/compaction/prompts/branch-summary-context.md +5 -0
  44. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  45. package/src/compaction/prompts/branch-summary.md +30 -0
  46. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  47. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  48. package/src/compaction/prompts/compaction-summary.md +38 -0
  49. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  50. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  51. package/src/compaction/prompts/file-operations.md +10 -0
  52. package/src/compaction/prompts/handoff-document.md +56 -0
  53. package/src/compaction/prompts/summarization-system.md +3 -0
  54. package/src/compaction/pruning.ts +1026 -0
  55. package/src/compaction/utils.ts +189 -0
  56. package/src/compaction.ts +1 -0
  57. package/src/harmony-leak.ts +457 -0
  58. package/src/heap-eviction-retainers.test.ts +293 -0
  59. package/src/image-placeholder-guard.ts +20 -0
  60. package/src/index.ts +23 -0
  61. package/src/prompts/escaped-nonascii-recovery.md +3 -0
  62. package/src/prompts/repeated-tool-failure-recovery.md +1 -0
  63. package/src/proxy.ts +408 -0
  64. package/src/run-collector.ts +728 -0
  65. package/src/run-resource-ledger.ts +345 -0
  66. package/src/telemetry.ts +2161 -0
  67. package/src/thinking.ts +20 -0
  68. package/src/tool-dispatch-identity.ts +87 -0
  69. package/src/types.ts +882 -0
@@ -0,0 +1,728 @@
1
+ /**
2
+ * Per-invocation run aggregator. Buffers per-chat and per-tool records as the
3
+ * loop executes and folds them into a single {@link AgentRunSummary} +
4
+ * {@link AgentRunCoverage} value at the end.
5
+ *
6
+ * One collector lives on each {@link AgentTelemetry} handle, which is
7
+ * constructed once per `agentLoop` invocation in {@link resolveTelemetry}.
8
+ * Collector lookups use the live `Span` as a `WeakMap` key — bounded memory,
9
+ * no cross-invoke leakage.
10
+ *
11
+ * The collector is fed exclusively by helpers in `./telemetry.ts`. Loop
12
+ * authors do not interact with it directly except via the public
13
+ * `recordSkippedTool` helper used for the two skip paths that bypass spans
14
+ * entirely (pre-run interrupt and the tail-sweep for tool calls that never
15
+ * produced a result message).
16
+ */
17
+
18
+ import type { Span } from "@opentelemetry/api";
19
+ import type { AssistantMessage, Model, StopReason } from "@vib-rato/ai";
20
+
21
+ /** Terminal status reported by an `execute_tool` span. */
22
+ export type ToolStatus = "ok" | "error" | "skipped" | "blocked" | "timeout" | "aborted";
23
+
24
+ /** Raw record for a single `chat` step, finalized by `finishChatSpan`. */
25
+ export interface ChatRecord {
26
+ readonly stepNumber: number;
27
+ readonly model: string;
28
+ readonly provider: string;
29
+ readonly stopReason: StopReason | undefined;
30
+ readonly latencyMs: number;
31
+ readonly inputTokens: number;
32
+ readonly outputTokens: number;
33
+ readonly cachedInputTokens: number;
34
+ readonly cacheWriteTokens: number;
35
+ readonly reasoningOutputTokens: number;
36
+ readonly totalTokens: number;
37
+ readonly costUsd: number | undefined;
38
+ readonly costUnavailableReason: string | undefined;
39
+ readonly errorType: string | undefined;
40
+ }
41
+
42
+ /** Raw record for a single `execute_tool` invocation. */
43
+ export interface ToolRecord {
44
+ readonly toolCallId: string;
45
+ readonly toolName: string;
46
+ readonly status: ToolStatus;
47
+ readonly latencyMs: number;
48
+ readonly errorType: string | undefined;
49
+ }
50
+
51
+ /** Per-tool counters surfaced under {@link AgentRunSummary.tools.byName}. */
52
+ export interface ToolCounters {
53
+ readonly total: number;
54
+ readonly ok: number;
55
+ readonly error: number;
56
+ readonly skipped: number;
57
+ readonly blocked: number;
58
+ readonly timeout: number;
59
+ readonly aborted: number;
60
+ readonly totalLatencyMs: number;
61
+ }
62
+
63
+ /**
64
+ * Run-level rollup returned in the `agent_end` event and passed to
65
+ * {@link AgentTelemetryConfig.onRunEnd}. Pure aggregation — no references to
66
+ * spans, no callbacks, no live state. Safe to persist / diff / assert.
67
+ */
68
+ export interface AgentRunSummary {
69
+ readonly chats: {
70
+ readonly total: number;
71
+ /** Bucketed by raw {@link StopReason}; absent reasons omitted. */
72
+ readonly byStopReason: Readonly<Record<string, number>>;
73
+ readonly totalLatencyMs: number;
74
+ };
75
+ readonly tools: {
76
+ readonly total: number;
77
+ readonly ok: number;
78
+ readonly error: number;
79
+ readonly skipped: number;
80
+ readonly blocked: number;
81
+ readonly timeout: number;
82
+ readonly aborted: number;
83
+ readonly totalLatencyMs: number;
84
+ /** Per-tool-name counters; keys sorted by name on snapshot. */
85
+ readonly byName: Readonly<Record<string, ToolCounters>>;
86
+ };
87
+ readonly usage: {
88
+ readonly inputTokens: number;
89
+ readonly outputTokens: number;
90
+ readonly cachedInputTokens: number;
91
+ readonly cacheWriteTokens: number;
92
+ readonly reasoningOutputTokens: number;
93
+ readonly totalTokens: number;
94
+ };
95
+ readonly cost: {
96
+ readonly estimatedUsd: number;
97
+ /** Sorted, deduped. */
98
+ readonly unavailableReasons: readonly string[];
99
+ };
100
+ readonly errors: {
101
+ readonly total: number;
102
+ readonly byType: Readonly<Record<string, number>>;
103
+ };
104
+ readonly stepCount: number;
105
+ }
106
+
107
+ /**
108
+ * Coverage rollup: registered-vs-invoked across the run. All arrays are
109
+ * sorted ascending and deduped so the value is stable for diffing.
110
+ */
111
+ export interface AgentRunCoverage {
112
+ readonly toolsAvailable: readonly string[];
113
+ readonly toolsInvoked: readonly string[];
114
+ readonly toolsUnused: readonly string[];
115
+ readonly modelsUsed: readonly string[];
116
+ readonly providersUsed: readonly string[];
117
+ }
118
+
119
+ interface ChatStart {
120
+ readonly stepNumber: number;
121
+ readonly startedAtMs: number;
122
+ readonly model: string;
123
+ readonly provider: string;
124
+ }
125
+
126
+ interface ToolStart {
127
+ readonly toolCallId: string;
128
+ readonly toolName: string;
129
+ readonly startedAtMs: number;
130
+ }
131
+
132
+ /**
133
+ * Per-invocation event buffer. Constructed unconditionally inside
134
+ * {@link resolveTelemetry}; cost is one allocation per `agentLoop` call.
135
+ *
136
+ * Methods are intentionally non-throwing — telemetry must never turn a
137
+ * successful agent run into a failed one. Span state is kept on live spans for
138
+ * span-enabled runs; spanless pending records use private pending queues. If
139
+ * a finish path is somehow reached without a matching begin (provider crash,
140
+ * tracer swap mid-run), the corresponding record is still emitted with
141
+ * `latencyMs: 0` rather than throwing.
142
+ */
143
+ const kChatStart = Symbol("agent.run-collector.chatStart");
144
+ const kToolStart = Symbol("agent.run-collector.toolStart");
145
+ type SpanWithChatStart = Span & { [kChatStart]?: ChatStart };
146
+ type SpanWithToolStart = Span & { [kToolStart]?: ToolStart };
147
+
148
+ export class AgentRunCollector {
149
+ readonly #chats: ChatRecord[] = [];
150
+ readonly #tools: ToolRecord[] = [];
151
+ readonly #availableTools = new Set<string>();
152
+ readonly #invokedTools = new Set<string>();
153
+ readonly #modelsUsed = new Set<string>();
154
+ readonly #providersUsed = new Set<string>();
155
+ readonly #spanlessChatStarts: ChatStart[] = [];
156
+ readonly #spanlessToolStarts = new Map<string, ToolStart[]>();
157
+ #runEnded = false;
158
+
159
+ /** True once `markRunEnded()` has been called for this invocation. */
160
+ get runEnded(): boolean {
161
+ return this.#runEnded;
162
+ }
163
+
164
+ /**
165
+ * Mark this run as logically ended. Callers use this to coordinate the
166
+ * `onRunEnd` hook between the success path (fires inside
167
+ * `buildAgentEndEvent`, before `stream.end()`) and the error path (fires
168
+ * inside `finishInvokeAgentSpan`'s finally). Idempotent — returns `true`
169
+ * the first time, `false` on subsequent calls.
170
+ */
171
+ markRunEnded(): boolean {
172
+ if (this.#runEnded) return false;
173
+ this.#runEnded = true;
174
+ return true;
175
+ }
176
+
177
+ /** Record the tool names exposed on a single chat step. */
178
+ noteAvailableTools(tools: readonly { readonly name: string }[] | undefined): void {
179
+ if (!tools) return;
180
+ for (const tool of tools) this.#availableTools.add(tool.name);
181
+ }
182
+
183
+ beginChat(
184
+ span: Span,
185
+ init: { readonly stepNumber: number; readonly model: Model; readonly provider?: string },
186
+ ): void {
187
+ const provider = init.provider ?? init.model.provider;
188
+ (span as SpanWithChatStart)[kChatStart] = {
189
+ stepNumber: init.stepNumber,
190
+ startedAtMs: performance.now(),
191
+ model: init.model.id,
192
+ provider,
193
+ };
194
+ this.#noteChatModel(init.model.id, provider);
195
+ }
196
+
197
+ /** Begin a chat record without allocating or mutating an OTEL span. */
198
+ beginChatWithoutSpan(init: {
199
+ readonly stepNumber: number;
200
+ readonly model: Model;
201
+ readonly provider?: string;
202
+ }): void {
203
+ const provider = init.provider ?? init.model.provider;
204
+ this.#spanlessChatStarts.push({
205
+ stepNumber: init.stepNumber,
206
+ startedAtMs: performance.now(),
207
+ model: init.model.id,
208
+ provider,
209
+ });
210
+ this.#noteChatModel(init.model.id, provider);
211
+ }
212
+
213
+ endChat(
214
+ span: Span,
215
+ message: AssistantMessage,
216
+ fields: {
217
+ readonly costUsd: number | undefined;
218
+ readonly costUnavailableReason: string | undefined;
219
+ },
220
+ ): void {
221
+ const start = (span as SpanWithChatStart)[kChatStart];
222
+ (span as SpanWithChatStart)[kChatStart] = undefined;
223
+ this.#recordChat(start, message, fields);
224
+ }
225
+
226
+ /** Finish a chat record without allocating or mutating an OTEL span. */
227
+ endChatWithoutSpan(
228
+ stepNumber: number | undefined,
229
+ message: AssistantMessage,
230
+ fields: {
231
+ readonly costUsd: number | undefined;
232
+ readonly costUnavailableReason: string | undefined;
233
+ },
234
+ ): void {
235
+ this.#recordChat(this.#takeSpanlessChatStart(stepNumber), message, fields);
236
+ }
237
+
238
+ /**
239
+ * Stamp the chat span as failed without a finalized AssistantMessage. Used
240
+ * by the `catch` arm of `streamAssistantResponse` so error chats still
241
+ * appear in the run summary.
242
+ */
243
+ failChat(span: Span, fields: { readonly errorType: string }): void {
244
+ const start = (span as SpanWithChatStart)[kChatStart];
245
+ (span as SpanWithChatStart)[kChatStart] = undefined;
246
+ this.#recordFailedChat(start, fields.errorType);
247
+ }
248
+
249
+ /** Record a failed chat without allocating or mutating an OTEL span. */
250
+ failChatWithoutSpan(stepNumber: number | undefined, fields: { readonly errorType: string }): void {
251
+ this.#recordFailedChat(this.#takeSpanlessChatStart(stepNumber), fields.errorType);
252
+ }
253
+
254
+ #noteChatModel(model: string, provider: string | undefined): void {
255
+ this.#modelsUsed.add(model);
256
+ if (provider) this.#providersUsed.add(provider);
257
+ }
258
+
259
+ #takeSpanlessChatStart(stepNumber: number | undefined): ChatStart | undefined {
260
+ for (let index = this.#spanlessChatStarts.length - 1; index >= 0; index -= 1) {
261
+ const start = this.#spanlessChatStarts[index];
262
+ if (stepNumber !== undefined && start.stepNumber !== stepNumber) continue;
263
+ this.#spanlessChatStarts.splice(index, 1);
264
+ return start;
265
+ }
266
+ return undefined;
267
+ }
268
+
269
+ #recordChat(
270
+ start: ChatStart | undefined,
271
+ message: AssistantMessage,
272
+ fields: {
273
+ readonly costUsd: number | undefined;
274
+ readonly costUnavailableReason: string | undefined;
275
+ },
276
+ ): void {
277
+ const usage = message.usage;
278
+ // Public surface: `inputTokens` is the total cost-bearing input the
279
+ // provider charged for, so it must include cache_read + cache_write.
280
+ // The per-bucket fields below preserve the breakdown for callers that
281
+ // want it. `aggregateAgentRunSummaries` sums each field independently
282
+ // and never re-derives `inputTokens` from the buckets, so this stays
283
+ // consistent across run merges.
284
+ const inputBase = usage?.input ?? 0;
285
+ const cachedInputTokens = usage?.cacheRead ?? 0;
286
+ const cacheWriteTokens = usage?.cacheWrite ?? 0;
287
+ const inputTokens = inputBase + cachedInputTokens + cacheWriteTokens;
288
+ const outputTokens = usage?.output ?? 0;
289
+ const reasoningOutputTokens = usage?.reasoningTokens ?? 0;
290
+ const totalTokens = usage?.totalTokens ?? inputTokens + outputTokens;
291
+ this.#chats.push({
292
+ stepNumber: start?.stepNumber ?? -1,
293
+ model: start?.model ?? message.model,
294
+ provider: start?.provider ?? message.provider,
295
+ stopReason: message.stopReason,
296
+ latencyMs: start ? Math.max(0, performance.now() - start.startedAtMs) : 0,
297
+ inputTokens,
298
+ outputTokens,
299
+ cachedInputTokens,
300
+ cacheWriteTokens,
301
+ reasoningOutputTokens,
302
+ totalTokens,
303
+ costUsd: fields.costUsd,
304
+ costUnavailableReason: fields.costUnavailableReason,
305
+ errorType: message.stopReason === "error" || message.stopReason === "aborted" ? message.stopReason : undefined,
306
+ });
307
+ }
308
+
309
+ #recordFailedChat(start: ChatStart | undefined, errorType: string): void {
310
+ this.#chats.push({
311
+ stepNumber: start?.stepNumber ?? -1,
312
+ model: start?.model ?? "",
313
+ provider: start?.provider ?? "",
314
+ stopReason: "error",
315
+ latencyMs: start ? Math.max(0, performance.now() - start.startedAtMs) : 0,
316
+ inputTokens: 0,
317
+ outputTokens: 0,
318
+ cachedInputTokens: 0,
319
+ cacheWriteTokens: 0,
320
+ reasoningOutputTokens: 0,
321
+ totalTokens: 0,
322
+ costUsd: undefined,
323
+ costUnavailableReason: undefined,
324
+ errorType,
325
+ });
326
+ }
327
+
328
+ beginTool(span: Span, init: { readonly toolCallId: string; readonly toolName: string }): void {
329
+ (span as SpanWithToolStart)[kToolStart] = {
330
+ toolCallId: init.toolCallId,
331
+ toolName: init.toolName,
332
+ startedAtMs: performance.now(),
333
+ };
334
+ this.#invokedTools.add(init.toolName);
335
+ }
336
+
337
+ /** Begin a tool record without allocating or mutating an OTEL span. */
338
+ beginToolWithoutSpan(init: { readonly toolCallId: string; readonly toolName: string }): void {
339
+ const starts = this.#spanlessToolStarts.get(init.toolCallId) ?? [];
340
+ starts.push({
341
+ toolCallId: init.toolCallId,
342
+ toolName: init.toolName,
343
+ startedAtMs: performance.now(),
344
+ });
345
+ this.#spanlessToolStarts.set(init.toolCallId, starts);
346
+ this.#invokedTools.add(init.toolName);
347
+ }
348
+
349
+ endTool(span: Span, fields: { readonly status: ToolStatus; readonly errorType: string | undefined }): void {
350
+ const start = (span as SpanWithToolStart)[kToolStart];
351
+ (span as SpanWithToolStart)[kToolStart] = undefined;
352
+ this.#recordTool(start, fields);
353
+ }
354
+
355
+ /** Finish a tool record without allocating or mutating an OTEL span. */
356
+ endToolWithoutSpan(record: {
357
+ readonly toolCallId: string;
358
+ readonly toolName: string;
359
+ readonly status: ToolStatus;
360
+ readonly errorType: string | undefined;
361
+ }): void {
362
+ const starts = this.#spanlessToolStarts.get(record.toolCallId);
363
+ const start = starts?.pop();
364
+ if (starts && starts.length === 0) this.#spanlessToolStarts.delete(record.toolCallId);
365
+ this.#recordTool(start ?? { ...record, startedAtMs: performance.now() }, record);
366
+ }
367
+
368
+ #recordTool(
369
+ start: ToolStart | undefined,
370
+ fields: { readonly status: ToolStatus; readonly errorType: string | undefined },
371
+ ): void {
372
+ this.#tools.push({
373
+ toolCallId: start?.toolCallId ?? "",
374
+ toolName: start?.toolName ?? "",
375
+ status: fields.status,
376
+ latencyMs: start ? Math.max(0, performance.now() - start.startedAtMs) : 0,
377
+ errorType: fields.errorType,
378
+ });
379
+ }
380
+
381
+ /**
382
+ * Record a tool that never produced a span — pre-run interrupt or tail
383
+ * sweep. The LLM still asked for it, so it counts toward
384
+ * {@link AgentRunCoverage.toolsInvoked}.
385
+ */
386
+ recordOrphanTool(record: {
387
+ readonly toolCallId: string;
388
+ readonly toolName: string;
389
+ readonly status: ToolStatus;
390
+ }): void {
391
+ this.#invokedTools.add(record.toolName);
392
+ this.#tools.push({
393
+ toolCallId: record.toolCallId,
394
+ toolName: record.toolName,
395
+ status: record.status,
396
+ latencyMs: 0,
397
+ errorType: undefined,
398
+ });
399
+ }
400
+
401
+ /** Build the immutable summary value from buffered records. */
402
+ snapshot(opts: { readonly stepCount: number }): {
403
+ readonly summary: AgentRunSummary;
404
+ readonly coverage: AgentRunCoverage;
405
+ } {
406
+ return {
407
+ summary: this.#buildSummary(opts.stepCount),
408
+ coverage: this.#buildCoverage(),
409
+ };
410
+ }
411
+
412
+ #buildSummary(stepCount: number): AgentRunSummary {
413
+ const byStopReason: Record<string, number> = {};
414
+ let chatLatency = 0;
415
+ let inputTokens = 0;
416
+ let outputTokens = 0;
417
+ let cachedInputTokens = 0;
418
+ let cacheWriteTokens = 0;
419
+ let reasoningOutputTokens = 0;
420
+ let totalTokens = 0;
421
+ let estimatedUsd = 0;
422
+ const unavailableReasons = new Set<string>();
423
+ const errorsByType: Record<string, number> = {};
424
+
425
+ for (const chat of this.#chats) {
426
+ chatLatency += chat.latencyMs;
427
+ inputTokens += chat.inputTokens;
428
+ outputTokens += chat.outputTokens;
429
+ cachedInputTokens += chat.cachedInputTokens;
430
+ cacheWriteTokens += chat.cacheWriteTokens;
431
+ reasoningOutputTokens += chat.reasoningOutputTokens;
432
+ totalTokens += chat.totalTokens;
433
+ if (chat.stopReason) byStopReason[chat.stopReason] = (byStopReason[chat.stopReason] ?? 0) + 1;
434
+ if (chat.costUsd != null) estimatedUsd += chat.costUsd;
435
+ if (chat.costUnavailableReason) unavailableReasons.add(chat.costUnavailableReason);
436
+ if (chat.errorType) errorsByType[chat.errorType] = (errorsByType[chat.errorType] ?? 0) + 1;
437
+ }
438
+
439
+ const byName: Record<string, ToolCounters> = {};
440
+ const counts: Record<ToolStatus, number> = {
441
+ ok: 0,
442
+ error: 0,
443
+ skipped: 0,
444
+ blocked: 0,
445
+ timeout: 0,
446
+ aborted: 0,
447
+ };
448
+ let toolLatency = 0;
449
+ for (const tool of this.#tools) {
450
+ counts[tool.status] += 1;
451
+ toolLatency += tool.latencyMs;
452
+ const existing = byName[tool.toolName] ?? {
453
+ total: 0,
454
+ ok: 0,
455
+ error: 0,
456
+ skipped: 0,
457
+ blocked: 0,
458
+ timeout: 0,
459
+ aborted: 0,
460
+ totalLatencyMs: 0,
461
+ };
462
+ byName[tool.toolName] = {
463
+ total: existing.total + 1,
464
+ ok: existing.ok + (tool.status === "ok" ? 1 : 0),
465
+ error: existing.error + (tool.status === "error" ? 1 : 0),
466
+ skipped: existing.skipped + (tool.status === "skipped" ? 1 : 0),
467
+ blocked: existing.blocked + (tool.status === "blocked" ? 1 : 0),
468
+ timeout: existing.timeout + (tool.status === "timeout" ? 1 : 0),
469
+ aborted: existing.aborted + (tool.status === "aborted" ? 1 : 0),
470
+ totalLatencyMs: existing.totalLatencyMs + tool.latencyMs,
471
+ };
472
+ if (tool.errorType) errorsByType[tool.errorType] = (errorsByType[tool.errorType] ?? 0) + 1;
473
+ }
474
+
475
+ let errorTotal = 0;
476
+ for (const v of Object.values(errorsByType)) errorTotal += v;
477
+
478
+ return {
479
+ chats: {
480
+ total: this.#chats.length,
481
+ byStopReason: sortedRecord(byStopReason),
482
+ totalLatencyMs: chatLatency,
483
+ },
484
+ tools: {
485
+ total: this.#tools.length,
486
+ ok: counts.ok,
487
+ error: counts.error,
488
+ skipped: counts.skipped,
489
+ blocked: counts.blocked,
490
+ timeout: counts.timeout,
491
+ aborted: counts.aborted,
492
+ totalLatencyMs: toolLatency,
493
+ byName: sortedRecord(byName),
494
+ },
495
+ usage: {
496
+ inputTokens,
497
+ outputTokens,
498
+ cachedInputTokens,
499
+ cacheWriteTokens,
500
+ reasoningOutputTokens,
501
+ totalTokens,
502
+ },
503
+ cost: {
504
+ estimatedUsd,
505
+ unavailableReasons: [...unavailableReasons].sort(),
506
+ },
507
+ errors: {
508
+ total: errorTotal,
509
+ byType: sortedRecord(errorsByType),
510
+ },
511
+ stepCount,
512
+ };
513
+ }
514
+
515
+ #buildCoverage(): AgentRunCoverage {
516
+ const toolsAvailable = [...this.#availableTools].sort();
517
+ const toolsInvoked = [...this.#invokedTools].sort();
518
+ const toolsUnused = toolsAvailable.filter(name => !this.#invokedTools.has(name));
519
+ // Tools the LLM invoked that were never declared on any request remain
520
+ // present in `toolsInvoked` but absent from `toolsAvailable`. Callers
521
+ // diff to detect this case if they care.
522
+ return {
523
+ toolsAvailable,
524
+ toolsInvoked,
525
+ toolsUnused,
526
+ modelsUsed: [...this.#modelsUsed].sort(),
527
+ providersUsed: [...this.#providersUsed].sort(),
528
+ };
529
+ }
530
+ }
531
+
532
+ /**
533
+ * Fold multiple per-run summaries into one. Pure aggregation — useful when a
534
+ * caller (verify pass, benchmark harness) drives the agent loop N times and
535
+ * needs a single rollup across all invocations.
536
+ *
537
+ * Counters sum element-wise. Sets (cost reasons, error types, per-tool
538
+ * counters) merge by key. Numeric totals sum. The output is in the same
539
+ * shape as a single `AgentRunSummary`, so all dashboards and persistence
540
+ * layers handle it uniformly.
541
+ */
542
+ export function aggregateAgentRunSummaries(summaries: readonly AgentRunSummary[]): AgentRunSummary {
543
+ if (summaries.length === 0) return EMPTY_SUMMARY;
544
+ if (summaries.length === 1) return summaries[0];
545
+
546
+ let chatTotal = 0;
547
+ let chatLatency = 0;
548
+ const byStopReason: Record<string, number> = {};
549
+
550
+ let toolTotal = 0;
551
+ let toolOk = 0;
552
+ let toolError = 0;
553
+ let toolSkipped = 0;
554
+ let toolBlocked = 0;
555
+ let toolTimeout = 0;
556
+ let toolAborted = 0;
557
+ let toolLatency = 0;
558
+ const byName: Record<string, ToolCounters> = {};
559
+
560
+ let inputTokens = 0;
561
+ let outputTokens = 0;
562
+ let cachedInputTokens = 0;
563
+ let cacheWriteTokens = 0;
564
+ let reasoningOutputTokens = 0;
565
+ let totalTokens = 0;
566
+
567
+ let estimatedUsd = 0;
568
+ const unavailableReasons = new Set<string>();
569
+
570
+ const errorsByType: Record<string, number> = {};
571
+ let errorsTotal = 0;
572
+ let stepCount = 0;
573
+
574
+ for (const s of summaries) {
575
+ chatTotal += s.chats.total;
576
+ chatLatency += s.chats.totalLatencyMs;
577
+ for (const [reason, count] of Object.entries(s.chats.byStopReason)) {
578
+ byStopReason[reason] = (byStopReason[reason] ?? 0) + count;
579
+ }
580
+
581
+ toolTotal += s.tools.total;
582
+ toolOk += s.tools.ok;
583
+ toolError += s.tools.error;
584
+ toolSkipped += s.tools.skipped;
585
+ toolBlocked += s.tools.blocked;
586
+ toolTimeout += s.tools.timeout;
587
+ toolAborted += s.tools.aborted;
588
+ toolLatency += s.tools.totalLatencyMs;
589
+ for (const [name, counters] of Object.entries(s.tools.byName)) {
590
+ const existing = byName[name];
591
+ byName[name] = existing
592
+ ? {
593
+ total: existing.total + counters.total,
594
+ ok: existing.ok + counters.ok,
595
+ error: existing.error + counters.error,
596
+ skipped: existing.skipped + counters.skipped,
597
+ blocked: existing.blocked + counters.blocked,
598
+ timeout: existing.timeout + counters.timeout,
599
+ aborted: existing.aborted + counters.aborted,
600
+ totalLatencyMs: existing.totalLatencyMs + counters.totalLatencyMs,
601
+ }
602
+ : counters;
603
+ }
604
+
605
+ inputTokens += s.usage.inputTokens;
606
+ outputTokens += s.usage.outputTokens;
607
+ cachedInputTokens += s.usage.cachedInputTokens;
608
+ cacheWriteTokens += s.usage.cacheWriteTokens;
609
+ reasoningOutputTokens += s.usage.reasoningOutputTokens;
610
+ totalTokens += s.usage.totalTokens;
611
+
612
+ estimatedUsd += s.cost.estimatedUsd;
613
+ for (const r of s.cost.unavailableReasons) unavailableReasons.add(r);
614
+
615
+ for (const [type, count] of Object.entries(s.errors.byType)) {
616
+ errorsByType[type] = (errorsByType[type] ?? 0) + count;
617
+ }
618
+ errorsTotal += s.errors.total;
619
+ stepCount += s.stepCount;
620
+ }
621
+
622
+ return {
623
+ chats: { total: chatTotal, byStopReason: sortedRecord(byStopReason), totalLatencyMs: chatLatency },
624
+ tools: {
625
+ total: toolTotal,
626
+ ok: toolOk,
627
+ error: toolError,
628
+ skipped: toolSkipped,
629
+ blocked: toolBlocked,
630
+ timeout: toolTimeout,
631
+ aborted: toolAborted,
632
+ totalLatencyMs: toolLatency,
633
+ byName: sortedRecord(byName),
634
+ },
635
+ usage: { inputTokens, outputTokens, cachedInputTokens, cacheWriteTokens, reasoningOutputTokens, totalTokens },
636
+ cost: { estimatedUsd, unavailableReasons: [...unavailableReasons].sort() },
637
+ errors: { total: errorsTotal, byType: sortedRecord(errorsByType) },
638
+ stepCount,
639
+ };
640
+ }
641
+
642
+ /** Union-merge multiple coverage values, preserving the sorted+deduped invariant. */
643
+ export function aggregateAgentRunCoverage(coverages: readonly AgentRunCoverage[]): AgentRunCoverage {
644
+ if (coverages.length === 0) return EMPTY_COVERAGE;
645
+ if (coverages.length === 1) return coverages[0];
646
+ const available = new Set<string>();
647
+ const invoked = new Set<string>();
648
+ const models = new Set<string>();
649
+ const providers = new Set<string>();
650
+ for (const c of coverages) {
651
+ for (const t of c.toolsAvailable) available.add(t);
652
+ for (const t of c.toolsInvoked) invoked.add(t);
653
+ for (const m of c.modelsUsed) models.add(m);
654
+ for (const p of c.providersUsed) providers.add(p);
655
+ }
656
+ const toolsAvailable = [...available].sort();
657
+ return {
658
+ toolsAvailable,
659
+ toolsInvoked: [...invoked].sort(),
660
+ toolsUnused: toolsAvailable.filter(name => !invoked.has(name)),
661
+ modelsUsed: [...models].sort(),
662
+ providersUsed: [...providers].sort(),
663
+ };
664
+ }
665
+
666
+ const EMPTY_SUMMARY: AgentRunSummary = Object.freeze({
667
+ chats: Object.freeze({ total: 0, byStopReason: Object.freeze({}), totalLatencyMs: 0 }),
668
+ tools: Object.freeze({
669
+ total: 0,
670
+ ok: 0,
671
+ error: 0,
672
+ skipped: 0,
673
+ blocked: 0,
674
+ timeout: 0,
675
+ aborted: 0,
676
+ totalLatencyMs: 0,
677
+ byName: Object.freeze({}),
678
+ }),
679
+ usage: Object.freeze({
680
+ inputTokens: 0,
681
+ outputTokens: 0,
682
+ cachedInputTokens: 0,
683
+ cacheWriteTokens: 0,
684
+ reasoningOutputTokens: 0,
685
+ totalTokens: 0,
686
+ }),
687
+ cost: Object.freeze({ estimatedUsd: 0, unavailableReasons: Object.freeze([]) as readonly string[] }),
688
+ errors: Object.freeze({ total: 0, byType: Object.freeze({}) }),
689
+ stepCount: 0,
690
+ }) as AgentRunSummary;
691
+
692
+ const EMPTY_COVERAGE: AgentRunCoverage = Object.freeze({
693
+ toolsAvailable: Object.freeze([]) as readonly string[],
694
+ toolsInvoked: Object.freeze([]) as readonly string[],
695
+ toolsUnused: Object.freeze([]) as readonly string[],
696
+ modelsUsed: Object.freeze([]) as readonly string[],
697
+ providersUsed: Object.freeze([]) as readonly string[],
698
+ }) as AgentRunCoverage;
699
+
700
+ /** Empty `AgentRunSummary` constant. Exported for tests and default-initializers. */
701
+ export function emptyAgentRunSummary(): AgentRunSummary {
702
+ return EMPTY_SUMMARY;
703
+ }
704
+
705
+ /** Empty `AgentRunCoverage` constant. Exported for tests and default-initializers. */
706
+ export function emptyAgentRunCoverage(): AgentRunCoverage {
707
+ return EMPTY_COVERAGE;
708
+ }
709
+
710
+ /**
711
+ * Distinguishable error class thrown when `beforeToolCall` returns
712
+ * `{ block: true }`. Lets the catch arm of `runTool` set the terminal status
713
+ * on the execute_tool span to `"blocked"` instead of conflating with a real
714
+ * tool exception.
715
+ */
716
+ export class ToolCallBlockedError extends Error {
717
+ override readonly name = "ToolCallBlockedError";
718
+ constructor(reason?: string) {
719
+ super(reason ?? "Tool execution was blocked");
720
+ }
721
+ }
722
+
723
+ /** Return a new object whose own keys are listed in ascending order. */
724
+ function sortedRecord<V>(record: Record<string, V>): Record<string, V> {
725
+ const out: Record<string, V> = {};
726
+ for (const key of Object.keys(record).sort()) out[key] = record[key];
727
+ return out;
728
+ }