@tangle-network/agent-eval 0.20.11 → 0.20.12

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 (52) hide show
  1. package/README.md +99 -170
  2. package/dist/benchmarks/index.d.ts +2 -1
  3. package/dist/{chunk-JAOLXRIA.js → chunk-75MCTH7P.js} +8 -2
  4. package/dist/chunk-75MCTH7P.js.map +1 -0
  5. package/dist/chunk-HKYRWNHV.js +1354 -0
  6. package/dist/chunk-HKYRWNHV.js.map +1 -0
  7. package/dist/{chunk-LSR4IAYN.js → chunk-HNJLMAJ2.js} +2 -2
  8. package/dist/chunk-IKFVX537.js +717 -0
  9. package/dist/chunk-IKFVX537.js.map +1 -0
  10. package/dist/chunk-KWUAAIHR.js +1764 -0
  11. package/dist/chunk-KWUAAIHR.js.map +1 -0
  12. package/dist/chunk-MCMV7DUL.js +1310 -0
  13. package/dist/chunk-MCMV7DUL.js.map +1 -0
  14. package/dist/chunk-ODFINDLQ.js +413 -0
  15. package/dist/chunk-ODFINDLQ.js.map +1 -0
  16. package/dist/chunk-PKCVBYTQ.js +200 -0
  17. package/dist/chunk-PKCVBYTQ.js.map +1 -0
  18. package/dist/chunk-YUFXO3TU.js +148 -0
  19. package/dist/chunk-YUFXO3TU.js.map +1 -0
  20. package/dist/cli.js +2 -2
  21. package/dist/control-C8NKbF3w.d.ts +258 -0
  22. package/dist/control.d.ts +5 -0
  23. package/dist/control.js +30 -0
  24. package/dist/control.js.map +1 -0
  25. package/dist/dataset-B9qvlm_o.d.ts +112 -0
  26. package/dist/emitter-BYO2nSDA.d.ts +387 -0
  27. package/dist/feedback-trajectory-BGQ_ANCN.d.ts +345 -0
  28. package/dist/{index-1PZOtZFr.d.ts → index-c5saLbKD.d.ts} +2 -133
  29. package/dist/index.d.ts +115 -2870
  30. package/dist/index.js +1049 -6156
  31. package/dist/index.js.map +1 -1
  32. package/dist/multi-shot-optimization-Bvtz294B.d.ts +598 -0
  33. package/dist/openapi.json +1 -1
  34. package/dist/optimization.d.ts +145 -0
  35. package/dist/optimization.js +60 -0
  36. package/dist/optimization.js.map +1 -0
  37. package/dist/reporting.d.ts +426 -0
  38. package/dist/reporting.js +32 -0
  39. package/dist/reporting.js.map +1 -0
  40. package/dist/run-record-CX_jcAyr.d.ts +134 -0
  41. package/dist/traces.d.ts +658 -0
  42. package/dist/traces.js +100 -0
  43. package/dist/traces.js.map +1 -0
  44. package/dist/wire/index.js +2 -2
  45. package/docs/concepts.md +16 -11
  46. package/docs/feature-guide.md +10 -17
  47. package/docs/integration-launch-gates.md +77 -0
  48. package/docs/product-eval-adoption.md +27 -0
  49. package/docs/trace-analysis.md +75 -0
  50. package/package.json +21 -1
  51. package/dist/chunk-JAOLXRIA.js.map +0 -1
  52. /package/dist/{chunk-LSR4IAYN.js.map → chunk-HNJLMAJ2.js.map} +0 -0
