agent-inspect 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +47 -4
  2. package/README.md +59 -37
  3. package/docs/ADAPTERS.md +117 -31
  4. package/docs/API.md +24 -6
  5. package/docs/CLI.md +126 -1
  6. package/docs/DIFF.md +8 -0
  7. package/docs/EXPORTS.md +86 -15
  8. package/docs/GETTING-STARTED.md +48 -2
  9. package/docs/KNOWN-ISSUES.md +6 -0
  10. package/docs/LIMITATIONS.md +11 -3
  11. package/docs/LOGS.md +22 -0
  12. package/docs/SCHEMA.md +8 -5
  13. package/docs/SCREENSHOTS.md +190 -9
  14. package/package.json +51 -1
  15. package/packages/cli/dist/index.cjs +3253 -1662
  16. package/packages/cli/dist/index.cjs.map +1 -1
  17. package/packages/cli/dist/index.mjs +3253 -1662
  18. package/packages/cli/dist/index.mjs.map +1 -1
  19. package/packages/core/dist/advanced.cjs +1437 -0
  20. package/packages/core/dist/advanced.cjs.map +1 -0
  21. package/packages/core/dist/advanced.d.cts +159 -0
  22. package/packages/core/dist/advanced.d.ts +159 -0
  23. package/packages/core/dist/advanced.mjs +8 -0
  24. package/packages/core/dist/advanced.mjs.map +1 -0
  25. package/packages/core/dist/chunk-5EMIZZXD.mjs +907 -0
  26. package/packages/core/dist/chunk-5EMIZZXD.mjs.map +1 -0
  27. package/packages/core/dist/chunk-7TGZLWEE.mjs +35 -0
  28. package/packages/core/dist/chunk-7TGZLWEE.mjs.map +1 -0
  29. package/packages/core/dist/chunk-BT7CATSD.mjs +497 -0
  30. package/packages/core/dist/chunk-BT7CATSD.mjs.map +1 -0
  31. package/packages/core/dist/chunk-E5F2LQCX.mjs +83 -0
  32. package/packages/core/dist/chunk-E5F2LQCX.mjs.map +1 -0
  33. package/packages/core/dist/chunk-EDTQHZPM.mjs +88 -0
  34. package/packages/core/dist/chunk-EDTQHZPM.mjs.map +1 -0
  35. package/packages/core/dist/chunk-HY7H3CQM.mjs +127 -0
  36. package/packages/core/dist/chunk-HY7H3CQM.mjs.map +1 -0
  37. package/packages/core/dist/chunk-Q6EPNB3V.mjs +539 -0
  38. package/packages/core/dist/chunk-Q6EPNB3V.mjs.map +1 -0
  39. package/packages/core/dist/chunk-QPAU2TPA.mjs +785 -0
  40. package/packages/core/dist/chunk-QPAU2TPA.mjs.map +1 -0
  41. package/packages/core/dist/chunk-QX3ZMPUF.mjs +451 -0
  42. package/packages/core/dist/chunk-QX3ZMPUF.mjs.map +1 -0
  43. package/packages/core/dist/chunk-VU6O5QAH.mjs +99 -0
  44. package/packages/core/dist/chunk-VU6O5QAH.mjs.map +1 -0
  45. package/packages/core/dist/chunk-XDBND27A.mjs +975 -0
  46. package/packages/core/dist/chunk-XDBND27A.mjs.map +1 -0
  47. package/packages/core/dist/chunk-YWAOOXLR.mjs +475 -0
  48. package/packages/core/dist/chunk-YWAOOXLR.mjs.map +1 -0
  49. package/packages/core/dist/diff.cjs +993 -0
  50. package/packages/core/dist/diff.cjs.map +1 -0
  51. package/packages/core/dist/diff.d.cts +81 -0
  52. package/packages/core/dist/diff.d.ts +81 -0
  53. package/packages/core/dist/diff.mjs +5 -0
  54. package/packages/core/dist/diff.mjs.map +1 -0
  55. package/packages/core/dist/exporters.cjs +1228 -0
  56. package/packages/core/dist/exporters.cjs.map +1 -0
  57. package/packages/core/dist/exporters.d.cts +113 -0
  58. package/packages/core/dist/exporters.d.ts +113 -0
  59. package/packages/core/dist/exporters.mjs +6 -0
  60. package/packages/core/dist/exporters.mjs.map +1 -0
  61. package/packages/core/dist/index.cjs +2982 -1829
  62. package/packages/core/dist/index.cjs.map +1 -1
  63. package/packages/core/dist/index.d.cts +201 -892
  64. package/packages/core/dist/index.d.ts +201 -892
  65. package/packages/core/dist/index.mjs +780 -4620
  66. package/packages/core/dist/index.mjs.map +1 -1
  67. package/packages/core/dist/log-config-BzGmDYum.d.cts +71 -0
  68. package/packages/core/dist/log-config-BzGmDYum.d.ts +71 -0
  69. package/packages/core/dist/logs.cjs +1007 -0
  70. package/packages/core/dist/logs.cjs.map +1 -0
  71. package/packages/core/dist/logs.d.cts +137 -0
  72. package/packages/core/dist/logs.d.ts +137 -0
  73. package/packages/core/dist/logs.mjs +6 -0
  74. package/packages/core/dist/logs.mjs.map +1 -0
  75. package/packages/core/dist/persisted.cjs +1057 -0
  76. package/packages/core/dist/persisted.cjs.map +1 -0
  77. package/packages/core/dist/persisted.d.cts +160 -0
  78. package/packages/core/dist/persisted.d.ts +160 -0
  79. package/packages/core/dist/persisted.mjs +5 -0
  80. package/packages/core/dist/persisted.mjs.map +1 -0
  81. package/packages/core/dist/types-Bkt7LS01.d.ts +226 -0
  82. package/packages/core/dist/types-CNbheSdk.d.cts +226 -0
@@ -1,156 +1,128 @@
1
+ import { T as TraceEvent, R as RunSummary, a as TraceMetadata, b as TraceMetadataStatus, S as StepType, c as StepStatus, d as TraceCorrelationMetadata, e as RedactionProfile, I as InspectRunOptions, f as StepOptions, O as ObserveOptions } from './types-Bkt7LS01.js';
2
+ export { A as ActiveStepContext, E as ErrorInfo, g as ExecutionContext, h as Run, i as RunCompletedEvent, j as RunStartedEvent, k as RunStatus, l as Step, m as StepCompletedEvent, n as StepMetadata, o as StepStartedEvent, p as TokenMetadata, q as TraceEventBase, r as TraceSchemaVersion, s as isStepStatus, t as isStepType, u as isTraceEvent } from './types-Bkt7LS01.js';
3
+ export { A as AttributionConfidence, E as EventSource, I as InspectEvent, a as InspectKind, b as InspectNode, c as InspectRunTree, L as LogEventMapping, d as LogIngestConfig, R as RedactionRule, e as RedactionStrategy } from './log-config-BzGmDYum.js';
4
+ import { PersistedInspectEvent } from './persisted.js';
5
+ export { InspectEventToPersistedOptions, PersistedEventSource, PersistedEventSourceType, PersistedEventStatus, PersistedInspectError, PersistedSchemaVersion, PersistedToInspectEventOptions, PersistedToTraceEventOptions, PersistedTokenUsage, PersistedTraceContext, PersistedTreeBridgeOptions, TraceEventToPersistedOptions, inspectEventToPersistedInspectEvent, inspectEventsToPersistedInspectEvents, isPersistedInspectEvent, persistedInspectEventToInspectEvent, persistedInspectEventToTraceEvents, persistedInspectEventsToInspectEvents, persistedInspectEventsToRunTrees, persistedInspectEventsToTraceEvents, traceEventToPersistedInspectEvent, traceEventsToPersistedInspectEvents, traceEventsToPersistedRunTrees } from './persisted.js';
6
+ export { DEFAULT_LOG_INGEST_CONFIG, DEFAULT_REDACT_KEYS, EventNormalizer, JsonLogParser, LiveLogAccumulator, LiveLogAccumulatorOptions, LiveLogUpdate, Log4jsParser, LogSourceFormat, LogToTreeResult, NormalizeOptions, ParseLogLineOptions, ParseLogsOptions, ParseResult, ParserWarning, ParserWarningCode, RawLogRecord, Redactor, RedactorOptions, RenderTreeOptions, TreeBuilder, TreeBuilderOptions, loadLogIngestConfig, matchMapping, mergeLogIngestConfig, parseLogLine, parseLogsToTrees, renderRunTree, renderRunTrees, wildcardMatch } from './logs.js';
7
+ export { DEFAULT_MAX_EVENT_BYTES, DEFAULT_MAX_METADATA_VALUE_LENGTH, DEFAULT_MAX_PREVIEW_LENGTH, DEFAULT_TRACE_DIR_NAME, FALLBACK_TRACE_DIR, MAX_NAME_LENGTH, MAX_TERMINAL_DEPTH, MAX_TERMINAL_NAME_LENGTH, RUNS_DIR_NAME, ResolvedRedactionProfile, TERMINAL_INDENT, TraceSafetyOptions, createRunId, createStepId, ensureTraceDir, formatDuration, formatError, formatTerminalName, formatTimestamp, getCurrentContext, getCurrentCorrelationMetadata, getCurrentDepth, getCurrentRunId, getCurrentRunName, getCurrentStepId, getDefaultTraceDir, getIndent, getParentStepId, getTraceDirFromContext, getTraceFilePath, getTraceSafetyFromContext, hasActiveContext, isSilentContext, prepareMetadataForDisk, prepareTraceEventForDisk, printError, printFailedAt, printRunComplete, printRunStart, printStepComplete, printStepStart, renderErrorLine, renderRunSummary, renderStepLine, resolveRedactionProfile, resolveTraceSafetyOptions, runWithContext, runWithStepContext, truncateName, warn } from './advanced.js';
1
8
  import { Stats } from 'node:fs';
