agent-inspect 1.0.3 → 1.2.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,12 +1,12 @@
1
1
  import { readFile, mkdir, writeFile, readdir, stat, appendFile } from 'fs/promises';
2
- import crypto from 'crypto';
3
- import { nanoid } from 'nanoid';
2
+ import crypto, { webcrypto } from 'crypto';
4
3
  import os from 'os';
5
4
  import path from 'path';
6
5
  import { AsyncLocalStorage } from 'async_hooks';
7
6
  import { createReadStream } from 'fs';
8
7
  import { createInterface } from 'readline';
9
- import chalk2 from 'chalk';
8
+ import process2 from 'process';
9
+ import tty from 'tty';
10
10
 
11
11
  // packages/core/src/types.ts
12
12
  var STEP_TYPES = [
@@ -54,7 +54,743 @@ function isTraceEvent(value) {
54
54
  return false;
55
55
  }
56
56
  }
57
- function isRecord2(v) {
57
+
58
+ // packages/core/src/types/persisted-inspect-event.ts
59
+ var INSPECT_KINDS = [
60
+ "RUN",
61
+ "AGENT",
62
+ "LLM",
63
+ "TOOL",
64
+ "CHAIN",
65
+ "RETRIEVER",
66
+ "DECISION",
67
+ "RESULT",
68
+ "ERROR",
69
+ "LOGIC",
70
+ "LOG"
71
+ ];
72
+ var ATTRIBUTION_CONFIDENCES = [
73
+ "explicit",
74
+ "correlated",
75
+ "heuristic",
76
+ "unknown"
77
+ ];
78
+ var PERSISTED_EVENT_SOURCE_TYPES = [
79
+ "manual",
80
+ "json-log",
81
+ "log4js",
82
+ "adapter",
83
+ "ai-sdk",
84
+ "otel"
85
+ ];
86
+ var PERSISTED_EVENT_STATUSES = [
87
+ "running",
88
+ "ok",
89
+ "error",
90
+ "unknown"
91
+ ];
92
+ function isRecord2(value) {
93
+ return typeof value === "object" && value !== null && !Array.isArray(value);
94
+ }
95
+ function isString(value) {
96
+ return typeof value === "string";
97
+ }
98
+ function isNonEmptyString(value) {
99
+ return typeof value === "string" && value.length > 0;
100
+ }
101
+ function isOptionalString(value) {
102
+ return value === void 0 || isString(value);
103
+ }
104
+ function isNonNegativeNumber(value) {
105
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
106
+ }
107
+ function isOptionalNonNegativeNumber(value) {
108
+ return value === void 0 || isNonNegativeNumber(value);
109
+ }
110
+ function isInspectKind(value) {
111
+ return typeof value === "string" && INSPECT_KINDS.includes(value);
112
+ }
113
+ function isAttributionConfidence(value) {
114
+ return typeof value === "string" && ATTRIBUTION_CONFIDENCES.includes(value);
115
+ }
116
+ function isPersistedEventSourceType(value) {
117
+ return typeof value === "string" && PERSISTED_EVENT_SOURCE_TYPES.includes(value);
118
+ }
119
+ function isPersistedEventStatus(value) {
120
+ return typeof value === "string" && PERSISTED_EVENT_STATUSES.includes(value);
121
+ }
122
+ function isPersistedEventSource(value) {
123
+ if (!isRecord2(value)) return false;
124
+ if (!isPersistedEventSourceType(value.type)) return false;
125
+ if (!isOptionalString(value.name)) return false;
126
+ if (!isOptionalString(value.version)) return false;
127
+ return true;
128
+ }
129
+ function isPersistedInspectError(value) {
130
+ if (!isRecord2(value)) return false;
131
+ if (!isNonEmptyString(value.message)) return false;
132
+ if (!isOptionalString(value.name)) return false;
133
+ if (!isOptionalString(value.code)) return false;
134
+ return true;
135
+ }
136
+ function isPersistedTokenUsage(value) {
137
+ if (!isRecord2(value)) return false;
138
+ if (!isOptionalNonNegativeNumber(value.input)) return false;
139
+ if (!isOptionalNonNegativeNumber(value.output)) return false;
140
+ if (!isOptionalNonNegativeNumber(value.total)) return false;
141
+ return true;
142
+ }
143
+ function isPersistedTraceContext(value) {
144
+ if (!isRecord2(value)) return false;
145
+ if (!isOptionalString(value.traceId)) return false;
146
+ if (!isOptionalString(value.spanId)) return false;
147
+ if (!isOptionalString(value.parentSpanId)) return false;
148
+ return true;
149
+ }
150
+ function isPersistedInspectEvent(value) {
151
+ if (!isRecord2(value)) return false;
152
+ if (value.schemaVersion !== "0.2") return false;
153
+ if (!isNonEmptyString(value.eventId)) return false;
154
+ if (!isNonEmptyString(value.runId)) return false;
155
+ if (!isInspectKind(value.kind)) return false;
156
+ if (!isNonEmptyString(value.name)) return false;
157
+ if (!isNonEmptyString(value.timestamp)) return false;
158
+ if (!isAttributionConfidence(value.confidence)) return false;
159
+ if (!isPersistedEventSource(value.source)) return false;
160
+ if (value.parentId !== void 0 && !isNonEmptyString(value.parentId)) {
161
+ return false;
162
+ }
163
+ if (value.status !== void 0 && !isPersistedEventStatus(value.status)) {
164
+ return false;
165
+ }
166
+ if (!isOptionalString(value.startedAt)) return false;
167
+ if (!isOptionalString(value.endedAt)) return false;
168
+ if (value.durationMs !== void 0 && !isNonNegativeNumber(value.durationMs)) {
169
+ return false;
170
+ }
171
+ if (value.attributes !== void 0 && !isRecord2(value.attributes)) {
172
+ return false;
173
+ }
174
+ if (value.error !== void 0 && !isPersistedInspectError(value.error)) {
175
+ return false;
176
+ }
177
+ if (value.tokenUsage !== void 0 && !isPersistedTokenUsage(value.tokenUsage)) {
178
+ return false;
179
+ }
180
+ if (value.trace !== void 0 && !isPersistedTraceContext(value.trace)) {
181
+ return false;
182
+ }
183
+ return true;
184
+ }
185
+
186
+ // packages/core/src/persisted/from-trace-event.ts
187
+ function sanitizeIdPart(value) {
188
+ return value.replace(/[^a-zA-Z0-9_-]/g, "_");
189
+ }
190
+ function nodeIdForEvent(event) {
191
+ switch (event.event) {
192
+ case "run_started":
193
+ case "run_completed":
194
+ return event.runId;
195
+ case "step_started":
196
+ case "step_completed":
197
+ return event.stepId;
198
+ default:
199
+ return "unknown";
200
+ }
201
+ }
202
+ function createPersistedEventId(event, eventIndex) {
203
+ const runId = sanitizeIdPart(event.runId);
204
+ const ev = sanitizeIdPart(event.event);
205
+ const node = sanitizeIdPart(nodeIdForEvent(event));
206
+ return `manual:${runId}:${ev}:${node}:${eventIndex}`;
207
+ }
208
+ function toIsoTimestamp(ms) {
209
+ if (typeof ms !== "number" || !Number.isFinite(ms)) {
210
+ return { iso: (/* @__PURE__ */ new Date(0)).toISOString(), invalidTimestamp: true };
211
+ }
212
+ return { iso: new Date(ms).toISOString(), invalidTimestamp: false };
213
+ }
214
+ function buildSource(options) {
215
+ return {
216
+ type: "manual",
217
+ name: options?.sourceName ?? "trace-event",
218
+ version: options?.sourceVersion ?? "0.1"
219
+ };
220
+ }
221
+ function mapStepTypeToInspectKind(type) {
222
+ switch (type) {
223
+ case "run":
224
+ return "RUN";
225
+ case "llm":
226
+ return "LLM";
227
+ case "tool":
228
+ return "TOOL";
229
+ case "decision":
230
+ return "DECISION";
231
+ case "logic":
232
+ case "state":
233
+ case "custom":
234
+ return "LOGIC";
235
+ default:
236
+ return "LOGIC";
237
+ }
238
+ }
239
+ function mapRunOrStepStatus(status) {
240
+ return status === "success" ? "ok" : "error";
241
+ }
242
+ function mapErrorInfo(error) {
243
+ if (!error?.message) {
244
+ return {};
245
+ }
246
+ const out = {
247
+ persisted: {
248
+ message: error.message,
249
+ name: "Error"
250
+ }
251
+ };
252
+ if (typeof error.stack === "string" && error.stack.length > 0) {
253
+ out.errorStack = error.stack;
254
+ }
255
+ return out;
256
+ }
257
+ function mapTokenUsageFromMetadata(metadata) {
258
+ const tokens = metadata?.tokens;
259
+ if (!tokens || typeof tokens !== "object") {
260
+ return void 0;
261
+ }
262
+ const input = typeof tokens.input === "number" && Number.isFinite(tokens.input) && tokens.input >= 0 ? tokens.input : void 0;
263
+ const output = typeof tokens.output === "number" && Number.isFinite(tokens.output) && tokens.output >= 0 ? tokens.output : void 0;
264
+ if (input === void 0 && output === void 0) {
265
+ return void 0;
266
+ }
267
+ const usage = {};
268
+ if (input !== void 0) usage.input = input;
269
+ if (output !== void 0) usage.output = output;
270
+ if (input !== void 0 && output !== void 0) {
271
+ usage.total = input + output;
272
+ }
273
+ return usage;
274
+ }
275
+ function compactAttributes(entries) {
276
+ const out = {};
277
+ for (const [key, value] of Object.entries(entries)) {
278
+ if (value !== void 0) {
279
+ out[key] = value;
280
+ }
281
+ }
282
+ return Object.keys(out).length > 0 ? out : void 0;
283
+ }
284
+ function traceEventToPersistedInspectEvent(event, options) {
285
+ const eventIndex = options?.eventIndex ?? 0;
286
+ const eventId = createPersistedEventId(event, eventIndex);
287
+ const source = buildSource(options);
288
+ const tsMain = toIsoTimestamp(event.timestamp);
289
+ switch (event.event) {
290
+ case "run_started": {
291
+ const tsStart = toIsoTimestamp(event.startTime);
292
+ const attributes = compactAttributes({
293
+ legacyEvent: "run_started",
294
+ metadata: event.metadata !== void 0 ? { ...event.metadata } : void 0,
295
+ invalidTimestamp: tsMain.invalidTimestamp || tsStart.invalidTimestamp ? true : void 0
296
+ });
297
+ return {
298
+ schemaVersion: "0.2",
299
+ eventId,
300
+ runId: event.runId,
301
+ kind: "RUN",
302
+ name: event.name,
303
+ status: "running",
304
+ timestamp: tsMain.iso,
305
+ startedAt: tsStart.iso,
306
+ confidence: "explicit",
307
+ source,
308
+ attributes
309
+ };
310
+ }
311
+ case "run_completed": {
312
+ const tsEnd = toIsoTimestamp(event.endTime);
313
+ const { persisted: error, errorStack } = mapErrorInfo(event.error);
314
+ const attributes = compactAttributes({
315
+ legacyEvent: "run_completed",
316
+ errorStack,
317
+ invalidTimestamp: tsMain.invalidTimestamp || tsEnd.invalidTimestamp ? true : void 0
318
+ });
319
+ return {
320
+ schemaVersion: "0.2",
321
+ eventId,
322
+ runId: event.runId,
323
+ kind: "RUN",
324
+ name: "run",
325
+ status: mapRunOrStepStatus(event.status),
326
+ timestamp: tsMain.iso,
327
+ endedAt: tsEnd.iso,
328
+ durationMs: event.durationMs,
329
+ confidence: "explicit",
330
+ source,
331
+ attributes,
332
+ error
333
+ };
334
+ }
335
+ case "step_started": {
336
+ const tsStart = toIsoTimestamp(event.startTime);
337
+ const tokenUsage = mapTokenUsageFromMetadata(event.metadata);
338
+ const attributes = compactAttributes({
339
+ legacyEvent: "step_started",
340
+ stepId: event.stepId,
341
+ stepType: event.type,
342
+ metadata: event.metadata !== void 0 ? { ...event.metadata } : void 0,
343
+ invalidTimestamp: tsMain.invalidTimestamp || tsStart.invalidTimestamp ? true : void 0
344
+ });
345
+ const out = {
346
+ schemaVersion: "0.2",
347
+ eventId,
348
+ runId: event.runId,
349
+ kind: mapStepTypeToInspectKind(event.type),
350
+ name: event.name,
351
+ status: "running",
352
+ timestamp: tsMain.iso,
353
+ startedAt: tsStart.iso,
354
+ confidence: "explicit",
355
+ source,
356
+ attributes
357
+ };
358
+ if (event.parentId !== void 0) {
359
+ out.parentId = event.parentId;
360
+ }
361
+ if (tokenUsage !== void 0) {
362
+ out.tokenUsage = tokenUsage;
363
+ }
364
+ return out;
365
+ }
366
+ case "step_completed": {
367
+ const tsEnd = toIsoTimestamp(event.endTime);
368
+ const { persisted: error, errorStack } = mapErrorInfo(event.error);
369
+ const attributes = compactAttributes({
370
+ legacyEvent: "step_completed",
371
+ stepId: event.stepId,
372
+ errorStack,
373
+ invalidTimestamp: tsMain.invalidTimestamp || tsEnd.invalidTimestamp ? true : void 0
374
+ });
375
+ return {
376
+ schemaVersion: "0.2",
377
+ eventId,
378
+ runId: event.runId,
379
+ kind: "LOGIC",
380
+ name: event.stepId,
381
+ status: mapRunOrStepStatus(event.status),
382
+ timestamp: tsMain.iso,
383
+ endedAt: tsEnd.iso,
384
+ durationMs: event.durationMs,
385
+ confidence: "explicit",
386
+ source,
387
+ attributes,
388
+ error
389
+ };
390
+ }
391
+ default: {
392
+ const _exhaustive = event;
393
+ throw new Error(`Unsupported trace event: ${_exhaustive.event}`);
394
+ }
395
+ }
396
+ }
397
+ function traceEventsToPersistedInspectEvents(events, options) {
398
+ return events.map(
399
+ (event, index) => traceEventToPersistedInspectEvent(event, { ...options, eventIndex: index })
400
+ );
401
+ }
402
+
403
+ // packages/core/src/persisted/from-inspect-event.ts
404
+ function sanitizeIdPart2(value) {
405
+ return value.replace(/[^a-zA-Z0-9_-]/g, "_");
406
+ }
407
+ function createFallbackEventId(event, eventIndex) {
408
+ const runId = sanitizeIdPart2(event.runId);
409
+ const kind = sanitizeIdPart2(event.kind);
410
+ const name = sanitizeIdPart2(event.name);
411
+ return `inspect:${runId}:${kind}:${name}:${eventIndex}`;
412
+ }
413
+ function toIsoTimestamp2(ms) {
414
+ if (typeof ms !== "number" || !Number.isFinite(ms)) {
415
+ return { iso: (/* @__PURE__ */ new Date(0)).toISOString(), invalidTimestamp: true };
416
+ }
417
+ return { iso: new Date(ms).toISOString(), invalidTimestamp: false };
418
+ }
419
+ function compactAttributes2(entries) {
420
+ const out = {};
421
+ for (const [key, value] of Object.entries(entries)) {
422
+ if (value !== void 0) {
423
+ out[key] = value;
424
+ }
425
+ }
426
+ return Object.keys(out).length > 0 ? out : void 0;
427
+ }
428
+ function mapInspectSourceToPersisted(source, options) {
429
+ const name = options?.sourceName;
430
+ const version = options?.sourceVersion;
431
+ switch (source.type) {
432
+ case "pino":
433
+ return {
434
+ persistedSource: {
435
+ type: "json-log",
436
+ name: name ?? "pino",
437
+ version
438
+ },
439
+ originalSourceType: "pino"
440
+ };
441
+ case "winston":
442
+ return {
443
+ persistedSource: {
444
+ type: "json-log",
445
+ name: name ?? "winston",
446
+ version
447
+ },
448
+ originalSourceType: "winston"
449
+ };
450
+ case "manual":
451
+ case "json-log":
452
+ case "log4js":
453
+ case "adapter":
454
+ return {
455
+ persistedSource: {
456
+ type: source.type,
457
+ name,
458
+ version
459
+ }
460
+ };
461
+ default:
462
+ return {
463
+ persistedSource: {
464
+ type: "json-log",
465
+ name,
466
+ version
467
+ }
468
+ };
469
+ }
470
+ }
471
+ function mapTokenUsageFromAttributes(attributes) {
472
+ const tokens = attributes?.tokens;
473
+ if (!tokens || typeof tokens !== "object" || Array.isArray(tokens)) {
474
+ return void 0;
475
+ }
476
+ const rec = tokens;
477
+ const input = typeof rec.input === "number" && Number.isFinite(rec.input) && rec.input >= 0 ? rec.input : void 0;
478
+ const output = typeof rec.output === "number" && Number.isFinite(rec.output) && rec.output >= 0 ? rec.output : void 0;
479
+ if (input === void 0 && output === void 0) {
480
+ return void 0;
481
+ }
482
+ const usage = {};
483
+ if (input !== void 0) usage.input = input;
484
+ if (output !== void 0) usage.output = output;
485
+ if (input !== void 0 && output !== void 0) {
486
+ usage.total = input + output;
487
+ }
488
+ return usage;
489
+ }
490
+ function mapErrorFromAttributes(event) {
491
+ if (event.status !== "error" || !event.attributes) {
492
+ return void 0;
493
+ }
494
+ const message = event.attributes.errorMessage;
495
+ if (typeof message !== "string" || message.length === 0) {
496
+ return void 0;
497
+ }
498
+ const err = { message };
499
+ if (typeof event.attributes.errorName === "string") {
500
+ err.name = event.attributes.errorName;
501
+ }
502
+ return err;
503
+ }
504
+ function inspectEventToPersistedInspectEvent(event, options) {
505
+ const eventIndex = options?.eventIndex ?? 0;
506
+ const eventId = typeof event.eventId === "string" && event.eventId.length > 0 ? event.eventId : createFallbackEventId(event, eventIndex);
507
+ const ts = toIsoTimestamp2(event.timestamp);
508
+ const { persistedSource, originalSourceType } = mapInspectSourceToPersisted(
509
+ event.source,
510
+ options
511
+ );
512
+ const attrsBase = event.attributes !== void 0 ? { ...event.attributes } : {};
513
+ const attributes = compactAttributes2({
514
+ ...attrsBase,
515
+ sourceFile: event.source.file,
516
+ sourceLine: event.source.line,
517
+ originalSourceType,
518
+ invalidTimestamp: ts.invalidTimestamp ? true : void 0
519
+ });
520
+ const tokenUsage = mapTokenUsageFromAttributes(event.attributes);
521
+ const error = mapErrorFromAttributes(event);
522
+ const inputPreview = event.attributes?.inputPreview;
523
+ const outputPreview = event.attributes?.outputPreview;
524
+ const out = {
525
+ schemaVersion: "0.2",
526
+ eventId,
527
+ runId: event.runId,
528
+ kind: event.kind,
529
+ name: event.name,
530
+ timestamp: ts.iso,
531
+ confidence: event.confidence,
532
+ source: persistedSource,
533
+ attributes
534
+ };
535
+ if (event.parentId !== void 0) {
536
+ out.parentId = event.parentId;
537
+ }
538
+ if (event.status !== void 0) {
539
+ out.status = event.status;
540
+ }
541
+ if (event.durationMs !== void 0 && Number.isFinite(event.durationMs) && event.durationMs >= 0) {
542
+ out.durationMs = event.durationMs;
543
+ }
544
+ if (tokenUsage !== void 0) {
545
+ out.tokenUsage = tokenUsage;
546
+ }
547
+ if (error !== void 0) {
548
+ out.error = error;
549
+ }
550
+ if (inputPreview !== void 0) {
551
+ out.inputSummary = inputPreview;
552
+ }
553
+ if (outputPreview !== void 0) {
554
+ out.outputSummary = outputPreview;
555
+ }
556
+ return out;
557
+ }
558
+ function inspectEventsToPersistedInspectEvents(events, options) {
559
+ return events.map(
560
+ (event, index) => inspectEventToPersistedInspectEvent(event, { ...options, eventIndex: index })
561
+ );
562
+ }
563
+
564
+ // packages/core/src/persisted/to-inspect-event.ts
565
+ function compactAttributes3(entries) {
566
+ const out = {};
567
+ for (const [key, value] of Object.entries(entries)) {
568
+ if (value !== void 0) {
569
+ out[key] = value;
570
+ }
571
+ }
572
+ return Object.keys(out).length > 0 ? out : void 0;
573
+ }
574
+ function parseIsoToMs(iso) {
575
+ const parsed = Date.parse(iso);
576
+ if (!Number.isFinite(parsed)) {
577
+ return { ms: 0, invalidTimestamp: true };
578
+ }
579
+ return { ms: parsed, invalidTimestamp: false };
580
+ }
581
+ function mapPersistedSourceToInspect(event) {
582
+ const attrs = event.attributes ?? {};
583
+ const sourceName = event.source.name;
584
+ if (sourceName === "pino") {
585
+ return {
586
+ type: "pino",
587
+ file: typeof attrs.sourceFile === "string" ? attrs.sourceFile : void 0,
588
+ line: typeof attrs.sourceLine === "number" ? attrs.sourceLine : void 0
589
+ };
590
+ }
591
+ if (sourceName === "winston") {
592
+ return {
593
+ type: "winston",
594
+ file: typeof attrs.sourceFile === "string" ? attrs.sourceFile : void 0,
595
+ line: typeof attrs.sourceLine === "number" ? attrs.sourceLine : void 0
596
+ };
597
+ }
598
+ const mapType = (t) => {
599
+ switch (t) {
600
+ case "manual":
601
+ return "manual";
602
+ case "json-log":
603
+ return "json-log";
604
+ case "log4js":
605
+ return "log4js";
606
+ case "adapter":
607
+ case "ai-sdk":
608
+ case "otel":
609
+ return "adapter";
610
+ default:
611
+ return "json-log";
612
+ }
613
+ };
614
+ return {
615
+ type: mapType(event.source.type),
616
+ file: typeof attrs.sourceFile === "string" ? attrs.sourceFile : void 0,
617
+ line: typeof attrs.sourceLine === "number" ? attrs.sourceLine : void 0
618
+ };
619
+ }
620
+ function buildInspectAttributes(event) {
621
+ const attrs = event.attributes !== void 0 ? { ...event.attributes } : {};
622
+ if (event.inputSummary !== void 0) {
623
+ attrs.inputSummary = event.inputSummary;
624
+ }
625
+ if (event.outputSummary !== void 0) {
626
+ attrs.outputSummary = event.outputSummary;
627
+ }
628
+ if (event.error) {
629
+ if (event.error.name !== void 0) {
630
+ attrs.errorName = event.error.name;
631
+ }
632
+ attrs.errorMessage = event.error.message;
633
+ if (event.error.code !== void 0) {
634
+ attrs.errorCode = event.error.code;
635
+ }
636
+ }
637
+ if (event.tokenUsage) {
638
+ attrs.tokens = { ...event.tokenUsage };
639
+ }
640
+ if (event.source.type === "ai-sdk" || event.source.type === "otel") {
641
+ attrs.originalSourceType = event.source.type;
642
+ }
643
+ if (event.source.name !== void 0) {
644
+ attrs.sourceName = event.source.name;
645
+ }
646
+ if (event.source.version !== void 0) {
647
+ attrs.sourceVersion = event.source.version;
648
+ }
649
+ return attrs;
650
+ }
651
+ function persistedInspectEventToInspectEvent(event) {
652
+ if (!isPersistedInspectEvent(event)) {
653
+ throw new Error("Invalid PersistedInspectEvent: failed isPersistedInspectEvent");
654
+ }
655
+ const ts = parseIsoToMs(event.timestamp);
656
+ const attrs = buildInspectAttributes(event);
657
+ if (ts.invalidTimestamp) {
658
+ attrs.invalidTimestamp = true;
659
+ }
660
+ let status;
661
+ if (event.status === "running" || event.status === "ok" || event.status === "error") {
662
+ status = event.status;
663
+ } else if (event.status === "unknown") {
664
+ attrs.persistedStatus = "unknown";
665
+ }
666
+ const out = {
667
+ eventId: event.eventId,
668
+ runId: event.runId,
669
+ name: event.name,
670
+ kind: event.kind,
671
+ timestamp: ts.ms,
672
+ confidence: event.confidence,
673
+ source: mapPersistedSourceToInspect(event),
674
+ attributes: compactAttributes3(attrs)
675
+ };
676
+ if (event.parentId !== void 0) {
677
+ out.parentId = event.parentId;
678
+ }
679
+ if (status !== void 0) {
680
+ out.status = status;
681
+ }
682
+ if (event.durationMs !== void 0 && Number.isFinite(event.durationMs) && event.durationMs >= 0) {
683
+ out.durationMs = event.durationMs;
684
+ }
685
+ return out;
686
+ }
687
+ function persistedInspectEventsToInspectEvents(events, options) {
688
+ const skipInvalid = options?.skipInvalid === true;
689
+ const out = [];
690
+ for (const event of events) {
691
+ if (!isPersistedInspectEvent(event)) {
692
+ if (skipInvalid) {
693
+ continue;
694
+ }
695
+ throw new Error("Invalid PersistedInspectEvent: failed isPersistedInspectEvent");
696
+ }
697
+ out.push(persistedInspectEventToInspectEvent(event));
698
+ }
699
+ return out;
700
+ }
701
+
702
+ // packages/core/src/logs/tree-builder.ts
703
+ function inc(map, key) {
704
+ map[key] = (map[key] ?? 0) + 1;
705
+ }
706
+ function computeRunStatus(events) {
707
+ let hasRunning = false;
708
+ for (const e of events) {
709
+ if (e.status === "error") return "error";
710
+ if (e.status === "running") hasRunning = true;
711
+ }
712
+ if (hasRunning) return "running";
713
+ return "ok";
714
+ }
715
+ var TreeBuilder = class {
716
+ constructor(options) {
717
+ void options?.config;
718
+ }
719
+ build(events) {
720
+ const byRun = /* @__PURE__ */ new Map();
721
+ for (const e of events) {
722
+ if (!byRun.has(e.runId)) byRun.set(e.runId, []);
723
+ byRun.get(e.runId).push(e);
724
+ }
725
+ const out = [];
726
+ for (const [runId, runEvents] of byRun.entries()) {
727
+ const sorted = [...runEvents].sort((a, b) => a.timestamp - b.timestamp);
728
+ const nodes = /* @__PURE__ */ new Map();
729
+ for (const e of sorted) {
730
+ nodes.set(e.eventId, { event: e, children: [], depth: 0 });
731
+ }
732
+ const roots = [];
733
+ for (const node of nodes.values()) {
734
+ const parentId = node.event.parentId;
735
+ if (parentId && nodes.has(parentId)) {
736
+ nodes.get(parentId).children.push(node);
737
+ } else {
738
+ roots.push(node);
739
+ }
740
+ }
741
+ const assignDepth = (n, depth) => {
742
+ n.depth = depth;
743
+ for (const c of n.children) assignDepth(c, depth + 1);
744
+ };
745
+ for (const r of roots) assignDepth(r, 0);
746
+ const confidenceBreakdown = {
747
+ explicit: 0,
748
+ correlated: 0,
749
+ heuristic: 0,
750
+ unknown: 0
751
+ };
752
+ const kinds = {};
753
+ for (const e of sorted) {
754
+ inc(confidenceBreakdown, e.confidence);
755
+ kinds[e.kind] = (kinds[e.kind] ?? 0) + 1;
756
+ }
757
+ const startedAt = sorted.length > 0 ? sorted[0].timestamp : void 0;
758
+ const endedAt = sorted.length > 0 ? sorted[sorted.length - 1].timestamp : void 0;
759
+ const status = computeRunStatus(sorted);
760
+ const durationMs = startedAt !== void 0 && endedAt !== void 0 && Number.isFinite(startedAt) && Number.isFinite(endedAt) && endedAt >= startedAt && status !== "running" ? endedAt - startedAt : void 0;
761
+ const name = sorted.find((e) => e.kind === "RUN")?.name;
762
+ out.push({
763
+ runId,
764
+ name,
765
+ status,
766
+ startedAt,
767
+ endedAt: status === "running" ? void 0 : endedAt,
768
+ durationMs,
769
+ children: roots,
770
+ metadata: {
771
+ totalEvents: sorted.length,
772
+ confidenceBreakdown,
773
+ kinds
774
+ }
775
+ });
776
+ }
777
+ out.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));
778
+ return out;
779
+ }
780
+ };
781
+
782
+ // packages/core/src/persisted/tree-bridge.ts
783
+ function persistedInspectEventsToRunTrees(events, options) {
784
+ const inspectEvents = persistedInspectEventsToInspectEvents(events, {
785
+ skipInvalid: options?.skipInvalid
786
+ });
787
+ return new TreeBuilder().build(inspectEvents);
788
+ }
789
+ function traceEventsToPersistedRunTrees(events) {
790
+ const persisted = traceEventsToPersistedInspectEvents(events);
791
+ return persistedInspectEventsToRunTrees(persisted);
792
+ }
793
+ function isRecord3(v) {
58
794
  return typeof v === "object" && v !== null && !Array.isArray(v);
59
795
  }