@@ -0,0 +1,658 @@
1
+ import { a as TraceStore, L as LlmSpan, J as JudgeSpan, R as Run, F as FailureClass, d as ToolSpan } from './emitter-BYO2nSDA.js';
2
+ export { A as Artifact, B as BudgetLedgerEntry, c as BudgetSpec, E as EventFilter, f as EventKind, g as FAILURE_CLASSES, h as FileSystemTraceStore, i as FileSystemTraceStoreOptions, G as GenericSpan, I as InMemoryTraceStore, M as Message, j as RetrievalSpan, e as RunFilter, k as RunLayer, C as RunOutcome, l as RunStatus, m as SandboxSpan, S as Span, n as SpanBase, o as SpanFilter, p as SpanHandle, q as SpanKind, r as SpanStatus, s as TRACE_SCHEMA_VERSION, T as TraceEmitter, t as TraceEmitterOptions, b as TraceEvent, u as isJudgeSpan, v as isLlmSpan, w as isRetrievalSpan, x as isSandboxSpan, y as isToolSpan, z as llmSpanFromProvider } from './emitter-BYO2nSDA.js';
3
+ import { AxAIService, AxFunction } from '@ax-llm/ax';
4
+
5
+ /**
6
+ * Typed query helpers over TraceStore.
7
+ *
8
+ * Not a full SQL engine — a minimal, composable set of operators that
9
+ * cover the canned-pipeline use cases. For ad-hoc analytics, persist to
10
+ * NDJSON and point DuckDB at it; the schema is stable so external SQL
11
+ * tooling works out of the box.
12
+ */
13
+
14
+ declare function runsForScenario(store: TraceStore, scenarioId: string): Promise<Run[]>;
15
+ declare function llmSpans(store: TraceStore, runId?: string): Promise<LlmSpan[]>;
16
+ declare function toolSpans(store: TraceStore, runId?: string, toolName?: string): Promise<ToolSpan[]>;
17
+ declare function judgeSpans(store: TraceStore, runId?: string): Promise<JudgeSpan[]>;
18
+ /** Group spans by any key selector. */
19
+ declare function groupBy<T, K extends string | number>(items: T[], key: (t: T) => K): Map<K, T[]>;
20
+ /** Hash tool arguments to an orderless-key-stable string for de-duplication. */
21
+ declare function argHash(args: unknown): string;
22
+ /** Sum an LLM-span array into aggregate token + cost. */
23
+ declare function aggregateLlm(spans: LlmSpan[]): {
24
+ inputTokens: number;
25
+ outputTokens: number;
26
+ cachedTokens: number;
27
+ costUsd: number;
28
+ };
29
+ /** Pick the outcome's failure class when present, else derive 'success' from run status. */
30
+ declare function runFailureClass(run: Run): FailureClass;
31
+
32
+ /**
33
+ * Redaction — remove PII / secrets from trace payloads before persist.
34
+ *
35
+ * Pre-persistence rules mean raw traces in storage are already scrubbed.
36
+ * Unredacted variants (for debugging / post-mortems) live in a separate
37
+ * storage layer with stricter access controls; this module only covers
38
+ * the default scrub-then-persist path.
39
+ *
40
+ * Rules compose: pass an array of `RedactionRule`, each is applied in
41
+ * order. Strings that match get replaced with a tagged sentinel so the
42
+ * eval framework can count how many redactions happened per run
43
+ * (surfaced via `redaction_applied` events).
44
+ */
45
+ interface RedactionRule {
46
+ id: string;
47
+ pattern: RegExp;
48
+ /** Replacement — e.g. '[PII:email]'. Defaults to `[redacted:{id}]`. */
49
+ replacement?: string;
50
+ }
51
+ interface RedactionReport {
52
+ redactionCount: number;
53
+ byRule: Record<string, number>;
54
+ }
55
+ /** OWASP / common-sense defaults — extend per-domain. */
56
+ declare const DEFAULT_REDACTION_RULES: RedactionRule[];
57
+ declare const REDACTION_VERSION = "1.0.0";
58
+ /**
59
+ * Redact a single string. Returns the new string and a per-rule count of
60
+ * how many substitutions fired.
61
+ */
62
+ declare function redactString(input: string, rules?: RedactionRule[]): {
63
+ output: string;
64
+ report: RedactionReport;
65
+ };
66
+ /**
67
+ * Walk a JSON-ish value applying `redactString` to every string leaf.
68
+ * Arrays and plain objects are recursed; other types pass through
69
+ * untouched. Circular references throw — traces should be tree-shaped.
70
+ */
71
+ declare function redactValue(value: unknown, rules?: RedactionRule[], report?: RedactionReport): {
72
+ value: unknown;
73
+ report: RedactionReport;
74
+ };
75
+
76
+ /**
77
+ * OpenTelemetry JSON export — maps TraceSchema v1 to OTLP/JSON so
78
+ * traces render natively in Jaeger / Honeycomb / Langfuse / Grafana.
79
+ *
80
+ * Wire format only. We do NOT depend on the @opentelemetry SDK — that
81
+ * would drag in polyfills incompatible with Workers/Edge. Consumers
82
+ * push the JSON to their collector of choice via HTTP.
83
+ *
84
+ * Reference: OTLP 1.3.2 (ResourceSpans / ScopeSpans / Span).
85
+ */
86
+
87
+ declare const OTEL_AGENT_EVAL_SCOPE: {
88
+ name: string;
89
+ version: string;
90
+ };
91
+ interface OtlpSpan {
92
+ traceId: string;
93
+ spanId: string;
94
+ parentSpanId?: string;
95
+ name: string;
96
+ kind: number;
97
+ startTimeUnixNano: string;
98
+ endTimeUnixNano: string;
99
+ attributes: Array<{
100
+ key: string;
101
+ value: {
102
+ stringValue?: string;
103
+ intValue?: string;
104
+ doubleValue?: number;
105
+ boolValue?: boolean;
106
+ };
107
+ }>;
108
+ events?: Array<{
109
+ timeUnixNano: string;
110
+ name: string;
111
+ attributes?: OtlpSpan['attributes'];
112
+ }>;
113
+ status?: {
114
+ code: number;
115
+ message?: string;
116
+ };
117
+ }
118
+ interface OtlpResourceSpans {
119
+ resource: {
120
+ attributes: OtlpSpan['attributes'];
121
+ };
122
+ scopeSpans: Array<{
123
+ scope: typeof OTEL_AGENT_EVAL_SCOPE;
124
+ spans: OtlpSpan[];
125
+ }>;
126
+ }
127
+ interface OtlpExport {
128
+ resourceSpans: OtlpResourceSpans[];
129
+ }
130
+ /** Export a single run's spans + events in OTLP/JSON. */
131
+ declare function exportRunAsOtlp(store: TraceStore, runId: string, resourceAttrs?: Record<string, string | number | boolean>): Promise<OtlpExport>;
132
+
133
+ /**
134
+ * Shared types for the trace-analyst module.
135
+ *
136
+ * Wire format. The store interface speaks `OtlpSpanLike` rows — one JSONL
137
+ * line per span, OTLP-shaped. We do NOT depend on a specific tracing
138
+ * vendor at the type level. Adapter
139
+ * layers map upstream shapes onto this interface.
140
+ *
141
+ * Design constraint. Every read operation that can return arbitrary
142
+ * payload must carry a byte budget so the agent's tool result stays
143
+ * bounded regardless of input trace size. Oversized responses
144
+ * substitute a deterministic summary instead of bytes — see
145
+ * `ViewTraceOversized`.
146
+ */
147
+ /** OTLP span kind (subset we actually use). */
148
+ type TraceAnalystSpanKind = 'AGENT' | 'LLM' | 'TOOL' | 'CHAIN' | 'GUARDRAIL' | 'SPAN' | 'UNKNOWN';
149
+ type TraceAnalystSpanStatus = 'OK' | 'ERROR' | 'UNSET';
150
+ /** Subset of OTLP span fields the analyst exposes to the agent. The
151
+ * store's job is to project upstream's full span shape down to this
152
+ * view — the analyst never sees vendor extensions directly. */
153
+ interface TraceAnalystSpan {
154
+ trace_id: string;
155
+ span_id: string;
156
+ parent_span_id: string | null;
157
+ name: string;
158
+ kind: TraceAnalystSpanKind;
159
+ start_time: string;
160
+ end_time: string;
161
+ duration_ms: number;
162
+ status: TraceAnalystSpanStatus;
163
+ status_message?: string;
164
+ service_name: string | null;
165
+ agent_name: string | null;
166
+ model_name: string | null;
167
+ tool_name: string | null;
168
+ /** Raw JSON-serialisable attribute map. May contain large strings;
169
+ * callers must respect the per-attribute byte cap. */
170
+ attributes: Record<string, unknown>;
171
+ }
172
+ interface TraceAnalystTraceSummary {
173
+ trace_id: string;
174
+ service_name: string | null;
175
+ agent_name: string | null;
176
+ span_count: number;
177
+ has_errors: boolean;
178
+ start_time: string;
179
+ end_time: string;
180
+ duration_ms: number;
181
+ raw_jsonl_bytes: number;
182
+ models: string[];
183
+ tools: string[];
184
+ }
185
+ interface TraceAnalystFilters {
186
+ /** Restrict to traces that contain at least one error span. */
187
+ has_errors?: boolean;
188
+ /** Match if any span's `service.name` is in this list. */
189
+ service_names?: string[];
190
+ /** Match if any span's `agent.name` is in this list. */
191
+ agent_names?: string[];
192
+ /** Match if any LLM span's `llm.model_name` is in this list. */
193
+ model_names?: string[];
194
+ /** Match if any tool span's `tool.name` is in this list. */
195
+ tool_names?: string[];
196
+ /** ISO-8601 lower bound on the trace's earliest start time. */
197
+ start_time_after?: string;
198
+ /** ISO-8601 upper bound on the trace's earliest start time. */
199
+ start_time_before?: string;
200
+ /** Single regex applied to raw JSONL bytes for the trace. Opt-in;
201
+ * expensive on large datasets. Use the indexed filters above first. */
202
+ regex_pattern?: string;
203
+ }
204
+ interface DatasetOverview {
205
+ total_traces: number;
206
+ raw_jsonl_bytes: number;
207
+ services: string[];
208
+ agents: string[];
209
+ models: string[];
210
+ tool_names: string[];
211
+ /** Up to 20 real trace ids the agent may pass to view/search tools. */
212
+ sample_trace_ids: string[];
213
+ errors: {
214
+ trace_count: number;
215
+ span_count: number;
216
+ };
217
+ time_range: {
218
+ earliest: string;
219
+ latest: string;
220
+ } | null;
221
+ }
222
+ interface QueryTracesPage {
223
+ traces: TraceAnalystTraceSummary[];
224
+ total: number;
225
+ has_more: boolean;
226
+ }
227
+ /** Full-trace view. When the response would exceed the per-call byte
228
+ * budget, `oversized` is populated INSTEAD of `spans` so the agent
229
+ * knows to switch to `searchTrace` / `viewSpans`. */
230
+ interface ViewTraceResult {
231
+ trace_id: string;
232
+ spans?: TraceAnalystSpan[];
233
+ oversized?: ViewTraceOversized;
234
+ }
235
+ interface ViewTraceOversized {
236
+ span_count: number;
237
+ /** Names with their counts, sorted desc. Capped at 20 entries. */
238
+ top_span_names: Array<[string, number]>;
239
+ /** Largest single span body (bytes after attribute-cap projection). */
240
+ span_response_bytes_max: number;
241
+ error_span_count: number;
242
+ }
243
+ interface ViewSpansResult {
244
+ trace_id: string;
245
+ spans: TraceAnalystSpan[];
246
+ /** Number of requested span ids that were not found in the trace. */
247
+ missing_span_ids: string[];
248
+ /** Number of attribute fields truncated to fit the per-attribute cap. */
249
+ truncated_attribute_count: number;
250
+ }
251
+ interface SpanMatchRecord {
252
+ trace_id: string;
253
+ span_id: string;
254
+ span_name: string;
255
+ span_kind: TraceAnalystSpanKind;
256
+ /** JSON pointer-style path to the matched value, e.g.
257
+ * `attributes."llm.input_messages"[2].content`. */
258
+ attribute_path: string;
259
+ matched_text: string;
260
+ context_before: string;
261
+ context_after: string;
262
+ match_offset: number;
263
+ }
264
+ interface SearchTraceResult {
265
+ trace_id: string;
266
+ hits: SpanMatchRecord[];
267
+ total_matches: number;
268
+ has_more: boolean;
269
+ }
270
+ interface SearchSpanResult {
271
+ trace_id: string;
272
+ span_id: string;
273
+ hits: SpanMatchRecord[];
274
+ total_matches: number;
275
+ has_more: boolean;
276
+ }
277
+ /** Tunable byte budgets for bounded RLM tool output. */
278
+ interface TraceAnalystByteBudgets {
279
+ /** Max bytes any single tool response may emit. Hard ceiling enforced
280
+ * by the store; oversized → summary. Default 150_000. */
281
+ perCallByteCeiling: number;
282
+ /** Per-attribute string truncation cap on `viewTrace` (discovery scan).
283
+ * Default 4096. */
284
+ perAttributeViewBudget: number;
285
+ /** Per-attribute string truncation cap on `viewSpans` (surgical reads).
286
+ * Default 16384. */
287
+ perAttributeSpanBudget: number;
288
+ /** Per-attribute cap on a single match record's `matched_text` and
289
+ * context window. Default 1024. */
290
+ perMatchTextBudget: number;
291
+ }
292
+ declare const DEFAULT_TRACE_ANALYST_BUDGETS: TraceAnalystByteBudgets;
293
+ /** Marker substituted in place of truncated string payloads. Callers
294
+ * parsing tool output can detect it deterministically. */
295
+ declare const TRACE_ANALYST_TRUNCATION_MARKER_PREFIX = "[trace-analyst truncated:";
296
+
297
+ /**
298
+ * `TraceAnalysisStore` — read-side interface the trace-analyst calls
299
+ * through. Six operations, all bounded:
300
+ *
301
+ * - `getOverview(filters?)` — dataset rollup + sample trace ids.
302
+ * - `queryTraces(filters?, limit, offset)` — paginated summaries.
303
+ * - `countTraces(filters?)` — cheap count without materialisation.
304
+ * - `viewTrace(trace_id, perAttrCap)` — full span list, oversized → summary.
305
+ * - `viewSpans(trace_id, span_ids, perAttrCap)` — surgical span fetch.
306
+ * - `searchTrace(trace_id, regex, max_matches)` — bounded regex hits.
307
+ * - `searchSpan(trace_id, span_id, regex, max_matches)` — single-span search.
308
+ *
309
+ * Multiple implementations ship in the core (`OtlpFileTraceStore`).
310
+ * Downstream callers can supply their own — e.g. a DuckDB-backed
311
+ * adapter or an in-memory adapter for tests — by implementing this
312
+ * interface.
313
+ *
314
+ * Filters compose with AND semantics. Empty/undefined fields impose
315
+ * no constraint. `regex_pattern` is the only opt-in raw-bytes scan —
316
+ * implementations may skip it via `count`/`overview` when not set.
317
+ */
318
+
319
+ interface TraceAnalysisStore {
320
+ getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview>;
321
+ queryTraces(opts: {
322
+ filters?: TraceAnalystFilters;
323
+ limit: number;
324
+ offset?: number;
325
+ }): Promise<QueryTracesPage>;
326
+ countTraces(filters?: TraceAnalystFilters): Promise<number>;
327
+ viewTrace(opts: {
328
+ trace_id: string;
329
+ /** Override per-attribute byte cap. Defaults to discovery budget. */
330
+ per_attribute_byte_cap?: number;
331
+ }): Promise<ViewTraceResult>;
332
+ viewSpans(opts: {
333
+ trace_id: string;
334
+ span_ids: readonly string[];
335
+ /** Override per-attribute byte cap. Defaults to surgical budget. */
336
+ per_attribute_byte_cap?: number;
337
+ }): Promise<ViewSpansResult>;
338
+ searchTrace(opts: {
339
+ trace_id: string;
340
+ regex_pattern: string;
341
+ /** Hard cap on matches returned. Default 50. */
342
+ max_matches?: number;
343
+ }): Promise<SearchTraceResult>;
344
+ searchSpan(opts: {
345
+ trace_id: string;
346
+ span_id: string;
347
+ regex_pattern: string;
348
+ max_matches?: number;
349
+ }): Promise<SearchSpanResult>;
350
+ }
351
+
352
+ interface AnalyzeTracesInput {
353
+ /** The user-facing question. Domain framing belongs here, not in the
354
+ * actor description. */
355
+ question: string;
356
+ }
357
+ interface AnalyzeTracesResult {
358
+ /** The responder's prose answer. */
359
+ answer: string;
360
+ /** Bulleted findings extracted from the responder's structured output. */
361
+ findings: string[];
362
+ /** Per-actor-turn snapshots captured via `actorTurnCallback`. */
363
+ turns: AnalyzeTracesTurnSnapshot[];
364
+ /** Total turns the actor took. */
365
+ turnCount: number;
366
+ /** Token usage by role. */
367
+ usage: TraceAnalystUsage;
368
+ /** Full system + assistant + tool message log by role. */
369
+ chatLog: TraceAnalystChatLog;
370
+ /** Prompt version that produced this run. */
371
+ actorPromptVersion: string;
372
+ }
373
+ interface TraceAnalystUsage {
374
+ actor: TraceAnalystUsageEntry[];
375
+ responder: TraceAnalystUsageEntry[];
376
+ }
377
+ interface TraceAnalystUsageEntry {
378
+ [key: string]: unknown;
379
+ }
380
+ interface TraceAnalystChatLog {
381
+ actor: TraceAnalystChatMessage[];
382
+ responder: TraceAnalystChatMessage[];
383
+ }
384
+ interface TraceAnalystChatMessage {
385
+ [key: string]: unknown;
386
+ }
387
+ interface AnalyzeTracesTurnSnapshot {
388
+ turn: number;
389
+ isError: boolean;
390
+ /** The JS code the actor produced for this turn. */
391
+ code: string;
392
+ /** The formatted action-log entry the actor sees on the next turn. */
393
+ output: string;
394
+ /** Provider thought (when `actorOptions.showThoughts` is true and the
395
+ * provider returns it). */
396
+ thought?: string;
397
+ }
398
+ interface AnalyzeTracesOptions {
399
+ /** Trace data source. Pass either an OTLP-JSONL path or a custom store. */
400
+ source: string | TraceAnalysisStore;
401
+ /** Caller-provided AxAIService. */
402
+ ai: AxAIService;
403
+ /** Model id forwarded to actor + responder. */
404
+ model?: string;
405
+ /** Recursion depth. 0 = no sub-agent dispatch. Default 1. */
406
+ maxDepth?: number;
407
+ /** Maximum actor turns. Default 12. */
408
+ maxTurns?: number;
409
+ /** Maximum parallel sub-agent calls in batched llmQuery. Default 2. */
410
+ maxParallelSubagents?: number;
411
+ /** Override the actor description. */
412
+ actorDescription?: string;
413
+ /** Override the subagent description. */
414
+ subagentDescription?: string;
415
+ /** Per-turn observability hook. */
416
+ onTurn?: (turn: AnalyzeTracesTurnSnapshot) => void | Promise<void>;
417
+ /** Override max runtime characters per turn. Default 6000. */
418
+ maxRuntimeChars?: number;
419
+ /** When set, every turn's snapshot is appended to this JSONL file
420
+ * immediately. If the analyst crashes mid-loop (provider 503,
421
+ * network error, validator reject) the partial reasoning is still
422
+ * on disk. Replay the file with the responder afterward to recover
423
+ * evidence. */
424
+ progressLogPath?: string;
425
+ }
426
+ /**
427
+ * Run the trace analyst.
428
+ *
429
+ * Throws:
430
+ * - `TraceFileMissingError` if `source` is a path and doesn't exist.
431
+ * - `AxAgentClarificationError` if the analyst asks for clarification.
432
+ * - Provider errors (auth, rate limits) propagate from the AI service.
433
+ */
434
+ declare function analyzeTraces(input: AnalyzeTracesInput, options: AnalyzeTracesOptions): Promise<AnalyzeTracesResult>;
435
+
436
+ /**
437
+ * `OtlpFileTraceStore` — read-only OTLP-JSONL trace store for the
438
+ * trace-analyst.
439
+ *
440
+ * Wire shape. Each line of the input file is one OTLP-shaped span. The
441
+ * store understands flattened OTLP JSONL plus the OpenInference vocab.
442
+ * We project upstream's full
443
+ * span shape down to `TraceAnalystSpan` lazily — full materialisation
444
+ * only happens for the spans the agent actually requests.
445
+ *
446
+ * Indexing. On first read the store builds an in-memory index keyed
447
+ * by `trace_id` carrying:
448
+ * - byte offsets + lengths for each span line (for surgical reads
449
+ * without re-parsing the whole file)
450
+ * - a `TraceAnalystTraceSummary` rollup
451
+ * - sets of services / agents / models / tools / has_errors
452
+ * - byte size of the trace's JSONL slab
453
+ *
454
+ * Memory bound. The index keeps span metadata only — names, kinds,
455
+ * offsets, status. Attribute payloads stay on disk until requested.
456
+ * For a 50MB JSONL with 50k spans, the index is ~5MB.
457
+ *
458
+ * Concurrency. The store builds the index once on first read and
459
+ * caches it. Subsequent reads reuse the index. The file is opened on
460
+ * each read; we never hold a long-lived FD.
461
+ */
462
+
463
+ interface OtlpFileTraceStoreOptions {
464
+ /** Path to the OTLP-JSONL file. */
465
+ path: string;
466
+ /** Override the discovery (`viewTrace`) per-attribute byte cap. */
467
+ perAttributeViewBudget?: number;
468
+ /** Override the surgical (`viewSpans`) per-attribute byte cap. */
469
+ perAttributeSpanBudget?: number;
470
+ /** Override the per-call ceiling that triggers oversized summaries. */
471
+ perCallByteCeiling?: number;
472
+ /** Override the per-match text budget. */
473
+ perMatchTextBudget?: number;
474
+ }
475
+ declare class OtlpFileTraceStore implements TraceAnalysisStore {
476
+ private readonly path;
477
+ private readonly perAttributeViewBudget;
478
+ private readonly perAttributeSpanBudget;
479
+ private readonly perCallByteCeiling;
480
+ private readonly perMatchTextBudget;
481
+ private indexPromise?;
482
+ /** Cached UTF-8 buffer of the file. We pin it once because every
483
+ * read needs slice access and re-reading on each call balloons the
484
+ * syscall count. */
485
+ private bufferPromise?;
486
+ constructor(opts: OtlpFileTraceStoreOptions);
487
+ getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview>;
488
+ queryTraces(opts: {
489
+ filters?: TraceAnalystFilters;
490
+ limit: number;
491
+ offset?: number;
492
+ }): Promise<QueryTracesPage>;
493
+ countTraces(filters?: TraceAnalystFilters): Promise<number>;
494
+ viewTrace(opts: {
495
+ trace_id: string;
496
+ per_attribute_byte_cap?: number;
497
+ }): Promise<ViewTraceResult>;
498
+ viewSpans(opts: {
499
+ trace_id: string;
500
+ span_ids: readonly string[];
501
+ per_attribute_byte_cap?: number;
502
+ }): Promise<ViewSpansResult>;
503
+ searchTrace(opts: {
504
+ trace_id: string;
505
+ regex_pattern: string;
506
+ max_matches?: number;
507
+ }): Promise<SearchTraceResult>;
508
+ searchSpan(opts: {
509
+ trace_id: string;
510
+ span_id: string;
511
+ regex_pattern: string;
512
+ max_matches?: number;
513
+ }): Promise<SearchSpanResult>;
514
+ /** Force the index to materialise. Useful to amortise startup cost
515
+ * before the first agent call. */
516
+ ensureIndexed(): Promise<void>;
517
+ private buffer;
518
+ private index;
519
+ private buildIndex;
520
+ private matchedTraces;
521
+ private toSummary;
522
+ private projectSpan;
523
+ private buildOversizedSummary;
524
+ private scanSpanForMatches;
525
+ }
526
+ declare class TraceFileMissingError extends Error {
527
+ constructor(path: string);
528
+ }
529
+ declare class TraceNotFoundError extends Error {
530
+ readonly trace_id: string;
531
+ constructor(trace_id: string);
532
+ }
533
+ declare class SpanNotFoundError extends Error {
534
+ readonly trace_id: string;
535
+ readonly span_id: string;
536
+ constructor(trace_id: string, span_id: string);
537
+ }
538
+
539
+ /**
540
+ * Trace-analyst tool surface — six namespaced AxFunctions the analyst
541
+ * agent calls from generated JS code via `traces.<name>(...)`.
542
+ *
543
+ * Discovery → narrow → deep-read protocol. Tool names + ordering
544
+ * support RLM discovery:
545
+ *
546
+ * 1. `getDatasetOverview` (cheap) — first call, sizes the dataset
547
+ * 2. `queryTraces` — paginated summaries with `raw_jsonl_bytes`
548
+ * 3. `countTraces` — cheap pre-flight before regex
549
+ * 4. `viewTrace` — full span list, oversized → summary
550
+ * 5. `viewSpans` — surgical 16KB-cap reads
551
+ * 6. `searchTrace` / `searchSpan` — bounded regex hits
552
+ *
553
+ * Failure mode. Tool handlers throw on bad input (invalid trace ids,
554
+ * out-of-range pagination, malformed regex). Ax converts thrown errors
555
+ * into actor-visible `[ERROR]` strings so the analyst can adjust on
556
+ * the next turn instead of looping.
557
+ */
558
+
559
+ interface BuildTraceAnalystToolsOpts {
560
+ store: TraceAnalysisStore;
561
+ /** Override the default sample-trace-id slot count (20). Mostly for tests. */
562
+ sampleTraceLimit?: number;
563
+ }
564
+ /**
565
+ * Build the trace-analyst function set. Pass the result into
566
+ * `agent(...).functions.local`.
567
+ */
568
+ declare function buildTraceAnalystTools(opts: BuildTraceAnalystToolsOpts): AxFunction[];
569
+ /**
570
+ * Convenience: same shape as `buildTraceAnalystTools` but returns the
571
+ * grouped form expected when registering trace tools alongside other
572
+ * agent function modules. */
573
+ declare function traceAnalystFunctionGroup(opts: BuildTraceAnalystToolsOpts): {
574
+ namespace: string;
575
+ title: string;
576
+ selectionCriteria: string;
577
+ description: string;
578
+ functions: AxFunction[];
579
+ };
580
+
581
+ /** Ax RLM prompt for bounded trace discovery and evidence-backed analysis. */
582
+ 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 maxDepth > 0 and the question splits into independent semantic branches, delegate well-defined subtasks to subagents using `await llmQuery(...)`. Pass narrow context and a focused query. Examples:\n\n const reviews = await llmQuery([\n { query: 'Drill into trace abc123 \u2014 what tool calls preceded the failure?', context: { trace_id: 'abc123' } },\n { query: 'Drill into trace def456 \u2014 same failure mode?', context: { trace_id: 'def456' } },\n ]);\n\nOBSERVABILITY rules:\n- Each non-final actor turn must emit at least one `console.log(...)` for evidence. Up to 3 logs per turn is fine when correlating multiple data sources (e.g. one log for findings list, one for source-file content, one for derived analysis).\n- Do NOT combine `console.log` with `final(...)` or `askClarification(...)` in the same turn \u2014 finish gathering data first, then call final on its own turn.\n- Reuse runtime variables across turns; don't recompute.\n- When done, call `await final(answer)` with the fully-formed report. The responder rewrites the answer into output fields; if you only pass a vague summary string the responder has nothing concrete to format.\n\nCRITICAL \u2014 `final()` payload contract for evidence-grounded analysis tasks:\n- Pass a STRUCTURED object as the second arg with the actual data the responder needs to format the answer. Do NOT pass abstract instructions; pass evidence.\n- Example for per-item verdict tasks:\n ```js\n await final(\"Format the per-item verdict report from the evidence below.\", {\n findings: [\n { id: 'sub-1-finding-1', claim: '...', verdict: 'TRUE-POSITIVE', evidence: 'lines 42-45 of contracts/X.sol show ...' },\n ...all items\n ],\n systemic_summary: '3 sentences I wrote based on the evidence above'\n });\n ```\n- Calling `final(\"answer\", {})` with no evidence is a failure mode \u2014 the responder will hallucinate or echo back the field names. Always include the gathered data.\n- Premature final after a single viewSpans call is INSUFFICIENT for per-finding analysis tasks. Read the requested attributes (e.g. `spans[i].attributes['redteam.finding.title']`), and for each one perform the requested cross-reference (e.g. read the source SPAN's `attributes['source.content']`).\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\nDo NOT invent trace ids, span ids, error messages, or model names. Every fact must be traceable to a tool result.";
583
+ declare const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = "trace-analyst-actor-v5-2026-05-06";
584
+ /** Subagent prompt for focused trace-inspection subtasks. */
585
+ declare const TRACE_ANALYST_SUBAGENT_DESCRIPTION = "You are a trace-analyst subagent. Your parent has delegated a focused trace-inspection question. Use the same DISCOVERY \u2192 NARROW \u2192 DEEP-READ protocol but stay tightly scoped: do exactly what was asked, return a concise compact answer, do NOT spawn further subagents unless the parent's question is genuinely multi-branch.\n\nCite trace ids and span ids for every claim. Do NOT invent ids.";
586
+
587
+ interface TraceInsightTask {
588
+ id: string;
589
+ name: string;
590
+ prompt?: string;
591
+ difficulty?: string;
592
+ tags?: string[];
593
+ outcome?: string;
594
+ score?: number;
595
+ gaps?: string[];
596
+ }
597
+ interface TraceInsightSuite {
598
+ name: string;
599
+ collectionId?: string;
600
+ tasks: TraceInsightTask[];
601
+ }
602
+ interface TraceInsightFinding {
603
+ kind: string;
604
+ severity?: string;
605
+ taskIds: string[];
606
+ evidence?: string;
607
+ proposedFixClass?: string;
608
+ }
609
+ interface TraceInsightQuestion {
610
+ id: string;
611
+ question: string;
612
+ why: string;
613
+ }
614
+ interface TraceInsightPanelRole {
615
+ id: string;
616
+ name: string;
617
+ responsibility: string;
618
+ }
619
+ interface TraceInsightPromptInput {
620
+ suite: TraceInsightSuite;
621
+ findings?: TraceInsightFinding[];
622
+ agent?: Record<string, unknown>;
623
+ totals?: Record<string, unknown>;
624
+ maxRepresentativeTraces?: number;
625
+ }
626
+ interface TraceInsightContext {
627
+ suite: TraceInsightSuite;
628
+ scope: string;
629
+ keywords: string[];
630
+ questions: TraceInsightQuestion[];
631
+ panel: TraceInsightPanelRole[];
632
+ findings: TraceInsightFinding[];
633
+ agent: Record<string, unknown> | null;
634
+ totals: Record<string, unknown> | null;
635
+ }
636
+ interface TraceInsightQualityGate {
637
+ id: string;
638
+ label: string;
639
+ passed: boolean;
640
+ severity: 'critical' | 'high' | 'medium' | 'low';
641
+ detail: string;
642
+ }
643
+ interface TraceInsightReadiness {
644
+ score: number;
645
+ grade: 'external-ready' | 'internal-review' | 'raw-analysis';
646
+ gates: TraceInsightQualityGate[];
647
+ }
648
+ declare function tokenizeDomainWords(value: string): string[];
649
+ declare function inferDomainKeywords(suite: TraceInsightSuite): string[];
650
+ declare function domainEvidencePattern(keywords: string[]): RegExp;
651
+ declare function describeTraceInsightScope(suite: TraceInsightSuite): string;
652
+ declare function planTraceInsightQuestions(input: TraceInsightPromptInput): TraceInsightQuestion[];
653
+ declare function buildTraceInsightContext(input: TraceInsightPromptInput): TraceInsightContext;
654
+ declare function scoreTraceInsightReadiness(context: TraceInsightContext): TraceInsightReadiness;
655
+ declare function defaultTraceInsightPanel(): TraceInsightPanelRole[];
656
+ declare function buildTraceInsightPrompt(input: TraceInsightPromptInput): string;
657
+
658
+ export { type AnalyzeTracesInput, type AnalyzeTracesOptions, type AnalyzeTracesResult, type AnalyzeTracesTurnSnapshot, DEFAULT_REDACTION_RULES, DEFAULT_TRACE_ANALYST_BUDGETS, type DatasetOverview, FailureClass, JudgeSpan, LlmSpan, OTEL_AGENT_EVAL_SCOPE, type OtlpExport, OtlpFileTraceStore, type OtlpFileTraceStoreOptions, type OtlpResourceSpans, type OtlpSpan, type QueryTracesPage, REDACTION_VERSION, type RedactionReport, type RedactionRule, Run, type SearchSpanResult, type SearchTraceResult, type SpanMatchRecord, SpanNotFoundError, TRACE_ANALYST_ACTOR_DESCRIPTION, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION, TRACE_ANALYST_SUBAGENT_DESCRIPTION, TRACE_ANALYST_TRUNCATION_MARKER_PREFIX, ToolSpan, type TraceAnalysisStore, type TraceAnalystByteBudgets, type TraceAnalystFilters, type TraceAnalystSpan, type TraceAnalystSpanKind, type TraceAnalystSpanStatus, type TraceAnalystTraceSummary, TraceFileMissingError, type TraceInsightContext, type TraceInsightFinding, type TraceInsightPanelRole, type TraceInsightPromptInput, type TraceInsightQualityGate, type TraceInsightQuestion, type TraceInsightReadiness, type TraceInsightSuite, type TraceInsightTask, TraceNotFoundError, TraceStore, type ViewSpansResult, type ViewTraceOversized, type ViewTraceResult, aggregateLlm, analyzeTraces, argHash, buildTraceAnalystTools, buildTraceInsightContext, buildTraceInsightPrompt, defaultTraceInsightPanel, describeTraceInsightScope, domainEvidencePattern, exportRunAsOtlp, groupBy, inferDomainKeywords, judgeSpans, llmSpans, planTraceInsightQuestions, redactString, redactValue, runFailureClass, runsForScenario, scoreTraceInsightReadiness, tokenizeDomainWords, toolSpans, traceAnalystFunctionGroup };