2
-
3
- type AttributionConfidence = "explicit" | "correlated" | "heuristic" | "unknown";
4
- type InspectKind = "RUN" | "AGENT" | "LLM" | "TOOL" | "CHAIN" | "RETRIEVER" | "DECISION" | "RESULT" | "ERROR" | "LOGIC" | "LOG";
5
- interface EventSource {
6
- type: "manual" | "json-log" | "log4js" | "pino" | "winston" | "adapter";
7
- file?: string;
8
- line?: number;
9
- }
10
- interface InspectEvent {
11
- eventId: string;
12
- runId: string;
13
- parentId?: string;
14
- name: string;
15
- kind: InspectKind;
16
- timestamp: number;
17
- status?: "running" | "ok" | "error";
18
- durationMs?: number;
19
- attributes?: Record<string, unknown>;
20
- confidence: AttributionConfidence;
21
- source: EventSource;
22
- }
23
- interface InspectNode {
24
- event: InspectEvent;
25
- children: InspectNode[];
26
- depth: number;
27
- }
28
- interface InspectRunTree {
29
- runId: string;
30
- name?: string;
31
- status?: "running" | "ok" | "error";
32
- startedAt?: number;
33
- endedAt?: number;
34
- durationMs?: number;
35
- children: InspectNode[];
36
- metadata: {
37
- totalEvents: number;
38
- confidenceBreakdown: Record<AttributionConfidence, number>;
39
- kinds: Record<InspectKind, number>;
40
- };
41
- }
42
-
43
- interface LogEventMapping {
44
- kind?: InspectKind;
45
- name?: string;
46
- parent?: string;
47
- status?: "running" | "ok" | "error";
48
- startsRun?: boolean;
49
- endsRun?: boolean;
50
- startsStep?: boolean;
51
- endsStep?: boolean;
52
- }
53
- type RedactionStrategy = "full" | "prefix" | "hash";
54
- type RedactionRule = string | {
55
- key: string;
56
- strategy: RedactionStrategy;
57
- keep?: number;
58
- };
59
- interface LogIngestConfig {
60
- runIdKeys: string[];
61
- eventKey: string;
62
- timestampKey?: string;
63
- messageKey?: string;
64
- levelKey?: string;
65
- parentIdKey?: string;
66
- durationKey?: string;
67
- statusKey?: string;
68
- mappings?: Record<string, LogEventMapping>;
69
- redact?: RedactionRule[];
70
- heuristicWindowMs?: number;
71
- }
9
+ export { DiffKind, DiffOptions, DiffPath, DiffPathSegment, DiffSeverity, RenderDiffOptions, RunComparable, RunDiffItem, RunDiffResult, RunDiffSummary, StepComparable, diffRuns, diffTraceEvents, manualTraceEventsToComparableRun, renderRunDiff } from './diff.js';
10
+ export { EXPORT_PAYLOAD_VERSION, ExportFormat, ExportOptions, ExportResult, ExportValidationResult, OpenInferenceExport, OpenInferenceSpan, TraceExporter, compactAttributes, escapeHtml, escapeMarkdown, exportHtml, exportMarkdown, exportOpenInference, exportOtlpJson, exportRunTree, flattenTree, manualTraceEventsToRunTree, mergeExportDefaults, redactRunTreeForExport, safeString, stableJson, summarizeTree, validateExport, validateExportContent } from './exporters.js';
72
11
 
73
12
  /**
74
- * Discriminator for what kind of work a {@link Step} represents.
75
- * `"decision"` captures agent branching/choices; other values cover runs, LLM calls, tools, and user-defined steps.
13
+ * Strict MVP validation before writing JSONL. Rejects empty ids, non-finite times, and malformed payloads.
76
14
  */
77
- type StepType = "run" | "llm" | "tool" | "decision" | "logic" | "state" | "custom";
78
- /** Lifecycle state of a single {@link Step}. */
79
- type StepStatus = "running" | "success" | "error";
80
- /** Lifecycle state of an entire {@link Run}. */
81
- type RunStatus = "running" | "success" | "error";
82
- /** Structured error attached to a run or step when status is `"error"`. */
83
- interface ErrorInfo {
84
- message: string;
85
- stack?: string;
86
- }
15
+ declare function validateEvent(event: unknown): event is TraceEvent;
16
+ /** Serializes a trace line as compact JSON without a trailing newline. */
17
+ declare function serializeEvent(event: TraceEvent): string;
87
18
  /**
88
- * Optional token counts for a step (e.g. LLM usage).
89
- * Reserved for future roadmap; MVP does not compute or persist token usage.
19
+ * Creates (or truncates) an empty JSONL file for a run. Uses {@link ensureTraceDir} then {@link getTraceFilePath}.
20
+ * On failure, retries once under {@link FALLBACK_TRACE_DIR}.
90
21
  */