60
796
  function isNonEmptyStringArray(v) {
@@ -66,7 +802,7 @@ function validateRedact(redact) {
66
802
  }
67
803
  for (const r of redact) {
68
804
  if (typeof r === "string") continue;
69
- if (!isRecord2(r)) {
805
+ if (!isRecord3(r)) {
70
806
  throw new Error("Invalid config: redact entries must be strings or objects");
71
807
  }
72
808
  if (typeof r.key !== "string" || r.key.trim() === "") {
@@ -85,7 +821,7 @@ function validateRedact(redact) {
85
821
  }
86
822
  }
87
823
  function validateMappings(mappings) {
88
- if (!isRecord2(mappings)) {
824
+ if (!isRecord3(mappings)) {
89
825
  throw new Error("Invalid config: mappings must be an object");
90
826
  }
91
827
  }
@@ -135,7 +871,7 @@ async function loadLogIngestConfig(configPath) {
135
871
  const msg = e instanceof Error ? e.message : String(e);
136
872
  throw new Error(`Invalid JSON in config file: ${configPath} (${msg})`);
137
873
  }
138
- if (!isRecord2(parsed)) {
874
+ if (!isRecord3(parsed)) {
139
875
  throw new Error("Invalid config: expected a JSON object at top-level");
140
876
  }
141
877
  const user = parsed;
@@ -172,7 +908,7 @@ async function loadLogIngestConfig(configPath) {
172
908
  }
173
909
  return mergeLogIngestConfig(DEFAULT_LOG_INGEST_CONFIG, user);
174
910
  }
175
- function isRecord3(v) {
911
+ function isRecord4(v) {
176
912
  return typeof v === "object" && v !== null && !Array.isArray(v);
177
913
  }
178
914
  var JsonLogParser = class {
@@ -197,7 +933,7 @@ var JsonLogParser = class {
197
933
  });
198
934
  continue;
199
935
  }
200
- if (!isRecord3(parsed)) {
936
+ if (!isRecord4(parsed)) {
201
937
  warnings.push({
202
938
  code: "MALFORMED_JSON",
203
939
  message: "JSON log line must be an object",
@@ -228,7 +964,7 @@ var JsonLogParser = class {
228
964
  return this.parseLines(lines, filePath);
229
965
  }
230
966
  };
231
- function isRecord4(v) {
967
+ function isRecord5(v) {
232
968
  return typeof v === "object" && v !== null && !Array.isArray(v);
233
969
  }
234
970
  function findLastJsonObjectSubstring(line) {
@@ -304,7 +1040,7 @@ var Log4jsParser = class {
304
1040
  });
305
1041
  continue;
306
1042
  }
307
- if (!isRecord4(parsed)) {
1043
+ if (!isRecord5(parsed)) {
308
1044
  warnings.push({
309
1045
  code: "UNSUPPORTED_LOG4JS_PAYLOAD",
310
1046
  message: "Embedded JSON payload must be an object",
@@ -382,7 +1118,7 @@ var DEFAULT_REDACT_KEYS = [
382
1118
  "secret",
383
1119
  "email"
384
1120
  ];
385
- function isRecord5(v) {
1121
+ function isRecord6(v) {
386
1122
  return typeof v === "object" && v !== null && !Array.isArray(v);
387
1123
  }
388
1124
  function toKey(s) {
@@ -450,7 +1186,7 @@ var Redactor = class {
450
1186
  if (Array.isArray(value)) {
451
1187
  return value.map((v) => this.#redactNested(v));
452
1188
  }
453
- if (isRecord5(value)) {
1189
+ if (isRecord6(value)) {
454
1190
  const out = {};
455
1191
  for (const [k, v] of Object.entries(value)) {
456
1192
  out[k] = this.redactValue(k, v);
@@ -460,6 +1196,36 @@ var Redactor = class {
460
1196
  return value;
461
1197
  }
462
1198
  };
1199
+
1200
+ // node_modules/.pnpm/nanoid@5.1.11/node_modules/nanoid/url-alphabet/index.js
1201
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
1202
+
1203
+ // node_modules/.pnpm/nanoid@5.1.11/node_modules/nanoid/index.js
1204
+ var POOL_SIZE_MULTIPLIER = 128;
1205
+ var pool;
1206
+ var poolOffset;
1207
+ function fillPool(bytes) {
1208
+ if (bytes < 0 || bytes > 1024) throw new RangeError("Wrong ID size");
1209
+ if (!pool || pool.length < bytes) {
1210
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
1211
+ webcrypto.getRandomValues(pool);
1212
+ poolOffset = 0;
1213
+ } else if (poolOffset + bytes > pool.length) {
1214
+ webcrypto.getRandomValues(pool);
1215
+ poolOffset = 0;
1216
+ }
1217
+ poolOffset += bytes;
1218
+ }
1219
+ function nanoid(size = 21) {
1220
+ fillPool(size |= 0);
1221
+ let id = "";
1222
+ for (let i = poolOffset - size; i < poolOffset; i++) {
1223
+ id += urlAlphabet[pool[i] & 63];
1224
+ }
1225
+ return id;
1226
+ }
1227
+
1228
+ // packages/core/src/logs/normalizer.ts
463
1229
  function isFiniteNumber(v) {
464
1230
  return typeof v === "number" && Number.isFinite(v);
465
1231
  }
@@ -640,86 +1406,6 @@ var EventNormalizer = class {
640
1406
  }
641
1407
  };
642
1408
 
643
- // packages/core/src/logs/tree-builder.ts
644
- function inc(map, key) {
645
- map[key] = (map[key] ?? 0) + 1;
646
- }
647
- function computeRunStatus(events) {
648
- let hasRunning = false;
649
- for (const e of events) {
650
- if (e.status === "error") return "error";
651
- if (e.status === "running") hasRunning = true;
652
- }
653
- if (hasRunning) return "running";
654
- return "ok";
655
- }
656
- var TreeBuilder = class {
657
- constructor(options) {
658
- void options?.config;
659
- }
660
- build(events) {
661
- const byRun = /* @__PURE__ */ new Map();
662
- for (const e of events) {
663
- if (!byRun.has(e.runId)) byRun.set(e.runId, []);
664
- byRun.get(e.runId).push(e);
665
- }
666
- const out = [];
667
- for (const [runId, runEvents] of byRun.entries()) {
668
- const sorted = [...runEvents].sort((a, b) => a.timestamp - b.timestamp);
669
- const nodes = /* @__PURE__ */ new Map();
670
- for (const e of sorted) {
671
- nodes.set(e.eventId, { event: e, children: [], depth: 0 });
672
- }
673
- const roots = [];
674
- for (const node of nodes.values()) {
675
- const parentId = node.event.parentId;
676
- if (parentId && nodes.has(parentId)) {
677
- nodes.get(parentId).children.push(node);
678
- } else {
679
- roots.push(node);
680
- }
681
- }
682
- const assignDepth = (n, depth) => {
683
- n.depth = depth;
684
- for (const c of n.children) assignDepth(c, depth + 1);
685
- };
686
- for (const r of roots) assignDepth(r, 0);
687
- const confidenceBreakdown = {
688
- explicit: 0,
689
- correlated: 0,
690
- heuristic: 0,
691
- unknown: 0
692
- };
693
- const kinds = {};
694
- for (const e of sorted) {
695
- inc(confidenceBreakdown, e.confidence);
696
- kinds[e.kind] = (kinds[e.kind] ?? 0) + 1;
697
- }
698
- const startedAt = sorted.length > 0 ? sorted[0].timestamp : void 0;
699
- const endedAt = sorted.length > 0 ? sorted[sorted.length - 1].timestamp : void 0;
700
- const status = computeRunStatus(sorted);
701
- const durationMs = startedAt !== void 0 && endedAt !== void 0 && Number.isFinite(startedAt) && Number.isFinite(endedAt) && endedAt >= startedAt && status !== "running" ? endedAt - startedAt : void 0;
702
- const name = sorted.find((e) => e.kind === "RUN")?.name;
703
- out.push({
704
- runId,
705
- name,
706
- status,
707
- startedAt,
708
- endedAt: status === "running" ? void 0 : endedAt,
709
- durationMs,
710
- children: roots,
711
- metadata: {
712
- totalEvents: sorted.length,
713
- confidenceBreakdown,
714
- kinds
715
- }
716
- });
717
- }
718
- out.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));
719
- return out;
720
- }
721
- };
722
-
723
1409
  // packages/core/src/logs/tree-renderer.ts
724
1410
  function truncate(v, max) {
725
1411
  if (v.length <= max) return v;
@@ -1142,168 +1828,38 @@ function formatError(error) {
1142
1828
  return { message: "Unknown error: undefined" };
1143
1829
  }
1144
1830
  if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") {
1145
- return { message: String(error) };
1146
- }
1147
- if (typeof error === "object") {
1148
- try {
1149
- return { message: JSON.stringify(error) };
1150
- } catch {
1151
- return { message: "Unknown error" };
1152
- }
1153
- }
1154
- return { message: "Unknown error" };
1155
- }
1156
- function truncateName(name, maxLength = MAX_NAME_LENGTH) {
1157
- if (typeof name !== "string" || name.trim() === "") {
1158
- return "unnamed";
1159
- }
1160
- const trimmed = name.trim();
1161
- if (trimmed.length <= maxLength) {
1162
- return trimmed;
1163
- }
1164
- const ellipsis = "...";
1165
- const head = Math.max(0, maxLength - ellipsis.length);
1166
- return `${trimmed.slice(0, head)}${ellipsis}`;
1167
- }
1168
- function warn(message, error) {
1169
- const base = `[AgentInspect] ${message}`;
1170
- if (error === void 0) {
1171
- console.warn(base);
1172
- return;
1173
- }
1174
- console.warn(`${base}: ${formatError(error).message}`);
1175
- }
1176
- var storage = new AsyncLocalStorage();
1177
- function toPublicContext(ctx) {
1178
- return {
1179
- runId: ctx.runId,
1180
- runName: ctx.runName,
1181
- traceDir: ctx.traceDir,
1182
- silent: ctx.silent,
1183
- metadata: ctx.metadata
1184
- };
1185
- }
1186
- function invoke(fn) {
1187
- return new Promise((resolve, reject) => {
1188
- try {
1189
- Promise.resolve(fn()).then(resolve, reject);
1190
- } catch (e) {
1191
- reject(e);
1192
- }
1193
- });
1194
- }
1195
- function getCurrentContext() {
1196
- try {
1197
- const s = storage.getStore();
1198
- if (!s) return void 0;
1199
- return toPublicContext(s);
1200
- } catch {
1201
- return void 0;
1202
- }
1203
- }
1204
- function getCurrentRunId() {
1205
- try {
1206
- return storage.getStore()?.runId;
1207
- } catch {
1208
- return void 0;
1209
- }
1210
- }
1211
- function getCurrentRunName() {
1212
- try {
1213
- return storage.getStore()?.runName;
1214
- } catch {
1215
- return void 0;
1216
- }
1217
- }
1218
- function getCurrentStepId() {
1219
- try {
1220
- return storage.getStore()?.currentStepId;
1221
- } catch {
1222
- return void 0;
1223
- }
1224
- }
1225
- function getParentStepId() {
1226
- return getCurrentStepId();
1227
- }
1228
- function getCurrentDepth() {
1229
- try {
1230
- const d = storage.getStore()?.currentDepth;
1231
- return typeof d === "number" && Number.isFinite(d) ? d : 0;
1232
- } catch {
1233
- return 0;
1234
- }
1235
- }
1236
- function hasActiveContext() {
1237
- try {
1238
- return storage.getStore() !== void 0;
1239
- } catch {
1240
- return false;
1831
+ return { message: String(error) };
1241
1832
  }
1242
- }
1243
- function getTraceDirFromContext() {
1244
- try {
1245
- return storage.getStore()?.traceDir;
1246
- } catch {
1247
- return void 0;
1833
+ if (typeof error === "object") {
1834
+ try {
1835
+ return { message: JSON.stringify(error) };
1836
+ } catch {
1837
+ return { message: "Unknown error" };
1838
+ }
1248
1839
  }
1840
+ return { message: "Unknown error" };
1249
1841
  }
1250
- function isSilentContext() {
1251
- try {
1252
- const s = storage.getStore();
1253
- return s ? s.silent : false;
1254
- } catch {
1255
- return false;
1842
+ function truncateName(name, maxLength = MAX_NAME_LENGTH) {
1843
+ if (typeof name !== "string" || name.trim() === "") {
1844
+ return "unnamed";
1256
1845
  }
1257
- }
1258
- function runWithContext(context, fn) {
1259
- const runtime = {
1260
- runId: context.runId,
1261
- runName: context.runName,
1262
- traceDir: context.traceDir,
1263
- silent: context.silent,
1264
- metadata: context.metadata,
1265
- currentDepth: 0
1266
- };
1267
- return new Promise((resolve, reject) => {
1268
- storage.run(runtime, () => {
1269
- try {
1270
- Promise.resolve(fn()).then(resolve, reject);
1271
- } catch (e) {
1272
- reject(e);
1273
- }
1274
- });
1275
- });
1276
- }
1277
- function runWithStepContext(stepId, fn) {
1278
- let parent;
1279
- try {
1280
- parent = storage.getStore();
1281
- } catch {
1282
- parent = void 0;
1846
+ const trimmed = name.trim();
1847
+ if (trimmed.length <= maxLength) {
1848
+ return trimmed;
1283
1849
  }
1284
- if (!parent) {
1285
- return invoke(fn);
1850
+ const ellipsis = "...";
1851
+ const head = Math.max(0, maxLength - ellipsis.length);
1852
+ return `${trimmed.slice(0, head)}${ellipsis}`;
1853
+ }
1854
+ function warn(message, error) {
1855
+ const base = `[AgentInspect] ${message}`;
1856
+ if (error === void 0) {
1857
+ console.warn(base);
1858
+ return;
1286
1859
  }
1287
- const derived = {
1288
- runId: parent.runId,
1289
- runName: parent.runName,
1290
- traceDir: parent.traceDir,
1291
- silent: parent.silent,
1292
- metadata: parent.metadata,
1293
- currentStepId: stepId,
1294
- currentDepth: parent.currentDepth + 1
1295
- };
1296
- return new Promise((resolve, reject) => {
1297
- storage.run(derived, () => {
1298
- try {
1299
- Promise.resolve(fn()).then(resolve, reject);
1300
- } catch (e) {
1301
- reject(e);
1302
- }
1303
- });
1304
- });
1860
+ console.warn(`${base}: ${formatError(error).message}`);
1305
1861
  }
1306
- function isRecord6(value) {
1862
+ function isRecord7(value) {
1307
1863
  return typeof value === "object" && value !== null && !Array.isArray(value);
1308
1864
  }
1309
1865
  function nonEmptyString(value) {
@@ -1314,7 +1870,7 @@ function finiteNumber(value) {
1314
1870
  }
1315
1871
  function optionalErrorInfo(value) {
1316
1872
  if (value === void 0) return true;
1317
- if (!isRecord6(value)) return false;
1873
+ if (!isRecord7(value)) return false;
1318
1874
  if (typeof value.message !== "string") return false;
1319
1875
  if ("stack" in value && value.stack !== void 0) {
1320
1876
  if (typeof value.stack !== "string") return false;
@@ -1322,7 +1878,7 @@ function optionalErrorInfo(value) {
1322
1878
  return true;
1323
1879
  }
1324
1880
  function validateEvent(event) {
1325
- if (!isRecord6(event)) return false;
1881
+ if (!isRecord7(event)) return false;
1326
1882
  if (event.schemaVersion !== "0.1") return false;
1327
1883
  if (!finiteNumber(event.timestamp)) return false;
1328
1884
  if (typeof event.event !== "string") return false;
@@ -1331,7 +1887,7 @@ function validateEvent(event) {
1331
1887
  if (!nonEmptyString(event.runId) || !nonEmptyString(event.name) || !finiteNumber(event.startTime)) {
1332
1888
  return false;
1333
1889
  }
1334
- if (event.metadata !== void 0 && !isRecord6(event.metadata)) {
1890
+ if (event.metadata !== void 0 && !isRecord7(event.metadata)) {
1335
1891
  return false;
1336
1892
  }
1337
1893
  return true;
@@ -1346,7 +1902,7 @@ function validateEvent(event) {
1346
1902
  if (event.parentId !== void 0 && typeof event.parentId !== "string") {
1347
1903
  return false;
1348
1904
  }
1349
- if (event.metadata !== void 0 && !isRecord6(event.metadata)) {
1905
+ if (event.metadata !== void 0 && !isRecord7(event.metadata)) {
1350
1906
  return false;
1351
1907
  }
1352
1908
  return true;
@@ -1384,12 +1940,20 @@ async function initializeTraceFile(runId, traceDir) {
1384
1940
  return void 0;
1385
1941
  }
1386
1942
  }
1943
+ function ensureEventWithinBounds(event) {
1944
+ const line = serializeEvent(event);
1945
+ if (line === "") return event;
1946
+ const bytes = Buffer.byteLength(line, "utf8");
1947
+ if (bytes <= DEFAULT_MAX_EVENT_BYTES) return event;
1948
+ return prepareTraceEventForDisk(event, resolveTraceSafetyOptions());
1949
+ }
1387
1950
  async function writeTraceEvent(event, traceDir) {
1388
- if (!validateEvent(event)) {
1951
+ const bounded = ensureEventWithinBounds(event);
1952
+ if (!validateEvent(bounded)) {
1389
1953
  warn("Skipped invalid trace event (validation failed)");
1390
1954
  return;
1391
1955
  }
1392
- const line = serializeEvent(event);
1956
+ const line = serializeEvent(bounded);
1393
1957
  if (line === "") {
1394
1958
  warn("Skipped trace event (serialization failed)");
1395
1959
  return;
@@ -1409,87 +1973,432 @@ async function writeTraceEvent(event, traceDir) {
1409
1973
  if (await tryAppend(traceDir)) {
1410
1974
  return;
1411
1975
  }
1412
- warn(`Failed to append trace event for run ${event.runId}`);
1413
- if (await tryAppend(FALLBACK_TRACE_DIR)) {
1414
- return;
1976
+ warn(`Failed to append trace event for run ${event.runId}`);
1977
+ if (await tryAppend(FALLBACK_TRACE_DIR)) {
1978
+ return;
1979
+ }
1980
+ warn("Failed to append trace event to fallback directory");
1981
+ }
1982
+ async function readTraceFile(runId, traceDir) {
1983
+ try {
1984
+ const filePath = getTraceFilePath(runId, traceDir);
1985
+ return await readFile(filePath, "utf-8");
1986
+ } catch (e) {
1987
+ if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") {
1988
+ return void 0;
1989
+ }
1990
+ warn("Unexpected error reading trace file", e);
1991
+ return void 0;
1992
+ }
1993
+ }
1994
+ async function readTraceEvents(runId, traceDir) {
1995
+ const out = [];
1996
+ try {
1997
+ const raw = await readTraceFile(runId, traceDir);
1998
+ if (raw === void 0) {
1999
+ return out;
2000
+ }
2001
+ const lines = raw.split("\n");
2002
+ for (const line of lines) {
2003
+ const trimmed = line.trim();
2004
+ if (trimmed === "") continue;
2005
+ let parsed;
2006
+ try {
2007
+ parsed = JSON.parse(trimmed);
2008
+ } catch {
2009
+ warn("Skipped invalid JSON line in trace file");
2010
+ continue;
2011
+ }
2012
+ if (validateEvent(parsed)) {
2013
+ out.push(parsed);
2014
+ } else {
2015
+ warn("Skipped invalid trace event line in trace file");
2016
+ }
2017
+ }
2018
+ } catch (e) {
2019
+ warn("Failed to read trace events", e);
2020
+ }
2021
+ return out;
2022
+ }
2023
+ async function listTraceFiles(traceDir) {
2024
+ try {
2025
+ const usable = path.resolve(traceDir);
2026
+ const names = await readdir(usable);
2027
+ const jsonl = names.filter((n) => n.endsWith(".jsonl"));
2028
+ const withStat = await Promise.all(
2029
+ jsonl.map(async (name) => {
2030
+ try {
2031
+ const st = await stat(path.join(usable, name));
2032
+ return { name, mtime: st.mtimeMs };
2033
+ } catch {
2034
+ return { name, mtime: 0 };
2035
+ }
2036
+ })
2037
+ );
2038
+ withStat.sort((a, b) => {
2039
+ if (b.mtime !== a.mtime) return b.mtime - a.mtime;
2040
+ return a.name.localeCompare(b.name);
2041
+ });
2042
+ return withStat.map((x) => x.name);
2043
+ } catch {
2044
+ return [];
2045
+ }
2046
+ }
2047
+ function getRunIdFromTraceFileName(fileName) {
2048
+ try {
2049
+ const base = path.basename(fileName);
2050
+ if (!base.endsWith(".jsonl")) return void 0;
2051
+ const id = base.slice(0, -".jsonl".length);
2052
+ return id === "" ? void 0 : id;
2053
+ } catch {
2054
+ return void 0;
2055
+ }
2056
+ }
2057
+
2058
+ // packages/core/src/trace-event-safety.ts
2059
+ var DEFAULT_MAX_METADATA_VALUE_LENGTH = 2e3;
2060
+ var DEFAULT_MAX_PREVIEW_LENGTH = 500;
2061
+ var DEFAULT_MAX_EVENT_BYTES = 65536;
2062
+ function isRecord8(value) {
2063
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2064
+ }
2065
+ function isPreviewKey(key) {
2066
+ return key.toLowerCase().includes("preview");
2067
+ }
2068
+ function truncateString(value, maxLen) {
2069
+ if (maxLen <= 0) return "\u2026";
2070
+ if (value.length <= maxLen) return value;
2071
+ return `${value.slice(0, maxLen)}\u2026`;
2072
+ }
2073
+ function byteLength(text) {
2074
+ return Buffer.byteLength(text, "utf8");
2075
+ }
2076
+ function resolveTraceSafetyOptions(options) {
2077
+ const redact = options?.redact;
2078
+ let redactEnabled = true;
2079
+ let redactionRules;
2080
+ if (redact === false) {
2081
+ redactEnabled = false;
2082
+ } else if (redact === true || redact === void 0) {
2083
+ redactEnabled = true;
2084
+ } else if (isRecord8(redact)) {
2085
+ redactEnabled = true;
2086
+ redactionRules = redact.rules;
2087
+ }
2088
+ return {
2089
+ redactEnabled,
2090
+ redactionRules,
2091
+ maxMetadataValueLength: typeof options?.maxMetadataValueLength === "number" && Number.isFinite(options.maxMetadataValueLength) && options.maxMetadataValueLength >= 0 ? Math.floor(options.maxMetadataValueLength) : DEFAULT_MAX_METADATA_VALUE_LENGTH,
2092
+ maxPreviewLength: typeof options?.maxPreviewLength === "number" && Number.isFinite(options.maxPreviewLength) && options.maxPreviewLength >= 0 ? Math.floor(options.maxPreviewLength) : DEFAULT_MAX_PREVIEW_LENGTH,
2093
+ maxEventBytes: typeof options?.maxEventBytes === "number" && Number.isFinite(options.maxEventBytes) && options.maxEventBytes > 0 ? Math.floor(options.maxEventBytes) : DEFAULT_MAX_EVENT_BYTES
2094
+ };
2095
+ }
2096
+ function boundMetadataValue(key, value, opts, seen, depth) {
2097
+ if (depth > 32) return "[MaxDepth]";
2098
+ if (value === null || typeof value !== "object") {
2099
+ if (typeof value === "string") {
2100
+ const max = isPreviewKey(key) ? opts.maxPreviewLength : opts.maxMetadataValueLength;
2101
+ return truncateString(value, max);
2102
+ }
2103
+ return value;
2104
+ }
2105
+ if (seen.has(value)) return "[Circular]";
2106
+ seen.add(value);
2107
+ if (Array.isArray(value)) {
2108
+ const maxItems = 50;
2109
+ const out2 = value.slice(0, maxItems).map(
2110
+ (item, index) => boundMetadataValue(String(index), item, opts, seen, depth + 1)
2111
+ );
2112
+ if (value.length > maxItems) {
2113
+ out2.push(`\u2026(+${value.length - maxItems} more)`);
2114
+ }
2115
+ return out2;
2116
+ }
2117
+ const record = value;
2118
+ const out = {};
2119
+ for (const [k, v] of Object.entries(record)) {
2120
+ out[k] = boundMetadataValue(k, v, opts, seen, depth + 1);
2121
+ }
2122
+ return out;
2123
+ }
2124
+ function redactMetadata(metadata, opts) {
2125
+ if (!opts.redactEnabled) return { ...metadata };
2126
+ const redactor = new Redactor({ rules: opts.redactionRules });
2127
+ return redactor.redactRecord(metadata);
2128
+ }
2129
+ function prepareMetadataForDisk(metadata, opts) {
2130
+ try {
2131
+ const redacted = redactMetadata(metadata, opts);
2132
+ const seen = /* @__PURE__ */ new WeakSet();
2133
+ const bounded = boundMetadataValue(
2134
+ "metadata",
2135
+ redacted,
2136
+ opts,
2137
+ seen,
2138
+ 0
2139
+ );
2140
+ return isRecord8(bounded) ? bounded : {};
2141
+ } catch {
2142
+ return { truncated: true, reason: "metadataPreparationFailed" };
2143
+ }
2144
+ }
2145
+ function truncateErrorStack(event, maxLen) {
2146
+ if (event.event !== "run_completed" && event.event !== "step_completed") {
2147
+ return event;
2148
+ }
2149
+ if (!event.error?.stack || typeof event.error.stack !== "string") {
2150
+ return event;
2151
+ }
2152
+ return {
2153
+ ...event,
2154
+ error: {
2155
+ ...event.error,
2156
+ stack: truncateString(event.error.stack, maxLen)
2157
+ }
2158
+ };
2159
+ }
2160
+ function replaceMetadataWithTruncationMarker(event, originalApproxBytes) {
2161
+ const marker = {
2162
+ truncated: true,
2163
+ reason: "maxEventBytes",
2164
+ originalApproxBytes
2165
+ };
2166
+ if (event.event === "run_started") {
2167
+ return { ...event, metadata: marker };
2168
+ }
2169
+ if (event.event === "step_started") {
2170
+ return { ...event, metadata: marker };
2171
+ }
2172
+ return event;
2173
+ }
2174
+ function shrinkMetadataLimits(opts, factor) {
2175
+ return {
2176
+ ...opts,
2177
+ maxMetadataValueLength: Math.max(32, Math.floor(opts.maxMetadataValueLength * factor)),
2178
+ maxPreviewLength: Math.max(16, Math.floor(opts.maxPreviewLength * factor))
2179
+ };
2180
+ }
2181
+ function applyMetadataToEvent(event, metadata) {
2182
+ if (event.event === "run_started") {
2183
+ return { ...event, metadata };
2184
+ }
2185
+ if (event.event === "step_started") {
2186
+ return { ...event, metadata };
2187
+ }
2188
+ return event;
2189
+ }
2190
+ function eventHasMetadata(event) {
2191
+ return (event.event === "run_started" || event.event === "step_started") && event.metadata !== void 0;
2192
+ }
2193
+ function getEventMetadata(event) {
2194
+ if (event.event === "run_started" || event.event === "step_started") {
2195
+ return event.metadata;
2196
+ }
2197
+ return void 0;
2198
+ }
2199
+ function prepareTraceEventForDisk(event, opts) {
2200
+ try {
2201
+ let working = { ...event };
2202
+ const rawMetadata = getEventMetadata(working);
2203
+ if (rawMetadata !== void 0) {
2204
+ const safe = prepareMetadataForDisk(rawMetadata, opts);
2205
+ working = applyMetadataToEvent(working, safe);
2206
+ }
2207
+ let serialized = serializeEvent(working);
2208
+ if (serialized === "") {
2209
+ return working;
2210
+ }
2211
+ let bytes = byteLength(serialized);
2212
+ if (bytes <= opts.maxEventBytes) {
2213
+ return working;
2214
+ }
2215
+ if (rawMetadata !== void 0) {
2216
+ for (const factor of [0.5, 0.25, 0.1]) {
2217
+ const tighter = shrinkMetadataLimits(opts, factor);
2218
+ const shrunk = prepareMetadataForDisk(rawMetadata, tighter);
2219
+ working = applyMetadataToEvent(working, shrunk);
2220
+ serialized = serializeEvent(working);
2221
+ if (serialized !== "" && byteLength(serialized) <= opts.maxEventBytes) {
2222
+ return working;
2223
+ }
2224
+ }
2225
+ working = replaceMetadataWithTruncationMarker(working, bytes);
2226
+ serialized = serializeEvent(working);
2227
+ if (serialized !== "" && byteLength(serialized) <= opts.maxEventBytes) {
2228
+ return working;
2229
+ }
2230
+ }
2231
+ working = truncateErrorStack(working, Math.min(opts.maxMetadataValueLength, 500));
2232
+ serialized = serializeEvent(working);
2233
+ if (serialized !== "" && byteLength(serialized) <= opts.maxEventBytes) {
2234
+ return working;
2235
+ }
2236
+ if (eventHasMetadata(working)) {
2237
+ working = replaceMetadataWithTruncationMarker(working, bytes);
2238
+ serialized = serializeEvent(working);
2239
+ if (serialized !== "" && byteLength(serialized) <= opts.maxEventBytes) {
2240
+ return working;
2241
+ }
2242
+ if (working.event === "run_started") {
2243
+ const { metadata: _meta, ...rest } = working;
2244
+ working = rest;
2245
+ } else if (working.event === "step_started") {
2246
+ const { metadata: _meta, ...rest } = working;
2247
+ working = rest;
2248
+ }
2249
+ }
2250
+ return working;
2251
+ } catch {
2252
+ if (event.event === "run_started" || event.event === "step_started") {
2253
+ return applyMetadataToEvent(event, {
2254
+ truncated: true,
2255
+ reason: "prepareTraceEventFailed"
2256
+ });
2257
+ }
2258
+ return event;
2259
+ }
2260
+ }
2261
+
2262
+ // packages/core/src/context.ts
2263
+ var storage = new AsyncLocalStorage();
2264
+ function toPublicContext(ctx) {
2265
+ return {
2266
+ runId: ctx.runId,
2267
+ runName: ctx.runName,
2268
+ traceDir: ctx.traceDir,
2269
+ silent: ctx.silent,
2270
+ metadata: ctx.metadata
2271
+ };
2272
+ }
2273
+ function invoke(fn) {
2274
+ return new Promise((resolve, reject) => {
2275
+ try {
2276
+ Promise.resolve(fn()).then(resolve, reject);
2277
+ } catch (e) {
2278
+ reject(e);
2279
+ }
2280
+ });
2281
+ }
2282
+ function getCurrentContext() {
2283
+ try {
2284
+ const s = storage.getStore();
2285
+ if (!s) return void 0;
2286
+ return toPublicContext(s);
2287
+ } catch {
2288
+ return void 0;
2289
+ }
2290
+ }
2291
+ function getCurrentRunId() {
2292
+ try {
2293
+ return storage.getStore()?.runId;
2294
+ } catch {
2295
+ return void 0;
2296
+ }
2297
+ }
2298
+ function getCurrentRunName() {
2299
+ try {
2300
+ return storage.getStore()?.runName;
2301
+ } catch {
2302
+ return void 0;
1415
2303
  }
1416
- warn("Failed to append trace event to fallback directory");
1417
2304
  }
1418
- async function readTraceFile(runId, traceDir) {
2305
+ function getCurrentStepId() {
1419
2306
  try {
1420
- const filePath = getTraceFilePath(runId, traceDir);
1421
- return await readFile(filePath, "utf-8");
1422
- } catch (e) {
1423
- if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") {
1424
- return void 0;
1425
- }
1426
- warn("Unexpected error reading trace file", e);
2307
+ return storage.getStore()?.currentStepId;
2308
+ } catch {
1427
2309
  return void 0;
1428
2310
  }
1429
2311
  }
1430
- async function readTraceEvents(runId, traceDir) {
1431
- const out = [];
2312
+ function getParentStepId() {
2313
+ return getCurrentStepId();
2314
+ }
2315
+ function getCurrentDepth() {
1432
2316
  try {
1433
- const raw = await readTraceFile(runId, traceDir);
1434
- if (raw === void 0) {
1435
- return out;
1436
- }
1437
- const lines = raw.split("\n");
1438
- for (const line of lines) {
1439
- const trimmed = line.trim();
1440
- if (trimmed === "") continue;
1441
- let parsed;
1442
- try {
1443
- parsed = JSON.parse(trimmed);
1444
- } catch {
1445
- warn("Skipped invalid JSON line in trace file");
1446
- continue;
1447
- }
1448
- if (validateEvent(parsed)) {
1449
- out.push(parsed);
1450
- } else {
1451
- warn("Skipped invalid trace event line in trace file");
1452
- }
1453
- }
1454
- } catch (e) {
1455
- warn("Failed to read trace events", e);
2317
+ const d = storage.getStore()?.currentDepth;
2318
+ return typeof d === "number" && Number.isFinite(d) ? d : 0;
2319
+ } catch {
2320
+ return 0;
1456
2321
  }
1457
- return out;
1458
2322
  }
1459
- async function listTraceFiles(traceDir) {
2323
+ function hasActiveContext() {
1460
2324
  try {
1461
- const usable = path.resolve(traceDir);
1462
- const names = await readdir(usable);
1463
- const jsonl = names.filter((n) => n.endsWith(".jsonl"));
1464
- const withStat = await Promise.all(
1465
- jsonl.map(async (name) => {
1466
- try {
1467
- const st = await stat(path.join(usable, name));
1468
- return { name, mtime: st.mtimeMs };
1469
- } catch {
1470
- return { name, mtime: 0 };
1471
- }
1472
- })
1473
- );
1474
- withStat.sort((a, b) => {
1475
- if (b.mtime !== a.mtime) return b.mtime - a.mtime;
1476
- return a.name.localeCompare(b.name);
1477
- });
1478
- return withStat.map((x) => x.name);
2325
+ return storage.getStore() !== void 0;
1479
2326
  } catch {
1480
- return [];
2327
+ return false;
1481
2328
  }
1482
2329
  }
1483
- function getRunIdFromTraceFileName(fileName) {
2330
+ function getTraceDirFromContext() {
1484
2331
  try {
1485
- const base = path.basename(fileName);
1486
- if (!base.endsWith(".jsonl")) return void 0;
1487
- const id = base.slice(0, -".jsonl".length);
1488
- return id === "" ? void 0 : id;
2332
+ return storage.getStore()?.traceDir;
2333
+ } catch {
2334
+ return void 0;
2335
+ }
2336
+ }
2337
+ function isSilentContext() {
2338
+ try {
2339
+ const s = storage.getStore();
2340
+ return s ? s.silent : false;
2341
+ } catch {
2342
+ return false;
2343
+ }
2344
+ }
2345
+ function getTraceSafetyFromContext() {
2346
+ try {
2347
+ return storage.getStore()?.traceSafety;
1489
2348
  } catch {
1490
2349
  return void 0;
1491
2350
  }
1492
2351
  }
2352
+ function runWithContext(context, fn, traceSafety = resolveTraceSafetyOptions()) {
2353
+ const runtime = {
2354
+ runId: context.runId,
2355
+ runName: context.runName,
2356
+ traceDir: context.traceDir,
2357
+ silent: context.silent,
2358
+ metadata: context.metadata,
2359
+ traceSafety,
2360
+ currentDepth: 0
2361
+ };
2362
+ return new Promise((resolve, reject) => {
2363
+ storage.run(runtime, () => {
2364
+ try {
2365
+ Promise.resolve(fn()).then(resolve, reject);
2366
+ } catch (e) {
2367
+ reject(e);
2368
+ }
2369
+ });
2370
+ });
2371
+ }
2372
+ function runWithStepContext(stepId, fn) {
2373
+ let parent;
2374
+ try {
2375
+ parent = storage.getStore();
2376
+ } catch {
2377
+ parent = void 0;
2378
+ }
2379
+ if (!parent) {
2380
+ return invoke(fn);
2381
+ }
2382
+ const derived = {
2383
+ runId: parent.runId,
2384
+ runName: parent.runName,
2385
+ traceDir: parent.traceDir,
2386
+ silent: parent.silent,
2387
+ metadata: parent.metadata,
2388
+ traceSafety: parent.traceSafety,
2389
+ currentStepId: stepId,
2390
+ currentDepth: parent.currentDepth + 1
2391
+ };
2392
+ return new Promise((resolve, reject) => {
2393
+ storage.run(derived, () => {
2394
+ try {
2395
+ Promise.resolve(fn()).then(resolve, reject);
2396
+ } catch (e) {
2397
+ reject(e);
2398
+ }
2399
+ });
2400
+ });
2401
+ }
1493
2402
  function resolveTraceDir(options = {}) {
1494
2403
  if (typeof options.dir === "string" && options.dir.trim() !== "") {
1495
2404
  return options.dir.trim();
@@ -1754,7 +2663,7 @@ var KNOWN_EVENTS = /* @__PURE__ */ new Set([
1754
2663
  "step_started",
1755
2664
  "step_completed"
1756
2665
  ]);
1757
- function isRecord7(value) {
2666
+ function isRecord9(value) {
1758
2667
  return typeof value === "object" && value !== null && !Array.isArray(value);
1759
2668
  }
1760
2669
  function safeParse(line) {
@@ -1776,7 +2685,7 @@ async function isAgentInspectTrace(filePath) {
1776
2685
  if (trimmed === "") continue;
1777
2686
  const parsed = safeParse(trimmed);
1778
2687
  if (!parsed) continue;
1779
- if (!isRecord7(parsed)) continue;
2688
+ if (!isRecord9(parsed)) continue;
1780
2689
  checked += 1;
1781
2690
  if (isTraceEvent(parsed)) return true;
1782
2691
  const ev = parsed.event;
@@ -1939,7 +2848,7 @@ function stableJson(value, pretty) {
1939
2848
  const sorted = sortKeysDeep(value);
1940
2849
  return pretty === true ? JSON.stringify(sorted, null, 2) : JSON.stringify(sorted);
1941
2850
  }
1942
- function compactAttributes(attrs, options) {
2851
+ function compactAttributes4(attrs, options) {
1943
2852
  if (attrs === void 0) return {};
1944
2853
  const maxLen = options?.maxLength ?? 500;
1945
2854
  const redacted = options?.redacted ?? true;
@@ -2294,6 +3203,498 @@ function diffRuns(left, right, options) {
2294
3203
  };
2295
3204
  return { summary, differences };
2296
3205
  }
3206
+
3207
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
3208
+ var ANSI_BACKGROUND_OFFSET = 10;
3209
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
3210
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
3211
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
3212
+ var styles = {
3213
+ modifier: {
3214
+ reset: [0, 0],
3215
+ // 21 isn't widely supported and 22 does the same thing
3216
+ bold: [1, 22],
3217
+ dim: [2, 22],
3218
+ italic: [3, 23],
3219
+ underline: [4, 24],
3220
+ overline: [53, 55],
3221
+ inverse: [7, 27],
3222
+ hidden: [8, 28],
3223
+ strikethrough: [9, 29]
3224
+ },
3225
+ color: {
3226
+ black: [30, 39],
3227
+ red: [31, 39],
3228
+ green: [32, 39],
3229
+ yellow: [33, 39],
3230
+ blue: [34, 39],
3231
+ magenta: [35, 39],
3232
+ cyan: [36, 39],
3233
+ white: [37, 39],
3234
+ // Bright color
3235
+ blackBright: [90, 39],
3236
+ gray: [90, 39],
3237
+ // Alias of `blackBright`
3238
+ grey: [90, 39],
3239
+ // Alias of `blackBright`
3240
+ redBright: [91, 39],
3241
+ greenBright: [92, 39],
3242
+ yellowBright: [93, 39],
3243
+ blueBright: [94, 39],
3244
+ magentaBright: [95, 39],
3245
+ cyanBright: [96, 39],
3246
+ whiteBright: [97, 39]
3247
+ },
3248
+ bgColor: {
3249
+ bgBlack: [40, 49],
3250
+ bgRed: [41, 49],
3251
+ bgGreen: [42, 49],
3252
+ bgYellow: [43, 49],
3253
+ bgBlue: [44, 49],
3254
+ bgMagenta: [45, 49],
3255
+ bgCyan: [46, 49],
3256
+ bgWhite: [47, 49],
3257
+ // Bright color
3258
+ bgBlackBright: [100, 49],
3259
+ bgGray: [100, 49],
3260
+ // Alias of `bgBlackBright`
3261
+ bgGrey: [100, 49],
3262
+ // Alias of `bgBlackBright`
3263
+ bgRedBright: [101, 49],
3264
+ bgGreenBright: [102, 49],
3265
+ bgYellowBright: [103, 49],
3266
+ bgBlueBright: [104, 49],
3267
+ bgMagentaBright: [105, 49],
3268
+ bgCyanBright: [106, 49],
3269
+ bgWhiteBright: [107, 49]
3270
+ }
3271
+ };
3272
+ Object.keys(styles.modifier);
3273
+ var foregroundColorNames = Object.keys(styles.color);
3274
+ var backgroundColorNames = Object.keys(styles.bgColor);
3275
+ [...foregroundColorNames, ...backgroundColorNames];
3276
+ function assembleStyles() {
3277
+ const codes = /* @__PURE__ */ new Map();
3278
+ for (const [groupName, group] of Object.entries(styles)) {
3279
+ for (const [styleName, style] of Object.entries(group)) {
3280
+ styles[styleName] = {
3281
+ open: `\x1B[${style[0]}m`,
3282
+ close: `\x1B[${style[1]}m`
3283
+ };
3284
+ group[styleName] = styles[styleName];
3285
+ codes.set(style[0], style[1]);
3286
+ }
3287
+ Object.defineProperty(styles, groupName, {
3288
+ value: group,
3289
+ enumerable: false
3290
+ });
3291
+ }
3292
+ Object.defineProperty(styles, "codes", {
3293
+ value: codes,
3294
+ enumerable: false
3295
+ });
3296
+ styles.color.close = "\x1B[39m";
3297
+ styles.bgColor.close = "\x1B[49m";
3298
+ styles.color.ansi = wrapAnsi16();
3299
+ styles.color.ansi256 = wrapAnsi256();
3300
+ styles.color.ansi16m = wrapAnsi16m();
3301
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
3302
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
3303
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
3304
+ Object.defineProperties(styles, {
3305
+ rgbToAnsi256: {
3306
+ value(red, green, blue) {
3307
+ if (red === green && green === blue) {
3308
+ if (red < 8) {
3309
+ return 16;
3310
+ }
3311
+ if (red > 248) {
3312
+ return 231;
3313
+ }
3314
+ return Math.round((red - 8) / 247 * 24) + 232;
3315
+ }
3316
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
3317
+ },
3318
+ enumerable: false
3319
+ },
3320
+ hexToRgb: {
3321
+ value(hex) {
3322
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
3323
+ if (!matches) {
3324
+ return [0, 0, 0];
3325
+ }
3326
+ let [colorString] = matches;
3327
+ if (colorString.length === 3) {
3328
+ colorString = [...colorString].map((character) => character + character).join("");
3329
+ }
3330
+ const integer = Number.parseInt(colorString, 16);
3331
+ return [
3332
+ /* eslint-disable no-bitwise */
3333
+ integer >> 16 & 255,
3334
+ integer >> 8 & 255,
3335
+ integer & 255
3336
+ /* eslint-enable no-bitwise */
3337
+ ];
3338
+ },
3339
+ enumerable: false
3340
+ },
3341
+ hexToAnsi256: {
3342
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
3343
+ enumerable: false
3344
+ },
3345
+ ansi256ToAnsi: {
3346
+ value(code) {
3347
+ if (code < 8) {
3348
+ return 30 + code;
3349
+ }
3350
+ if (code < 16) {
3351
+ return 90 + (code - 8);
3352
+ }
3353
+ let red;
3354
+ let green;
3355
+ let blue;
3356
+ if (code >= 232) {
3357
+ red = ((code - 232) * 10 + 8) / 255;
3358
+ green = red;
3359
+ blue = red;
3360
+ } else {
3361
+ code -= 16;
3362
+ const remainder = code % 36;
3363
+ red = Math.floor(code / 36) / 5;
3364
+ green = Math.floor(remainder / 6) / 5;
3365
+ blue = remainder % 6 / 5;
3366
+ }
3367
+ const value = Math.max(red, green, blue) * 2;
3368
+ if (value === 0) {
3369
+ return 30;
3370
+ }
3371
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
3372
+ if (value === 2) {
3373
+ result += 60;
3374
+ }
3375
+ return result;
3376
+ },
3377
+ enumerable: false
3378
+ },
3379
+ rgbToAnsi: {
3380
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
3381
+ enumerable: false
3382
+ },
3383
+ hexToAnsi: {
3384
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
3385
+ enumerable: false
3386
+ }
3387
+ });
3388
+ return styles;
3389
+ }
3390
+ var ansiStyles = assembleStyles();
3391
+ var ansi_styles_default = ansiStyles;
3392
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
3393
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
3394
+ const position = argv.indexOf(prefix + flag);
3395
+ const terminatorPosition = argv.indexOf("--");
3396
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
3397
+ }
3398
+ var { env } = process2;
3399
+ var flagForceColor;
3400
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
3401
+ flagForceColor = 0;
3402
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
3403
+ flagForceColor = 1;
3404
+ }
3405
+ function envForceColor() {
3406
+ if ("FORCE_COLOR" in env) {
3407
+ if (env.FORCE_COLOR === "true") {
3408
+ return 1;
3409
+ }
3410
+ if (env.FORCE_COLOR === "false") {
3411
+ return 0;
3412
+ }
3413
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
3414
+ }
3415
+ }
3416
+ function translateLevel(level) {
3417
+ if (level === 0) {
3418
+ return false;
3419
+ }
3420
+ return {
3421
+ level,
3422
+ hasBasic: true,
3423
+ has256: level >= 2,
3424
+ has16m: level >= 3
3425
+ };
3426
+ }
3427
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
3428
+ const noFlagForceColor = envForceColor();
3429
+ if (noFlagForceColor !== void 0) {
3430
+ flagForceColor = noFlagForceColor;
3431
+ }
3432
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
3433
+ if (forceColor === 0) {
3434
+ return 0;
3435
+ }
3436
+ if (sniffFlags) {
3437
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
3438
+ return 3;
3439
+ }
3440
+ if (hasFlag("color=256")) {
3441
+ return 2;
3442
+ }
3443
+ }
3444
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
3445
+ return 1;
3446
+ }
3447
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
3448
+ return 0;
3449
+ }
3450
+ const min = forceColor || 0;
3451
+ if (env.TERM === "dumb") {
3452
+ return min;
3453
+ }
3454
+ if (process2.platform === "win32") {
3455
+ const osRelease = os.release().split(".");
3456
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
3457
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
3458
+ }
3459
+ return 1;
3460
+ }
3461
+ if ("CI" in env) {
3462
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
3463
+ return 3;
3464
+ }
3465
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
3466
+ return 1;
3467
+ }
3468
+ return min;
3469
+ }
3470
+ if ("TEAMCITY_VERSION" in env) {
3471
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
3472
+ }
3473
+ if (env.COLORTERM === "truecolor") {
3474
+ return 3;
3475
+ }
3476
+ if (env.TERM === "xterm-kitty") {
3477
+ return 3;
3478
+ }
3479
+ if (env.TERM === "xterm-ghostty") {
3480
+ return 3;
3481
+ }
3482
+ if (env.TERM === "wezterm") {
3483
+ return 3;
3484
+ }
3485
+ if ("TERM_PROGRAM" in env) {
3486
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
3487
+ switch (env.TERM_PROGRAM) {
3488
+ case "iTerm.app": {
3489
+ return version >= 3 ? 3 : 2;
3490
+ }
3491
+ case "Apple_Terminal": {
3492
+ return 2;
3493
+ }
3494
+ }
3495
+ }
3496
+ if (/-256(color)?$/i.test(env.TERM)) {
3497
+ return 2;
3498
+ }
3499
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
3500
+ return 1;
3501
+ }
3502
+ if ("COLORTERM" in env) {
3503
+ return 1;
3504
+ }
3505
+ return min;
3506
+ }
3507
+ function createSupportsColor(stream, options = {}) {
3508
+ const level = _supportsColor(stream, {
3509
+ streamIsTTY: stream && stream.isTTY,
3510
+ ...options
3511
+ });
3512
+ return translateLevel(level);
3513
+ }
3514
+ var supportsColor = {
3515
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
3516
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
3517
+ };
3518
+ var supports_color_default = supportsColor;
3519
+
3520
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
3521
+ function stringReplaceAll(string, substring, replacer) {
3522
+ let index = string.indexOf(substring);
3523
+ if (index === -1) {
3524
+ return string;
3525
+ }
3526
+ const substringLength = substring.length;
3527
+ let endIndex = 0;
3528
+ let returnValue = "";
3529
+ do {
3530
+ returnValue += string.slice(endIndex, index) + substring + replacer;
3531
+ endIndex = index + substringLength;
3532
+ index = string.indexOf(substring, endIndex);
3533
+ } while (index !== -1);
3534
+ returnValue += string.slice(endIndex);
3535
+ return returnValue;
3536
+ }
3537
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
3538
+ let endIndex = 0;
3539
+ let returnValue = "";
3540
+ do {
3541
+ const gotCR = string[index - 1] === "\r";
3542
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
3543
+ endIndex = index + 1;
3544
+ index = string.indexOf("\n", endIndex);
3545
+ } while (index !== -1);
3546
+ returnValue += string.slice(endIndex);
3547
+ return returnValue;
3548
+ }
3549
+
3550
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
3551
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
3552
+ var GENERATOR = /* @__PURE__ */ Symbol("GENERATOR");
3553
+ var STYLER = /* @__PURE__ */ Symbol("STYLER");
3554
+ var IS_EMPTY = /* @__PURE__ */ Symbol("IS_EMPTY");
3555
+ var levelMapping = [
3556
+ "ansi",
3557
+ "ansi",
3558
+ "ansi256",
3559
+ "ansi16m"
3560
+ ];
3561
+ var styles2 = /* @__PURE__ */ Object.create(null);
3562
+ var applyOptions = (object, options = {}) => {
3563
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
3564
+ throw new Error("The `level` option should be an integer from 0 to 3");
3565
+ }
3566
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
3567
+ object.level = options.level === void 0 ? colorLevel : options.level;
3568
+ };
3569
+ var chalkFactory = (options) => {
3570
+ const chalk2 = (...strings) => strings.join(" ");
3571
+ applyOptions(chalk2, options);
3572
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
3573
+ return chalk2;
3574
+ };
3575
+ function createChalk(options) {
3576
+ return chalkFactory(options);
3577
+ }
3578
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
3579
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
3580
+ styles2[styleName] = {
3581
+ get() {
3582
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
3583
+ Object.defineProperty(this, styleName, { value: builder });
3584
+ return builder;
3585
+ }
3586
+ };
3587
+ }
3588
+ styles2.visible = {
3589
+ get() {
3590
+ const builder = createBuilder(this, this[STYLER], true);
3591
+ Object.defineProperty(this, "visible", { value: builder });
3592
+ return builder;
3593
+ }
3594
+ };
3595
+ var getModelAnsi = (model, level, type, ...arguments_) => {
3596
+ if (model === "rgb") {
3597
+ if (level === "ansi16m") {
3598
+ return ansi_styles_default[type].ansi16m(...arguments_);
3599
+ }
3600
+ if (level === "ansi256") {
3601
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
3602
+ }
3603
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
3604
+ }
3605
+ if (model === "hex") {
3606
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
3607
+ }
3608
+ return ansi_styles_default[type][model](...arguments_);
3609
+ };
3610
+ var usedModels = ["rgb", "hex", "ansi256"];
3611
+ for (const model of usedModels) {
3612
+ styles2[model] = {
3613
+ get() {
3614
+ const { level } = this;
3615
+ return function(...arguments_) {
3616
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
3617
+ return createBuilder(this, styler, this[IS_EMPTY]);
3618
+ };
3619
+ }
3620
+ };
3621
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
3622
+ styles2[bgModel] = {
3623
+ get() {
3624
+ const { level } = this;
3625
+ return function(...arguments_) {
3626
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
3627
+ return createBuilder(this, styler, this[IS_EMPTY]);
3628
+ };
3629
+ }
3630
+ };
3631
+ }
3632
+ var proto = Object.defineProperties(() => {
3633
+ }, {
3634
+ ...styles2,
3635
+ level: {
3636
+ enumerable: true,
3637
+ get() {
3638
+ return this[GENERATOR].level;
3639
+ },
3640
+ set(level) {
3641
+ this[GENERATOR].level = level;
3642
+ }
3643
+ }
3644
+ });
3645
+ var createStyler = (open, close, parent) => {
3646
+ let openAll;
3647
+ let closeAll;
3648
+ if (parent === void 0) {
3649
+ openAll = open;
3650
+ closeAll = close;
3651
+ } else {
3652
+ openAll = parent.openAll + open;
3653
+ closeAll = close + parent.closeAll;
3654
+ }
3655
+ return {
3656
+ open,
3657
+ close,
3658
+ openAll,
3659
+ closeAll,
3660
+ parent
3661
+ };
3662
+ };
3663
+ var createBuilder = (self, _styler, _isEmpty) => {
3664
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
3665
+ Object.setPrototypeOf(builder, proto);
3666
+ builder[GENERATOR] = self;
3667
+ builder[STYLER] = _styler;
3668
+ builder[IS_EMPTY] = _isEmpty;
3669
+ return builder;
3670
+ };
3671
+ var applyStyle = (self, string) => {
3672
+ if (self.level <= 0 || !string) {
3673
+ return self[IS_EMPTY] ? "" : string;
3674
+ }
3675
+ let styler = self[STYLER];
3676
+ if (styler === void 0) {
3677
+ return string;
3678
+ }
3679
+ const { openAll, closeAll } = styler;
3680
+ if (string.includes("\x1B")) {
3681
+ while (styler !== void 0) {
3682
+ string = stringReplaceAll(string, styler.close, styler.open);
3683
+ styler = styler.parent;
3684
+ }
3685
+ }
3686
+ const lfIndex = string.indexOf("\n");
3687
+ if (lfIndex !== -1) {
3688
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
3689
+ }
3690
+ return openAll + string + closeAll;
3691
+ };
3692
+ Object.defineProperties(createChalk.prototype, styles2);
3693
+ var chalk = createChalk();
3694
+ createChalk({ level: stderrColor ? stderrColor.level : 0 });
3695
+ var source_default = chalk;
3696
+
3697
+ // packages/core/src/diff/renderer.ts
2297
3698
  function formatPath(path5) {
2298
3699
  if (path5 === void 0 || path5.path.length === 0) {
2299
3700
  return "(run)";
@@ -2317,9 +3718,9 @@ function renderRunDiff(result, options) {
2317
3718
  }
2318
3719
  const sev = (s, level) => {
2319
3720
  if (!color) return s;
2320
- if (level === "error") return chalk2.red(s);
2321
- if (level === "warning") return chalk2.yellow(s);
2322
- return chalk2.gray(s);
3721
+ if (level === "error") return source_default.red(s);
3722
+ if (level === "warning") return source_default.yellow(s);
3723
+ return source_default.gray(s);
2323
3724
  };
2324
3725
  const lines = [];
2325
3726
  const { summary } = result;
@@ -2382,6 +3783,8 @@ function diffTraceEvents(leftEvents, rightEvents, options) {
2382
3783
  const right = manualTraceEventsToComparableRun(rightEvents);
2383
3784
  return diffRuns(left, right, options);
2384
3785
  }
3786
+
3787
+ // packages/core/src/terminal.ts
2385
3788
  var TERMINAL_INDENT = " ";
2386
3789
  var MAX_TERMINAL_NAME_LENGTH = 80;
2387
3790
  var MAX_TERMINAL_DEPTH = 10;
@@ -2407,24 +3810,24 @@ function formatTerminalName(name) {
2407
3810
  return truncateName(name, MAX_TERMINAL_NAME_LENGTH);
2408
3811
  }
2409
3812
  function getStatusIcon(status) {
2410
- if (status === "success") return chalk2.green("\u2714");
2411
- if (status === "error") return chalk2.red("\u2716");
2412
- return chalk2.yellow("\u23F3");
3813
+ if (status === "success") return source_default.green("\u2714");
3814
+ if (status === "error") return source_default.red("\u2716");
3815
+ return source_default.yellow("\u23F3");
2413
3816
  }
2414
3817
  function renderStepLine(name, durationMs, status, depth) {
2415
3818
  try {
2416
3819
  const nm = formatTerminalName(name);
2417
3820
  const ind = getIndent(depth ?? 0);
2418
3821
  if (status === "running" && durationMs === void 0) {
2419
- return `${ind}${chalk2.yellow("\u23F3")} ${nm}`;
3822
+ return `${ind}${source_default.yellow("\u23F3")} ${nm}`;
2420
3823
  }
2421
3824
  const hasDur = durationMs !== void 0 && Number.isFinite(durationMs);
2422
3825
  const dur = hasDur ? formatDuration2(durationMs) : void 0;
2423
3826
  if (status === "running") {
2424
- return dur !== void 0 ? `${ind}${chalk2.yellow("\u23F3")} ${nm} (${dur})` : `${ind}${chalk2.yellow("\u23F3")} ${nm}`;
3827
+ return dur !== void 0 ? `${ind}${source_default.yellow("\u23F3")} ${nm} (${dur})` : `${ind}${source_default.yellow("\u23F3")} ${nm}`;
2425
3828
  }
2426
3829
  if (!hasDur || dur === void 0) {
2427
- return `${ind}${chalk2.yellow("\u23F3")} ${nm}`;
3830
+ return `${ind}${source_default.yellow("\u23F3")} ${nm}`;
2428
3831
  }
2429
3832
  if (status === "success") {
2430
3833
  return `${ind}${getStatusIcon("success")} ${nm} (${dur})`;
@@ -2460,7 +3863,7 @@ function printRunStart(runId, name) {
2460
3863
  if (isSilentContext()) return;
2461
3864
  try {
2462
3865
  safePrint("");
2463
- const header = `${chalk2.cyan.bold("\u{1F50D} AgentInspect:")} ${formatTerminalName(name)} ${chalk2.dim(`(${runId})`)}`;
3866
+ const header = `${source_default.cyan.bold("\u{1F50D} AgentInspect:")} ${formatTerminalName(name)} ${source_default.dim(`(${runId})`)}`;
2464
3867
  safePrint(header);
2465
3868
  } catch {
2466
3869
  }
@@ -2493,10 +3896,10 @@ function printRunComplete(_name, _runId, durationMs, status, traceFilePath) {
2493
3896
  for (let i = 0; i < lines.length; i++) {
2494
3897
  const line = lines[i];
2495
3898
  if (i === 0) {
2496
- const color = status === "error" ? chalk2.red : status === "running" ? chalk2.yellow : chalk2.green;
3899
+ const color = status === "error" ? source_default.red : status === "running" ? source_default.yellow : source_default.green;
2497
3900
  safePrint(color(line));
2498
3901
  } else {
2499
- safePrint(chalk2.dim(line));
3902
+ safePrint(source_default.dim(line));
2500
3903
  }
2501
3904
  }
2502
3905
  } catch {
@@ -2534,6 +3937,7 @@ async function inspectRun(name, fn, options) {
2534
3937
  const runName = normalizeRunName(name);
2535
3938
  const runId = createRunId();
2536
3939
  const traceDir = resolveTraceDir({ dir: options?.traceDir });
3940
+ const traceSafety = resolveTraceSafetyOptions(options);
2537
3941
  const context = {
2538
3942
  runId,
2539
3943
  runName,
@@ -2557,7 +3961,10 @@ async function inspectRun(name, fn, options) {
2557
3961
  startTime,
2558
3962
  ...options?.metadata !== void 0 ? { metadata: options.metadata } : {}
2559
3963
  };
2560
- await writeTraceEvent(started, traceDir);
3964
+ await writeTraceEvent(
3965
+ prepareTraceEventForDisk(started, traceSafety),
3966
+ traceDir
3967
+ );
2561
3968
  });
2562
3969
  await safeInstrumentation("printRunStart", () => {
2563
3970
  printRunStart(runId, runName);
@@ -2581,7 +3988,10 @@ async function inspectRun(name, fn, options) {
2581
3988
  durationMs: durationMs2,
2582
3989
  error: formatted
2583
3990
  };
2584
- await writeTraceEvent(completed, traceDir);
3991
+ await writeTraceEvent(
3992
+ prepareTraceEventForDisk(completed, traceSafety),
3993
+ traceDir
3994
+ );
2585
3995
  });
2586
3996
  await safeInstrumentation("printRunComplete(error)", () => {
2587
3997
  printRunComplete(runName, runId, durationMs2, "error", printPath2);
@@ -2601,13 +4011,16 @@ async function inspectRun(name, fn, options) {
2601
4011
  endTime,
2602
4012
  durationMs
2603
4013
  };
2604
- await writeTraceEvent(completed, traceDir);
4014
+ await writeTraceEvent(
4015
+ prepareTraceEventForDisk(completed, traceSafety),
4016
+ traceDir
4017
+ );
2605
4018
  });
2606
4019
  await safeInstrumentation("printRunComplete(success)", () => {
2607
4020
  printRunComplete(runName, runId, durationMs, "success", printPath);
2608
4021
  });
2609
4022
  return result;
2610
- });
4023
+ }, traceSafety);
2611
4024
  }
2612
4025
 
2613
4026
  // packages/core/src/maybe-inspect-run.ts
@@ -2658,6 +4071,7 @@ async function stepImpl(name, fn, options) {
2658
4071
  const parentId = getParentStepId();
2659
4072
  const stepType = options?.type ?? "logic";
2660
4073
  const metadata = options?.metadata;
4074
+ const traceSafety = getTraceSafetyFromContext();
2661
4075
  const startTime = Date.now();
2662
4076
  await safeInstrumentation2("writeTraceEvent(step_started)", async () => {
2663
4077
  const started = {
@@ -2672,7 +4086,8 @@ async function stepImpl(name, fn, options) {
2672
4086
  startTime,
2673
4087
  ...metadata !== void 0 ? { metadata } : {}
2674
4088
  };
2675
- await writeTraceEvent(started, context.traceDir);
4089
+ const safe = traceSafety !== void 0 ? prepareTraceEventForDisk(started, traceSafety) : started;
4090
+ await writeTraceEvent(safe, context.traceDir);
2676
4091
  });
2677
4092
  await safeInstrumentation2("printStepStart", () => {
2678
4093
  printStepStart(stepName, renderDepth);
@@ -2698,7 +4113,8 @@ async function stepImpl(name, fn, options) {
2698
4113
  durationMs: durationMs2,
2699
4114
  error: formatted
2700
4115
  };
2701
- await writeTraceEvent(completed, context.traceDir);
4116
+ const safe = traceSafety !== void 0 ? prepareTraceEventForDisk(completed, traceSafety) : completed;
4117
+ await writeTraceEvent(safe, context.traceDir);
2702
4118
  });
2703
4119
  await safeInstrumentation2("printStepComplete(error)", () => {
2704
4120
  printStepComplete(stepName, durationMs2, "error", renderDepth);
@@ -2724,7 +4140,8 @@ async function stepImpl(name, fn, options) {
2724
4140
  endTime,
2725
4141
  durationMs
2726
4142
  };
2727
- await writeTraceEvent(completed, context.traceDir);
4143
+ const safe = traceSafety !== void 0 ? prepareTraceEventForDisk(completed, traceSafety) : completed;
4144
+ await writeTraceEvent(safe, context.traceDir);
2728
4145
  });
2729
4146
  await safeInstrumentation2("printStepComplete(success)", () => {
2730
4147
  printStepComplete(stepName, durationMs, "success", renderDepth);
@@ -2913,7 +4330,7 @@ function exportHtml(tree, options) {
2913
4330
  attrsHtml += "<h2>Attributes (bounded)</h2>";
2914
4331
  for (const n of flat) {
2915
4332
  if (!n.event.attributes || Object.keys(n.event.attributes).length === 0) continue;
2916
- const compact = compactAttributes(n.event.attributes, {
4333
+ const compact = compactAttributes4(n.event.attributes, {
2917
4334
  maxLength: maxLen,
2918
4335
  redacted
2919
4336
  });
@@ -3064,7 +4481,7 @@ function exportMarkdown(tree, options) {
3064
4481
  lines.push("");
3065
4482
  for (const n of flat) {
3066
4483
  if (!n.event.attributes || Object.keys(n.event.attributes).length === 0) continue;
3067
- const compact = compactAttributes(n.event.attributes, {
4484
+ const compact = compactAttributes4(n.event.attributes, {
3068
4485
  maxLength: maxLen,
3069
4486
  redacted
3070
4487
  });
@@ -3593,6 +5010,6 @@ function validateExport(result) {
3593
5010
  };
3594
5011
  }
3595
5012
 
3596
- export { DEFAULT_LOG_INGEST_CONFIG, DEFAULT_REDACT_KEYS, DEFAULT_TRACE_DIR_NAME, EXPORT_PAYLOAD_VERSION, EventNormalizer, FALLBACK_TRACE_DIR, JsonLogParser, LiveLogAccumulator, Log4jsParser, MAX_NAME_LENGTH, MAX_TERMINAL_DEPTH, MAX_TERMINAL_NAME_LENGTH, RUNS_DIR_NAME, Redactor, TERMINAL_INDENT, TraceDirectory, TreeBuilder, buildRunSummary, compactAttributes, createRunId, createStepId, diffRuns, diffTraceEvents, ensureTraceDir, escapeHtml, escapeMarkdown, exportHtml, exportMarkdown, exportOpenInference, exportOtlpJson, exportRunTree, extractMetadata, filterTraces, flattenTree, formatDuration2 as formatDuration, formatError, formatTerminalName, formatTimestamp, getCurrentContext, getCurrentDepth, getCurrentRunId, getCurrentRunName, getCurrentStepId, getDefaultTraceDir, getIndent, getParentStepId, getRunIdFromTraceFileName, getTraceDirFromContext, getTraceFilePath, hasActiveContext, initializeTraceFile, inspectRun, isAgentInspectEnabled, isAgentInspectTrace, isSilentContext, isStepStatus, isStepType, isTraceEvent, listTraceFiles, loadLogIngestConfig, manualTraceEventsToComparableRun, manualTraceEventsToRunTree, matchMapping, maybeInspectRun, mergeExportDefaults, mergeLogIngestConfig, observe, parseDuration, parseLogLine, parseLogsToTrees, printError, printFailedAt, printRunComplete, printRunStart, printStepComplete, printStepStart, readTraceEvents, readTraceFile, renderErrorLine, renderRunDiff, renderRunSummary, renderRunTree, renderRunTrees, renderStepLine, resolveTraceDir, runWithContext, runWithStepContext, safeString2 as safeString, serializeEvent, stableJson, step, summarizeTree, truncateName, validateEvent, validateExport, validateExportContent, warn, wildcardMatch, writeTraceEvent };
5013
+ export { DEFAULT_LOG_INGEST_CONFIG, DEFAULT_MAX_EVENT_BYTES, DEFAULT_MAX_METADATA_VALUE_LENGTH, DEFAULT_MAX_PREVIEW_LENGTH, DEFAULT_REDACT_KEYS, DEFAULT_TRACE_DIR_NAME, EXPORT_PAYLOAD_VERSION, EventNormalizer, FALLBACK_TRACE_DIR, JsonLogParser, LiveLogAccumulator, Log4jsParser, MAX_NAME_LENGTH, MAX_TERMINAL_DEPTH, MAX_TERMINAL_NAME_LENGTH, RUNS_DIR_NAME, Redactor, TERMINAL_INDENT, TraceDirectory, TreeBuilder, buildRunSummary, compactAttributes4 as compactAttributes, createRunId, createStepId, diffRuns, diffTraceEvents, ensureTraceDir, escapeHtml, escapeMarkdown, exportHtml, exportMarkdown, exportOpenInference, exportOtlpJson, exportRunTree, extractMetadata, filterTraces, flattenTree, formatDuration2 as formatDuration, formatError, formatTerminalName, formatTimestamp, getCurrentContext, 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, renderErrorLine, renderRunDiff, renderRunSummary, renderRunTree, renderRunTrees, renderStepLine, resolveTraceDir, resolveTraceSafetyOptions, runWithContext, runWithStepContext, safeString2 as safeString, serializeEvent, stableJson, step, summarizeTree, traceEventToPersistedInspectEvent, traceEventsToPersistedInspectEvents, traceEventsToPersistedRunTrees, truncateName, validateEvent, validateExport, validateExportContent, warn, wildcardMatch, writeTraceEvent };
3597
5014
  //# sourceMappingURL=index.mjs.map
3598
5015
  //# sourceMappingURL=index.mjs.map