@tangle-network/agent-eval 0.120.1 → 0.120.2

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 (171) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/package.json +1 -1
  3. package/dist/analyst/index.d.ts +0 -3111
  4. package/dist/analyst/index.js +0 -403
  5. package/dist/analyst/index.js.map +0 -1
  6. package/dist/authenticity/index.d.ts +0 -161
  7. package/dist/authenticity/index.js +0 -215
  8. package/dist/authenticity/index.js.map +0 -1
  9. package/dist/belief-state/index.d.ts +0 -1301
  10. package/dist/belief-state/index.js +0 -2152
  11. package/dist/belief-state/index.js.map +0 -1
  12. package/dist/benchmarks/index.d.ts +0 -974
  13. package/dist/benchmarks/index.js +0 -60
  14. package/dist/benchmarks/index.js.map +0 -1
  15. package/dist/builder-eval/index.d.ts +0 -695
  16. package/dist/builder-eval/index.js +0 -366
  17. package/dist/builder-eval/index.js.map +0 -1
  18. package/dist/campaign/index.d.ts +0 -7454
  19. package/dist/campaign/index.js +0 -272
  20. package/dist/campaign/index.js.map +0 -1
  21. package/dist/chunk-32BZXMSO.js +0 -3878
  22. package/dist/chunk-32BZXMSO.js.map +0 -1
  23. package/dist/chunk-3A246TSA.js +0 -998
  24. package/dist/chunk-3A246TSA.js.map +0 -1
  25. package/dist/chunk-3RF76KTD.js +0 -84
  26. package/dist/chunk-3RF76KTD.js.map +0 -1
  27. package/dist/chunk-3YYRZDON.js +0 -45
  28. package/dist/chunk-3YYRZDON.js.map +0 -1
  29. package/dist/chunk-4I2E3LLO.js +0 -1030
  30. package/dist/chunk-4I2E3LLO.js.map +0 -1
  31. package/dist/chunk-ARU2PZFM.js +0 -312
  32. package/dist/chunk-ARU2PZFM.js.map +0 -1
  33. package/dist/chunk-BOD4O7OF.js +0 -40
  34. package/dist/chunk-BOD4O7OF.js.map +0 -1
  35. package/dist/chunk-DPZAEKA6.js +0 -880
  36. package/dist/chunk-DPZAEKA6.js.map +0 -1
  37. package/dist/chunk-DTJ6QUQB.js +0 -131
  38. package/dist/chunk-DTJ6QUQB.js.map +0 -1
  39. package/dist/chunk-GGE4NNQT.js +0 -65
  40. package/dist/chunk-GGE4NNQT.js.map +0 -1
  41. package/dist/chunk-H5UD2323.js +0 -286
  42. package/dist/chunk-H5UD2323.js.map +0 -1
  43. package/dist/chunk-HHWE3POT.js +0 -94
  44. package/dist/chunk-HHWE3POT.js.map +0 -1
  45. package/dist/chunk-HKUCJ437.js +0 -787
  46. package/dist/chunk-HKUCJ437.js.map +0 -1
  47. package/dist/chunk-JHCHEVET.js +0 -274
  48. package/dist/chunk-JHCHEVET.js.map +0 -1
  49. package/dist/chunk-JHOJHHU7.js +0 -867
  50. package/dist/chunk-JHOJHHU7.js.map +0 -1
  51. package/dist/chunk-JM2SKQMS.js +0 -750
  52. package/dist/chunk-JM2SKQMS.js.map +0 -1
  53. package/dist/chunk-JN2FCO5W.js +0 -7958
  54. package/dist/chunk-JN2FCO5W.js.map +0 -1
  55. package/dist/chunk-K4DBDHLK.js +0 -158
  56. package/dist/chunk-K4DBDHLK.js.map +0 -1
  57. package/dist/chunk-K6N6XJJX.js +0 -306
  58. package/dist/chunk-K6N6XJJX.js.map +0 -1
  59. package/dist/chunk-MA6HLL3S.js +0 -65
  60. package/dist/chunk-MA6HLL3S.js.map +0 -1
  61. package/dist/chunk-MAZ26DC7.js +0 -99
  62. package/dist/chunk-MAZ26DC7.js.map +0 -1
  63. package/dist/chunk-MOXWMGPC.js +0 -577
  64. package/dist/chunk-MOXWMGPC.js.map +0 -1
  65. package/dist/chunk-NJC7U437.js +0 -626
  66. package/dist/chunk-NJC7U437.js.map +0 -1
  67. package/dist/chunk-NPCTHQIO.js +0 -91
  68. package/dist/chunk-NPCTHQIO.js.map +0 -1
  69. package/dist/chunk-ONWEPEDO.js +0 -57
  70. package/dist/chunk-ONWEPEDO.js.map +0 -1
  71. package/dist/chunk-OYZAPX5G.js +0 -1526
  72. package/dist/chunk-OYZAPX5G.js.map +0 -1
  73. package/dist/chunk-PC4UYEBM.js +0 -166
  74. package/dist/chunk-PC4UYEBM.js.map +0 -1
  75. package/dist/chunk-PICTDURQ.js +0 -766
  76. package/dist/chunk-PICTDURQ.js.map +0 -1
  77. package/dist/chunk-PJQFMIOX.js +0 -1182
  78. package/dist/chunk-PJQFMIOX.js.map +0 -1
  79. package/dist/chunk-PXD6ZFNY.js +0 -1107
  80. package/dist/chunk-PXD6ZFNY.js.map +0 -1
  81. package/dist/chunk-PXE2VKMX.js +0 -140
  82. package/dist/chunk-PXE2VKMX.js.map +0 -1
  83. package/dist/chunk-PZ5AY32C.js +0 -10
  84. package/dist/chunk-PZ5AY32C.js.map +0 -1
  85. package/dist/chunk-QBRSJK47.js +0 -622
  86. package/dist/chunk-QBRSJK47.js.map +0 -1
  87. package/dist/chunk-QWMPPZ3X.js +0 -550
  88. package/dist/chunk-QWMPPZ3X.js.map +0 -1
  89. package/dist/chunk-S3UZOQ5Y.js +0 -328
  90. package/dist/chunk-S3UZOQ5Y.js.map +0 -1
  91. package/dist/chunk-S5TT5R3L.js +0 -2668
  92. package/dist/chunk-S5TT5R3L.js.map +0 -1
  93. package/dist/chunk-T4SQEITX.js +0 -95
  94. package/dist/chunk-T4SQEITX.js.map +0 -1
  95. package/dist/chunk-TT4KNT67.js +0 -124
  96. package/dist/chunk-TT4KNT67.js.map +0 -1
  97. package/dist/chunk-U5CHZ5M3.js +0 -357
  98. package/dist/chunk-U5CHZ5M3.js.map +0 -1
  99. package/dist/chunk-ULOKLHIQ.js +0 -1937
  100. package/dist/chunk-ULOKLHIQ.js.map +0 -1
  101. package/dist/chunk-VI2UW6B6.js +0 -162
  102. package/dist/chunk-VI2UW6B6.js.map +0 -1
  103. package/dist/chunk-VQMK5FMP.js +0 -247
  104. package/dist/chunk-VQMK5FMP.js.map +0 -1
  105. package/dist/chunk-VSMTAMNK.js +0 -53
  106. package/dist/chunk-VSMTAMNK.js.map +0 -1
  107. package/dist/chunk-VZSRQ272.js +0 -149
  108. package/dist/chunk-VZSRQ272.js.map +0 -1
  109. package/dist/chunk-WW2A73HW.js +0 -159
  110. package/dist/chunk-WW2A73HW.js.map +0 -1
  111. package/dist/chunk-X4UCIOTZ.js +0 -136
  112. package/dist/chunk-X4UCIOTZ.js.map +0 -1
  113. package/dist/chunk-XDIRG3TO.js +0 -1266
  114. package/dist/chunk-XDIRG3TO.js.map +0 -1
  115. package/dist/chunk-XJYR7XFV.js +0 -317
  116. package/dist/chunk-XJYR7XFV.js.map +0 -1
  117. package/dist/chunk-ZET2UAYW.js +0 -89
  118. package/dist/chunk-ZET2UAYW.js.map +0 -1
  119. package/dist/chunk-ZZUXHH3R.js +0 -99
  120. package/dist/chunk-ZZUXHH3R.js.map +0 -1
  121. package/dist/cli.d.ts +0 -1
  122. package/dist/cli.js +0 -112
  123. package/dist/cli.js.map +0 -1
  124. package/dist/contract/index.d.ts +0 -4972
  125. package/dist/contract/index.js +0 -1654
  126. package/dist/contract/index.js.map +0 -1
  127. package/dist/control.d.ts +0 -1013
  128. package/dist/control.js +0 -34
  129. package/dist/control.js.map +0 -1
  130. package/dist/fuzz.d.ts +0 -759
  131. package/dist/fuzz.js +0 -714
  132. package/dist/fuzz.js.map +0 -1
  133. package/dist/hosted/index.d.ts +0 -730
  134. package/dist/hosted/index.js +0 -14
  135. package/dist/hosted/index.js.map +0 -1
  136. package/dist/index.d.ts +0 -16780
  137. package/dist/index.js +0 -12168
  138. package/dist/index.js.map +0 -1
  139. package/dist/matrix/index.d.ts +0 -155
  140. package/dist/matrix/index.js +0 -8
  141. package/dist/matrix/index.js.map +0 -1
  142. package/dist/meta-eval/index.d.ts +0 -1030
  143. package/dist/meta-eval/index.js +0 -417
  144. package/dist/meta-eval/index.js.map +0 -1
  145. package/dist/multishot/index.d.ts +0 -579
  146. package/dist/multishot/index.js +0 -589
  147. package/dist/multishot/index.js.map +0 -1
  148. package/dist/openapi.json +0 -992
  149. package/dist/pipelines/index.d.ts +0 -567
  150. package/dist/pipelines/index.js +0 -515
  151. package/dist/pipelines/index.js.map +0 -1
  152. package/dist/reporting.d.ts +0 -1277
  153. package/dist/reporting.js +0 -48
  154. package/dist/reporting.js.map +0 -1
  155. package/dist/rl.d.ts +0 -4092
  156. package/dist/rl.js +0 -1724
  157. package/dist/rl.js.map +0 -1
  158. package/dist/run-campaign-HNFPJET4.js +0 -14
  159. package/dist/run-campaign-HNFPJET4.js.map +0 -1
  160. package/dist/storyboard/index.d.ts +0 -279
  161. package/dist/storyboard/index.js +0 -767
  162. package/dist/storyboard/index.js.map +0 -1
  163. package/dist/trace-attributes.d.ts +0 -52
  164. package/dist/trace-attributes.js +0 -62
  165. package/dist/trace-attributes.js.map +0 -1
  166. package/dist/traces.d.ts +0 -2343
  167. package/dist/traces.js +0 -249
  168. package/dist/traces.js.map +0 -1
  169. package/dist/wire/index.d.ts +0 -1252
  170. package/dist/wire/index.js +0 -81
  171. package/dist/wire/index.js.map +0 -1
