agent-inspect 1.0.2 → 1.1.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.
@@ -1,5 +1,75 @@
1
1
  import { Stats } from 'node:fs';
2
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
+ }
72
+
3
73
  /**
4
74
  * Discriminator for what kind of work a {@link Step} represents.
5
75
  * `"decision"` captures agent branching/choices; other values cover runs, LLM calls, tools, and user-defined steps.
@@ -150,11 +220,29 @@ interface StepCompletedEvent extends TraceEventBase {
150
220
  }
151
221
  /** Discriminated union of all MVP trace events written as JSONL lines. */
152
222
  type TraceEvent = RunStartedEvent | RunCompletedEvent | StepStartedEvent | StepCompletedEvent;
153
- /** Options for `inspectRun()` (implemented in a later step). */
223
+ /** Options for `inspectRun()` and `maybeInspectRun()`. */
154
224
  interface InspectRunOptions {
155
225
  traceDir?: string;
156
226
  silent?: boolean;
157
227
  metadata?: Record<string, unknown>;
228
+ /**
229
+ * When `false`, runs `fn` with no trace file, no execution context, and no terminal output.
230
+ * Omitted or `true` preserves default tracing behavior.
231
+ */
232
+ enabled?: boolean;
233
+ /**
234
+ * Redact sensitive metadata keys before writing JSONL. Default `true` (conservative keys).
235
+ * Pass `false` to persist metadata as-is (explicit opt-out).
236
+ */
237
+ redact?: boolean | {
238
+ rules?: RedactionRule[];
239
+ };
240
+ /** Max UTF-8 bytes for a serialized trace event line. Default 65536. */
241
+ maxEventBytes?: number;
242
+ /** Max length for string metadata values (non-preview keys). Default 2000. */
243
+ maxMetadataValueLength?: number;
244
+ /** Max length for preview-like metadata keys (contains `preview`). Default 500. */
245
+ maxPreviewLength?: number;
158
246
  }
159
247
  /** Options passed when opening a logical step (implemented in a later step). */