91
- interface TokenMetadata {
92
- input?: number;
93
- output?: number;
22
+ declare function initializeTraceFile(runId: string, traceDir: string): Promise<string | undefined>;
23
+ declare function writeTraceEvent(event: TraceEvent, traceDir: string): Promise<void>;
24
+ /**
25
+ * Reads raw JSONL file contents for a run, or `undefined` if missing or unreadable.
26
+ */
27
+ declare function readTraceFile(runId: string, traceDir: string): Promise<string | undefined>;
28
+ /**
29
+ * Parses JSONL into validated {@link TraceEvent} rows (v0.1 native or v0.2 normalized).
30
+ * Invalid lines are skipped with a warning.
31
+ */
32
+ declare function readTraceEvents(runId: string, traceDir: string): Promise<TraceEvent[]>;
33
+ /**
34
+ * Lists `.jsonl` file names in `traceDir`, newest by mtime first (name sort as tie-breaker).
35
+ */
36
+ declare function listTraceFiles(traceDir: string): Promise<string[]>;
37
+ /** Maps a `.jsonl` file name to its run id (basename only; no traversal). */
38
+ declare function getRunIdFromTraceFileName(fileName: string): string | undefined;
39
+
40
+ type TraceJsonlFormat = "0.1" | "0.2" | "mixed" | "empty";
41
+ interface ParseTraceJsonlResult {
42
+ format: TraceJsonlFormat;
43
+ events: TraceEvent[];
44
+ persisted: PersistedInspectEvent[];
94
45
  }
95
- /** Arbitrary structured fields for a step; safe extensions use string keys. */
96
- interface StepMetadata {
97
- model?: string;
98
- toolName?: string;
99
- tokens?: TokenMetadata;
100
- retryCount?: number;
101
- [key: string]: unknown;
46
+ interface ParseTraceJsonlOptions {
47
+ validate?: (value: unknown) => value is TraceEvent;
102
48
  }
103
49
  /**
104
- * One traced agent run (root of an execution tree).
105
- * MVP intentionally omits `input` / `output` on the run to limit PII, secrets, and serialization risk.
50
+ * Parses JSONL content into normalized v0.1 {@link TraceEvent} rows.
51
+ * Accepts homogenous v0.1 or v0.2 files; mixed files are converted with a warning.
106
52
  */
107
- interface Run {
108
- id: string;
109
- name: string;
110
- status: RunStatus;
111
- startTime: number;
112
- endTime?: number;
113
- durationMs?: number;
114
- error?: ErrorInfo;
115
- metadata?: Record<string, unknown>;
116
- }
53
+ declare function parseTraceJsonl(raw: string, options?: ParseTraceJsonlOptions): ParseTraceJsonlResult;
117
54
  /**
118
- * One node in the execution tree under a {@link Run}.
119
- * MVP intentionally omits `input` / `output`; capture/redaction may come in a later version.
55
+ * Returns a user-facing message when a trace file uses an unsupported schema version.
120
56
  */
121
- interface Step {
122
- id: string;
123
- runId: string;
124
- parentId?: string;
57
+ declare function unknownTraceFormatMessage(): string;
58
+
59
+ interface TraceDirectoryOptions {
60
+ dir?: string;
61
+ }
62
+ declare function resolveTraceDir(options?: TraceDirectoryOptions): string;
63
+ declare class TraceDirectory {
64
+ #private;
65
+ constructor(options?: TraceDirectoryOptions);
66
+ getPath(filename?: string): string;
67
+ list(): Promise<string[]>;
68
+ getFileStats(filename: string): Promise<Stats>;
69
+ }
70
+
71
+ declare function extractMetadata(filePath: string, _quickScan?: boolean): Promise<TraceMetadata>;
72
+ declare function buildRunSummary(events: TraceEvent[]): RunSummary;
73
+
74
+ interface TraceFilterOptions {
75
+ status?: TraceMetadataStatus;
76
+ name?: string;
77
+ since?: string;
78
+ limit?: number;
79
+ }
80
+ declare function filterTraces(traces: TraceMetadata[], options: TraceFilterOptions): TraceMetadata[];
81
+
82
+ type TimelineFocus = "all" | "slow";
83
+ interface TimelineEntry {
84
+ stepId: string;
125
85
  name: string;
126
86
  type: StepType;
127
87
  status: StepStatus;
128
- startTime: number;
129
- endTime?: number;
88
+ depth: number;
89
+ startedAt: number;
90
+ offsetMs: number;
130
91
  durationMs?: number;
131
- error?: ErrorInfo;
132
- metadata?: StepMetadata;
92
+ isError: boolean;
93
+ slow?: boolean;
94
+ streaming?: {
95
+ chunkCount?: number;
96
+ streamDurationMs?: number;
97
+ streamedCharCount?: number;
98
+ };
133
99
  }
134
- /** Version of the JSONL trace line schema consumed by AgentInspect tooling. */
135
- type TraceSchemaVersion = "0.1";
136
- /**
137
- * Status for lightweight trace metadata extraction.
138
- * `"unknown"` means the file contained valid events but a run status could not be determined safely.
139
- */
140
- type TraceMetadataStatus = "success" | "error" | "running" | "unknown";
141
- interface TraceMetadata {
100
+ interface RunTimeline {
142
101
  runId: string;
143
102
  name?: string;
144
103
  status: TraceMetadataStatus;
145
104
  startedAt?: number;
146
105
  endedAt?: number;
147
106
  durationMs?: number;
148
- eventCount: number;
149
- filePath: string;
150
- fileSize: number;
151
- createdAt: Date;
107
+ correlation?: {
108
+ correlationId?: string;
109
+ requestId?: string;
110
+ decisionId?: string;
111
+ groupId?: string;
112
+ };
113
+ entries: TimelineEntry[];
114
+ }
115
+ interface TimelineOptions {
116
+ focus?: TimelineFocus;
117
+ slowTopN?: number;
152
118
  }
153
- interface RunSummary {
119
+ declare function buildRunTimeline(events: TraceEvent[], options?: TimelineOptions): RunTimeline;
120
+ interface RenderTimelineOptions {
121
+ focus?: TimelineFocus;
122
+ }
123
+ declare function renderTimeline(timeline: RunTimeline, options?: RenderTimelineOptions): string;
124
+
125
+ interface RunWhatSummary {
154
126
  runId: string;
155
127
  name?: string;
156
128
  status: TraceMetadataStatus;
@@ -170,574 +142,126 @@ interface RunSummary {
170
142
  input: number;
171
143
  output: number;
172
144
  };
173
- }
174
- /** Fields shared by every persisted trace event line. */
175
- interface TraceEventBase {
176
- schemaVersion: TraceSchemaVersion;
177
- event: string;
178
- timestamp: number;
179
- }
180
- /** Emitted when a run begins. */
181
- interface RunStartedEvent extends TraceEventBase {
182
- event: "run_started";
183
- runId: string;
184
- name: string;
185
- startTime: number;
186
- metadata?: Record<string, unknown>;
187
- }
188
- /** Emitted when a run finishes successfully or with an error. */
189
- interface RunCompletedEvent extends TraceEventBase {
190
- event: "run_completed";
191
- runId: string;
192
- status: "success" | "error";
193
- endTime: number;
194
- durationMs: number;
195
- error?: ErrorInfo;
196
- }
197
- /** Emitted when a step begins (including nested steps under `parentId`). */
198
- interface StepStartedEvent extends TraceEventBase {
199
- event: "step_started";
200
- runId: string;
201
- stepId: string;
202
- parentId?: string;
203
- name: string;
204
- type: StepType;
205
- startTime: number;
206
- metadata?: StepMetadata;
145
+ correlation?: TraceCorrelationMetadata;
146
+ failedStepNames: string[];
147
+ runErrorMessage?: string;
207
148
  }
208
149
  /**
209
- * Emitted when a step finishes (success or failure).
210
- * Failures use `status: "error"` and optional {@link ErrorInfo}; there is no separate `step_failed` event in MVP.
150
+ * Build a concise inspection summary for `what` / report workflows.
151
+ * Read-only over in-memory v0.1 {@link TraceEvent} rows.
211
152
  */
212
- interface StepCompletedEvent extends TraceEventBase {
213
- event: "step_completed";
214
- runId: string;
215
- stepId: string;
216
- status: "success" | "error";
217
- endTime: number;
218
- durationMs: number;
219
- error?: ErrorInfo;
220
- }
221
- /** Discriminated union of all MVP trace events written as JSONL lines. */
222
- type TraceEvent = RunStartedEvent | RunCompletedEvent | StepStartedEvent | StepCompletedEvent;
223
- /** Named redaction presets for trace writing and share-safe exports (v1.3.0+). */
224
- type RedactionProfile = "local" | "share" | "strict";
225
- /** Optional correlation fields for grouping and cross-run tracing (v1.3.0+). */
226
- interface TraceCorrelationMetadata {
227
- correlationId?: string;
228
- requestId?: string;
229
- decisionId?: string;
230
- groupId?: string;
231
- }
232
- /** Options for `inspectRun()` and `maybeInspectRun()`. */
233
- interface InspectRunOptions extends TraceCorrelationMetadata {
234
- traceDir?: string;
235
- silent?: boolean;
236
- metadata?: Record<string, unknown>;
237
- /**
238
- * When `false`, runs `fn` with no trace file, no execution context, and no terminal output.
239
- * Omitted or `true` preserves default tracing behavior.
240
- */
241
- enabled?: boolean;
242
- /**
243
- * Redact sensitive metadata keys before writing JSONL. Default `true` (conservative keys).
244
- * Pass `false` to persist metadata as-is (explicit opt-out).
245
- */
246
- redact?: boolean | {
247
- rules?: RedactionRule[];
248
- };
249
- /**
250
- * Redaction preset for trace metadata. Default `local` (same keys as default redaction).
251
- * `share` and `strict` add extra key-based redaction and tighter string bounds.
252
- * Ignored when `redact: false`.
253
- */
254
- redactionProfile?: RedactionProfile;
255
- /** Max UTF-8 bytes for a serialized trace event line. Default 65536. */
256
- maxEventBytes?: number;
257
- /** Max length for string metadata values (non-preview keys). Default 2000. */
258
- maxMetadataValueLength?: number;
259
- /** Max length for preview-like metadata keys (contains `preview`). Default 500. */
260
- maxPreviewLength?: number;
261
- }
262
- /** Options passed when opening a logical step (implemented in a later step). */
263
- interface StepOptions {
264
- type?: StepType;
265
- metadata?: StepMetadata;
153
+ declare function buildRunWhatSummary(events: TraceEvent[]): RunWhatSummary;
154
+ interface RenderWhatOptions {
155
+ /** Include correlation ids when present (default true). */
156
+ correlation?: boolean;
266
157
  }
267
- /** Options for `observe()` — same surface as {@link InspectRunOptions} in MVP. */
268
- type ObserveOptions = InspectRunOptions;
269
158
  /**
270
- * Resolved settings for the active run while tracing is enabled.
271
- * Populated by runtime code in a later step; defined here for `context.ts`.
159
+ * Render a human-readable `what` summary (plain text, no ANSI).
272
160
  */
273
- interface ExecutionContext {
274
- runId: string;
275
- runName: string;
276
- traceDir: string;
277
- silent: boolean;
278
- metadata?: Record<string, unknown>;
161
+ declare function renderRunWhat(summary: RunWhatSummary, options?: RenderWhatOptions): string;
162
+
163
+ type ReportFormat = "markdown" | "html";
164
+ interface ReportOptions {
165
+ format: ReportFormat;
166
+ includeAttributes?: boolean;
167
+ includeErrors?: boolean;
168
+ redactionProfile?: RedactionProfile;
169
+ /** Include correlation ids in the what section (default true). */
170
+ correlation?: boolean;
279
171
  }
280
- /** Stack position of the step currently executing (used by future context tracking). */
281
- interface ActiveStepContext {
282
- stepId: string;
283
- parentId?: string;
284
- depth: number;
172
+ interface ReportResult {
173
+ format: ReportFormat;
174
+ content: string;
175
+ contentType: string;
176
+ fileExtension: string;
285
177
  }
286
- /** Returns true if `value` is one of the MVP {@link StepType} literals. */
287
- declare function isStepType(value: unknown): value is StepType;
288
- /** Returns true if `value` is one of the MVP {@link StepStatus} literals. */
289
- declare function isStepStatus(value: unknown): value is StepStatus;
290
178
  /**
291
- * Narrowing guard for a {@link TraceEvent} object with required MVP fields.
292
- * Does not deeply validate optional `metadata` shapes.
179
+ * Build a local inspection report (markdown or HTML) from v0.1 trace events.
180
+ * Composes `what`, timeline, and execution-tree sections.
293
181
  */
294
- declare function isTraceEvent(value: unknown): value is TraceEvent;
182
+ declare function buildRunReport(events: TraceEvent[], options: ReportOptions): ReportResult;
295
183
 
296
- type PersistedSchemaVersion = "0.2";
297
- type PersistedEventSourceType = "manual" | "json-log" | "log4js" | "adapter" | "ai-sdk" | "otel";
298
- interface PersistedEventSource {
299
- type: PersistedEventSourceType;
300
- name?: string;
301
- version?: string;
302
- }
303
- type PersistedEventStatus = "running" | "ok" | "error" | "unknown";
304
- interface PersistedInspectError {
305
- name?: string;
306
- message: string;
307
- code?: string;
308
- }
309
- interface PersistedTokenUsage {
310
- input?: number;
311
- output?: number;
312
- total?: number;
313
- }
314
- interface PersistedTraceContext {
315
- traceId?: string;
316
- spanId?: string;
317
- parentSpanId?: string;
184
+ interface DurationStats {
185
+ minMs?: number;
186
+ maxMs?: number;
187
+ avgMs?: number;
188
+ p50Ms?: number;
189
+ p95Ms?: number;
318
190
  }
319
- interface PersistedInspectEvent {
320
- schemaVersion: PersistedSchemaVersion;
321
- eventId: string;
191
+ interface TraceStatsRankedRun {
322
192
  runId: string;
323
- parentId?: string;
324
- kind: InspectKind;
325
- name: string;
326
- status?: PersistedEventStatus;
327
- timestamp: string;
328
- startedAt?: string;
329
- endedAt?: string;
193
+ name?: string;
330
194
  durationMs?: number;
331
- confidence: AttributionConfidence;
332
- source: PersistedEventSource;
333
- attributes?: Record<string, unknown>;
334
- inputSummary?: unknown;
335
- outputSummary?: unknown;
336
- error?: PersistedInspectError;
337
- tokenUsage?: PersistedTokenUsage;
338
- trace?: PersistedTraceContext;
339
- }
340
- /**
341
- * Runtime guard for a v0.2 {@link PersistedInspectEvent} JSON object.
342
- *
343
- * Timestamp fields (`timestamp`, `startedAt`, `endedAt`) are validated as
344
- * non-empty strings only — stricter ISO-8601 parsing may be added later.
345
- */
346
- declare function isPersistedInspectEvent(value: unknown): value is PersistedInspectEvent;
347
-
348
- interface TraceEventToPersistedOptions {
349
- /**
350
- * Stable index within the source event list.
351
- * Used only to make synthetic eventId deterministic when v0.1 has no eventId.
352
- */
353
- eventIndex?: number;
354
- /**
355
- * Optional source name override.
356
- * Default: "trace-event"
357
- */
358
- sourceName?: string;
359
- /**
360
- * Optional source version override.
361
- * Default: "0.1"
362
- */
363
- sourceVersion?: string;
195
+ status: string;
364
196
  }
365
- /**
366
- * Maps one v0.1 {@link TraceEvent} to a v0.2 {@link PersistedInspectEvent}.
367
- * Does not mutate `event`.
368
- */
369
- declare function traceEventToPersistedInspectEvent(event: TraceEvent, options?: TraceEventToPersistedOptions): PersistedInspectEvent;
370
- /**
371
- * Maps a v0.1 trace event list to persisted v0.2 events (one output per input).
372
- */
373
- declare function traceEventsToPersistedInspectEvents(events: readonly TraceEvent[], options?: Omit<TraceEventToPersistedOptions, "eventIndex">): PersistedInspectEvent[];
374
-
375
- interface InspectEventToPersistedOptions {
376
- /**
377
- * Optional source name override.
378
- * If omitted, derived from event.source.type.
379
- */
380
- sourceName?: string;
381
- /**
382
- * Optional source version override.
383
- */
384
- sourceVersion?: string;
385
- /**
386
- * Stable index for deterministic fallback IDs if needed.
387
- */
388
- eventIndex?: number;
389
- }
390
- /**
391
- * Maps one in-memory {@link InspectEvent} to a v0.2 {@link PersistedInspectEvent}.
392
- * Does not mutate `event`.
393
- */
394
- declare function inspectEventToPersistedInspectEvent(event: InspectEvent, options?: InspectEventToPersistedOptions): PersistedInspectEvent;
395
- /**
396
- * Maps in-memory {@link InspectEvent} rows to persisted v0.2 events.
397
- */
398
- declare function inspectEventsToPersistedInspectEvents(events: readonly InspectEvent[], options?: Omit<InspectEventToPersistedOptions, "eventIndex">): PersistedInspectEvent[];
399
-
400
- interface PersistedToInspectEventOptions {
401
- /**
402
- * If true, invalid persisted events are skipped by batch conversion.
403
- * If false or omitted, invalid events throw.
404
- */
405
- skipInvalid?: boolean;
406
- }
407
- /**
408
- * Maps one v0.2 {@link PersistedInspectEvent} to in-memory {@link InspectEvent}.
409
- * Throws if `event` fails {@link isPersistedInspectEvent}.
410
- */
411
- declare function persistedInspectEventToInspectEvent(event: PersistedInspectEvent): InspectEvent;
412
- /**
413
- * Maps persisted v0.2 events to in-memory {@link InspectEvent} rows.
414
- */
415
- declare function persistedInspectEventsToInspectEvents(events: readonly PersistedInspectEvent[], options?: PersistedToInspectEventOptions): InspectEvent[];
416
-
417
- interface PersistedTreeBridgeOptions {
418
- /**
419
- * If true, invalid persisted events are skipped.
420
- * If false or omitted, invalid persisted events throw.
421
- */
422
- skipInvalid?: boolean;
423
- }
424
- /**
425
- * Builds {@link InspectRunTree} rows from v0.2 {@link PersistedInspectEvent} input.
426
- * Uses {@link TreeBuilder} as the canonical tree builder. Does not mutate `events`.
427
- */
428
- declare function persistedInspectEventsToRunTrees(events: readonly PersistedInspectEvent[], options?: PersistedTreeBridgeOptions): InspectRunTree[];
429
- /**
430
- * Builds {@link InspectRunTree} rows from legacy v0.1 {@link TraceEvent} input
431
- * via the persisted-event model. Does not mutate `events`.
432
- */
433
- declare function traceEventsToPersistedRunTrees(events: readonly TraceEvent[]): InspectRunTree[];
434
-
435
- type ParserWarningCode = "MALFORMED_JSON" | "MISSING_RUN_ID" | "MISSING_EVENT" | "MISSING_TIMESTAMP" | "UNSUPPORTED_LOG4JS_PAYLOAD" | "CONFIG_ERROR" | "UNKNOWN";
436
- interface ParserWarning {
437
- code: ParserWarningCode;
438
- message: string;
439
- file?: string;
440
- line?: number;
441
- raw?: string;
442
- }
443
- interface ParseResult<T> {
444
- records: T[];
445
- warnings: ParserWarning[];
446
- }
447
-
448
- declare const DEFAULT_LOG_INGEST_CONFIG: LogIngestConfig;
449
- declare function mergeLogIngestConfig(base: LogIngestConfig, override: Partial<LogIngestConfig>): LogIngestConfig;
450
- declare function loadLogIngestConfig(configPath?: string): Promise<LogIngestConfig>;
451
-
452
- interface RawLogRecord {
453
- raw: Record<string, unknown>;
454
- file?: string;
455
- line: number;
456
- sourceType: "json-log" | "log4js";
457
- }
458
-
459
- declare class JsonLogParser {
460
- parseLines(lines: string[], filePath?: string): ParseResult<RawLogRecord>;
461
- parseFile(filePath: string): Promise<ParseResult<RawLogRecord>>;
462
- }
463
-
464
- declare class Log4jsParser {
465
- parseLines(lines: string[], filePath?: string): ParseResult<RawLogRecord>;
466
- parseFile(filePath: string): Promise<ParseResult<RawLogRecord>>;
467
- }
468
-
469
- declare function wildcardMatch(pattern: string, value: string): boolean;
470
- declare function matchMapping(eventName: string, mappings?: Record<string, LogEventMapping>): LogEventMapping | undefined;
471
-
472
- declare const DEFAULT_REDACT_KEYS: readonly ["authorization", "cookie", "token", "apiKey", "password", "secret", "email"];
473
- interface RedactorOptions {
474
- rules?: RedactionRule[];
475
- /** Additional exact keys (case-insensitive) to redact in addition to defaults. */
476
- extraKeys?: readonly string[];
477
- }
478
- declare class Redactor {
479
- #private;
480
- constructor(options?: RedactorOptions);
481
- redactValue(key: string, value: unknown): unknown;
482
- redactRecord(record: Record<string, unknown>): Record<string, unknown>;
483
- }
484
-
485
- interface NormalizeOptions {
486
- config: LogIngestConfig;
487
- sourceFile?: string;
488
- }
489
- declare class EventNormalizer {
490
- #private;
491
- constructor(options: NormalizeOptions);
492
- normalize(record: RawLogRecord): InspectEvent | ParserWarning;
493
- normalizeAll(records: RawLogRecord[]): ParseResult<InspectEvent>;
494
- }
495
-
496
- interface TreeBuilderOptions {
497
- config?: LogIngestConfig;
498
- }
499
- declare class TreeBuilder {
500
- constructor(options?: TreeBuilderOptions);
501
- build(events: InspectEvent[]): InspectRunTree[];
502
- }
503
-
504
- interface RenderTreeOptions {
505
- verbose?: boolean;
506
- showConfidence?: "always" | "non-explicit" | "never";
507
- showMetadata?: boolean;
508
- color?: boolean;
509
- maxAttributeLength?: number;
510
- summary?: boolean;
511
- }
512
- declare function renderRunTree(tree: InspectRunTree, options?: RenderTreeOptions): string;
513
- declare function renderRunTrees(trees: InspectRunTree[], options?: RenderTreeOptions): string;
514
-
515
- type LogSourceFormat = "json" | "log4js" | "auto";
516
- interface ParseLogLineOptions {
517
- format?: LogSourceFormat;
518
- file?: string;
519
- line?: number;
520
- }
521
- declare function parseLogLine(line: string, options?: ParseLogLineOptions): ParseResult<RawLogRecord>;
522
-
523
- interface LiveLogUpdate {
524
- events: InspectEvent[];
525
- trees: InspectRunTree[];
526
- warnings: ParserWarning[];
527
- }
528
- interface LiveLogAccumulatorOptions {
529
- config: LogIngestConfig;
530
- format?: LogSourceFormat;
531
- file?: string;
532
- }
533
- declare class LiveLogAccumulator {
534
- #private;
535
- constructor(options: LiveLogAccumulatorOptions);
536
- pushLine(line: string, lineNumber?: number): LiveLogUpdate;
537
- getEvents(): InspectEvent[];
538
- getTrees(): InspectRunTree[];
539
- getWarnings(): ParserWarning[];
540
- reset(): void;
541
- }
542
-
543
- interface ParseLogsOptions {
544
- format?: "json" | "log4js" | "auto";
545
- config?: LogIngestConfig;
546
- configPath?: string;
547
- runIdKeys?: string[];
548
- eventKey?: string;
549
- timestampKey?: string;
550
- messageKey?: string;
551
- levelKey?: string;
552
- parentIdKey?: string;
553
- durationKey?: string;
554
- statusKey?: string;
555
- warnings?: "none" | "summary" | "all";
556
- }
557
- interface LogToTreeResult {
558
- events: InspectEvent[];
559
- trees: InspectRunTree[];
560
- warnings: ParserWarning[];
561
- }
562
- /**
563
- * @experimental Compatibility-oriented API for parsing structured logs into normalized run trees.
564
- * Subject to refinement before a future stability declaration.
565
- */
566
- declare function parseLogsToTrees(filePath: string, options?: ParseLogsOptions): Promise<LogToTreeResult>;
567
-
568
- /** Default folder under the user home for AgentInspect data. */
569
- declare const DEFAULT_TRACE_DIR_NAME = ".agent-inspect";
570
- /** Subfolder where JSONL run traces are stored. */
571
- declare const RUNS_DIR_NAME = "runs";
572
- /** Writable trace root when the default home path cannot be used. */
573
- declare const FALLBACK_TRACE_DIR: string;
574
- /** Maximum display length for run/step names before truncation. */
575
- declare const MAX_NAME_LENGTH = 100;
576
- /** Returns `run_` + a 10-character nanoid segment. */
577
- declare function createRunId(): string;
578
- /** Returns `step_` + a 10-character nanoid segment. */
579
- declare function createStepId(): string;
580
- /** Formats a duration for CLI display (v0.2 rules). */
581
- declare function formatDuration(ms: number): string;
582
- /**
583
- * Formats a Unix timestamp (ms) as local `YYYY-MM-DD HH:mm:ss`.
584
- * Invalid values yield `"Invalid date"` (no throw).
585
- */
586
- declare function formatTimestamp(timestamp: number): string;
587
- /**
588
- * Default directory for trace files: `~/DEFAULT_TRACE_DIR_NAME/RUNS_DIR_NAME`.
589
- * Falls back to {@link FALLBACK_TRACE_DIR} when home cannot be resolved.
590
- */
591
- declare function getDefaultTraceDir(): string;
592
- /**
593
- * Full path to the JSONL trace file for a run.
594
- * `runId` is passed through `path.basename` to avoid traversal; empty ids become `run_unknown`.
595
- */
596
- declare function getTraceFilePath(runId: string, traceDir?: string): string;
597
- /**
598
- * Ensures a trace directory exists (recursive). Tries {@link FALLBACK_TRACE_DIR} on failure.
599
- * Returns the directory path that callers should prefer: primary, fallback, or original if both mkdir attempts fail.
600
- * Emits concise `[AgentInspect]` warnings on failure; never throws.
601
- */
602
- declare function ensureTraceDir(traceDir: string): Promise<string>;
603
- /**
604
- * Normalizes any thrown/caught value into {@link ErrorInfo}.
605
- * Never throws (circular structures and non-JSON values fall back to a generic message).
606
- */
607
- declare function formatError(error: unknown): ErrorInfo;
608
- /**
609
- * Truncates a display name to `maxLength`, appending `"..."` when shortened.
610
- * Empty or non-string input becomes `"unnamed"`.
611
- */
612
- declare function truncateName(name: string, maxLength?: number): string;
613
- /**
614
- * Instrumentation-only warning to stderr. Not a general-purpose logger.
615
- * Optional `error` is summarized via {@link formatError} (message only).
616
- */
617
- declare function warn(message: string, error?: unknown): void;
618
-
619
- interface ResolvedRedactionProfile {
620
- profile: RedactionProfile;
621
- extraKeys: readonly string[];
622
- maxMetadataValueLengthCap?: number;
623
- maxPreviewLengthCap?: number;
624
- }
625
- /** Resolves named profile behavior (keys + metadata string caps). */
626
- declare function resolveRedactionProfile(profile?: RedactionProfile): ResolvedRedactionProfile;
627
-
628
- /** Default max length for string metadata values (non-preview keys). */
629
- declare const DEFAULT_MAX_METADATA_VALUE_LENGTH = 2000;
630
- /** Default max length for preview-like metadata keys (contains `preview`, case-insensitive). */
631
- declare const DEFAULT_MAX_PREVIEW_LENGTH = 500;
632
- /** Default max serialized JSONL line size in bytes (UTF-8). */
633
- declare const DEFAULT_MAX_EVENT_BYTES = 65536;
634
- /** Resolved trace safety settings used at write time. */
635
- interface TraceSafetyOptions {
636
- redactEnabled: boolean;
637
- redactionRules?: RedactionRule[];
638
- redactionProfile: RedactionProfile;
639
- profileExtraKeys: readonly string[];
640
- maxMetadataValueLength: number;
641
- maxPreviewLength: number;
642
- maxEventBytes: number;
643
- }
644
-
645
- /** Resolves {@link InspectRunOptions} trace safety fields with safe defaults. */
646
- declare function resolveTraceSafetyOptions(options?: Pick<InspectRunOptions, "redact" | "redactionProfile" | "maxEventBytes" | "maxMetadataValueLength" | "maxPreviewLength">): TraceSafetyOptions;
647
- /** Redacts (when enabled) and truncates metadata values for disk persistence. */
648
- declare function prepareMetadataForDisk(metadata: Record<string, unknown> | StepMetadata, opts: TraceSafetyOptions): Record<string, unknown>;
649
- /**
650
- * Applies redaction, metadata truncation, and final serialized size bounds.
651
- * Never throws; returns a schema-valid event or a minimally truncated variant.
652
- */
653
- declare function prepareTraceEventForDisk(event: TraceEvent, opts: TraceSafetyOptions): TraceEvent;
654
-
655
- /** Returns the active run context, without internal step fields. */
656
- declare function getCurrentContext(): ExecutionContext | undefined;
657
- /** Active `runId` when inside `runWithContext`, else `undefined`. */
658
- declare function getCurrentRunId(): string | undefined;
659
- /**
660
- * Correlation metadata for the active run (`correlationId`, `requestId`, `decisionId`, `groupId`).
661
- * `undefined` outside `inspectRun` / `maybeInspectRun` or when no correlation fields were set.
662
- */
663
- declare function getCurrentCorrelationMetadata(): TraceCorrelationMetadata | undefined;
664
- /** Active `runName` when inside `runWithContext`, else `undefined`. */
665
- declare function getCurrentRunName(): string | undefined;
666
- /**
667
- * Active step id in this async scope (parent for nested `step()` calls).
668
- * `undefined` at run root or outside any run.
669
- */
670
- declare function getCurrentStepId(): string | undefined;
671
- /** Alias of {@link getCurrentStepId} for readability in step instrumentation. */
672
- declare function getParentStepId(): string | undefined;
673
- /**
674
- * Nesting depth: `0` at run root, increments by one per nested `runWithStepContext`.
675
- * Returns `0` outside any run.
676
- */
677
- declare function getCurrentDepth(): number;
678
- declare function hasActiveContext(): boolean;
679
- declare function getTraceDirFromContext(): string | undefined;
680
- declare function isSilentContext(): boolean;
681
- /** Resolved trace safety settings for the active run (redaction + size bounds). */
682
- declare function getTraceSafetyFromContext(): TraceSafetyOptions | undefined;
683
- /**
684
- * Runs `fn` with a fresh AgentInspect run context (depth 0, no active step).
685
- * Propagates sync/async results and rejections; does not swallow user errors.
686
- */
687
- declare function runWithContext<T>(context: ExecutionContext, fn: () => Promise<T> | T, traceSafety?: TraceSafetyOptions): Promise<T>;
688
- /**
689
- * Runs `fn` with `stepId` as the active step (incremented depth).
690
- * If no run is active, runs `fn` without altering async context.
691
- */
692
- declare function runWithStepContext<T>(stepId: string, fn: () => Promise<T> | T): Promise<T>;
693
-
694
- /**
695
- * Strict MVP validation before writing JSONL. Rejects empty ids, non-finite times, and malformed payloads.
696
- */
697
- declare function validateEvent(event: unknown): event is TraceEvent;
698
- /** Serializes a trace line as compact JSON without a trailing newline. */
699
- declare function serializeEvent(event: TraceEvent): string;
700
- /**
701
- * Creates (or truncates) an empty JSONL file for a run. Uses {@link ensureTraceDir} then {@link getTraceFilePath}.
702
- * On failure, retries once under {@link FALLBACK_TRACE_DIR}.
703
- */
704
- declare function initializeTraceFile(runId: string, traceDir: string): Promise<string | undefined>;
705
- declare function writeTraceEvent(event: TraceEvent, traceDir: string): Promise<void>;
706
- /**
707
- * Reads raw JSONL file contents for a run, or `undefined` if missing or unreadable.
708
- */
709
- declare function readTraceFile(runId: string, traceDir: string): Promise<string | undefined>;
710
- /** Parses JSONL into validated {@link TraceEvent} rows; invalid lines are skipped with a warning. */
711
- declare function readTraceEvents(runId: string, traceDir: string): Promise<TraceEvent[]>;
712
- /**
713
- * Lists `.jsonl` file names in `traceDir`, newest by mtime first (name sort as tie-breaker).
714
- */
715
- declare function listTraceFiles(traceDir: string): Promise<string[]>;
716
- /** Maps a `.jsonl` file name to its run id (basename only; no traversal). */
717
- declare function getRunIdFromTraceFileName(fileName: string): string | undefined;
718
-
719
- interface TraceDirectoryOptions {
720
- dir?: string;
197
+ interface TraceStatsRankedStep {
198
+ runId: string;
199
+ stepName: string;
200
+ stepType: string;
201
+ durationMs: number;
721
202
  }
722
- declare function resolveTraceDir(options?: TraceDirectoryOptions): string;
723
- declare class TraceDirectory {
724
- #private;
725
- constructor(options?: TraceDirectoryOptions);
726
- getPath(filename?: string): string;
727
- list(): Promise<string[]>;
728
- getFileStats(filename: string): Promise<Stats>;
203
+ interface TraceStats {
204
+ traceDir: string;
205
+ since?: string;
206
+ correlationId?: string;
207
+ groupId?: string;
208
+ totalRuns: number;
209
+ successCount: number;
210
+ errorCount: number;
211
+ runningCount: number;
212
+ unknownCount: number;
213
+ errorRate: number;
214
+ duration: DurationStats;
215
+ totalSteps: number;
216
+ avgStepsPerRun: number;
217
+ totalLlmSteps: number;
218
+ totalToolSteps: number;
219
+ totalErrorSteps: number;
220
+ slowestRuns: TraceStatsRankedRun[];
221
+ slowestSteps: TraceStatsRankedStep[];
222
+ }
223
+ interface TraceStatsOptions {
224
+ traceDir: string;
225
+ since?: string;
226
+ correlationId?: string;
227
+ groupId?: string;
228
+ slowRunLimit?: number;
229
+ slowStepLimit?: number;
729
230
  }
231
+ declare function buildTraceStats(metas: TraceMetadata[], options: TraceStatsOptions): Promise<TraceStats>;
232
+ declare function renderTraceStats(stats: TraceStats): string;
730
233
 
731
- declare function extractMetadata(filePath: string, _quickScan?: boolean): Promise<TraceMetadata>;
732
- declare function buildRunSummary(events: TraceEvent[]): RunSummary;
733
-
734
- interface TraceFilterOptions {
735
- status?: TraceMetadataStatus;
736
- name?: string;
234
+ interface TraceSearchOptions {
235
+ traceDir: string;
737
236
  since?: string;
237
+ status?: "success" | "error" | "running" | "unknown";
238
+ kind?: string;
239
+ type?: string;
240
+ name?: string;
241
+ tool?: string;
242
+ duration?: string;
738
243
  limit?: number;
739
244
  }
740
- declare function filterTraces(traces: TraceMetadata[], options: TraceFilterOptions): TraceMetadata[];
245
+ interface TraceSearchResult {
246
+ runId: string;
247
+ runName?: string;
248
+ runStatus: string;
249
+ stepId?: string;
250
+ stepName?: string;
251
+ stepType?: string;
252
+ timestamp?: number;
253
+ durationMs?: number;
254
+ matchReason: string;
255
+ matchedFields: string[];
256
+ filePath: string;
257
+ }
258
+ interface ParsedDurationFilter {
259
+ op: ">" | ">=" | "<" | "<=";
260
+ ms: number;
261
+ }
262
+ declare function parseDurationFilter(expr: string): ParsedDurationFilter;
263
+ declare function searchTraces(metas: TraceMetadata[], options: TraceSearchOptions): Promise<TraceSearchResult[]>;
264
+ declare function loadTraceMetadataList(_traceDir: string, fileNames: string[], getPath: (fileName: string) => string): Promise<TraceMetadata[]>;
741
265
 
742
266
  /**
743
267
  * Safety check for cleanup workflows: returns true only when the file appears to be an AgentInspect trace.
@@ -753,112 +277,6 @@ declare function isAgentInspectTrace(filePath: string): Promise<boolean>;
753
277
  */
754
278
  declare function parseDuration(duration: string): number;
755
279
 
756
- type DiffSeverity = "info" | "warning" | "error";
757
- type DiffKind = "run-status" | "structure" | "step-added" | "step-removed" | "step-status" | "step-type" | "duration" | "error" | "metadata" | "output" | "first-divergence";
758
- interface DiffPathSegment {
759
- index: number;
760
- name: string;
761
- stepId?: string;
762
- }
763
- interface DiffPath {
764
- path: DiffPathSegment[];
765
- }
766
- interface RunDiffItem {
767
- kind: DiffKind;
768
- severity: DiffSeverity;
769
- message: string;
770
- path?: DiffPath;
771
- left?: unknown;
772
- right?: unknown;
773
- }
774
- interface StepComparable {
775
- id: string;
776
- name: string;
777
- type?: string;
778
- status?: string;
779
- durationMs?: number;
780
- error?: string;
781
- metadata?: Record<string, unknown>;
782
- outputPreview?: unknown;
783
- children: StepComparable[];
784
- }
785
- interface RunComparable {
786
- runId: string;
787
- name?: string;
788
- status?: string;
789
- durationMs?: number;
790
- steps: StepComparable[];
791
- }
792
- interface RunDiffSummary {
793
- leftRunId: string;
794
- rightRunId: string;
795
- totalDifferences: number;
796
- errors: number;
797
- warnings: number;
798
- info: number;
799
- firstDivergence?: RunDiffItem;
800
- }
801
- interface RunDiffResult {
802
- summary: RunDiffSummary;
803
- differences: RunDiffItem[];
804
- }
805
- interface DiffOptions {
806
- ignoreDuration?: boolean;
807
- durationThresholdMs?: number;
808
- focus?: "all" | "errors" | "structure" | "outputs";
809
- check?: "all" | "structure" | "outputs" | "errors" | "timing";
810
- }
811
- interface RenderDiffOptions {
812
- json?: boolean;
813
- verbose?: boolean;
814
- color?: boolean;
815
- }
816
-
817
- /**
818
- * Normalize v0.1 manual JSONL events into a comparable run tree.
819
- * Does not mutate input events.
820
- */
821
- declare function manualTraceEventsToComparableRun(events: TraceEvent[]): RunComparable;
822
-
823
- declare function diffRuns(left: RunComparable, right: RunComparable, options?: DiffOptions): RunDiffResult;
824
-
825
- declare function renderRunDiff(result: RunDiffResult, options?: RenderDiffOptions): string;
826
-
827
- /**
828
- * @experimental Compare two v0.1 manual traces as normalized trees (read-only).
829
- * Subject to refinement before a future stability declaration.
830
- */
831
- declare function diffTraceEvents(leftEvents: TraceEvent[], rightEvents: TraceEvent[], options?: DiffOptions): RunDiffResult;
832
-
833
- /** Two spaces per nesting level in terminal output. */
834
- declare const TERMINAL_INDENT = " ";
835
- /** Max display length for names in terminal output. */
836
- declare const MAX_TERMINAL_NAME_LENGTH = 80;
837
- /** Max nesting depth used for indentation (prevents huge indents). */
838
- declare const MAX_TERMINAL_DEPTH = 10;
839
- /** Indentation string for a nesting depth (capped, never negative). */
840
- declare function getIndent(depth: number): string;
841
- /** Truncates a display name for terminal use; invalid input becomes `"unnamed"`. */
842
- declare function formatTerminalName(name: string): string;
843
- /** Renders a single step line (colored); does not consult silent mode. */
844
- declare function renderStepLine(name: string, durationMs: number | undefined, status: StepStatus, depth?: number): string;
845
- /** Renders an error summary line (no stack in MVP). */
846
- declare function renderErrorLine(error: ErrorInfo, depth?: number): string;
847
- /** Plain-text run summary lines (no chalk) for stable testing and CLI reuse. */
848
- declare function renderRunSummary(durationMs: number, status: RunStatus, traceFilePath?: string): string[];
849
- /** Prints run header with icon and dim run id. */
850
- declare function printRunStart(runId: string, name: string): void;
851
- /** Prints a running step line. */
852
- declare function printStepStart(name: string, depth?: number): void;
853
- /** Prints a completed step line with duration and status icon. */
854
- declare function printStepComplete(name: string, durationMs: number, status: StepStatus, depth?: number): void;
855
- /** Prints a structured error line (message only, no stack). */
856
- declare function printError(error: ErrorInfo, depth?: number): void;
857
- /** Prints run completion summary and optional trace path. */
858
- declare function printRunComplete(_name: string, _runId: string, durationMs: number, status: RunStatus, traceFilePath?: string): void;
859
- /** Prints which step failed. */
860
- declare function printFailedAt(stepName: string): void;
861
-
862
280
  /**
863
281
  * Stable v1.0 API for local manual run tracing.
864
282
  *
@@ -908,113 +326,4 @@ declare const step: StepFunction;
908
326
  */
909
327
  declare function observe<T>(agent: T, options?: ObserveOptions): T;
910
328
 
911
- /**
912
- * v0.7 local export formats. No sinks — string output only.
913
- */
914
-
915
- type ExportFormat = "markdown" | "html" | "openinference" | "otlp-json";
916
- interface ExportOptions {
917
- format: ExportFormat;
918
- includeMetadata?: boolean;
919
- includeAttributes?: boolean;
920
- includeErrors?: boolean;
921
- pretty?: boolean;
922
- redacted?: boolean;
923
- maxAttributeLength?: number;
924
- /**
925
- * Redaction preset for exported copies. Default `local`.
926
- * `share` and `strict` apply stronger key-based redaction before rendering.
927
- */
928
- redactionProfile?: RedactionProfile;
929
- }
930
- interface ExportResult {
931
- format: ExportFormat;
932
- content: string;
933
- contentType: string;
934
- fileExtension: string;
935
- warnings: string[];
936
- }
937
- interface ExportValidationResult {
938
- ok: boolean;
939
- format: ExportFormat;
940
- errors: string[];
941
- warnings: string[];
942
- }
943
- interface TraceExporter {
944
- name: string;
945
- format: ExportFormat;
946
- export(tree: InspectRunTree, options?: Partial<ExportOptions>): ExportResult;
947
- validate?(content: string): ExportValidationResult;
948
- }
949
- /** Library version string embedded in JSON exports (human-readable, not semver guarantee for formats). */
950
- declare const EXPORT_PAYLOAD_VERSION = "0.1.2";
951
-
952
- declare function safeString(value: unknown, maxLength?: number): string;
953
- /** Escape markdown table pipes and normalize line breaks for safe inline text. */
954
- declare function escapeMarkdown(value: string): string;
955
- declare function escapeHtml(value: string): string;
956
- declare function stableJson(value: unknown, pretty?: boolean): string;
957
- declare function compactAttributes(attrs: Record<string, unknown> | undefined, options?: {
958
- maxLength?: number;
959
- redacted?: boolean;
960
- }): Record<string, unknown>;
961
- declare function summarizeTree(tree: InspectRunTree): Record<string, unknown>;
962
- /** Depth-first pre-order flatten (matches typical tree display). */
963
- declare function flattenTree(tree: InspectRunTree): InspectNode[];
964
-
965
- /**
966
- * Build an {@link InspectRunTree} from v0.1 JSONL {@link TraceEvent} rows (manual tracing).
967
- * Does not mutate the input array or event objects.
968
- */
969
- declare function manualTraceEventsToRunTree(events: TraceEvent[]): InspectRunTree;
970
-
971
- declare function exportMarkdown(tree: InspectRunTree, options?: Partial<ExportOptions>): ExportResult;
972
-
973
- declare function exportHtml(tree: InspectRunTree, options?: Partial<ExportOptions>): ExportResult;
974
-
975
- interface OpenInferenceSpan {
976
- trace_id: string;
977
- span_id: string;
978
- parent_span_id?: string;
979
- name: string;
980
- start_time_unix_nano: number;
981
- end_time_unix_nano?: number;
982
- attributes: Record<string, unknown>;
983
- status?: {
984
- code: "OK" | "ERROR" | "UNSET";
985
- message?: string;
986
- };
987
- }
988
- interface OpenInferenceExport {
989
- exporter: "agent-inspect";
990
- format: "openinference";
991
- compatibility: "openinference-compatible";
992
- version: string;
993
- trace_id: string;
994
- spans: OpenInferenceSpan[];
995
- warnings: string[];
996
- }
997
- declare function exportOpenInference(tree: InspectRunTree, options?: Partial<ExportOptions>): ExportResult;
998
-
999
- declare function exportOtlpJson(tree: InspectRunTree, options?: Partial<ExportOptions>): ExportResult;
1000
-
1001
- declare function validateExportContent(format: ExportFormat, content: string): ExportValidationResult;
1002
-
1003
- interface RedactRunTreeForExportOptions {
1004
- redactionProfile?: RedactionProfile;
1005
- }
1006
- /**
1007
- * Returns a deep copy of `tree` with profile-based redaction applied to event attributes.
1008
- * Does not mutate the input tree.
1009
- */
1010
- declare function redactRunTreeForExport(tree: InspectRunTree, options?: RedactRunTreeForExportOptions): InspectRunTree;
1011
-
1012
- declare function mergeExportDefaults(options: ExportOptions): ExportOptions;
1013
- /**
1014
- * @experimental Compatibility-oriented export API. Exports are local-only and do not upload anywhere.
1015
- * Subject to refinement before a future stability declaration.
1016
- */
1017
- declare function exportRunTree(tree: InspectRunTree, options: ExportOptions): ExportResult;
1018
- declare function validateExport(result: ExportResult): ExportValidationResult;
1019
-
1020
- export { type ActiveStepContext, type AttributionConfidence, DEFAULT_LOG_INGEST_CONFIG, DEFAULT_MAX_EVENT_BYTES, DEFAULT_MAX_METADATA_VALUE_LENGTH, DEFAULT_MAX_PREVIEW_LENGTH, DEFAULT_REDACT_KEYS, DEFAULT_TRACE_DIR_NAME, type DiffKind, type DiffOptions, type DiffPath, type DiffPathSegment, type DiffSeverity, EXPORT_PAYLOAD_VERSION, type ErrorInfo, EventNormalizer, type EventSource, type ExecutionContext, type ExportFormat, type ExportOptions, type ExportResult, type ExportValidationResult, FALLBACK_TRACE_DIR, type InspectEvent, type InspectEventToPersistedOptions, type InspectKind, type InspectNode, type InspectRunOptions, type InspectRunTree, JsonLogParser, LiveLogAccumulator, type LiveLogAccumulatorOptions, type LiveLogUpdate, Log4jsParser, type LogEventMapping, type LogIngestConfig, type LogSourceFormat, type LogToTreeResult, MAX_NAME_LENGTH, MAX_TERMINAL_DEPTH, MAX_TERMINAL_NAME_LENGTH, type NormalizeOptions, type ObserveOptions, type OpenInferenceExport, type OpenInferenceSpan, type ParseLogLineOptions, type ParseLogsOptions, type ParseResult, type ParserWarning, type ParserWarningCode, type PersistedEventSource, type PersistedEventSourceType, type PersistedEventStatus, type PersistedInspectError, type PersistedInspectEvent, type PersistedSchemaVersion, type PersistedToInspectEventOptions, type PersistedTokenUsage, type PersistedTraceContext, type PersistedTreeBridgeOptions, RUNS_DIR_NAME, type RawLogRecord, type RedactionProfile, type RedactionRule, type RedactionStrategy, Redactor, type RedactorOptions, type RenderDiffOptions, type RenderTreeOptions, type ResolvedRedactionProfile, type Run, type RunComparable, type RunCompletedEvent, type RunDiffItem, type RunDiffResult, type RunDiffSummary, type RunStartedEvent, type RunStatus, type RunSummary, type Step, type StepComparable, type StepCompletedEvent, type StepMetadata, type StepOptions, type StepStartedEvent, type StepStatus, type StepType, TERMINAL_INDENT, type TokenMetadata, type TraceCorrelationMetadata, TraceDirectory, type TraceDirectoryOptions, type TraceEvent, type TraceEventBase, type TraceEventToPersistedOptions, type TraceExporter, type TraceFilterOptions, type TraceMetadata, type TraceMetadataStatus, type TraceSafetyOptions, type TraceSchemaVersion, TreeBuilder, type TreeBuilderOptions, buildRunSummary, compactAttributes, createRunId, createStepId, diffRuns, diffTraceEvents, ensureTraceDir, escapeHtml, escapeMarkdown, exportHtml, exportMarkdown, exportOpenInference, exportOtlpJson, exportRunTree, extractMetadata, filterTraces, flattenTree, formatDuration, formatError, formatTerminalName, formatTimestamp, getCurrentContext, getCurrentCorrelationMetadata, getCurrentDepth, getCurrentRunId, getCurrentRunName, getCurrentStepId, getDefaultTraceDir, getIndent, getParentStepId, getRunIdFromTraceFileName, getTraceDirFromContext, getTraceFilePath, getTraceSafetyFromContext, hasActiveContext, initializeTraceFile, inspectEventToPersistedInspectEvent, inspectEventsToPersistedInspectEvents, inspectRun, isAgentInspectEnabled, isAgentInspectTrace, isPersistedInspectEvent, isSilentContext, isStepStatus, isStepType, isTraceEvent, listTraceFiles, loadLogIngestConfig, manualTraceEventsToComparableRun, manualTraceEventsToRunTree, matchMapping, maybeInspectRun, mergeExportDefaults, mergeLogIngestConfig, observe, parseDuration, parseLogLine, parseLogsToTrees, persistedInspectEventToInspectEvent, persistedInspectEventsToInspectEvents, persistedInspectEventsToRunTrees, prepareMetadataForDisk, prepareTraceEventForDisk, printError, printFailedAt, printRunComplete, printRunStart, printStepComplete, printStepStart, readTraceEvents, readTraceFile, redactRunTreeForExport, renderErrorLine, renderRunDiff, renderRunSummary, renderRunTree, renderRunTrees, renderStepLine, resolveRedactionProfile, resolveTraceDir, resolveTraceSafetyOptions, runWithContext, runWithStepContext, safeString, serializeEvent, stableJson, step, summarizeTree, traceEventToPersistedInspectEvent, traceEventsToPersistedInspectEvents, traceEventsToPersistedRunTrees, truncateName, validateEvent, validateExport, validateExportContent, warn, wildcardMatch, writeTraceEvent };
329
+ export { type DurationStats, InspectRunOptions, ObserveOptions, type ParseTraceJsonlOptions, type ParseTraceJsonlResult, type ParsedDurationFilter, PersistedInspectEvent, RedactionProfile, type RenderTimelineOptions, type RenderWhatOptions, type ReportFormat, type ReportOptions, type ReportResult, RunSummary, type RunTimeline, type RunWhatSummary, StepOptions, StepStatus, StepType, type TimelineEntry, type TimelineFocus, type TimelineOptions, TraceCorrelationMetadata, TraceDirectory, type TraceDirectoryOptions, TraceEvent, type TraceFilterOptions, type TraceJsonlFormat, TraceMetadata, TraceMetadataStatus, type TraceSearchOptions, type TraceSearchResult, type TraceStats, type TraceStatsOptions, type TraceStatsRankedRun, type TraceStatsRankedStep, buildRunReport, buildRunSummary, buildRunTimeline, buildRunWhatSummary, buildTraceStats, extractMetadata, filterTraces, getRunIdFromTraceFileName, initializeTraceFile, inspectRun, isAgentInspectEnabled, isAgentInspectTrace, listTraceFiles, loadTraceMetadataList, maybeInspectRun, observe, parseDuration, parseDurationFilter, parseTraceJsonl, readTraceEvents, readTraceFile, renderRunWhat, renderTimeline, renderTraceStats, resolveTraceDir, searchTraces, serializeEvent, step, unknownTraceFormatMessage, validateEvent, writeTraceEvent };