package/dist/traces.d.ts DELETED
@@ -1,2343 +0,0 @@
1
- import { AxAIService, AxAgentActorTurnCallbackArgs, AxFunction } from '@ax-llm/ax';
2
-
3
- /**
4
- * Error taxonomy for `@tangle-network/agent-eval`.
5
- *
6
- * Every error this package throws as part of its *public contract* extends
7
- * `AgentEvalError`. Consumers can pattern-match by `instanceof <Subclass>` or
8
- * by the stable string `code` carried on the base class.
9
- *
10
- * The codes are stable across minor versions; new codes can be added, but
11
- * existing codes never change meaning. New subclasses are non-breaking.
12
- *
13
- * Internal invariant guards (`throw new Error('this should never happen')`)
14
- * remain plain `Error`s on purpose — they're programmer-mistake assertions,
15
- * not consumer-catchable contract failures.
16
- */
17
- type AgentEvalErrorCode = 'validation' | 'not_found' | 'config' | 'capture_integrity' | 'judge' | 'verification' | 'replay' | 'backend_integrity' | 'profile_matrix';
18
- /**
19
- * Base class for every contract error this package throws — carries the stable
20
- * string `code` taxonomy so consumers can `instanceof`-match or switch on `code`.
21
- */
22
- declare class AgentEvalError extends Error {
23
- /** Stable string code. Survives minification; safe to switch on. */
24
- readonly code: AgentEvalErrorCode;
25
- constructor(code: AgentEvalErrorCode, message: string, options?: {
26
- cause?: unknown;
27
- });
28
- }
29
- /** A named resource (run, span, rubric, scenario, dataset row, route) does not exist. */
30
- declare class NotFoundError extends AgentEvalError {
31
- constructor(message: string, options?: {
32
- cause?: unknown;
33
- });
34
- }
35
- /**
36
- * A run is missing the artifacts a launch-grade check requires:
37
- * raw HTTP capture absent, no LLM spans, route assertion failed, run-end
38
- * assertion tripped. Block ship on this; do not catch and move on.
39
- */
40
- declare class CaptureIntegrityError extends AgentEvalError {
41
- constructor(message: string, options?: {
42
- cause?: unknown;
43
- });
44
- }
45
- /** Replay cache cannot satisfy a request: miss with no fallback, sink lacks list(), unsupported URL. */
46
- declare class ReplayError extends AgentEvalError {
47
- constructor(message: string, options?: {
48
- cause?: unknown;
49
- });
50
- }
51
-
52
- /**
53
- * RawProviderSink — first-class persistence for the actual HTTP-level
54
- * request/response bodies of every LLM provider call.
55
- *
56
- * Why this is a separate sink from the structured `LlmSpan`:
57
- *
58
- * - `LlmSpan` records the *intent* — model name, messages, output text,
59
- * usage. It's what dashboards read; it's NOT enough for forensics.
60
- * - When a downstream consumer reports "the verifier used the wrong route"
61
- * or "tokens look right but reasoning was missing," the only way to
62
- * answer is the raw HTTP body. Span fields can lie (a proxy can echo
63
- * a different `model` value than what actually answered); the raw
64
- * response is ground truth.
65
- *
66
- * Default behaviour: opt-in. Pass `rawSink` to `LlmClientOptions` (or the
67
- * matrix runner / BuilderSession sets it up automatically) and every
68
- * request, response, and error is recorded — including retries, with the
69
- * attempt index attached so a flaky call's full event chain is recoverable.
70
- *
71
- * Redaction is enforced at sink time. The default redactor strips
72
- * `Authorization`, `X-Api-Key`, `X-Auth-Token`, `Cookie` headers and any
73
- * payload field whose key matches `apiKey | api_key | bearer | password |
74
- * secret | token` (case-insensitive). Override via the sink constructor or
75
- * the per-call `redactor`. The `redactedFields` array on the persisted
76
- * event lets a reviewer see what was stripped without exposing the values.
77
- */
78
- type RawProviderDirection = 'request' | 'response' | 'error';
79
- interface RawProviderEvent {
80
- /** Stable id. Generated by the sink if omitted. */
81
- eventId: string;
82
- /** Trace context populated by `LlmClient` when the call is wrapped in a span. */
83
- runId?: string;
84
- spanId?: string;
85
- /**
86
- * Logical provider name. Free-form so callers can use whatever id matches
87
- * their topology (`'openai'`, `'anthropic'`, `'tangle-router'`, …). When
88
- * omitted, derived from `baseUrl` in `LlmClientOptions`.
89
- */
90
- provider: string;
91
- model: string;
92
- /** Endpoint path, e.g. `'/v1/chat/completions'`. */
93
- endpoint: string;
94
- /** Base URL used for the call (already-normalised — no trailing slash). */
95
- baseUrl: string;
96
- /** 0-indexed retry attempt. The first attempt is 0; a retried call gets 1, 2, … */
97
- attemptIndex: number;
98
- direction: RawProviderDirection;
99
- /** Unix ms. */
100
- timestamp: number;
101
- /** Wall-clock duration of the call leg. Set on `response` and `error` events; null on `request`. */
102
- durationMs?: number;
103
- statusCode?: number;
104
- requestHeaders?: Record<string, string>;
105
- requestBody?: unknown;
106
- responseHeaders?: Record<string, string>;
107
- responseBody?: unknown;
108
- /** Set on `direction: 'error'` events. */
109
- errorMessage?: string;
110
- /** Field paths the redactor stripped from this event ('header:Authorization', 'body.apiKey', …). */
111
- redactedFields: string[];
112
- }
113
- interface RawProviderSinkFilter {
114
- runId?: string;
115
- spanId?: string;
116
- direction?: RawProviderDirection;
117
- attemptIndex?: number;
118
- }
119
- interface RawProviderSink {
120
- record(event: RawProviderEvent): Promise<void>;
121
- /** Optional listing — implementations that durably persist (file, db) should support this. */
122
- list?(filter?: RawProviderSinkFilter): Promise<RawProviderEvent[]>;
123
- /** Optional teardown for backed implementations. */
124
- close?(): Promise<void>;
125
- }
126
- type ProviderRedactor = (event: RawProviderEvent) => RawProviderEvent;
127
- /**
128
- * Default redactor — strips well-known auth headers and any body field whose
129
- * key matches the credential pattern. Records every redacted path on
130
- * `event.redactedFields` so a downstream reviewer can see what was removed.
131
- */
132
- declare function defaultProviderRedactor(event: RawProviderEvent): RawProviderEvent;
133
- interface InMemoryRawProviderSinkOptions {
134
- redactor?: ProviderRedactor;
135
- }
136
- declare class InMemoryRawProviderSink implements RawProviderSink {
137
- private events;
138
- private redactor;
139
- constructor(opts?: InMemoryRawProviderSinkOptions);
140
- record(event: RawProviderEvent): Promise<void>;
141
- list(filter?: RawProviderSinkFilter): Promise<RawProviderEvent[]>;
142
- size(): number;
143
- }
144
- declare class NoopRawProviderSink implements RawProviderSink {
145
- record(): Promise<void>;
146
- /**
147
- * Returns an empty array. Implemented so `assertRunCaptured` does not
148
- * trip the `no_raw_sink` issue when a caller explicitly opts out of
149
- * capture by passing this sink — opt-out is a deliberate choice, not a
150
- * misconfiguration.
151
- */
152
- list(): Promise<RawProviderEvent[]>;
153
- }
154
- interface FileSystemRawProviderSinkOptions {
155
- /** Directory the NDJSON file is written into. Created if missing. */
156
- dir: string;
157
- /** File name; default `'raw-provider-events.ndjson'`. */
158
- fileName?: string;
159
- /** Bytes after which the writer rolls over to a new file (default 32 MiB). */
160
- rollAtBytes?: number;
161
- redactor?: ProviderRedactor;
162
- }
163
- declare class FileSystemRawProviderSink implements RawProviderSink {
164
- private dir;
165
- private fileName;
166
- private rollAtBytes;
167
- private redactor;
168
- private bytesWritten;
169
- private rollIndex;
170
- private initPromise;
171
- constructor(opts: FileSystemRawProviderSinkOptions);
172
- private ensureInit;
173
- private currentPath;
174
- record(event: RawProviderEvent): Promise<void>;
175
- list(filter?: RawProviderSinkFilter): Promise<RawProviderEvent[]>;
176
- }
177
- /**
178
- * Best-effort provider id from a base URL. Falls back to the URL host when
179
- * none of the well-known patterns match.
180
- */
181
- declare function providerFromBaseUrl(baseUrl: string): string;
182
-
183
- /**
184
- * Replay-from-raw-events — turn every captured campaign run into a
185
- * re-runnable artifact.
186
- *
187
- * `RawProviderSink` captures every provider HTTP envelope; `runEvalCampaign`
188
- * makes that capture the default. Together they make every past run a
189
- * complete fingerprint of what happened on the wire — enough to replay
190
- * the run without burning new LLM cost.
191
- *
192
- * Three use cases this primitive enables:
193
- *
194
- * 1. **Post-hoc judging** — apply a new judge / rubric / scoring callback
195
- * to last week's runs without re-calling any LLM. The cost of trying
196
- * a new rubric drops from "another full sweep" to a CPU-bound replay.
197
- * 2. **Determinism audits** — replay the same campaign and verify the
198
- * raw responses match byte-for-byte. Any drift is a non-determinism
199
- * bug (in the harness, the prompt builder, the sandbox, …).
200
- * 3. **Free judge calibration** — run two judges on identical responses
201
- * and measure inter-judge agreement without doubling LLM spend.
202
- *
203
- * The interface is deliberately fetch-shaped. Inject `createReplayFetch`
204
- * into `LlmClientOptions.fetch` and every `callLlm` transparently reads
205
- * from the cache instead of calling the network. No new code path through
206
- * the LLM client is needed; the cache hit is invisible to the runner.
207
- */
208
-
209
- declare class ReplayCacheMissError extends ReplayError {
210
- readonly url: string;
211
- readonly requestKey: string;
212
- constructor(url: string, requestKey: string, message?: string);
213
- }
214
- interface ReplayCacheEntry {
215
- request: RawProviderEvent;
216
- response: RawProviderEvent;
217
- }
218
- interface ReplayCacheStats {
219
- total: number;
220
- byProvider: Record<string, number>;
221
- byModel: Record<string, number>;
222
- /** Spans for which we have a request but no response (run aborted mid-call). */
223
- orphanRequests: number;
224
- }
225
- /**
226
- * In-memory deterministic cache of (request → response) keyed on a stable
227
- * hash of the request body. Built from a `RawProviderSink` containing
228
- * paired `request` and `response` events from a previous run.
229
- *
230
- * The cache is the source of truth for replay; `createReplayFetch` is a
231
- * thin wrapper that reads from it.
232
- */
233
- declare class ReplayCache {
234
- private byKey;
235
- private orphans;
236
- private byProvider;
237
- private byModel;
238
- /**
239
- * Build a cache from a sink's events. The sink must implement `list()`.
240
- * Filter by `runId` / `spanId` to scope to a specific replay.
241
- */
242
- static fromSink(sink: RawProviderSink, filter?: {
243
- runId?: string;
244
- spanId?: string;
245
- }): Promise<ReplayCache>;
246
- /** Build a cache from an in-memory event list. */
247
- static fromEvents(events: RawProviderEvent[]): Promise<ReplayCache>;
248
- /** Number of cacheable (request, response) pairs in the cache. */
249
- size(): number;
250
- stats(): ReplayCacheStats;
251
- /** Iterate every cached `(request, response)` pair in insertion order. */
252
- entries(): IterableIterator<ReplayCacheEntry>;
253
- /**
254
- * Look up a cached response by hashing the (model, messages, temperature,
255
- * maxTokens, response_format) shape. Returns `undefined` on miss; the
256
- * caller decides whether to throw, fall back to the network, or skip.
257
- */
258
- lookup(requestBody: unknown): Promise<ReplayCacheEntry | undefined>;
259
- }
260
- interface ReplayFetchOptions {
261
- /**
262
- * Behaviour on cache miss. Default `'throw'`. `'fallback'` calls the
263
- * `fallbackFetch` (typically `globalThis.fetch`) so a partial replay can
264
- * still complete; `'fail-closed'` returns a synthetic 599 response so the
265
- * call site sees a non-retriable failure.
266
- */
267
- onMiss?: 'throw' | 'fallback' | 'fail-closed';
268
- fallbackFetch?: typeof fetch;
269
- /** Optional callback fired once per replayed call (for telemetry / counters). */
270
- onHit?: (info: {
271
- url: string;
272
- provider: string;
273
- model: string;
274
- }) => void;
275
- /** Optional callback fired on cache miss before the `onMiss` policy applies. */
276
- onMissNotify?: (info: {
277
- url: string;
278
- requestBody: unknown;
279
- }) => void;
280
- }
281
- /**
282
- * Build a `fetch`-shaped function that serves cached responses out of a
283
- * `ReplayCache` for any URL ending in `/chat/completions`. Pass through
284
- * `LlmClientOptions.fetch` and `callLlm` becomes free.
285
- *
286
- * Non-`/chat/completions` URLs are passed straight to the fallback fetch
287
- * (default: `globalThis.fetch`). This matters because non-LLM HTTP work
288
- * (judge HTTP servers, sandbox callbacks) sometimes flows through the same
289
- * `fetch` and shouldn't be intercepted.
290
- */
291
- declare function createReplayFetch(cache: ReplayCache, opts?: ReplayFetchOptions): typeof fetch;
292
- /**
293
- * Convenience iterator over `(request, response)` pairs in a sink — for
294
- * post-hoc scoring that doesn't need a `fetch` shim. The judge or scorer
295
- * runs purely in-process over cached LLM outputs.
296
- */
297
- declare function iterateRawCalls(sink: RawProviderSink, filter?: {
298
- runId?: string;
299
- spanId?: string;
300
- }): AsyncGenerator<ReplayCacheEntry>;
301
-
302
- type AgentProfileCellSchemaVersion = 'agent-profile-cell/v1';
303
- type AgentProfileDimensionValue = string | number | boolean | null;
304
- interface AgentProfileSource {
305
- /** Runtime/profile contract being fingerprinted, e.g. `agent-interface-profile`. */
306
- kind: string;
307
- /** sha256 over the canonical source profile object. */
308
- hash: string;
309
- }
310
- interface AgentProfileHarness {
311
- id: string;
312
- version?: string;
313
- hash?: string;
314
- }
315
- interface AgentProfileCell {
316
- schemaVersion: AgentProfileCellSchemaVersion;
317
- cellId: string;
318
- profileId: string;
319
- sourceProfile: AgentProfileSource;
320
- harness?: AgentProfileHarness;
321
- model?: string;
322
- promptHash?: string;
323
- dimensions?: Record<string, AgentProfileDimensionValue>;
324
- }
325
-
326
- /**
327
- * TraceSchema v1 — the canonical data model for agent-eval.
328
- *
329
- * Every score, every failure class, every pipeline in the framework is
330
- * a view over this data. Shape it once, live with it.
331
- *
332
- * Wire-compatible with OpenTelemetry span semantics (see trace/otel.ts)
333
- * but extended with agent-specific span kinds (llm, tool, retrieval,
334
- * judge, sandbox) and first-class BudgetLedger / Artifact / JudgeVerdict
335
- * entities that OTEL leaves as free-form attributes.
336
- */
337
- declare const TRACE_SCHEMA_VERSION = "1.0.0";
338
- type RunStatus = 'running' | 'completed' | 'failed' | 'aborted';
339
- interface BudgetSpec {
340
- tokens?: number;
341
- wallMs?: number;
342
- calls?: number;
343
- usd?: number;
344
- }
345
- interface RunOutcome$1 {
346
- score?: number;
347
- pass?: boolean;
348
- failureClass?: FailureClass;
349
- notes?: string;
350
- }
351
- /**
352
- * Layer — optional classification in a nested build workflow.
353
- * `builder`: the meta-agent editing a project (e.g. agent-builder Forge chat).
354
- * `app-build`: sandbox harness that compiled + tested the generated scaffold.
355
- * `app-runtime`: a run of the generated agent against a domain scenario.
356
- * `meta`: any meta-eval (judge replay, correlation analysis).
357
- */
358
- type RunLayer = 'builder' | 'app-build' | 'app-runtime' | 'meta' | 'custom';
359
- interface Run {
360
- runId: string;
361
- /**
362
- * Stable identifier of the scenario being executed.
363
- *
364
- * Always populated on the persisted Run — but `TraceEmitter.startRun` accepts
365
- * input WITHOUT this field, substituting a sensible default
366
- * (`run.layer ?? run.tags?.['kind'] ?? 'runtime'`) when the caller has no
367
- * curated scenario to anchor to (runtime / operator / meta-eval runs). This
368
- * keeps the persisted shape unambiguous for downstream filters + aggregations
369
- * while removing the boilerplate of inventing placeholder ids at the call site.
370
- */
371
- scenarioId: string;
372
- variantId?: string;
373
- datasetVersion?: string;
374
- /** Git SHA of agent code at run time. */
375
- codeSha?: string;
376
- /** Hash of the prompt template + any system prompt. */
377
- promptSha?: string;
378
- /** Model id + date + system-prompt hash, concatenated. */
379
- modelFingerprint?: string;
380
- seed?: number;
381
- /** Arbitrary environment markers (shell, docker version, tz). */
382
- envFingerprint?: Record<string, string>;
383
- /** Version of the redaction rules applied to this run. */
384
- redactionVersion?: string;
385
- /** Parent run in a nested build workflow. A builder run's children are
386
- * app-build runs; those children are app-runtime runs. */
387
- parentRunId?: string;
388
- /** Stable project identifier — groups runs across chats + sessions. */
389
- projectId?: string;
390
- /** Chat/conversation identifier within a project. */
391
- chatId?: string;
392
- /** Layer classification — hint for aggregation; not enforced. */
393
- layer?: RunLayer;
394
- startedAt: number;
395
- endedAt?: number;
396
- status: RunStatus;
397
- outcome?: RunOutcome$1;
398
- budget?: BudgetSpec;
399
- /** Free-form labels for downstream grouping. */
400
- tags?: Record<string, string>;
401
- }
402
- type SpanKind = 'agent' | 'llm' | 'tool' | 'retrieval' | 'judge' | 'sandbox' | 'custom';
403
- type SpanStatus = 'ok' | 'error';
404
- interface SpanBase {
405
- spanId: string;
406
- parentSpanId?: string;
407
- runId: string;
408
- kind: SpanKind;
409
- name: string;
410
- startedAt: number;
411
- endedAt?: number;
412
- status?: SpanStatus;
413
- error?: string;
414
- /** Anything not covered by typed fields. Kept deliberately free-form. */
415
- attributes?: Record<string, unknown>;
416
- }
417
- interface Message {
418
- role: 'system' | 'user' | 'assistant' | 'tool';
419
- content: string;
420
- tokens?: number;
421
- /** Multi-modal content descriptors; blobs themselves live in Artifacts. */
422
- images?: Array<{
423
- artifactId?: string;
424
- url?: string;
425
- mime?: string;
426
- }>;
427
- }
428
- interface LlmSpan extends SpanBase {
429
- kind: 'llm';
430
- model: string;
431
- messages: Message[];
432
- output?: string;
433
- inputTokens?: number;
434
- /** All generated tokens, including the reasoning subset when present. */
435
- outputTokens?: number;
436
- cachedTokens?: number;
437
- cacheWriteTokens?: number;
438
- /** Reasoning-token subset of `outputTokens`. */
439
- reasoningTokens?: number;
440
- costUsd?: number;
441
- finishReason?: string;
442
- }
443
- interface ToolSpan extends SpanBase {
444
- kind: 'tool';
445
- toolName: string;
446
- args: unknown;
447
- /** False when the source observed the call but did not capture its arguments. */
448
- argsCaptured?: boolean;
449
- result?: unknown;
450
- latencyMs?: number;
451
- }
452
- interface RetrievalSpan extends SpanBase {
453
- kind: 'retrieval';
454
- query: string;
455
- hits: Array<{
456
- docId: string;
457
- score: number;
458
- content?: string;
459
- }>;
460
- }
461
- interface JudgeSpan extends SpanBase {
462
- kind: 'judge';
463
- judgeId: string;
464
- /** Span this judgment applies to. */
465
- targetSpanId: string;
466
- dimension: string;
467
- /** Numeric score (free-range; interpretation up to the judge). */
468
- score: number;
469
- rationale?: string;
470
- evidence?: string;
471
- }
472
- interface SandboxSpan extends SpanBase {
473
- kind: 'sandbox';
474
- image?: string;
475
- command?: string;
476
- exitCode?: number;
477
- testsTotal?: number;
478
- testsPassed?: number;
479
- stdoutHash?: string;
480
- stderrHash?: string;
481
- /** Duration in ms; the harness fills this explicitly (endedAt - startedAt may miss setup). */
482
- wallMs?: number;
483
- }
484
- interface GenericSpan extends SpanBase {
485
- kind: 'agent' | 'custom';
486
- }
487
- type Span = LlmSpan | ToolSpan | RetrievalSpan | JudgeSpan | SandboxSpan | GenericSpan;
488
- type EventKind = 'log' | 'error' | 'budget_decrement' | 'budget_breach' | 'state_mutation' | 'policy_violation' | 'redaction_applied' | 'custom';
489
- interface TraceEvent {
490
- eventId: string;
491
- runId: string;
492
- spanId?: string;
493
- kind: EventKind;
494
- timestamp: number;
495
- payload: Record<string, unknown>;
496
- }
497
- interface BudgetLedgerEntry {
498
- runId: string;
499
- dimension: keyof BudgetSpec;
500
- limit: number;
501
- consumed: number;
502
- remaining: number;
503
- timestamp: number;
504
- breached: boolean;
505
- /** Span that triggered this entry, if any. */
506
- spanId?: string;
507
- }
508
- interface Artifact {
509
- artifactId: string;
510
- runId: string;
511
- spanId?: string;
512
- contentType: string;
513
- sizeBytes: number;
514
- /** sha256 in hex. */
515
- hash: string;
516
- /** External storage URL (R2, S3, filesystem path). */
517
- storageUrl?: string;
518
- /** Inline content for small blobs — keep under ~64KB. */
519
- inlineContent?: string;
520
- }
521
- type FailureClass = 'success' | 'reasoning_error' | 'tool_selection_error' | 'tool_argument_error' | 'tool_recovery_failure' | 'hallucination' | 'instruction_following' | 'safety_refusal_miss' | 'policy_violation' | 'budget_exceeded' | 'format_drift' | 'permission_escalation' | 'pii_leak' | 'cost_overrun' | 'timeout' | 'sandbox_failure' | 'missing_user_data' | 'missing_domain_data' | 'missing_codebase_context' | 'missing_runtime_context' | 'missing_credentials' | 'missing_integration_connection' | 'missing_integration_scope' | 'integration_approval_required' | 'integration_auth_expired' | 'integration_provider_failure' | 'bad_integration_manifest' | 'unsafe_integration_write_denied' | 'stale_external_data' | 'bad_retrieval' | 'insufficient_evidence' | 'contradictory_evidence' | 'ambiguous_user_intent' | 'knowledge_readiness_blocked' | 'unknown';
522
- declare const FAILURE_CLASSES: readonly FailureClass[];
523
- declare function isLlmSpan(s: Span): s is LlmSpan;
524
- declare function isToolSpan(s: Span): s is ToolSpan;
525
- declare function isRetrievalSpan(s: Span): s is RetrievalSpan;
526
- declare function isJudgeSpan(s: Span): s is JudgeSpan;
527
- declare function isSandboxSpan(s: Span): s is SandboxSpan;
528
-
529
- /**
530
- * Paper-grade RunRecord schema + runtime validator.
531
- *
532
- * Every run that participates in a promotion gate, paper table, or
533
- * researcher loop SHOULD be recorded as a `RunRecord`. The mandatory
534
- * fields are exactly those the paper "Two Loops, Three Roles" requires
535
- * for reproducibility: who/what/when/cost/seed/hash, plus the search vs
536
- * holdout split tag and either a `searchScore` or a `holdoutScore`.
537
- *
538
- * This is intentionally NOT a replacement for the rich `Run` /
539
- * `ProposeReviewReport` / `ScenarioResult` types already in the
540
- * package. Those are runtime structures with full provenance. A
541
- * `RunRecord` is the analysis-time projection — the JSON-friendly
542
- * row you'd put in a parquet file or paste into a notebook.
543
- *
544
- * Validate at the boundary:
545
- *
546
- * const rec = validateRunRecord(rawJson) // throws on missing
547
- * const ok = isRunRecord(rawJson) // boolean check
548
- * const rec = parseRunRecordSafe(rawJson) // { ok, value | error }
549
- *
550
- * The validator runs in pure TS — zod is intentionally NOT a
551
- * dependency. Round-trip tested in `tests/run-record.test.ts`.
552
- */
553
-
554
- /** Search/dev/holdout split tag. 'search' is the paper-grade alias for the
555
- * combined train+test pool that the optimizer is allowed to read. */
556
- type RunSplitTag = 'search' | 'dev' | 'holdout';
557
- interface RunTokenUsage {
558
- input: number;
559
- /** All generated tokens charged as output, including reasoning tokens. */
560
- output: number;
561
- /** Reasoning-token subset of `output`, when the provider reports it. */
562
- reasoning?: number;
563
- /** Prompt tokens served from a provider cache. */
564
- cached?: number;
565
- /** Prompt tokens written into a provider cache. */
566
- cacheWrite?: number;
567
- }
568
- /**
569
- * How a run's USD amount was obtained.
570
- *
571
- * `costUsd` remains mandatory for wire compatibility. New producers should
572
- * always populate this discriminated union so a missing bill is never
573
- * mistaken for an observed zero-dollar run. For `uncaptured`, `costUsd` uses
574
- * the legacy `0` sentinel while this field carries the truthful null.
575
- */
576
- type RunCostProvenance = {
577
- kind: 'observed';
578
- usd: number;
579
- } | {
580
- kind: 'estimated';
581
- usd: number;
582
- } | {
583
- kind: 'uncaptured';
584
- usd: null;
585
- };
586
- interface RunJudgeMetadata {
587
- model: string;
588
- promptVersion: string;
589
- /** [0,1] confidence the judge declared. Constant judge confidence
590
- * across many runs is a fallback signal (see `canary.ts`). */
591
- confidence: number;
592
- /** True if the judge degraded to a fallback path (rules-only,
593
- * prior-call cache, etc.). The canary uses this to alert. */
594
- fallback: boolean;
595
- }
596
- /**
597
- * Per-judge / per-dimension breakdown for runs scored by an ensemble of
598
- * judges over a multi-dimensional rubric.
599
- *
600
- * The collapsed `outcome.searchScore` / `holdoutScore` carries the
601
- * composite the gate uses. The full breakdown belongs here so consumers
602
- * can answer "which judge disagreed?", "which dimension dragged the
603
- * composite down?", and "did half the panel fail?" without re-running.
604
- *
605
- * `perJudge[judgeId][dim]` is the canonical source; `perDimMean` and
606
- * `composite` are convenience projections — derivable but precomputed so
607
- * downstream IRR primitives (`interRaterReliability`,
608
- * `corpusInterRaterAgreement`) and reporters don't pay the same
609
- * aggregation twice.
610
- *
611
- * Fail-loud discipline: judges that errored out land in `failedJudges`
612
- * by id. A missing key in `perJudge` is ambiguous (silent zero vs not
613
- * run); the explicit list makes a partial-failure recorded as such.
614
- */
615
- interface JudgeScoresRecord {
616
- /** Per-judge per-dimension scores. `{ "kimi-k2.6": { helpfulness: 0.8, clarity: 0.7 }, ... }`. */
617
- perJudge: Record<string, Record<string, number>>;
618
- /** Per-dim mean across judges. Convenience — derivable from `perJudge`. */
619
- perDimMean: Record<string, number>;
620
- /** Composite mean across all dims and judges. Mirrors the score
621
- * the gate sees on `outcome.searchScore` / `holdoutScore`. */
622
- composite: number;
623
- /** Judges that errored or returned an unparseable verdict. Recorded
624
- * by id (e.g. `['glm-5.1']`) so a partial-failure case is explicit,
625
- * not inferred from missing keys in `perJudge`. */
626
- failedJudges?: string[];
627
- /** Free-form notes the judges emitted (joined across judges or
628
- * first-judge only — consumer's choice). */
629
- notes?: string;
630
- }
631
- interface RunOutcome {
632
- /** Score on the search/optimization split. Optional because a
633
- * holdout-only evaluation only fills `holdoutScore`. */
634
- searchScore?: number;
635
- /** Score on the held-out split. Optional because a search-only run
636
- * only fills `searchScore`. At least one must be present. */
637
- holdoutScore?: number;
638
- /** Bag of any other metric the run produced — judge dimensions,
639
- * pass/fail counters, latency stats, etc. Numeric only — keeps
640
- * reporters honest. */
641
- raw: Record<string, number>;
642
- /** Per-judge / per-dim breakdown. Consumers writing ensemble
643
- * judgements populate this; substrate primitives like
644
- * `interRaterReliability` and `corpusInterRaterAgreement` accept
645
- * these records as input. Optional — single-judge or scalar-only
646
- * runs leave it unset. */
647
- judgeScores?: JudgeScoresRecord;
648
- /** Authenticity / realness verdict — did the run build the REAL thing on the
649
- * intended infra, or fake it (see `./authenticity`)? Optional: only domains
650
- * with an authenticity config populate it. Carried in the corpus so the
651
- * flywheel / off-policy learning can optimize for real completion, not gamed
652
- * pass-rate. `score` is 0-1; `gated` is the anti-Goodhart flag — a gated run
653
- * must not count as a real success regardless of `score`. */
654
- realness?: {
655
- score: number;
656
- gated: boolean;
657
- reason?: string;
658
- };
659
- }
660
- /**
661
- * Mandatory paper-grade fields for a single evaluation run. Optional
662
- * fields are extension points; mandatory fields throw if missing.
663
- *
664
- * Hash discipline:
665
- * - `promptHash` is the sha256 of the EFFECTIVE prompt sent to the
666
- * model (after any steering bundle merge).
667
- * - `configHash` is the sha256 of the effective run config (model,
668
- * temperature, tools, judges, splits). The pair (promptHash,
669
- * configHash) uniquely identifies an experiment cell.
670
- *
671
- * Model snapshot discipline:
672
- * - `model` MUST encode a snapshot version. Bare aliases like
673
- * `claude-sonnet-4` or `gpt-4o` are banned — they remap silently.
674
- * Use `claude-sonnet-4-6@2025-04-15` or `gpt-4o-2024-11-20`.
675
- */
676
- interface RunRecord {
677
- /** UUID for the run. */
678
- runId: string;
679
- /** Logical experiment grouping (a treatment vs a baseline within
680
- * the same sweep should share `experimentId`). */
681
- experimentId: string;
682
- /** Stable identifier for the candidate (variant) being run. The
683
- * promotion gate compares two `candidateId`s on matched items. */
684
- candidateId: string;
685
- /** RNG seed for the run. Always recorded — silent re-seeding is
686
- * the most common cause of non-reproducible numbers. */
687
- seed: number;
688
- /** Model identifier WITH snapshot version. */
689
- model: string;
690
- /** sha256 of the effective prompt (post-steering). */
691
- promptHash: string;
692
- /** sha256 of the effective config. */
693
- configHash: string;
694
- /** Git SHA the harness was run from. */
695
- commitSha: string;
696
- /** End-to-end wall-clock duration in milliseconds. */
697
- wallMs: number;
698
- /** Time spent queued before execution started, if known. */
699
- queueMs?: number;
700
- /** Total USD cost. Mandatory — runs without a cost number are
701
- * unbounded by definition and must not be admitted into the gate.
702
- * `0` is retained as the compatibility sentinel for an uncaptured amount;
703
- * inspect `costProvenance` before treating it as observed. */
704
- costUsd: number;
705
- /** Observed, model-priced estimate, or genuinely uncaptured USD amount.
706
- * Optional only so existing serialized RunRecords remain valid. */
707
- costProvenance?: RunCostProvenance;
708
- /** Token usage breakdown. */
709
- tokenUsage: RunTokenUsage;
710
- /** Judge-side metadata, if a judge was used. */
711
- judgeMetadata?: RunJudgeMetadata;
712
- /** Per-split scores + raw bag. */
713
- outcome: RunOutcome;
714
- /** Canonical, cross-agent failure class drawn from the shared
715
- * `FAILURE_CLASSES` taxonomy. This is the aggregation key that makes
716
- * "which failure dominates across the whole fleet" answerable in ONE
717
- * vocabulary — every agent classifies against the same enum. Producers
718
- * set it via the substrate classifier; leave unset only when the failure
719
- * genuinely can't be classified. */
720
- failureClass?: FailureClass;
721
- /** Free-form domain-specific failure detail, scoped UNDER `failureClass`
722
- * (e.g. failureClass='tool_recovery_failure', failureMode='forge_build_unsatisfied').
723
- * The within-agent drill-down; `failureClass` is the cross-agent key. */
724
- failureMode?: string;
725
- /** Which split this run was drawn from. */
726
- splitTag: RunSplitTag;
727
- /**
728
- * Stable scenario identifier the run was scored against. Optional for
729
- * backwards compatibility, but **strongly recommended**: every primitive
730
- * that pairs runs by scenario (preferences, paired stats, BT tournament)
731
- * keys on this. The campaign artifact populates it canonically; legacy
732
- * runs without it fall back to inference from `outcome.raw.scenario_id`
733
- * or `experimentId`.
734
- */
735
- scenarioId?: string;
736
- /**
737
- * Canonical identity for the agent profile cell that produced this row:
738
- * profile artifact hash plus optional harness/model/prompt/reporting
739
- * dimensions. Use `agentProfile.cellId` to group persona sweeps and
740
- * longitudinal reports by the complete source profile, not by a loose
741
- * candidate label or opaque config hash.
742
- */
743
- agentProfile?: AgentProfileCell;
744
- }
745
-
746
- /**
747
- * Provider response and SSE usage extraction.
748
- *
749
- * Missing usage returns `null`; reported zeroes and cache-only activity remain
750
- * distinguishable from absent telemetry.
751
- */
752
-
753
- type ExtractedUsage = RunTokenUsage;
754
- type SseUsageMode = 'cumulative' | 'delta';
755
- interface ExtractUsageFromSseOptions {
756
- /** Provider usage events are cumulative snapshots unless explicitly marked as deltas. */
757
- mode?: SseUsageMode;
758
- }
759
- /**
760
- * Pull `{ input, output, cached?, cacheWrite? }` from a parsed response
761
- * body. Accepts a top-level `usage` object (the common case) or a body that IS
762
- * the usage object. Returns null only when none of those categories is present.
763
- */
764
- declare function extractUsage(body: unknown): ExtractedUsage | null;
765
- /**
766
- * Extract token usage from a complete SSE response body using the shared SSE
767
- * frame parser. Cumulative snapshots are the fail-safe default because summing
768
- * them inflates billing; callers with explicit delta events opt into `mode: 'delta'`.
769
- */
770
- declare function extractUsageFromSse(text: string, options?: ExtractUsageFromSseOptions): ExtractedUsage | null;
771
- /**
772
- * Extract usage from an HTTP `Response` without consuming the caller's body:
773
- * clones, reads the text, and tries the JSON parser first, then the SSE
774
- * accumulator. Best-effort — returns null on any read/parse miss so a usage tee
775
- * never takes down the underlying call.
776
- */
777
- declare function extractUsageFromResponse(response: Response, sseOptions?: ExtractUsageFromSseOptions): Promise<ExtractedUsage | null>;
778
-
779
- /**
780
- * Wrap a provider `fetch` and record request, response, and error events.
781
- *
782
- * The returned value is a plain `typeof fetch`. Capture is best-effort by
783
- * default; set `failClosed` when telemetry loss must stop the provider call.
784
- */
785
-
786
- interface CaptureFetchContext {
787
- /** Logical run id stamped on every captured event. Required — without it
788
- * the raw events can't be paired with their parent `Run`. */
789
- runId: string;
790
- /** Optional logical span id (enables span-level sink filtering). */
791
- spanId?: string;
792
- /** Resolved base URL (normalised, no trailing slash). Used for the event's
793
- * `baseUrl` and for endpoint-path extraction. */
794
- baseUrl: string;
795
- /** Model id the caller intends to invoke. Stamped on every event. */
796
- model: string;
797
- /** Provider override. When omitted, `providerFromBaseUrl(baseUrl)`. */
798
- provider?: string;
799
- }
800
- interface CaptureFetchOptions {
801
- /** Override the capture-time redactor. Default `defaultProviderRedactor`. */
802
- redactor?: ProviderRedactor;
803
- /** Cap on captured response-body bytes; beyond it the body is truncated and
804
- * `body_truncated` is added to `redactedFields`. Default 2 MiB. */
805
- responseBodyByteCap?: number;
806
- /** When true, a sink-write failure propagates to the caller. Default false
807
- * — capture is best-effort so a sink failure never kills the LLM call. */
808
- failClosed?: boolean;
809
- /**
810
- * Invoked with the token usage parsed off each successful response (JSON or
811
- * SSE), keyed by the captured context. Lets a caller fold usage → cost without
812
- * re-cloning the response themselves. Not called when the response carries no
813
- * usage. Best-effort: a throw here is swallowed (it never kills the LLM call)
814
- * unless `failClosed` is set.
815
- */
816
- onUsage?: (usage: ExtractedUsage, ctx: CaptureFetchContext) => void;
817
- /** How repeated SSE usage events should be reconciled. Default `cumulative`. */
818
- sseUsageMode?: SseUsageMode;
819
- }
820
- declare function captureFetchToRawSink(fetch: typeof globalThis.fetch, sink: RawProviderSink, ctx: CaptureFetchContext, opts?: CaptureFetchOptions): typeof globalThis.fetch;
821
-
822
- interface RunFilter {
823
- scenarioId?: string;
824
- variantId?: string;
825
- status?: RunStatus;
826
- since?: number;
827
- until?: number;
828
- tag?: {
829
- key: string;
830
- value: string;
831
- };
832
- parentRunId?: string;
833
- projectId?: string;
834
- chatId?: string;
835
- layer?: RunLayer;
836
- }
837
- interface SpanFilter {
838
- runId?: string;
839
- parentSpanId?: string;
840
- kind?: SpanKind;
841
- name?: string;
842
- toolName?: string;
843
- judgeId?: string;
844
- since?: number;
845
- until?: number;
846
- }
847
- interface EventFilter {
848
- runId?: string;
849
- spanId?: string;
850
- kind?: EventKind;
851
- since?: number;
852
- until?: number;
853
- }
854
- interface TraceStore {
855
- appendRun(run: Run): Promise<void>;
856
- updateRun(runId: string, patch: Partial<Run>): Promise<void>;
857
- appendSpan(span: Span): Promise<void>;
858
- updateSpan(spanId: string, patch: Partial<Span>): Promise<void>;
859
- appendEvent(event: TraceEvent): Promise<void>;
860
- appendArtifact(artifact: Artifact): Promise<void>;
861
- appendBudgetEntry(entry: BudgetLedgerEntry): Promise<void>;
862
- getRun(runId: string): Promise<Run | undefined>;
863
- listRuns(filter?: RunFilter): Promise<Run[]>;
864
- spans(filter?: SpanFilter): Promise<Span[]>;
865
- events(filter?: EventFilter): Promise<TraceEvent[]>;
866
- budget(runId: string): Promise<BudgetLedgerEntry[]>;
867
- artifacts(runId: string): Promise<Artifact[]>;
868
- }
869
- declare class InMemoryTraceStore implements TraceStore {
870
- private runs;
871
- private allSpans;
872
- private allEvents;
873
- private allArtifacts;
874
- private allBudget;
875
- appendRun(run: Run): Promise<void>;
876
- updateRun(runId: string, patch: Partial<Run>): Promise<void>;
877
- appendSpan(span: Span): Promise<void>;
878
- updateSpan(spanId: string, patch: Partial<Span>): Promise<void>;
879
- appendEvent(event: TraceEvent): Promise<void>;
880
- appendArtifact(artifact: Artifact): Promise<void>;
881
- appendBudgetEntry(entry: BudgetLedgerEntry): Promise<void>;
882
- getRun(runId: string): Promise<Run | undefined>;
883
- listRuns(filter?: RunFilter): Promise<Run[]>;
884
- spans(filter?: SpanFilter): Promise<Span[]>;
885
- events(filter?: EventFilter): Promise<TraceEvent[]>;
886
- budget(runId: string): Promise<BudgetLedgerEntry[]>;
887
- artifacts(runId: string): Promise<Artifact[]>;
888
- }
889
- interface FileSystemTraceStoreOptions {
890
- dir: string;
891
- /** Roll over NDJSON files when they exceed this size in bytes. Default 32 MB. */
892
- maxBytes?: number;
893
- }
894
- declare class FileSystemTraceStore implements TraceStore {
895
- private dir;
896
- private maxBytes;
897
- /** Lazy in-memory index for queries — populated on first read. */
898
- private index?;
899
- /** Memoized index build — concurrent first reads share one build, and an
900
- * append racing an in-flight load awaits this so its row isn't lost. */
901
- private indexPromise?;
902
- /** Strictly-increasing rollover stamp. Date.now() alone collides when two
903
- * rollovers land in the same millisecond, overwriting a rolled file. */
904
- private lastRolloverStamp;
905
- /**
906
- * Per-file append serialization. stat → conditional-rename → appendFile is a
907
- * read-modify-write on the active file; without a lock two concurrent appends
908
- * to the same `name` can both pass the size check (exceeding maxBytes) or one
909
- * can append to a file the other just renamed away. Each entry chains the
910
- * next append behind the prior one for that file.
911
- */
912
- private appendLocks;
913
- constructor(options: FileSystemTraceStoreOptions);
914
- private ensureDir;
915
- private append;
916
- private appendLocked;
917
- private insertInto;
918
- private load;
919
- private buildIndex;
920
- appendRun(run: Run): Promise<void>;
921
- updateRun(runId: string, patch: Partial<Run>): Promise<void>;
922
- appendSpan(span: Span): Promise<void>;
923
- updateSpan(spanId: string, patch: Partial<Span>): Promise<void>;
924
- appendEvent(event: TraceEvent): Promise<void>;
925
- appendArtifact(artifact: Artifact): Promise<void>;
926
- appendBudgetEntry(entry: BudgetLedgerEntry): Promise<void>;
927
- getRun(runId: string): Promise<Run | undefined>;
928
- listRuns(filter?: RunFilter): Promise<Run[]>;
929
- spans(filter?: SpanFilter): Promise<Span[]>;
930
- events(filter?: EventFilter): Promise<TraceEvent[]>;
931
- budget(runId: string): Promise<BudgetLedgerEntry[]>;
932
- artifacts(runId: string): Promise<Artifact[]>;
933
- }
934
-
935
- /**
936
- * TraceEmitter — hierarchical span builder that auto-parents using an
937
- * internal stack. One emitter per Run; emitters do NOT share state.
938
- *
939
- * Convenience methods (`llm`, `tool`, `retrieval`, `judge`, `sandbox`)
940
- * return a `SpanHandle` with `.end()` / `.fail()` so callers don't
941
- * have to thread spanIds manually. For async workflows that can't use
942
- * the stack (e.g. fan-out parallel calls), pass `parentSpanId`
943
- * explicitly.
944
- */
945
-
946
- interface SpanHandle<S extends Span = Span> {
947
- span: S;
948
- end(patch?: Partial<S>): Promise<void>;
949
- fail(error: string | Error, patch?: Partial<S>): Promise<void>;
950
- }
951
- interface RunCompleteHookContext {
952
- runId: string;
953
- emitter: TraceEmitter;
954
- store: TraceStore;
955
- /** Outcome the caller passed to `endRun` (undefined for `abortRun`). */
956
- outcome?: RunOutcome$1;
957
- /** Final run status. */
958
- status: 'completed' | 'failed' | 'aborted';
959
- }
960
- type RunCompleteHook = (ctx: RunCompleteHookContext) => Promise<void> | void;
961
- interface TraceEmitterOptions {
962
- runId?: string;
963
- /** Inject a clock for deterministic tests. */
964
- now?: () => number;
965
- /** Inject an id generator for deterministic tests. */
966
- id?: () => string;
967
- /**
968
- * Hooks fired after `endRun` / `abortRun` writes the final run state.
969
- * Designed for trace-analyst auto-execution, integrity assertions, and
970
- * outbound notifications. Hooks run sequentially in the order supplied.
971
- *
972
- * By default a hook that throws is swallowed and logged as a `note` event
973
- * on the run — auto-orchestration must not crash the underlying flow.
974
- * Set `hookErrors: 'throw'` to propagate.
975
- */
976
- onRunComplete?: RunCompleteHook[];
977
- /** `'swallow'` (default) | `'throw'`. */
978
- hookErrors?: 'swallow' | 'throw';
979
- }
980
- declare class TraceEmitter {
981
- private store;
982
- private stack;
983
- private _runId;
984
- private now;
985
- private id;
986
- private hooks;
987
- private hookErrors;
988
- constructor(store: TraceStore, options?: TraceEmitterOptions);
989
- get runId(): string;
990
- get traceStore(): TraceStore;
991
- /** Append a hook after construction (e.g. attach the trace analyst). */
992
- addRunCompleteHook(hook: RunCompleteHook): void;
993
- /**
994
- * Begin a Run.
995
- *
996
- * `scenarioId` is required on the persisted Run shape — every Run downstream
997
- * gets a non-empty scenarioId so filters and aggregations stay simple — but
998
- * the INPUT here accepts it as optional. When omitted, startRun substitutes
999
- * a sensible default (`run.layer ?? run.tags?.['kind'] ?? 'runtime'`) so
1000
- * runtime / operator / meta-eval runs that have no curated-scenario corpus
1001
- * to anchor to don't have to invent placeholder strings at the call site.
1002
- */
1003
- startRun(run: Omit<Run, 'runId' | 'scenarioId' | 'startedAt' | 'status'> & {
1004
- scenarioId?: string;
1005
- }): Promise<Run>;
1006
- endRun(outcome?: RunOutcome$1): Promise<void>;
1007
- abortRun(reason: string): Promise<void>;
1008
- private runHooks;
1009
- span<S extends Span = Span>(init: {
1010
- kind: SpanKind;
1011
- name: string;
1012
- parentSpanId?: string;
1013
- attributes?: Record<string, unknown>;
1014
- } & Partial<Omit<S, 'spanId' | 'runId' | 'startedAt' | 'kind' | 'name'>>): Promise<SpanHandle<S>>;
1015
- private handle;
1016
- private pop;
1017
- llm(init: Omit<LlmSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>): Promise<SpanHandle<LlmSpan>>;
1018
- tool(init: Omit<ToolSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>): Promise<SpanHandle<ToolSpan>>;
1019
- retrieval(init: Omit<RetrievalSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>): Promise<SpanHandle<RetrievalSpan>>;
1020
- recordJudge(verdict: Omit<JudgeSpan, 'spanId' | 'runId' | 'kind' | 'startedAt' | 'endedAt'>): Promise<JudgeSpan>;
1021
- sandbox(init: Omit<SandboxSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>): Promise<SpanHandle<SandboxSpan>>;
1022
- emit(event: {
1023
- kind: EventKind;
1024
- spanId?: string;
1025
- payload?: Record<string, unknown>;
1026
- }): Promise<TraceEvent>;
1027
- recordBudget(entry: Omit<BudgetLedgerEntry, 'runId' | 'timestamp'> & {
1028
- timestamp?: number;
1029
- }): Promise<BudgetLedgerEntry>;
1030
- recordArtifact(artifact: Omit<Artifact, 'artifactId' | 'runId'>): Promise<Artifact>;
1031
- /**
1032
- * Runs `fn` inside a span; auto-ends on success, auto-fails on throw.
1033
- * Returns the fn's return value. Use this for the 95% case.
1034
- */
1035
- within<T>(init: Parameters<TraceEmitter['span']>[0], fn: (handle: SpanHandle) => Promise<T>): Promise<T>;
1036
- }
1037
- /** Helper to build an LLM span handle args object from a provider-shaped response. */
1038
- declare function llmSpanFromProvider(args: {
1039
- name?: string;
1040
- model: string;
1041
- messages: Message[];
1042
- output: string;
1043
- usage?: {
1044
- inputTokens?: number;
1045
- outputTokens?: number;
1046
- cachedTokens?: number;
1047
- cacheWriteTokens?: number;
1048
- reasoningTokens?: number;
1049
- };
1050
- costUsd?: number;
1051
- finishReason?: string;
1052
- }): Omit<LlmSpan, 'spanId' | 'runId' | 'kind' | 'startedAt'>;
1053
-
1054
- /**
1055
- * Run-completion integrity check — at end of run, verify the expected event
1056
- * types were actually captured. The point is the launch-review failure mode:
1057
- * a run *appears* successful but the raw provider events were never written,
1058
- * so a downstream reviewer can't reconstruct what happened.
1059
- *
1060
- * Pattern:
1061
- *
1062
- * const report = await assertRunCaptured(store, runId, {
1063
- * llmSpansMin: 1,
1064
- * judgeSpansMin: 1,
1065
- * rawSink: providerSink, // must have ≥ 1 event for this run
1066
- * requireRawCoverageOfLlmSpans: true, // every llm span has matching raw events
1067
- * })
1068
- * if (!report.ok) throwIfRunIncomplete(report) // or mark run failed and continue
1069
- *
1070
- * The function is read-only on the store and returns a structured report;
1071
- * the caller chooses the failure mode (throw, mark run failed, log warning).
1072
- * `throwIfRunIncomplete` is the convenient strict mode.
1073
- */
1074
-
1075
- interface RunIntegrityExpectations {
1076
- /** Minimum LLM span count. Default 0 (no requirement). */
1077
- llmSpansMin?: number;
1078
- /** Minimum judge span count. Default 0. */
1079
- judgeSpansMin?: number;
1080
- /** Minimum tool span count. Default 0. */
1081
- toolSpansMin?: number;
1082
- /**
1083
- * Raw provider sink to consult for capture verification. When present,
1084
- * the check requires at least one raw event for the run.
1085
- */
1086
- rawSink?: RawProviderSink;
1087
- /** Minimum raw provider event count. Default 0; ignored when `rawSink` absent. */
1088
- rawProviderEventsMin?: number;
1089
- /**
1090
- * Every LLM span must have at least one matching raw `request` event
1091
- * (matched by spanId). Catches the common bug where the structured span
1092
- * was emitted but the raw HTTP capture was wired to a different sink.
1093
- */
1094
- requireRawCoverageOfLlmSpans?: boolean;
1095
- /** Run outcome must be set (not null/undefined). Default false. */
1096
- requireOutcome?: boolean;
1097
- }
1098
- type RunIntegrityIssueCode = 'no_run' | 'missing_llm_spans' | 'missing_judge_spans' | 'missing_tool_spans' | 'missing_raw_events' | 'no_raw_sink' | 'orphan_llm_span' | 'missing_outcome';
1099
- interface RunIntegrityIssue {
1100
- code: RunIntegrityIssueCode;
1101
- message: string;
1102
- detail?: Record<string, unknown>;
1103
- }
1104
- interface RunIntegrityReport {
1105
- ok: boolean;
1106
- runId: string;
1107
- llmSpanCount: number;
1108
- judgeSpanCount: number;
1109
- toolSpanCount: number;
1110
- rawProviderEventCount: number;
1111
- /**
1112
- * Coverage of LLM spans by raw provider events keyed on spanId.
1113
- * `total` is the number of LLM spans; `covered` is the count with at
1114
- * least one matching `request` raw event.
1115
- */
1116
- rawSpanCoverage: {
1117
- covered: number;
1118
- total: number;
1119
- };
1120
- issues: RunIntegrityIssue[];
1121
- }
1122
- declare class RunIntegrityError extends CaptureIntegrityError {
1123
- readonly report: RunIntegrityReport;
1124
- constructor(report: RunIntegrityReport);
1125
- }
1126
- declare function assertRunCaptured(store: TraceStore, runId: string, expectations?: RunIntegrityExpectations): Promise<RunIntegrityReport>;
1127
- /** Strict mode: throws `RunIntegrityError` when the report isn't ok. */
1128
- declare function throwIfRunIncomplete(report: RunIntegrityReport): void;
1129
-
1130
- /**
1131
- * OpenTelemetry JSON export — maps TraceSchema v1 to OTLP/JSON so
1132
- * traces render natively in Jaeger / Honeycomb / Langfuse / Grafana.
1133
- *
1134
- * Wire format only. We do NOT depend on the @opentelemetry SDK — that
1135
- * would drag in polyfills incompatible with Workers/Edge. Consumers
1136
- * push the JSON to their collector of choice via HTTP.
1137
- *
1138
- * Reference: OTLP 1.3.2 (ResourceSpans / ScopeSpans / Span).
1139
- */
1140
-
1141
- declare const OTEL_AGENT_EVAL_SCOPE: {
1142
- name: string;
1143
- version: string;
1144
- };
1145
- interface OtlpSpan {
1146
- traceId: string;
1147
- spanId: string;
1148
- parentSpanId?: string;
1149
- name: string;
1150
- kind: number;
1151
- startTimeUnixNano: string;
1152
- endTimeUnixNano: string;
1153
- attributes: Array<{
1154
- key: string;
1155
- value: {
1156
- stringValue?: string;
1157
- intValue?: string;
1158
- doubleValue?: number;
1159
- boolValue?: boolean;
1160
- };
1161
- }>;
1162
- events?: Array<{
1163
- timeUnixNano: string;
1164
- name: string;
1165
- attributes?: OtlpSpan['attributes'];
1166
- }>;
1167
- status?: {
1168
- code: number;
1169
- message?: string;
1170
- };
1171
- }
1172
- interface OtlpResourceSpans {
1173
- resource: {
1174
- attributes: OtlpSpan['attributes'];
1175
- };
1176
- scopeSpans: Array<{
1177
- scope: typeof OTEL_AGENT_EVAL_SCOPE;
1178
- spans: OtlpSpan[];
1179
- }>;
1180
- }
1181
- interface OtlpExport {
1182
- resourceSpans: OtlpResourceSpans[];
1183
- }
1184
- /** Export a single run's spans + events in OTLP/JSON. */
1185
- declare function exportRunAsOtlp(store: TraceStore, runId: string, resourceAttrs?: Record<string, string | number | boolean>): Promise<OtlpExport>;
1186
-
1187
- /** Canonical OpenInference-over-OTLP attribute names used at trace boundaries. */
1188
- declare const OPENINFERENCE_SPAN_KIND = "openinference.span.kind";
1189
- declare const LLM_MODEL_NAME = "llm.model_name";
1190
- declare const LLM_INPUT_TOKENS = "llm.token_count.prompt";
1191
- declare const LLM_OUTPUT_TOKENS = "llm.token_count.completion";
1192
- declare const LLM_REASONING_TOKENS = "llm.token_count.reasoning";
1193
- declare const LLM_CACHED_TOKENS = "llm.token_count.prompt_cache_hit";
1194
- declare const LLM_CACHE_WRITE_TOKENS = "llm.token_count.prompt_cache_write";
1195
- /** Exact prompt context after summing mutually exclusive input/cache categories. */
1196
- declare const LLM_CONTEXT_TOKENS = "tangle.llm.context_tokens";
1197
- declare const LLM_COST_USD = "llm.cost_usd";
1198
- declare const TOOL_NAME = "tool.name";
1199
- declare const TOOL_ARGS_CAPTURED = "tool.args_captured";
1200
- declare const TOOL_LATENCY_MS = "tool.latency_ms";
1201
- declare const INPUT_VALUE = "input.value";
1202
- declare const OUTPUT_VALUE = "output.value";
1203
- declare const SPAN_KIND_ATTR_KEYS: readonly ["openinference.span.kind", "inference.observation_kind"];
1204
- declare const LLM_MODEL_ATTR_KEYS: readonly ["llm.model_name", "inference.llm.model_name", "llm.model", ...string[], "tangle.model"];
1205
- declare const LLM_INPUT_TOKEN_ATTR_KEYS: readonly ["llm.token_count.prompt", "inference.llm.input_tokens", "llm.input_tokens", ...string[], "tangle.tokens.in", "tokens.in"];
1206
- declare const LLM_OUTPUT_TOKEN_ATTR_KEYS: readonly ["llm.token_count.completion", "inference.llm.output_tokens", "llm.output_tokens", ...string[], "tangle.tokens.out", "tokens.out"];
1207
- /** Reasoning-token subset of output, when a producer exposes it separately. */
1208
- declare const LLM_REASONING_TOKEN_ATTR_KEYS: readonly ["llm.token_count.reasoning", "inference.llm.reasoning_tokens", "llm.reasoning_tokens", "gen_ai.usage.reasoning_tokens", "gen_ai.usage.reasoning_output_tokens", "reasoning_tokens", "reasoning_output_tokens", "tangle.tokens.reasoning", "gen_ai.usage.output_tokens_details.reasoning_tokens", "gen_ai.usage.completion_tokens_details.reasoning_tokens"];
1209
- declare const LLM_CACHED_TOKEN_ATTR_KEYS: readonly ["llm.token_count.prompt_cache_hit", "inference.llm.cached_tokens", "llm.cached_tokens", "gen_ai.usage.cached_tokens", "gen_ai.usage.prompt_tokens_details.cached_tokens", "gen_ai.usage.input_tokens_details.cached_tokens", "gen_ai.usage.cache_read_tokens", "gen_ai.usage.cache_read_input_tokens", "cache_read_tokens", "cache_read_input_tokens", "input_cache_read", "tangle.tokens.cached"];
1210
- declare const LLM_CACHE_WRITE_TOKEN_ATTR_KEYS: readonly ["llm.token_count.prompt_cache_write", "inference.llm.cache_write_tokens", "llm.cache_write_tokens", "gen_ai.usage.cache_creation_tokens", "gen_ai.usage.cache_creation_input_tokens", "cache_creation_tokens", "cache_creation_input_tokens", "input_cache_creation", "tangle.tokens.cache_write"];
1211
- declare const LLM_COST_ATTR_KEYS: readonly ["llm.cost_usd", "inference.llm.cost.total", "llm.cost.total", "gen_ai.usage.cost", "gen_ai.usage.cost_usd", "tangle.cost.usd", "cost.usd", "cost"];
1212
- /** Explicit run-total cost keys safe to preserve on an untyped span. */
1213
- declare const RUN_COST_ATTR_KEYS: readonly ["tangle.cost.usd", "cost.usd"];
1214
- declare const TOOL_NAME_ATTR_KEYS: readonly ["tool.name", "inference.tool.name"];
1215
- /** Read a numeric attribute, tolerating numeric strings; `null` if absent or invalid. */
1216
- declare function asNumber(value: unknown): number | null;
1217
- /** First finite numeric value across a list of candidate attribute keys. */
1218
- declare function firstNumberAttr(attributes: Record<string, unknown>, keys: readonly string[]): number | null;
1219
- /** Sum producer-supplied, mutually exclusive prompt-token categories. */
1220
- declare function contextInputTokens(usage: {
1221
- inputTokens?: number | null;
1222
- cachedTokens?: number | null;
1223
- cacheWriteTokens?: number | null;
1224
- }): number | undefined;
1225
- interface LlmSpanOtlpInput {
1226
- model?: string;
1227
- inputTokens?: number;
1228
- outputTokens?: number;
1229
- reasoningTokens?: number;
1230
- cachedTokens?: number;
1231
- cacheWriteTokens?: number;
1232
- costUsd?: number;
1233
- finishReason?: string;
1234
- }
1235
- /** Write the canonical LLM attributes shared by trace producers. */
1236
- declare function applyLlmSpanOtlpAttributes(attributes: Record<string, unknown>, span: LlmSpanOtlpInput): void;
1237
-
1238
- /** Canonical OpenInference-over-OTLP attribute vocabulary used at the trace boundary. */
1239
-
1240
- type ToolSpanOtlpInput = Pick<ToolSpan, 'toolName' | 'args' | 'argsCaptured' | 'result' | 'latencyMs'>;
1241
- declare function applyToolSpanOtlpAttributes(attributes: Record<string, unknown>, span: ToolSpanOtlpInput): void;
1242
- declare function traceSpanKindToOpenInferenceKind(kind: string): string;
1243
-
1244
- /**
1245
- * OTEL span exporter — streams spans to an OTLP/HTTP collector.
1246
- *
1247
- * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env
1248
- * when no explicit config is given. Batches spans and flushes periodically
1249
- * or when the batch fills. No @opentelemetry SDK dependency — minimal
1250
- * OTLP/JSON serializer (~120 LOC) using the existing otel.ts helpers.
1251
- */
1252
-
1253
- interface OtelExportConfig {
1254
- /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */
1255
- endpoint?: string;
1256
- /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */
1257
- headers?: Record<string, string>;
1258
- /** Batch size before flush. Default 64. */
1259
- batchSize?: number;
1260
- /** Flush interval ms. Default 5000. */
1261
- flushIntervalMs?: number;
1262
- /** Resource attributes stamped on every export. */
1263
- resourceAttributes?: Record<string, string | number | boolean>;
1264
- /** Service name. Default 'agent-eval'. */
1265
- serviceName?: string;
1266
- }
1267
- interface OtelExporter {
1268
- /** Called by the TraceEmitter on every span close. */
1269
- exportSpan(span: ExportableSpan): void;
1270
- /** Force flush pending spans. */
1271
- flush(): Promise<void>;
1272
- /** Shutdown cleanly — flushes remaining spans and stops the timer. */
1273
- shutdown(): Promise<void>;
1274
- }
1275
- interface ExportableSpan {
1276
- traceId: string;
1277
- spanId: string;
1278
- parentSpanId?: string;
1279
- name: string;
1280
- kind: string;
1281
- startedAt: number;
1282
- endedAt?: number;
1283
- status?: string;
1284
- error?: string;
1285
- model?: string;
1286
- inputTokens?: number;
1287
- outputTokens?: number;
1288
- reasoningTokens?: number;
1289
- cachedTokens?: number;
1290
- cacheWriteTokens?: number;
1291
- costUsd?: number;
1292
- tool?: ToolSpanOtlpInput;
1293
- attributes?: Record<string, unknown>;
1294
- }
1295
- /**
1296
- * Create an OTEL exporter. Returns undefined when no endpoint is configured
1297
- * (neither via config nor env) — callers should check before attaching.
1298
- */
1299
- declare function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined;
1300
-
1301
- /**
1302
- * OTEL bridge — connects TraceEmitter span lifecycle to the OtelExporter.
1303
- *
1304
- * When an OtelExporter is active, every span that closes through the
1305
- * TraceEmitter is also pushed to the exporter for real-time streaming to
1306
- * the user's OTEL collector.
1307
- *
1308
- * The bridge is opt-in: attach via `otelRunCompleteHook(exporter)` as a
1309
- * RunCompleteHook, or wrap the store with `createOtelTracingStore` for
1310
- * real-time per-span export.
1311
- */
1312
-
1313
- /**
1314
- * Create a RunCompleteHook that exports all spans from the completed run
1315
- * to the OTEL exporter, then flushes.
1316
- */
1317
- declare function otelRunCompleteHook(exporter: OtelExporter): RunCompleteHook;
1318
- /**
1319
- * Create an auto-exporting TraceStore wrapper that intercepts updateSpan
1320
- * calls. When a span gets an endedAt, it's exported immediately. This
1321
- * gives real-time streaming instead of batch-at-end.
1322
- *
1323
- * This is the preferred integration path: wrap the store before
1324
- * constructing the TraceEmitter.
1325
- */
1326
- declare function createOtelTracingStore(inner: TraceStore, exporter: OtelExporter, traceId: string): TraceStore;
1327
-
1328
- /**
1329
- * Typed query helpers over TraceStore.
1330
- *
1331
- * Not a full SQL engine — a minimal, composable set of operators that
1332
- * cover the canned-pipeline use cases. For ad-hoc analytics, persist to
1333
- * NDJSON and point DuckDB at it; the schema is stable so external SQL
1334
- * tooling works out of the box.
1335
- */
1336
-
1337
- declare function runsForScenario(store: TraceStore, scenarioId: string): Promise<Run[]>;
1338
- declare function llmSpans(store: TraceStore, runId?: string): Promise<LlmSpan[]>;
1339
- declare function toolSpans(store: TraceStore, runId?: string, toolName?: string): Promise<ToolSpan[]>;
1340
- /** Query judge-kind spans from the trace store, optionally scoped to a single run. */
1341
- declare function judgeSpans(store: TraceStore, runId?: string): Promise<JudgeSpan[]>;
1342
- /** Group spans by any key selector. */
1343
- declare function groupBy<T, K extends string | number>(items: T[], key: (t: T) => K): Map<K, T[]>;
1344
- /** Hash tool arguments to an orderless-key-stable string for de-duplication. */
1345
- declare function argHash(args: unknown): string;
1346
- /** Whether argument-based comparisons are valid for this tool call. */
1347
- declare function hasCapturedToolArgs(span: ToolSpan): boolean;
1348
- /** Sum an LLM-span array into aggregate token + cost. */
1349
- declare function aggregateLlm(spans: LlmSpan[]): {
1350
- inputTokens: number;
1351
- outputTokens: number;
1352
- cachedTokens: number;
1353
- cacheWriteTokens: number;
1354
- reasoningTokens: number;
1355
- costUsd: number;
1356
- };
1357
- /** Pick the outcome's failure class when present, else derive 'success' from run status. */
1358
- declare function runFailureClass(run: Run): FailureClass;
1359
-
1360
- /**
1361
- * Redaction — remove PII / secrets from trace payloads before persist.
1362
- *
1363
- * Pre-persistence rules mean raw traces in storage are already scrubbed.
1364
- * Unredacted variants (for debugging / post-mortems) live in a separate
1365
- * storage layer with stricter access controls; this module only covers
1366
- * the default scrub-then-persist path.
1367
- *
1368
- * Rules compose: pass an array of `RedactionRule`, each is applied in
1369
- * order. Strings that match get replaced with a tagged sentinel so the
1370
- * eval framework can count how many redactions happened per run
1371
- * (surfaced via `redaction_applied` events).
1372
- */
1373
- interface RedactionRule {
1374
- id: string;
1375
- pattern: RegExp;
1376
- /** Replacement — e.g. '[PII:email]'. Defaults to `[redacted:{id}]`. */
1377
- replacement?: string;
1378
- }
1379
- interface RedactionReport {
1380
- redactionCount: number;
1381
- byRule: Record<string, number>;
1382
- }
1383
- /** OWASP / common-sense defaults — extend per-domain. */
1384
- declare const DEFAULT_REDACTION_RULES: RedactionRule[];
1385
- declare const REDACTION_VERSION = "1.0.0";
1386
- /**
1387
- * Redact a single string. Returns the new string and a per-rule count of
1388
- * how many substitutions fired.
1389
- */
1390
- declare function redactString(input: string, rules?: RedactionRule[]): {
1391
- output: string;
1392
- report: RedactionReport;
1393
- };
1394
- /**
1395
- * Walk a JSON-ish value applying `redactString` to every string leaf.
1396
- * Arrays and plain objects are recursed; other types pass through
1397
- * untouched. Circular references throw — traces should be tree-shaped.
1398
- */
1399
- declare function redactValue(value: unknown, rules?: RedactionRule[], report?: RedactionReport): {
1400
- value: unknown;
1401
- report: RedactionReport;
1402
- };
1403
-
1404
- /**
1405
- * Convert agent-eval's internal trace shape (`FileSystemTraceStore` → `Run`,
1406
- * `Span`, `TraceEvent`) into the OTLP-flat JSONL the trace analyst
1407
- * (`analyzeTraces` + `OtlpFileTraceStore`) reads.
1408
- *
1409
- * Eval harnesses shard a `FileSystemTraceStore` per cell (persona / variant)
1410
- * under a run directory. The analyst consumes a single OTLP-NDJSON file keyed
1411
- * on `trace_id` + `span_id` with `start_time`/`end_time` in ISO-8601 and
1412
- * resource + `attributes` rolled up per-span. This module walks every shard,
1413
- * projects each `Span` (plus events pinned to it) into the flat OTLP shape,
1414
- * and emits one NDJSON file.
1415
- *
1416
- * Generic OTLP/OpenInference fields are always emitted (`service.name`,
1417
- * `agent.name`, `run.id`/`run.status`, `openinference.span.kind`,
1418
- * `llm.model_name`, …). Domain attributes (`legal.*`, `tax.*`, …) are injected
1419
- * per-run via {@link TraceStoreToOtlpOptions.resourceAttributes} /
1420
- * {@link TraceStoreToOtlpOptions.runAttributes} so consumers don't re-roll the
1421
- * walker.
1422
- */
1423
-
1424
- interface TracesToOtlpResult {
1425
- /** Total spans emitted across every cell. */
1426
- spanCount: number;
1427
- /** Total run-anchor spans (one per Run) appended for analyst visibility. */
1428
- runCount: number;
1429
- /** Cells whose shards parsed cleanly. */
1430
- cellCount: number;
1431
- /** Cells that errored mid-conversion — surfaced so a partial conversion
1432
- * isn't silently masked. */
1433
- cellErrorCount: number;
1434
- }
1435
- /**
1436
- * A trace source the analyst should ingest. Two layouts are supported:
1437
- *
1438
- * - `celled` (default): the root holds one cell subdirectory per
1439
- * persona/variant, each a `FileSystemTraceStore` (`runs.ndjson`,
1440
- * `spans.ndjson`, `events.ndjson`).
1441
- * - `flat`: the root is itself a single `FileSystemTraceStore` (e.g. a
1442
- * production-ingestion sidecar that appends one ndjson set directly under
1443
- * the chosen directory).
1444
- */
1445
- interface TraceStoreSource {
1446
- /** Absolute path to the trace store root. */
1447
- root: string;
1448
- /** Layout — `celled` (default) or `flat`. */
1449
- layout?: 'celled' | 'flat';
1450
- /** OTLP `service.name` for this source. Overrides the options default. */
1451
- serviceName?: string;
1452
- }
1453
- /** Domain hooks. The walker is generic; consumers inject the namespaced
1454
- * attributes that ride along on every run + span for analyst discovery. */
1455
- interface TraceStoreToOtlpOptions {
1456
- /** Default OTLP `service.name` when a source doesn't set its own.
1457
- * Default `agent-eval`. */
1458
- serviceName?: string;
1459
- /** Extra resource attributes per run, e.g.
1460
- * `(run) => ({ 'legal.persona_id': run.tags?.personaId ?? '' })`. */
1461
- resourceAttributes?: (run: Run) => Record<string, unknown>;
1462
- /** Extra attributes on the per-run anchor span, e.g. domain outcome fields. */
1463
- runAttributes?: (run: Run) => Record<string, unknown>;
1464
- }
1465
- /**
1466
- * Read every per-cell shard under each source root and write a flat OTLP-JSONL
1467
- * view of the corpus to `outPath`. Each cell directory is a
1468
- * `FileSystemTraceStore` — NDJSON append-only with size-based rotation;
1469
- * `updateRun`/`updateSpan` append `{ id, ...patch, _update: true }` rows
1470
- * rather than rewriting, so readers must merge those patches in (done here).
1471
- *
1472
- * A `string` source is treated as a celled root.
1473
- */
1474
- declare function convertTraceStoresToOtlp(source: string | TraceStoreSource | readonly TraceStoreSource[], outPath: string, opts?: TraceStoreToOtlpOptions): TracesToOtlpResult;
1475
-
1476
- /**
1477
- * Shared types for the trace-analyst module.
1478
- *
1479
- * Wire format. The store interface speaks `OtlpSpanLike` rows — one JSONL
1480
- * line per span, OTLP-shaped. We do NOT depend on a specific tracing
1481
- * vendor at the type level. Adapter
1482
- * layers map upstream shapes onto this interface.
1483
- *
1484
- * Design constraint. Every read operation that can return arbitrary
1485
- * payload must carry a byte budget so the agent's tool result stays
1486
- * bounded regardless of input trace size. Oversized responses
1487
- * substitute a deterministic summary instead of bytes — see
1488
- * `ViewTraceOversized`.
1489
- */
1490
- /** OTLP span kind (subset we actually use). */
1491
- type TraceAnalystSpanKind = 'AGENT' | 'LLM' | 'TOOL' | 'CHAIN' | 'GUARDRAIL' | 'SPAN' | 'UNKNOWN';
1492
- type TraceAnalystSpanStatus = 'OK' | 'ERROR' | 'UNSET';
1493
- /** Subset of OTLP span fields the analyst exposes to the agent. The
1494
- * store's job is to project upstream's full span shape down to this
1495
- * view — the analyst never sees vendor extensions directly. */
1496
- interface TraceAnalystSpan {
1497
- trace_id: string;
1498
- span_id: string;
1499
- parent_span_id: string | null;
1500
- name: string;
1501
- kind: TraceAnalystSpanKind;
1502
- start_time: string;
1503
- end_time: string;
1504
- duration_ms: number;
1505
- status: TraceAnalystSpanStatus;
1506
- status_message?: string;
1507
- service_name: string | null;
1508
- agent_name: string | null;
1509
- model_name: string | null;
1510
- tool_name: string | null;
1511
- /** Raw JSON-serialisable attribute map. May contain large strings;
1512
- * callers must respect the per-attribute byte cap. */
1513
- attributes: Record<string, unknown>;
1514
- }
1515
- interface TraceAnalystTraceSummary {
1516
- trace_id: string;
1517
- service_name: string | null;
1518
- agent_name: string | null;
1519
- span_count: number;
1520
- has_errors: boolean;
1521
- start_time: string;
1522
- end_time: string;
1523
- duration_ms: number;
1524
- raw_jsonl_bytes: number;
1525
- models: string[];
1526
- tools: string[];
1527
- }
1528
- interface TraceAnalystFilters {
1529
- /** Restrict to traces that contain at least one error span. */
1530
- has_errors?: boolean;
1531
- /** Match if any span's `service.name` is in this list. */
1532
- service_names?: string[];
1533
- /** Match if any span's `agent.name` is in this list. */
1534
- agent_names?: string[];
1535
- /** Match if any LLM span's `llm.model_name` is in this list. */
1536
- model_names?: string[];
1537
- /** Match if any tool span's `tool.name` is in this list. */
1538
- tool_names?: string[];
1539
- /** ISO-8601 lower bound on the trace's earliest start time. */
1540
- start_time_after?: string;
1541
- /** ISO-8601 upper bound on the trace's earliest start time. */
1542
- start_time_before?: string;
1543
- /** Single regex applied to raw JSONL bytes for the trace. Opt-in;
1544
- * expensive on large datasets. Use the indexed filters above first. */
1545
- regex_pattern?: string;
1546
- }
1547
- /** One distinct error signature across the dataset — the deterministic unit of
1548
- * failure coverage. Signatures normalize volatile tokens (digits, hex/uuids,
1549
- * paths, durations) out of the span `status_message` so semantically identical
1550
- * failures collapse into one cluster. An analyst that accounts for every
1551
- * cluster has, by construction, covered every distinct failure mode. */
1552
- interface ErrorCluster {
1553
- /** Normalized status_message — the cluster key. */
1554
- signature: string;
1555
- /** A verbatim, un-normalized exemplar message (for exact-string citation). */
1556
- status_message_sample: string;
1557
- /** The span name that most often carries this signature, if any. */
1558
- span_name: string | null;
1559
- /** The tool that most often carries this signature, if any. */
1560
- tool_name: string | null;
1561
- trace_count: number;
1562
- span_count: number;
1563
- /** trace_count / total error traces in the matched set (0..1). */
1564
- prevalence: number;
1565
- /** Real trace ids carrying this signature (capped), passable to view/search. */
1566
- exemplar_trace_ids: string[];
1567
- /** Real span ids carrying this signature (capped). */
1568
- exemplar_span_ids: string[];
1569
- }
1570
- interface DatasetOverview {
1571
- total_traces: number;
1572
- raw_jsonl_bytes: number;
1573
- services: string[];
1574
- agents: string[];
1575
- models: string[];
1576
- tool_names: string[];
1577
- /** Up to 20 real trace ids the agent may pass to view/search tools. */
1578
- sample_trace_ids: string[];
1579
- errors: {
1580
- trace_count: number;
1581
- span_count: number;
1582
- };
1583
- /** The COMPLETE deterministic error-signature population, sorted by
1584
- * trace_count desc. This is the failure-coverage checklist: an analysis is
1585
- * complete only when every cluster here is accounted for. Empty when the
1586
- * matched set has no error spans. */
1587
- error_clusters: ErrorCluster[];
1588
- time_range: {
1589
- earliest: string;
1590
- latest: string;
1591
- } | null;
1592
- }
1593
- interface QueryTracesPage {
1594
- traces: TraceAnalystTraceSummary[];
1595
- total: number;
1596
- has_more: boolean;
1597
- }
1598
- /** Full-trace view. When the response would exceed the per-call byte
1599
- * budget, `oversized` is populated INSTEAD of `spans` so the agent
1600
- * knows to switch to `searchTrace` / `viewSpans`. */
1601
- interface ViewTraceResult {
1602
- trace_id: string;
1603
- spans?: TraceAnalystSpan[];
1604
- oversized?: ViewTraceOversized;
1605
- }
1606
- interface ViewTraceOversized {
1607
- span_count: number;
1608
- /** Names with their counts, sorted desc. Capped at 20 entries. */
1609
- top_span_names: Array<[string, number]>;
1610
- /** Largest single span body (bytes after attribute-cap projection). */
1611
- span_response_bytes_max: number;
1612
- error_span_count: number;
1613
- }
1614
- interface ViewSpansResult {
1615
- trace_id: string;
1616
- spans: TraceAnalystSpan[];
1617
- /** Number of requested span ids that were not found in the trace. */
1618
- missing_span_ids: string[];
1619
- /** Number of attribute fields truncated to fit the per-attribute cap. */
1620
- truncated_attribute_count: number;
1621
- }
1622
- interface SpanMatchRecord {
1623
- trace_id: string;
1624
- span_id: string;
1625
- span_name: string;
1626
- span_kind: TraceAnalystSpanKind;
1627
- /** JSON pointer-style path to the matched value, e.g.
1628
- * `attributes."llm.input_messages"[2].content`. */
1629
- attribute_path: string;
1630
- matched_text: string;
1631
- context_before: string;
1632
- context_after: string;
1633
- match_offset: number;
1634
- }
1635
- interface SearchTraceResult {
1636
- trace_id: string;
1637
- hits: SpanMatchRecord[];
1638
- total_matches: number;
1639
- has_more: boolean;
1640
- }
1641
- interface SearchSpanResult {
1642
- trace_id: string;
1643
- span_id: string;
1644
- hits: SpanMatchRecord[];
1645
- total_matches: number;
1646
- has_more: boolean;
1647
- }
1648
- /** Tunable byte budgets for bounded RLM tool output. */
1649
- interface TraceAnalystByteBudgets {
1650
- /** Max bytes any single tool response may emit. Hard ceiling enforced
1651
- * by the store; oversized → summary. Default 150_000. */
1652
- perCallByteCeiling: number;
1653
- /** Per-attribute string truncation cap on `viewTrace` (discovery scan).
1654
- * Default 4096. */
1655
- perAttributeViewBudget: number;
1656
- /** Per-attribute string truncation cap on `viewSpans` (surgical reads).
1657
- * Default 16384. */
1658
- perAttributeSpanBudget: number;
1659
- /** Per-attribute cap on a single match record's `matched_text` and
1660
- * context window. Default 1024. */
1661
- perMatchTextBudget: number;
1662
- }
1663
- declare const DEFAULT_TRACE_ANALYST_BUDGETS: TraceAnalystByteBudgets;
1664
- /** Marker substituted in place of truncated string payloads. Callers
1665
- * parsing tool output can detect it deterministically. */
1666
- declare const TRACE_ANALYST_TRUNCATION_MARKER_PREFIX = "[trace-analyst truncated:";
1667
-
1668
- /**
1669
- * `TraceAnalysisStore` — read-side interface the trace-analyst calls
1670
- * through. Six operations, all bounded:
1671
- *
1672
- * - `getOverview(filters?)` — dataset rollup + sample trace ids.
1673
- * - `queryTraces(filters?, limit, offset)` — paginated summaries.
1674
- * - `countTraces(filters?)` — cheap count without materialisation.
1675
- * - `viewTrace(trace_id, perAttrCap)` — full span list, oversized → summary.
1676
- * - `viewSpans(trace_id, span_ids, perAttrCap)` — surgical span fetch.
1677
- * - `searchTrace(trace_id, regex, max_matches)` — bounded regex hits.
1678
- * - `searchSpan(trace_id, span_id, regex, max_matches)` — single-span search.
1679
- *
1680
- * Multiple implementations ship in the core (`OtlpFileTraceStore`).
1681
- * Downstream callers can supply their own — e.g. a DuckDB-backed
1682
- * adapter or an in-memory adapter for tests — by implementing this
1683
- * interface.
1684
- *
1685
- * Filters compose with AND semantics. Empty/undefined fields impose
1686
- * no constraint. `regex_pattern` is the only opt-in raw-bytes scan —
1687
- * implementations may skip it via `count`/`overview` when not set.
1688
- */
1689
-
1690
- interface TraceAnalysisStore {
1691
- getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview>;
1692
- queryTraces(opts: {
1693
- filters?: TraceAnalystFilters;
1694
- limit: number;
1695
- offset?: number;
1696
- }): Promise<QueryTracesPage>;
1697
- countTraces(filters?: TraceAnalystFilters): Promise<number>;
1698
- viewTrace(opts: {
1699
- trace_id: string;
1700
- /** Override per-attribute byte cap. Defaults to discovery budget. */
1701
- per_attribute_byte_cap?: number;
1702
- }): Promise<ViewTraceResult>;
1703
- viewSpans(opts: {
1704
- trace_id: string;
1705
- span_ids: readonly string[];
1706
- /** Override per-attribute byte cap. Defaults to surgical budget. */
1707
- per_attribute_byte_cap?: number;
1708
- }): Promise<ViewSpansResult>;
1709
- searchTrace(opts: {
1710
- trace_id: string;
1711
- regex_pattern: string;
1712
- /** Hard cap on matches returned. Default 50. */
1713
- max_matches?: number;
1714
- }): Promise<SearchTraceResult>;
1715
- searchSpan(opts: {
1716
- trace_id: string;
1717
- span_id: string;
1718
- regex_pattern: string;
1719
- max_matches?: number;
1720
- }): Promise<SearchSpanResult>;
1721
- }
1722
-
1723
- interface AnalyzeTracesInput {
1724
- /** The user-facing question. Domain framing belongs here, not in the
1725
- * actor description. */
1726
- question: string;
1727
- }
1728
- interface AnalyzeTracesResult {
1729
- /** The actor's submitted prose answer. */
1730
- answer: string;
1731
- /** Bulleted findings from the actor's structured completion. */
1732
- findings: string[];
1733
- /** Per-turn snapshots captured via `actorTurnCallback`. */
1734
- turns: AnalyzeTracesTurnSnapshot[];
1735
- /** Total turns the actor took. */
1736
- turnCount: number;
1737
- /** Token usage by role. */
1738
- usage: TraceAnalystUsage;
1739
- /** Full system + assistant + tool message log by role. */
1740
- chatLog: TraceAnalystChatLog;
1741
- /** Prompt version that produced this run. */
1742
- actorPromptVersion: string;
1743
- }
1744
- interface TraceAnalystUsage {
1745
- actor: TraceAnalystUsageEntry[];
1746
- responder: TraceAnalystUsageEntry[];
1747
- }
1748
- interface TraceAnalystUsageEntry {
1749
- [key: string]: unknown;
1750
- }
1751
- interface TraceAnalystChatLog {
1752
- actor: TraceAnalystChatMessage[];
1753
- responder: TraceAnalystChatMessage[];
1754
- }
1755
- interface TraceAnalystChatMessage {
1756
- [key: string]: unknown;
1757
- }
1758
- interface AnalyzeTracesTurnSnapshot {
1759
- stage: AxAgentActorTurnCallbackArgs['stage'];
1760
- turn: number;
1761
- isError: boolean;
1762
- /** The JS code the actor produced for this turn. */
1763
- code: string;
1764
- /** The formatted action-log entry the actor sees on the next turn. */
1765
- output: string;
1766
- /** Provider thought (when `executorOptions.showThoughts` is true and the
1767
- * provider returns it). */
1768
- thought?: string;
1769
- }
1770
- interface AnalyzeTracesOptions {
1771
- /** Trace data source. Pass either an OTLP-JSONL path or a custom store. */
1772
- source: string | TraceAnalysisStore;
1773
- /** Caller-provided AxAIService. */
1774
- ai: AxAIService;
1775
- /** Model id forwarded to the actor. */
1776
- model?: string;
1777
- /** Maximum model subqueries. 0 disables model fan-out. Default 4. */
1778
- maxSubqueries?: number;
1779
- /** Maximum actor turns. Default 12. */
1780
- maxTurns?: number;
1781
- /** Maximum parallel model subqueries. Default 2. */
1782
- maxParallelSubqueries?: number;
1783
- /** Cancels in-flight model and tool work. */
1784
- signal?: AbortSignal;
1785
- /** Override the actor description. */
1786
- actorDescription?: string;
1787
- /** Per-turn observability hook. */
1788
- onTurn?: (turn: AnalyzeTracesTurnSnapshot) => void | Promise<void>;
1789
- /** Override max runtime characters per turn. Default 6000. */
1790
- maxRuntimeChars?: number;
1791
- /** When set, every turn's snapshot is appended to this JSONL file
1792
- * immediately. If the analyst crashes mid-loop (provider 503,
1793
- * network error, validator reject) the partial reasoning is still
1794
- * on disk for diagnosis and recovery. */
1795
- progressLogPath?: string;
1796
- }
1797
- /**
1798
- * Run the trace analyst.
1799
- *
1800
- * Throws:
1801
- * - `TraceFileMissingError` if `source` is a path and doesn't exist.
1802
- * - `AxAgentClarificationError` if the analyst asks for clarification.
1803
- * - Provider errors (auth, rate limits) propagate from the AI service.
1804
- */
1805
- declare function analyzeTraces(input: AnalyzeTracesInput, options: AnalyzeTracesOptions): Promise<AnalyzeTracesResult>;
1806
-
1807
- /**
1808
- * Trace-analyst auto-execution hook.
1809
- *
1810
- * Wires `analyzeTraces` into a `TraceEmitter`'s `onRunComplete` so a
1811
- * direct matrix run produces an analysis artifact without an out-of-band
1812
- * step. Designed for the case where the consumer reports "the analyst
1813
- * never ran" — the cause is almost always orchestration, not the analyst.
1814
- *
1815
- * Usage:
1816
- *
1817
- * const emitter = new TraceEmitter(store, {
1818
- * onRunComplete: [traceAnalystOnRunComplete({ analyze: opts, save })],
1819
- * })
1820
- *
1821
- * Hooks are best-effort by default — they never crash the underlying run.
1822
- * The caller decides whether to gate the run on the analysis result via
1823
- * the `gateOn` callback.
1824
- */
1825
-
1826
- interface TraceAnalystHookOptions {
1827
- /**
1828
- * Options forwarded to `analyzeTraces`. The hook supplies the question
1829
- * if you don't pass one — defaulting to a launch-grade prompt that asks
1830
- * for failure modes, surprising findings, and a recommendation.
1831
- */
1832
- analyze: Omit<AnalyzeTracesOptions, 'source'> & {
1833
- source?: AnalyzeTracesOptions['source'];
1834
- };
1835
- /**
1836
- * Override the question. The default is intentionally generic:
1837
- * "Summarise what happened in this run, surface any failure modes,
1838
- * surprising findings, or evidence the verdict is wrong."
1839
- */
1840
- question?: string;
1841
- /**
1842
- * Persist the result. The hook calls this with the analysis output and
1843
- * the run context. Common implementations write to a TraceAnalysisStore
1844
- * or append to a per-run JSONL.
1845
- */
1846
- save?: (result: AnalyzeTracesResult, ctx: RunCompleteHookContext) => Promise<void>;
1847
- /**
1848
- * Predicate gating execution per run. Default: every completed run.
1849
- * Use to skip aborted runs, debug runs, or runs without LLM activity.
1850
- */
1851
- shouldRun?: (ctx: RunCompleteHookContext) => boolean;
1852
- /**
1853
- * Optional gate: if set and returns false, the hook records the failure
1854
- * as a log event on the run instead of staying quiet. The caller can
1855
- * then trigger downstream alerts off `analyst_gate_failed` log events.
1856
- */
1857
- gateOn?: (result: AnalyzeTracesResult, ctx: RunCompleteHookContext) => boolean;
1858
- }
1859
- declare function traceAnalystOnRunComplete(opts: TraceAnalystHookOptions): RunCompleteHook;
1860
-
1861
- interface TraceInsightTask {
1862
- id: string;
1863
- name: string;
1864
- prompt?: string;
1865
- difficulty?: string;
1866
- tags?: string[];
1867
- outcome?: string;
1868
- score?: number;
1869
- gaps?: string[];
1870
- }
1871
- interface TraceInsightSuite {
1872
- name: string;
1873
- collectionId?: string;
1874
- tasks: TraceInsightTask[];
1875
- }
1876
- interface TraceInsightFinding {
1877
- kind: string;
1878
- severity?: string;
1879
- taskIds: string[];
1880
- evidence?: string;
1881
- proposedFixClass?: string;
1882
- }
1883
- interface TraceInsightQuestion {
1884
- id: string;
1885
- question: string;
1886
- why: string;
1887
- }
1888
- interface TraceInsightPanelRole {
1889
- id: string;
1890
- name: string;
1891
- responsibility: string;
1892
- }
1893
- interface TraceInsightPromptInput {
1894
- suite: TraceInsightSuite;
1895
- findings?: TraceInsightFinding[];
1896
- agent?: Record<string, unknown>;
1897
- totals?: Record<string, unknown>;
1898
- maxRepresentativeTraces?: number;
1899
- }
1900
- interface TraceInsightContext {
1901
- suite: TraceInsightSuite;
1902
- scope: string;
1903
- keywords: string[];
1904
- questions: TraceInsightQuestion[];
1905
- panel: TraceInsightPanelRole[];
1906
- findings: TraceInsightFinding[];
1907
- agent: Record<string, unknown> | null;
1908
- totals: Record<string, unknown> | null;
1909
- }
1910
- interface TraceInsightQualityGate {
1911
- id: string;
1912
- label: string;
1913
- passed: boolean;
1914
- severity: 'critical' | 'high' | 'medium' | 'low';
1915
- detail: string;
1916
- }
1917
- interface TraceInsightReadiness {
1918
- score: number;
1919
- grade: 'external-ready' | 'internal-review' | 'raw-analysis';
1920
- gates: TraceInsightQualityGate[];
1921
- }
1922
- declare function tokenizeDomainWords(value: string): string[];
1923
- declare function inferDomainKeywords(suite: TraceInsightSuite): string[];
1924
- declare function domainEvidencePattern(keywords: string[]): RegExp;
1925
- declare function describeTraceInsightScope(suite: TraceInsightSuite): string;
1926
- declare function planTraceInsightQuestions(input: TraceInsightPromptInput): TraceInsightQuestion[];
1927
- declare function buildTraceInsightContext(input: TraceInsightPromptInput): TraceInsightContext;
1928
- declare function scoreTraceInsightReadiness(context: TraceInsightContext): TraceInsightReadiness;
1929
- declare function defaultTraceInsightPanel(): TraceInsightPanelRole[];
1930
- declare function buildTraceInsightPrompt(input: TraceInsightPromptInput): string;
1931
-
1932
- /**
1933
- * `flattenOtlpExportToNdjson` — flatten an `OtlpExport` (the shape
1934
- * `exportRunAsOtlp` produces) into the per-line JSON the analyst's
1935
- * `OtlpFileTraceStore` index reads. Replaces three per-consumer OTLP
1936
- * flatteners with one canonical projection.
1937
- *
1938
- * Pure function, no I/O — the caller does `.map(JSON.stringify).join('\n')`
1939
- * and writes the file (consumers want control over rotation + naming).
1940
- */
1941
-
1942
- interface OtlpFlatLine {
1943
- trace_id: string;
1944
- span_id: string;
1945
- parent_span_id: string | null;
1946
- name: string;
1947
- kind: string;
1948
- start_time: string;
1949
- end_time: string;
1950
- status: {
1951
- code: 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR' | 'STATUS_CODE_UNSET';
1952
- message?: string;
1953
- };
1954
- resource: {
1955
- attributes: Record<string, string | number | boolean>;
1956
- };
1957
- attributes: Record<string, string | number | boolean>;
1958
- events?: Array<{
1959
- name: string;
1960
- timeUnixNano?: string;
1961
- attributes?: Record<string, unknown>;
1962
- }>;
1963
- }
1964
- interface FlattenOtlpOptions {
1965
- /** `'openinference'` (default) mirrors legacy per-span attributes into the
1966
- * canonical OpenInference vocabulary the analyst readers consume. `'none'`
1967
- * passes attributes through untouched. */
1968
- attributeVocabulary?: 'openinference' | 'none';
1969
- /** Override the numeric-kind → otlp-string mapping. */
1970
- kindMap?: Partial<Record<number, string>>;
1971
- }
1972
- declare function flattenOtlpExportToNdjson(otlpExport: OtlpExport, opts?: FlattenOtlpOptions): OtlpFlatLine[];
1973
-
1974
- /**
1975
- * Canonical OTLP-flat-line readers shared by every consumer of the
1976
- * OTLP-JSONL wire shape (one OTLP span per line; the form
1977
- * `flattenOtlpExportToNdjson` produces and the form AppWorld / HALO
1978
- * emit via their OpenInference OTLP exporter).
1979
- *
1980
- * `OtlpFileTraceStore` indexes spans with these; `otlpToRunRecords`
1981
- * aggregates spans into `RunRecord`s with the same readers. One parser,
1982
- * one vocabulary — a divergence between the analyst's view of a trace and
1983
- * the RunRecord projected from it is a class of bug this consolidation
1984
- * removes by construction.
1985
- *
1986
- * Vocabulary. The readers understand BOTH dialects that appear in the
1987
- * wild:
1988
- * - the substrate's own `llm.*` / `tool.*` / `span.kind` attributes
1989
- * (`flattenSpanAttributes` in `trace/otel.ts`), and
1990
- * - the OpenInference / inference-export attributes AppWorld / HALO
1991
- * emit (`openinference.span.kind`, `inference.observation_kind`,
1992
- * `inference.llm.input_tokens`, `llm.token_count.prompt`, …).
1993
- *
1994
- * Pure, no I/O.
1995
- */
1996
-
1997
- /**
1998
- * The structural fields a flat OTLP-JSONL line projects to. `attributes`
1999
- * is the merged resource+span attribute map (span overrides resource);
2000
- * the named fields are the pivots every reader of a trace needs without
2001
- * paying the full attribute materialisation.
2002
- */
2003
- interface ProjectedOtlpSpan {
2004
- trace_id: string;
2005
- span_id: string;
2006
- parent_span_id: string | null;
2007
- name: string;
2008
- kind: TraceAnalystSpanKind;
2009
- start_time: string;
2010
- end_time: string;
2011
- duration_ms: number;
2012
- status: TraceAnalystSpanStatus;
2013
- status_message: string | undefined;
2014
- service_name: string | null;
2015
- agent_name: string | null;
2016
- model_name: string | null;
2017
- tool_name: string | null;
2018
- /** Merged resource + span attributes, span winning on overlap. */
2019
- attributes: Record<string, unknown>;
2020
- }
2021
- /**
2022
- * Project one parsed OTLP-JSONL object to `ProjectedOtlpSpan`, or `null`
2023
- * when the line is missing the mandatory `trace_id` + `span_id`.
2024
- */
2025
- declare function projectOtlpFlatLine(raw: Record<string, unknown>): ProjectedOtlpSpan | null;
2026
- declare function readOtlpStatus(raw: Record<string, unknown>): {
2027
- code: TraceAnalystSpanStatus;
2028
- message: string | undefined;
2029
- };
2030
- declare function inferOtlpKind(attrs: Record<string, unknown>): TraceAnalystSpanKind;
2031
- /**
2032
- * Flatten OTLP `attributes` + `resource.attributes` into a single
2033
- * dotted-key map. Span attributes override resource attributes when keys
2034
- * overlap. Nested objects/arrays are preserved as-is.
2035
- */
2036
- declare function extractOtlpAttributes(raw: Record<string, unknown>): Record<string, unknown>;
2037
- declare function stringField(raw: Record<string, unknown>, key: string): string | undefined;
2038
- declare function asString(v: unknown): string | null;
2039
- /** First non-empty string value across a list of candidate attribute keys. */
2040
- declare function firstStringAttr(attrs: Record<string, unknown>, keys: readonly string[]): string | null;
2041
-
2042
- /**
2043
- * `otlpToRunRecords` — fold an OTLP traces.jsonl (one OTLP span per line;
2044
- * the form AppWorld / HALO emit via their OpenInference OTLP exporter, the
2045
- * same shape `flattenOtlpExportToNdjson` produces) into validated
2046
- * `RunRecord[]` — one record per `trace_id` by default, or per caller-defined
2047
- * logical run when one task is fragmented across multiple OTLP traces.
2048
- *
2049
- * This is the offline ingestion primitive the AppWorld proposer bench and the
2050
- * hosted Intelligence product both stand on: traces in, paper-grade rows
2051
- * out, ready for `compareProposers` / `analyzeRuns` / the promotion gate.
2052
- *
2053
- * Aggregation per trace:
2054
- * - tokenUsage: reconcile input, output, cache-read, and cache-write across
2055
- * nested model-call wrappers without double-counting parent aggregates.
2056
- * - costUsd: reconcile complete observed model-call cost when present; else priced via
2057
- * `opts.priceUsdPerToken` from the aggregated tokens; else 0 with a
2058
- * loud `raw.cost_unpriced = 1` marker so a missing price is visible, not
2059
- * a silent zero folded into a gate.
2060
- * - failureMode: the first `STATUS_CODE_ERROR` span's normalized status
2061
- * message (carries the real failure signature, not a generic class).
2062
- * - model: the dominant LLM model in the trace (snapshot-padded to satisfy
2063
- * `validateRunRecord` when the trace's model is a bare alias).
2064
- * - outcome score: `opts.scoreForTrace` (AppWorld `world.evaluate()` →
2065
- * TGC/SGC) when supplied; else 1 when the trace had no error span, 0
2066
- * when it did — a defensible default the caller can override.
2067
- * - prompt / completion: carried into `raw` as token-count signals and,
2068
- * when the first/last LLM span exposes `input.value` / `output.value`,
2069
- * the verbatim text is preserved on the optional `promptText` /
2070
- * `completionText` of the returned `OtlpTraceRunRecord`.
2071
- *
2072
- * Fail-loud: an OTLP file with zero valid spans throws. A trace with no
2073
- * spans is impossible (a trace exists only because a span referenced it).
2074
- * `validateRunRecord` runs on every row — a malformed projection throws
2075
- * rather than silently producing a half-record.
2076
- */
2077
-
2078
- interface OtlpToRunRecordsOptions {
2079
- /** Logical experiment grouping for every produced record. */
2080
- experimentId: string;
2081
- /** Candidate (variant) id — the surface these traces exercised. The
2082
- * bench passes the proposer label here so `compareProposers` can pair rows. */
2083
- candidateId: string;
2084
- /** Split assignment for every produced record. Default `'holdout'` —
2085
- * ingested traces are evidence, not the optimizer's training pool. */
2086
- splitTag?: RunSplitTag;
2087
- /** Git SHA the traces were produced from. Default `'unknown'`. */
2088
- commitSha?: string;
2089
- /** sha256 of the effective prompt surface. Default `'unknown'`. */
2090
- promptHash?: string;
2091
- /** sha256 of the effective config. Default `'unknown'`. */
2092
- configHash?: string;
2093
- /** RNG seed recorded on every row. Default 0. */
2094
- seed?: number;
2095
- /**
2096
- * Fallback model snapshot when the trace exposes no LLM model attribute
2097
- * OR exposes a bare alias `validateRunRecord` would reject. The trace's
2098
- * own model wins when it already carries a snapshot. Default
2099
- * `'unknown@otlp'` (opaque-snapshot form the validator accepts).
2100
- */
2101
- fallbackModel?: string;
2102
- /**
2103
- * USD per total token (input+output) used to price a trace when no
2104
- * per-span cost attribute is present. When unset, an unpriced trace
2105
- * records `costUsd: 0` AND `raw.cost_unpriced = 1` — the zero is flagged,
2106
- * never silent.
2107
- */
2108
- priceUsdPerToken?: number;
2109
- /**
2110
- * Map each OTLP `trace_id` to the logical run it belongs to. Use this when a
2111
- * provider emits several traces for one task attempt. All mapped traces are
2112
- * aggregated into one record; duplicate span ids remain isolated by their
2113
- * source trace. The callback must return a non-empty id for every trace.
2114
- *
2115
- * When omitted, every `trace_id` remains an independent run.
2116
- */
2117
- logicalRunIdForTrace?: (traceId: string) => string;
2118
- /**
2119
- * Score for a produced run's outcome (AppWorld `world.evaluate()` →
2120
- * TGC/SGC, or
2121
- * any [0,1] task-success signal). Keyed by the logical run id when
2122
- * `logicalRunIdForTrace` is supplied, otherwise by `trace_id`; falls through to
2123
- * the error-derived default (1 = no error span, 0 = had one) when the map
2124
- * has no entry or the function returns undefined.
2125
- */
2126
- scoreForTrace?: (runId: string, span: TraceAggregate) => number | undefined;
2127
- /**
2128
- * Per-record judge metadata when an external judge produced the score.
2129
- * Keyed by the logical run id when supplied, otherwise by `trace_id`.
2130
- */
2131
- judgeMetadataForTrace?: (runId: string) => RunRecord['judgeMetadata'] | undefined;
2132
- }
2133
- /** A `RunRecord` plus the verbatim prompt/completion text when the trace's
2134
- * LLM spans exposed it. The text is NOT on the validated `RunRecord`
2135
- * (`outcome.raw` is numeric-only) but consumers ingesting full traces want
2136
- * it — so it rides alongside. */
2137
- interface OtlpTraceRunRecord {
2138
- record: RunRecord;
2139
- /** Verbatim first-LLM-span `input.value`, when present. */
2140
- promptText?: string;
2141
- /** Verbatim last-LLM-span `output.value`, when present. */
2142
- completionText?: string;
2143
- }
2144
- /** Per-trace rollup the score callback can inspect. */
2145
- interface TraceAggregate {
2146
- traceId: string;
2147
- /** Number of source OTLP traces folded into this run. */
2148
- sourceTraceCount: number;
2149
- /** Source OTLP trace ids folded into this run, sorted for deterministic audit output. */
2150
- sourceTraceIds: readonly string[];
2151
- spanCount: number;
2152
- llmSpanCount: number;
2153
- toolSpanCount: number;
2154
- agentSpanCount: number;
2155
- errorSpanCount: number;
2156
- tokenUsage: RunTokenUsage;
2157
- /** First error span's normalized status message, if any. */
2158
- firstErrorMessage?: string;
2159
- model: string;
2160
- startTime: string;
2161
- endTime: string;
2162
- wallMs: number;
2163
- }
2164
- /**
2165
- * Parse + aggregate an OTLP traces.jsonl string into validated
2166
- * `RunRecord[]` (one per trace). Use {@link otlpToTraceRunRecords} when you
2167
- * also want the verbatim prompt/completion text alongside each record.
2168
- */
2169
- declare function otlpToRunRecords(otlpJsonl: string, opts: OtlpToRunRecordsOptions): RunRecord[];
2170
- /**
2171
- * Aggregate already-parsed OTLP flat rows without serializing them back to
2172
- * JSONL. This is the in-memory counterpart to {@link otlpToRunRecords}; both
2173
- * paths share projection, reconciliation, validation, and ordering.
2174
- */
2175
- declare function otlpRowsToRunRecords(rows: Iterable<object>, opts: OtlpToRunRecordsOptions): RunRecord[];
2176
- /** As {@link otlpToRunRecords} but returns the prompt/completion text too. */
2177
- declare function otlpToTraceRunRecords(otlpJsonl: string, opts: OtlpToRunRecordsOptions): OtlpTraceRunRecord[];
2178
- /** Parsed-row counterpart to {@link otlpToTraceRunRecords}. */
2179
- declare function otlpRowsToTraceRunRecords(rows: Iterable<object>, opts: OtlpToRunRecordsOptions): OtlpTraceRunRecord[];
2180
-
2181
- /** Ax RLM prompt for bounded trace discovery and evidence-backed analysis. */
2182
- declare const TRACE_ANALYST_ACTOR_DESCRIPTION = "You answer questions about an OTLP-shaped JSONL trace dataset using the trace tools provided in the `traces` namespace.\n\nDISCOVERY \u2192 NARROW \u2192 DEEP-READ protocol \u2014 follow exactly:\n\n1. ALWAYS call `traces.getDatasetOverview({})` FIRST without a regex_pattern. The result tells you total_traces, raw_jsonl_bytes, services, agents, models, and sample_trace_ids (real ids \u2014 never fabricate one).\n\n2. Use raw_jsonl_bytes to gauge how expensive raw scans will be. `filters.regex_pattern` is the one scan-heavy filter on getDatasetOverview / queryTraces / countTraces \u2014 narrow with indexed fields (has_errors, model_names, service_names, agent_names, time bounds) BEFORE adding a regex on a large dataset.\n\n3. To list more traces than the sample, call `traces.queryTraces({ filters?, limit, offset? })`. Each summary carries raw_jsonl_bytes \u2014 use it to choose between viewTrace and searchTrace BEFORE calling either.\n\n4. Per-trace inspection:\n - SMALL trace (raw_jsonl_bytes well under 150_000): call `traces.viewTrace({ trace_id })`. Returns all spans. Per-attribute payloads are head-capped at ~4KB; large `input.value` / `output.value` / `llm.input_messages` will show a `[trace-analyst truncated: N bytes]` marker.\n - LARGE trace (raw_jsonl_bytes near or above 150_000, or you saw an `oversized` response): use `traces.searchTrace({ trace_id, regex_pattern })` to get bounded SpanMatchRecords (span metadata + matched text + surrounding context). Then call `traces.viewSpans({ trace_id, span_ids: [...] })` for surgical reads (~16KB cap, 4\u00D7 higher than discovery), or `traces.searchSpan({ trace_id, span_id, regex_pattern })` for one large span. Stays bounded regardless of trace size.\n - Useful regex patterns: `STATUS_CODE_ERROR` (failures), tool names like `grep` or `view_trace`, error strings like `MaxTurnsExceeded`, model names, attribute keys.\n\n5. ONLY call viewTrace / viewSpans / searchTrace / searchSpan with trace/span ids you have already seen in sample_trace_ids, a queryTraces page, or a previous search result. Never invent ids.\n\n5a. **Result-shape contract** \u2014 searchTrace and searchSpan return `{ trace_id, hits, total_matches, has_more }`. Iterate `result.hits` (NOT result.matches). Each hit has `{ span_id, span_name, span_kind, attribute_path, matched_text, context_before, context_after, match_offset }`. viewTrace returns `{ trace_id, spans }` (or `oversized`). viewSpans returns `{ trace_id, spans, missing_span_ids, truncated_attribute_count }`. Never assume a field name \u2014 log the result shape first if unsure.\n\n6. If viewTrace returns an `oversized` summary instead of `spans`, DO NOT retry the same call. Read the summary's top_span_names, span_count, span_response_bytes_max, error_span_count to plan a follow-up: switch to searchTrace (or searchSpan for one large span), then viewSpans on a smaller, surgical span_ids set.\n\n7. If searchTrace or searchSpan returns has_more=true, REFINE the regex to be more specific rather than blindly raising max_matches.\n\n8. If a tool errors (invalid regex, range error), STOP and reconsider \u2014 don't retry with a guessed id or argument. Use the discovery tools above to recover.\n\n9. If a ~4KB-truncated payload from viewTrace / searchTrace matters for your answer, first try viewSpans on that span id (~16KB cap). If a 16KB-truncated payload from viewSpans still matters, narrow further with searchSpan against a more specific regex rather than asking for the full payload again.\n\n10. If the question splits into independent reasoning branches, use bounded `llmQuery(...)` calls over evidence you already loaded. Subqueries cannot inspect the trace store, so pass the exact trace excerpts they need. Example:\n\n const reviews = await llmQuery([\n { query: 'Classify the failure mechanism in this excerpt.', context: traceAbcExcerpt },\n { query: 'Classify the failure mechanism in this excerpt.', context: traceDefExcerpt },\n ]);\n\nOBSERVABILITY rules:\n- Each discovery turn must emit at least one concise `console.log(...)` showing what evidence was learned.\n- Finish gathering evidence before submitting the analysis.\n- Reuse runtime variables across turns; don't recompute.\n\nOUTPUT contract \u2014 your final answer must include:\n- A clear prose conclusion answering the user's question.\n- Trace ids and span ids cited as evidence for each claim.\n- Failure modes named in the user's domain language, with frequency and concrete examples.\n- A concise findings array containing only claims supported by inspected evidence.\n\nDo NOT invent trace ids, span ids, error messages, or model names. Every fact must be traceable to a tool result.";
2183
- declare const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = "trace-analyst-actor-v6-2026-07-14";
2184
-
2185
- /**
2186
- * `OtlpFileTraceStore` — read-only OTLP-JSONL trace store for the
2187
- * trace-analyst.
2188
- *
2189
- * Wire shape. Each line of the input file is one OTLP-shaped span. The
2190
- * store understands flattened OTLP JSONL plus the OpenInference vocab.
2191
- * We project upstream's full
2192
- * span shape down to `TraceAnalystSpan` lazily — full materialisation
2193
- * only happens for the spans the agent actually requests.
2194
- *
2195
- * Indexing. On first read the store builds an in-memory index keyed
2196
- * by `trace_id` carrying:
2197
- * - byte offsets + lengths for each span line (for surgical reads
2198
- * without re-parsing the whole file)
2199
- * - a `TraceAnalystTraceSummary` rollup
2200
- * - sets of services / agents / models / tools / has_errors
2201
- * - byte size of the trace's JSONL slab
2202
- *
2203
- * Memory bound. The index keeps span metadata only — names, kinds,
2204
- * offsets, status. Attribute payloads stay on disk until requested.
2205
- * For a 50MB JSONL with 50k spans, the index is ~5MB.
2206
- *
2207
- * Concurrency. The store builds the index once on first read and
2208
- * caches it. Subsequent reads reuse the index. The file is opened on
2209
- * each read; we never hold a long-lived FD.
2210
- */
2211
-
2212
- interface OtlpFileTraceStoreOptions {
2213
- /** Path to the OTLP-JSONL file. */
2214
- path: string;
2215
- /** Override the discovery (`viewTrace`) per-attribute byte cap. */
2216
- perAttributeViewBudget?: number;
2217
- /** Override the surgical (`viewSpans`) per-attribute byte cap. */
2218
- perAttributeSpanBudget?: number;
2219
- /** Override the per-call ceiling that triggers oversized summaries. */
2220
- perCallByteCeiling?: number;
2221
- /** Override the per-match text budget. */
2222
- perMatchTextBudget?: number;
2223
- /**
2224
- * Hard ceiling on the trace file size in bytes. The store reads the
2225
- * whole file into one Buffer and indexes it in memory, so an
2226
- * unbounded file OOMs the process. Above this size the store fails
2227
- * loud with `TraceFileTooLargeError` instead of degrading silently.
2228
- * Default 256 MiB.
2229
- */
2230
- maxFileBytes?: number;
2231
- }
2232
- declare class OtlpFileTraceStore implements TraceAnalysisStore {
2233
- private readonly path;
2234
- private readonly perAttributeViewBudget;
2235
- private readonly perAttributeSpanBudget;
2236
- private readonly perCallByteCeiling;
2237
- private readonly perMatchTextBudget;
2238
- private readonly maxFileBytes;
2239
- private indexPromise?;
2240
- /** Cached UTF-8 buffer of the file. We pin it once because every
2241
- * read needs slice access and re-reading on each call balloons the
2242
- * syscall count. */
2243
- private bufferPromise?;
2244
- constructor(opts: OtlpFileTraceStoreOptions);
2245
- getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview>;
2246
- queryTraces(opts: {
2247
- filters?: TraceAnalystFilters;
2248
- limit: number;
2249
- offset?: number;
2250
- }): Promise<QueryTracesPage>;
2251
- countTraces(filters?: TraceAnalystFilters): Promise<number>;
2252
- viewTrace(opts: {
2253
- trace_id: string;
2254
- per_attribute_byte_cap?: number;
2255
- }): Promise<ViewTraceResult>;
2256
- viewSpans(opts: {
2257
- trace_id: string;
2258
- span_ids: readonly string[];
2259
- per_attribute_byte_cap?: number;
2260
- }): Promise<ViewSpansResult>;
2261
- searchTrace(opts: {
2262
- trace_id: string;
2263
- regex_pattern: string;
2264
- max_matches?: number;
2265
- }): Promise<SearchTraceResult>;
2266
- searchSpan(opts: {
2267
- trace_id: string;
2268
- span_id: string;
2269
- regex_pattern: string;
2270
- max_matches?: number;
2271
- }): Promise<SearchSpanResult>;
2272
- /** Force the index to materialise. Useful to amortise startup cost
2273
- * before the first agent call. */
2274
- ensureIndexed(): Promise<void>;
2275
- private buffer;
2276
- /** Stat-then-read so an oversized file fails loud BEFORE we allocate a
2277
- * multi-hundred-MB Buffer and OOM the process. A missing file surfaces
2278
- * as TraceFileMissingError; any other stat/read error propagates. */
2279
- private readGuarded;
2280
- private index;
2281
- private buildIndex;
2282
- private matchedTraces;
2283
- private toSummary;
2284
- private projectSpan;
2285
- private buildOversizedSummary;
2286
- private scanSpanForMatches;
2287
- }
2288
- declare class TraceFileMissingError extends NotFoundError {
2289
- constructor(path: string);
2290
- }
2291
- declare class TraceNotFoundError extends NotFoundError {
2292
- readonly trace_id: string;
2293
- constructor(trace_id: string);
2294
- }
2295
- declare class SpanNotFoundError extends NotFoundError {
2296
- readonly trace_id: string;
2297
- readonly span_id: string;
2298
- constructor(trace_id: string, span_id: string);
2299
- }
2300
-
2301
- /**
2302
- * Trace-analyst tool surface — six namespaced AxFunctions the analyst
2303
- * agent calls from generated JS code via `traces.<name>(...)`.
2304
- *
2305
- * Discovery → narrow → deep-read protocol. Tool names + ordering
2306
- * support RLM discovery:
2307
- *
2308
- * 1. `getDatasetOverview` (cheap) — first call, sizes the dataset
2309
- * 2. `queryTraces` — paginated summaries with `raw_jsonl_bytes`
2310
- * 3. `countTraces` — cheap pre-flight before regex
2311
- * 4. `viewTrace` — full span list, oversized → summary
2312
- * 5. `viewSpans` — surgical 16KB-cap reads
2313
- * 6. `searchTrace` / `searchSpan` — bounded regex hits
2314
- *
2315
- * Failure mode. Tool handlers throw on bad input (invalid trace ids,
2316
- * out-of-range pagination, malformed regex). Ax converts thrown errors
2317
- * into actor-visible `[ERROR]` strings so the analyst can adjust on
2318
- * the next turn instead of looping.
2319
- */
2320
-
2321
- interface BuildTraceAnalystToolsOpts {
2322
- store: TraceAnalysisStore;
2323
- /** Override the default sample-trace-id slot count (20). Mostly for tests. */
2324
- sampleTraceLimit?: number;
2325
- }
2326
- /**
2327
- * Build the trace-analyst function set. Pass the result into
2328
- * `agent(...).functions.local`.
2329
- */
2330
- declare function buildTraceAnalystTools(opts: BuildTraceAnalystToolsOpts): AxFunction[];
2331
- /**
2332
- * Convenience: same shape as `buildTraceAnalystTools` but returns the
2333
- * grouped form expected when registering trace tools alongside other
2334
- * agent function modules. */
2335
- declare function traceAnalystFunctionGroup(opts: BuildTraceAnalystToolsOpts): {
2336
- namespace: string;
2337
- title: string;
2338
- selectionCriteria: string;
2339
- description: string;
2340
- functions: AxFunction[];
2341
- };
2342
-
2343
- export { type AnalyzeTracesInput, type AnalyzeTracesOptions, type AnalyzeTracesResult, type AnalyzeTracesTurnSnapshot, type Artifact, type BudgetLedgerEntry, type BudgetSpec, type CaptureFetchContext, type CaptureFetchOptions, DEFAULT_REDACTION_RULES, DEFAULT_TRACE_ANALYST_BUDGETS, type DatasetOverview, type ErrorCluster, type EventFilter, type EventKind, type ExportableSpan, type ExtractUsageFromSseOptions, type ExtractedUsage, FAILURE_CLASSES, type FailureClass, FileSystemRawProviderSink, type FileSystemRawProviderSinkOptions, FileSystemTraceStore, type FileSystemTraceStoreOptions, type FlattenOtlpOptions, type GenericSpan, INPUT_VALUE, InMemoryRawProviderSink, type InMemoryRawProviderSinkOptions, InMemoryTraceStore, type JudgeSpan, LLM_CACHED_TOKENS, LLM_CACHED_TOKEN_ATTR_KEYS, LLM_CACHE_WRITE_TOKENS, LLM_CACHE_WRITE_TOKEN_ATTR_KEYS, LLM_CONTEXT_TOKENS, LLM_COST_ATTR_KEYS, LLM_COST_USD, LLM_INPUT_TOKENS, LLM_INPUT_TOKEN_ATTR_KEYS, LLM_MODEL_ATTR_KEYS, LLM_MODEL_NAME, LLM_OUTPUT_TOKENS, LLM_OUTPUT_TOKEN_ATTR_KEYS, LLM_REASONING_TOKENS, LLM_REASONING_TOKEN_ATTR_KEYS, type LlmSpan, type LlmSpanOtlpInput, type Message, NoopRawProviderSink, OPENINFERENCE_SPAN_KIND, OTEL_AGENT_EVAL_SCOPE, OUTPUT_VALUE, type OtelExportConfig, type OtelExporter, type OtlpExport, OtlpFileTraceStore, type OtlpFileTraceStoreOptions, type OtlpFlatLine, type OtlpResourceSpans, type OtlpSpan, type OtlpToRunRecordsOptions, type OtlpTraceRunRecord, type ProjectedOtlpSpan, type ProviderRedactor, type QueryTracesPage, REDACTION_VERSION, RUN_COST_ATTR_KEYS, type RawProviderDirection, type RawProviderEvent, type RawProviderSink, type RawProviderSinkFilter, type RedactionReport, type RedactionRule, ReplayCache, type ReplayCacheEntry, ReplayCacheMissError, type ReplayCacheStats, type ReplayFetchOptions, type RetrievalSpan, type Run, type RunCompleteHook, type RunCompleteHookContext, type RunFilter, RunIntegrityError, type RunIntegrityExpectations, type RunIntegrityIssue, type RunIntegrityIssueCode, type RunIntegrityReport, type RunLayer, type RunOutcome$1 as RunOutcome, type RunStatus, SPAN_KIND_ATTR_KEYS, type SandboxSpan, type SearchSpanResult, type SearchTraceResult, type Span, type SpanBase, type SpanFilter, type SpanHandle, type SpanKind, type SpanMatchRecord, SpanNotFoundError, type SpanStatus, type SseUsageMode, TOOL_ARGS_CAPTURED, TOOL_LATENCY_MS, TOOL_NAME, TOOL_NAME_ATTR_KEYS, TRACE_ANALYST_ACTOR_DESCRIPTION, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION, TRACE_ANALYST_TRUNCATION_MARKER_PREFIX, TRACE_SCHEMA_VERSION, type ToolSpan, type ToolSpanOtlpInput, type TraceAggregate, type TraceAnalysisStore, type TraceAnalystByteBudgets, type TraceAnalystFilters, type TraceAnalystHookOptions, type TraceAnalystSpan, type TraceAnalystSpanKind, type TraceAnalystSpanStatus, type TraceAnalystTraceSummary, TraceEmitter, type TraceEmitterOptions, type TraceEvent, TraceFileMissingError, type TraceInsightContext, type TraceInsightFinding, type TraceInsightPanelRole, type TraceInsightPromptInput, type TraceInsightQualityGate, type TraceInsightQuestion, type TraceInsightReadiness, type TraceInsightSuite, type TraceInsightTask, TraceNotFoundError, type TraceStore, type TraceStoreSource, type TraceStoreToOtlpOptions, type TracesToOtlpResult, type ViewSpansResult, type ViewTraceOversized, type ViewTraceResult, aggregateLlm, analyzeTraces, applyLlmSpanOtlpAttributes, applyToolSpanOtlpAttributes, argHash, asNumber, asString, assertRunCaptured, buildTraceAnalystTools, buildTraceInsightContext, buildTraceInsightPrompt, captureFetchToRawSink, contextInputTokens, convertTraceStoresToOtlp, createOtelExporter, createOtelTracingStore, createReplayFetch, defaultProviderRedactor, defaultTraceInsightPanel, describeTraceInsightScope, domainEvidencePattern, exportRunAsOtlp, extractOtlpAttributes, extractUsage, extractUsageFromResponse, extractUsageFromSse, firstNumberAttr, firstStringAttr, flattenOtlpExportToNdjson, groupBy, hasCapturedToolArgs, inferDomainKeywords, inferOtlpKind, isJudgeSpan, isLlmSpan, isRetrievalSpan, isSandboxSpan, isToolSpan, iterateRawCalls, judgeSpans, llmSpanFromProvider, llmSpans, otelRunCompleteHook, otlpRowsToRunRecords, otlpRowsToTraceRunRecords, otlpToRunRecords, otlpToTraceRunRecords, planTraceInsightQuestions, projectOtlpFlatLine, providerFromBaseUrl, readOtlpStatus, redactString, redactValue, runFailureClass, runsForScenario, scoreTraceInsightReadiness, stringField, throwIfRunIncomplete, tokenizeDomainWords, toolSpans, traceAnalystFunctionGroup, traceAnalystOnRunComplete, traceSpanKindToOpenInferenceKind };