160
248
  interface StepOptions {
@@ -190,76 +278,6 @@ declare function isStepStatus(value: unknown): value is StepStatus;
190
278
  */
191
279
  declare function isTraceEvent(value: unknown): value is TraceEvent;
192
280
 
193
- type AttributionConfidence = "explicit" | "correlated" | "heuristic" | "unknown";
194
- type InspectKind = "RUN" | "AGENT" | "LLM" | "TOOL" | "CHAIN" | "RETRIEVER" | "DECISION" | "RESULT" | "ERROR" | "LOGIC" | "LOG";
195
- interface EventSource {
196
- type: "manual" | "json-log" | "log4js" | "pino" | "winston" | "adapter";
197
- file?: string;
198
- line?: number;
199
- }
200
- interface InspectEvent {
201
- eventId: string;
202
- runId: string;
203
- parentId?: string;
204
- name: string;
205
- kind: InspectKind;
206
- timestamp: number;
207
- status?: "running" | "ok" | "error";
208
- durationMs?: number;
209
- attributes?: Record<string, unknown>;
210
- confidence: AttributionConfidence;
211
- source: EventSource;
212
- }
213
- interface InspectNode {
214
- event: InspectEvent;
215
- children: InspectNode[];
216
- depth: number;
217
- }
218
- interface InspectRunTree {
219
- runId: string;
220
- name?: string;
221
- status?: "running" | "ok" | "error";
222
- startedAt?: number;
223
- endedAt?: number;
224
- durationMs?: number;
225
- children: InspectNode[];
226
- metadata: {
227
- totalEvents: number;
228
- confidenceBreakdown: Record<AttributionConfidence, number>;
229
- kinds: Record<InspectKind, number>;
230
- };
231
- }
232
-
233
- interface LogEventMapping {
234
- kind?: InspectKind;
235
- name?: string;
236
- parent?: string;
237
- status?: "running" | "ok" | "error";
238
- startsRun?: boolean;
239
- endsRun?: boolean;
240
- startsStep?: boolean;
241
- endsStep?: boolean;
242
- }
243
- type RedactionStrategy = "full" | "prefix" | "hash";
244
- type RedactionRule = string | {
245
- key: string;
246
- strategy: RedactionStrategy;
247
- keep?: number;
248
- };
249
- interface LogIngestConfig {
250
- runIdKeys: string[];
251
- eventKey: string;
252
- timestampKey?: string;
253
- messageKey?: string;
254
- levelKey?: string;
255
- parentIdKey?: string;
256
- durationKey?: string;
257
- statusKey?: string;
258
- mappings?: Record<string, LogEventMapping>;
259
- redact?: RedactionRule[];
260
- heuristicWindowMs?: number;
261
- }
262
-
263
281
  type ParserWarningCode = "MALFORMED_JSON" | "MISSING_RUN_ID" | "MISSING_EVENT" | "MISSING_TIMESTAMP" | "UNSUPPORTED_LOG4JS_PAYLOAD" | "CONFIG_ERROR" | "UNKNOWN";
264
282
  interface ParserWarning {
265
283
  code: ParserWarningCode;
@@ -442,6 +460,30 @@ declare function truncateName(name: string, maxLength?: number): string;
442
460
  */
443
461
  declare function warn(message: string, error?: unknown): void;
444
462
 
463
+ /** Default max length for string metadata values (non-preview keys). */
464
+ declare const DEFAULT_MAX_METADATA_VALUE_LENGTH = 2000;
465
+ /** Default max length for preview-like metadata keys (contains `preview`, case-insensitive). */
466
+ declare const DEFAULT_MAX_PREVIEW_LENGTH = 500;
467
+ /** Default max serialized JSONL line size in bytes (UTF-8). */
468
+ declare const DEFAULT_MAX_EVENT_BYTES = 65536;
469
+ /** Resolved trace safety settings used at write time. */
470
+ interface TraceSafetyOptions {
471
+ redactEnabled: boolean;
472
+ redactionRules?: RedactionRule[];
473
+ maxMetadataValueLength: number;
474
+ maxPreviewLength: number;
475
+ maxEventBytes: number;
476
+ }
477
+ /** Resolves {@link InspectRunOptions} trace safety fields with safe defaults. */
478
+ declare function resolveTraceSafetyOptions(options?: Pick<InspectRunOptions, "redact" | "maxEventBytes" | "maxMetadataValueLength" | "maxPreviewLength">): TraceSafetyOptions;
479
+ /** Redacts (when enabled) and truncates metadata values for disk persistence. */
480
+ declare function prepareMetadataForDisk(metadata: Record<string, unknown> | StepMetadata, opts: TraceSafetyOptions): Record<string, unknown>;
481
+ /**
482
+ * Applies redaction, metadata truncation, and final serialized size bounds.
483
+ * Never throws; returns a schema-valid event or a minimally truncated variant.
484
+ */
485
+ declare function prepareTraceEventForDisk(event: TraceEvent, opts: TraceSafetyOptions): TraceEvent;
486
+
445
487
  /** Returns the active run context, without internal step fields. */
446
488
  declare function getCurrentContext(): ExecutionContext | undefined;
447
489
  /** Active `runId` when inside `runWithContext`, else `undefined`. */
@@ -463,11 +505,13 @@ declare function getCurrentDepth(): number;
463
505
  declare function hasActiveContext(): boolean;
464
506
  declare function getTraceDirFromContext(): string | undefined;
465
507
  declare function isSilentContext(): boolean;
508
+ /** Resolved trace safety settings for the active run (redaction + size bounds). */
509
+ declare function getTraceSafetyFromContext(): TraceSafetyOptions | undefined;
466
510
  /**
467
511
  * Runs `fn` with a fresh AgentInspect run context (depth 0, no active step).
468
512
  * Propagates sync/async results and rejections; does not swallow user errors.
469
513
  */
470
- declare function runWithContext<T>(context: ExecutionContext, fn: () => Promise<T> | T): Promise<T>;
514
+ declare function runWithContext<T>(context: ExecutionContext, fn: () => Promise<T> | T, traceSafety?: TraceSafetyOptions): Promise<T>;
471
515
  /**
472
516
  * Runs `fn` with `stepId` as the active step (incremented depth).
473
517
  * If no run is active, runs `fn` without altering async context.
@@ -485,9 +529,6 @@ declare function serializeEvent(event: TraceEvent): string;
485
529
  * On failure, retries once under {@link FALLBACK_TRACE_DIR}.
486
530
  */
487
531
  declare function initializeTraceFile(runId: string, traceDir: string): Promise<string | undefined>;
488
- /**
489
- * Appends one validated JSONL line for `event.runId`. Falls back to {@link FALLBACK_TRACE_DIR} on append failure.
490
- */
491
532
  declare function writeTraceEvent(event: TraceEvent, traceDir: string): Promise<void>;
492
533
  /**
493
534
  * Reads raw JSONL file contents for a run, or `undefined` if missing or unreadable.
@@ -653,6 +694,19 @@ declare function printFailedAt(stepName: string): void;
653
694
  */
654
695
  declare function inspectRun<T>(name: string, fn: () => Promise<T> | T, options?: InspectRunOptions): Promise<T>;
655
696
 
697
+ /**
698
+ * Returns true when `value` is one of the recognized AGENT_INSPECT enable tokens
699
+ * (`1`, `true`, `yes`, `on`, `enabled`, case-insensitive). Undefined or any other value is false.
700
+ */
701
+ declare function isAgentInspectEnabled(value?: string): boolean;
702
+ /**
703
+ * Runs `fn` with tracing when enabled; otherwise passthrough (no trace file, no context).
704
+ *
705
+ * Enablement order: explicit `options.enabled` wins; when omitted, reads `process.env.AGENT_INSPECT`.
706
+ * Unset or unrecognized env values disable tracing.
707
+ */
708
+ declare function maybeInspectRun<T>(name: string, fn: () => Promise<T> | T, options?: InspectRunOptions): Promise<T>;
709
+
656
710
  /**
657
711
  * Stable v1.0 API for instrumenting a named step inside an AgentInspect run.
658
712
  *
@@ -776,4 +830,4 @@ declare function mergeExportDefaults(options: ExportOptions): ExportOptions;
776
830
  declare function exportRunTree(tree: InspectRunTree, options: ExportOptions): ExportResult;
777
831
  declare function validateExport(result: ExportResult): ExportValidationResult;
778
832
 
779
- export { type ActiveStepContext, type AttributionConfidence, DEFAULT_LOG_INGEST_CONFIG, 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 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, RUNS_DIR_NAME, type RawLogRecord, type RedactionRule, type RedactionStrategy, Redactor, type RedactorOptions, type RenderDiffOptions, type RenderTreeOptions, 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, TraceDirectory, type TraceDirectoryOptions, type TraceEvent, type TraceEventBase, type TraceExporter, type TraceFilterOptions, type TraceMetadata, type TraceMetadataStatus, 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, getCurrentDepth, getCurrentRunId, getCurrentRunName, getCurrentStepId, getDefaultTraceDir, getIndent, getParentStepId, getRunIdFromTraceFileName, getTraceDirFromContext, getTraceFilePath, hasActiveContext, initializeTraceFile, inspectRun, isAgentInspectTrace, isSilentContext, isStepStatus, isStepType, isTraceEvent, listTraceFiles, loadLogIngestConfig, manualTraceEventsToComparableRun, manualTraceEventsToRunTree, matchMapping, mergeExportDefaults, mergeLogIngestConfig, observe, parseDuration, parseLogLine, parseLogsToTrees, printError, printFailedAt, printRunComplete, printRunStart, printStepComplete, printStepStart, readTraceEvents, readTraceFile, renderErrorLine, renderRunDiff, renderRunSummary, renderRunTree, renderRunTrees, renderStepLine, resolveTraceDir, runWithContext, runWithStepContext, safeString, serializeEvent, stableJson, step, summarizeTree, truncateName, validateEvent, validateExport, validateExportContent, warn, wildcardMatch, writeTraceEvent };
833
+ 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 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, RUNS_DIR_NAME, type RawLogRecord, type RedactionRule, type RedactionStrategy, Redactor, type RedactorOptions, type RenderDiffOptions, type RenderTreeOptions, 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, TraceDirectory, type TraceDirectoryOptions, type TraceEvent, type TraceEventBase, 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, getCurrentDepth, getCurrentRunId, getCurrentRunName, getCurrentStepId, getDefaultTraceDir, getIndent, getParentStepId, getRunIdFromTraceFileName, getTraceDirFromContext, getTraceFilePath, getTraceSafetyFromContext, hasActiveContext, initializeTraceFile, inspectRun, isAgentInspectEnabled, isAgentInspectTrace, isSilentContext, isStepStatus, isStepType, isTraceEvent, listTraceFiles, loadLogIngestConfig, manualTraceEventsToComparableRun, manualTraceEventsToRunTree, matchMapping, maybeInspectRun, mergeExportDefaults, mergeLogIngestConfig, observe, parseDuration, parseLogLine, parseLogsToTrees, prepareMetadataForDisk, prepareTraceEventForDisk, printError, printFailedAt, printRunComplete, printRunStart, printStepComplete, printStepStart, readTraceEvents, readTraceFile, renderErrorLine, renderRunDiff, renderRunSummary, renderRunTree, renderRunTrees, renderStepLine, resolveTraceDir, resolveTraceSafetyOptions, runWithContext, runWithStepContext, safeString, serializeEvent, stableJson, step, summarizeTree, truncateName, validateEvent, validateExport, validateExportContent, warn, wildcardMatch, writeTraceEvent };
@@ -1,5 +1,75 @@
1
1
  import { Stats } from 'node:fs';
2
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
+ }
72
+
3
73
  /**
4
74
  * Discriminator for what kind of work a {@link Step} represents.
5
75
  * `"decision"` captures agent branching/choices; other values cover runs, LLM calls, tools, and user-defined steps.
@@ -150,11 +220,29 @@ interface StepCompletedEvent extends TraceEventBase {
150
220
  }
151
221
  /** Discriminated union of all MVP trace events written as JSONL lines. */
152
222
  type TraceEvent = RunStartedEvent | RunCompletedEvent | StepStartedEvent | StepCompletedEvent;
153
- /** Options for `inspectRun()` (implemented in a later step). */
223
+ /** Options for `inspectRun()` and `maybeInspectRun()`. */
154
224
  interface InspectRunOptions {
155
225
  traceDir?: string;
156
226
  silent?: boolean;
157
227
  metadata?: Record<string, unknown>;
228
+ /**
229
+ * When `false`, runs `fn` with no trace file, no execution context, and no terminal output.
230
+ * Omitted or `true` preserves default tracing behavior.
231
+ */
232
+ enabled?: boolean;
233
+ /**
234
+ * Redact sensitive metadata keys before writing JSONL. Default `true` (conservative keys).
235
+ * Pass `false` to persist metadata as-is (explicit opt-out).
236
+ */
237
+ redact?: boolean | {
238
+ rules?: RedactionRule[];
239
+ };
240
+ /** Max UTF-8 bytes for a serialized trace event line. Default 65536. */
241
+ maxEventBytes?: number;
242
+ /** Max length for string metadata values (non-preview keys). Default 2000. */
243
+ maxMetadataValueLength?: number;
244
+ /** Max length for preview-like metadata keys (contains `preview`). Default 500. */
245
+ maxPreviewLength?: number;
158
246
  }
159
247
  /** Options passed when opening a logical step (implemented in a later step). */
160
248
  interface StepOptions {
@@ -190,76 +278,6 @@ declare function isStepStatus(value: unknown): value is StepStatus;
190
278
  */
191
279
  declare function isTraceEvent(value: unknown): value is TraceEvent;
192
280
 
193
- type AttributionConfidence = "explicit" | "correlated" | "heuristic" | "unknown";
194
- type InspectKind = "RUN" | "AGENT" | "LLM" | "TOOL" | "CHAIN" | "RETRIEVER" | "DECISION" | "RESULT" | "ERROR" | "LOGIC" | "LOG";
195
- interface EventSource {
196
- type: "manual" | "json-log" | "log4js" | "pino" | "winston" | "adapter";
197
- file?: string;
198
- line?: number;
199
- }
200
- interface InspectEvent {
201
- eventId: string;
202
- runId: string;
203
- parentId?: string;
204
- name: string;
205
- kind: InspectKind;
206
- timestamp: number;
207
- status?: "running" | "ok" | "error";
208
- durationMs?: number;
209
- attributes?: Record<string, unknown>;
210
- confidence: AttributionConfidence;
211
- source: EventSource;
212
- }
213
- interface InspectNode {
214
- event: InspectEvent;
215
- children: InspectNode[];
216
- depth: number;
217
- }
218
- interface InspectRunTree {
219
- runId: string;
220
- name?: string;
221
- status?: "running" | "ok" | "error";
222
- startedAt?: number;
223
- endedAt?: number;
224
- durationMs?: number;
225
- children: InspectNode[];
226
- metadata: {
227
- totalEvents: number;
228
- confidenceBreakdown: Record<AttributionConfidence, number>;
229
- kinds: Record<InspectKind, number>;
230
- };
231
- }
232
-
233
- interface LogEventMapping {
234
- kind?: InspectKind;
235
- name?: string;
236
- parent?: string;
237
- status?: "running" | "ok" | "error";
238
- startsRun?: boolean;
239
- endsRun?: boolean;
240
- startsStep?: boolean;
241
- endsStep?: boolean;
242
- }
243
- type RedactionStrategy = "full" | "prefix" | "hash";
244
- type RedactionRule = string | {
245
- key: string;
246
- strategy: RedactionStrategy;
247
- keep?: number;
248
- };
249
- interface LogIngestConfig {
250
- runIdKeys: string[];
251
- eventKey: string;
252
- timestampKey?: string;
253
- messageKey?: string;
254
- levelKey?: string;
255
- parentIdKey?: string;
256
- durationKey?: string;
257
- statusKey?: string;
258
- mappings?: Record<string, LogEventMapping>;
259
- redact?: RedactionRule[];
260
- heuristicWindowMs?: number;
261
- }
262
-
263
281
  type ParserWarningCode = "MALFORMED_JSON" | "MISSING_RUN_ID" | "MISSING_EVENT" | "MISSING_TIMESTAMP" | "UNSUPPORTED_LOG4JS_PAYLOAD" | "CONFIG_ERROR" | "UNKNOWN";
264
282
  interface ParserWarning {
265
283
  code: ParserWarningCode;
@@ -442,6 +460,30 @@ declare function truncateName(name: string, maxLength?: number): string;
442
460
  */
443
461
  declare function warn(message: string, error?: unknown): void;
444
462
 
463
+ /** Default max length for string metadata values (non-preview keys). */
464
+ declare const DEFAULT_MAX_METADATA_VALUE_LENGTH = 2000;
465
+ /** Default max length for preview-like metadata keys (contains `preview`, case-insensitive). */
466
+ declare const DEFAULT_MAX_PREVIEW_LENGTH = 500;
467
+ /** Default max serialized JSONL line size in bytes (UTF-8). */
468
+ declare const DEFAULT_MAX_EVENT_BYTES = 65536;
469
+ /** Resolved trace safety settings used at write time. */
470
+ interface TraceSafetyOptions {
471
+ redactEnabled: boolean;
472
+ redactionRules?: RedactionRule[];
473
+ maxMetadataValueLength: number;
474
+ maxPreviewLength: number;
475
+ maxEventBytes: number;
476
+ }
477
+ /** Resolves {@link InspectRunOptions} trace safety fields with safe defaults. */
478
+ declare function resolveTraceSafetyOptions(options?: Pick<InspectRunOptions, "redact" | "maxEventBytes" | "maxMetadataValueLength" | "maxPreviewLength">): TraceSafetyOptions;
479
+ /** Redacts (when enabled) and truncates metadata values for disk persistence. */
480
+ declare function prepareMetadataForDisk(metadata: Record<string, unknown> | StepMetadata, opts: TraceSafetyOptions): Record<string, unknown>;
481
+ /**
482
+ * Applies redaction, metadata truncation, and final serialized size bounds.
483
+ * Never throws; returns a schema-valid event or a minimally truncated variant.
484
+ */
485
+ declare function prepareTraceEventForDisk(event: TraceEvent, opts: TraceSafetyOptions): TraceEvent;
486
+
445
487
  /** Returns the active run context, without internal step fields. */
446
488
  declare function getCurrentContext(): ExecutionContext | undefined;
447
489
  /** Active `runId` when inside `runWithContext`, else `undefined`. */
@@ -463,11 +505,13 @@ declare function getCurrentDepth(): number;
463
505
  declare function hasActiveContext(): boolean;
464
506
  declare function getTraceDirFromContext(): string | undefined;
465
507
  declare function isSilentContext(): boolean;
508
+ /** Resolved trace safety settings for the active run (redaction + size bounds). */
509
+ declare function getTraceSafetyFromContext(): TraceSafetyOptions | undefined;
466
510
  /**
467
511
  * Runs `fn` with a fresh AgentInspect run context (depth 0, no active step).
468
512
  * Propagates sync/async results and rejections; does not swallow user errors.
469
513
  */
470
- declare function runWithContext<T>(context: ExecutionContext, fn: () => Promise<T> | T): Promise<T>;
514
+ declare function runWithContext<T>(context: ExecutionContext, fn: () => Promise<T> | T, traceSafety?: TraceSafetyOptions): Promise<T>;
471
515
  /**
472
516
  * Runs `fn` with `stepId` as the active step (incremented depth).
473
517
  * If no run is active, runs `fn` without altering async context.
@@ -485,9 +529,6 @@ declare function serializeEvent(event: TraceEvent): string;
485
529
  * On failure, retries once under {@link FALLBACK_TRACE_DIR}.
486
530
  */
487
531
  declare function initializeTraceFile(runId: string, traceDir: string): Promise<string | undefined>;
488
- /**
489
- * Appends one validated JSONL line for `event.runId`. Falls back to {@link FALLBACK_TRACE_DIR} on append failure.
490
- */
491
532
  declare function writeTraceEvent(event: TraceEvent, traceDir: string): Promise<void>;
492
533
  /**
493
534
  * Reads raw JSONL file contents for a run, or `undefined` if missing or unreadable.
@@ -653,6 +694,19 @@ declare function printFailedAt(stepName: string): void;
653
694
  */
654
695
  declare function inspectRun<T>(name: string, fn: () => Promise<T> | T, options?: InspectRunOptions): Promise<T>;
655
696
 
697
+ /**
698
+ * Returns true when `value` is one of the recognized AGENT_INSPECT enable tokens
699
+ * (`1`, `true`, `yes`, `on`, `enabled`, case-insensitive). Undefined or any other value is false.
700
+ */
701
+ declare function isAgentInspectEnabled(value?: string): boolean;
702
+ /**
703
+ * Runs `fn` with tracing when enabled; otherwise passthrough (no trace file, no context).
704
+ *
705
+ * Enablement order: explicit `options.enabled` wins; when omitted, reads `process.env.AGENT_INSPECT`.
706
+ * Unset or unrecognized env values disable tracing.
707
+ */
708
+ declare function maybeInspectRun<T>(name: string, fn: () => Promise<T> | T, options?: InspectRunOptions): Promise<T>;
709
+
656
710
  /**
657
711
  * Stable v1.0 API for instrumenting a named step inside an AgentInspect run.
658
712
  *
@@ -776,4 +830,4 @@ declare function mergeExportDefaults(options: ExportOptions): ExportOptions;
776
830
  declare function exportRunTree(tree: InspectRunTree, options: ExportOptions): ExportResult;
777
831
  declare function validateExport(result: ExportResult): ExportValidationResult;
778
832
 
779
- export { type ActiveStepContext, type AttributionConfidence, DEFAULT_LOG_INGEST_CONFIG, 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 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, RUNS_DIR_NAME, type RawLogRecord, type RedactionRule, type RedactionStrategy, Redactor, type RedactorOptions, type RenderDiffOptions, type RenderTreeOptions, 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, TraceDirectory, type TraceDirectoryOptions, type TraceEvent, type TraceEventBase, type TraceExporter, type TraceFilterOptions, type TraceMetadata, type TraceMetadataStatus, 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, getCurrentDepth, getCurrentRunId, getCurrentRunName, getCurrentStepId, getDefaultTraceDir, getIndent, getParentStepId, getRunIdFromTraceFileName, getTraceDirFromContext, getTraceFilePath, hasActiveContext, initializeTraceFile, inspectRun, isAgentInspectTrace, isSilentContext, isStepStatus, isStepType, isTraceEvent, listTraceFiles, loadLogIngestConfig, manualTraceEventsToComparableRun, manualTraceEventsToRunTree, matchMapping, mergeExportDefaults, mergeLogIngestConfig, observe, parseDuration, parseLogLine, parseLogsToTrees, printError, printFailedAt, printRunComplete, printRunStart, printStepComplete, printStepStart, readTraceEvents, readTraceFile, renderErrorLine, renderRunDiff, renderRunSummary, renderRunTree, renderRunTrees, renderStepLine, resolveTraceDir, runWithContext, runWithStepContext, safeString, serializeEvent, stableJson, step, summarizeTree, truncateName, validateEvent, validateExport, validateExportContent, warn, wildcardMatch, writeTraceEvent };
833
+ 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 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, RUNS_DIR_NAME, type RawLogRecord, type RedactionRule, type RedactionStrategy, Redactor, type RedactorOptions, type RenderDiffOptions, type RenderTreeOptions, 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, TraceDirectory, type TraceDirectoryOptions, type TraceEvent, type TraceEventBase, 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, getCurrentDepth, getCurrentRunId, getCurrentRunName, getCurrentStepId, getDefaultTraceDir, getIndent, getParentStepId, getRunIdFromTraceFileName, getTraceDirFromContext, getTraceFilePath, getTraceSafetyFromContext, hasActiveContext, initializeTraceFile, inspectRun, isAgentInspectEnabled, isAgentInspectTrace, isSilentContext, isStepStatus, isStepType, isTraceEvent, listTraceFiles, loadLogIngestConfig, manualTraceEventsToComparableRun, manualTraceEventsToRunTree, matchMapping, maybeInspectRun, mergeExportDefaults, mergeLogIngestConfig, observe, parseDuration, parseLogLine, parseLogsToTrees, prepareMetadataForDisk, prepareTraceEventForDisk, printError, printFailedAt, printRunComplete, printRunStart, printStepComplete, printStepStart, readTraceEvents, readTraceFile, renderErrorLine, renderRunDiff, renderRunSummary, renderRunTree, renderRunTrees, renderStepLine, resolveTraceDir, resolveTraceSafetyOptions, runWithContext, runWithStepContext, safeString, serializeEvent, stableJson, step, summarizeTree, truncateName, validateEvent, validateExport, validateExportContent, warn, wildcardMatch, writeTraceEvent };