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.
@@ -2,20 +2,21 @@
2
2
 
3
3
  var promises = require('fs/promises');
4
4
  var crypto = require('crypto');
5
- var nanoid = require('nanoid');
6
5
  var os = require('os');
7
6
  var path = require('path');
8
7
  var async_hooks = require('async_hooks');
9
8
  var fs = require('fs');
10
9
  var readline = require('readline');
11
- var chalk2 = require('chalk');
10
+ var process2 = require('process');
11
+ var tty = require('tty');
12
12
 
13
13
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
14
 
15
15
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
16
16
  var os__default = /*#__PURE__*/_interopDefault(os);
17
17
  var path__default = /*#__PURE__*/_interopDefault(path);
18
- var chalk2__default = /*#__PURE__*/_interopDefault(chalk2);
18
+ var process2__default = /*#__PURE__*/_interopDefault(process2);
19
+ var tty__default = /*#__PURE__*/_interopDefault(tty);
19
20
 
20
21
  // packages/core/src/types.ts
21
22
  var STEP_TYPES = [
@@ -63,7 +64,743 @@ function isTraceEvent(value) {
63
64
  return false;
64
65
  }
65
66
  }
66
- function isRecord2(v) {
67
+
68
+ // packages/core/src/types/persisted-inspect-event.ts
69
+ var INSPECT_KINDS = [
70
+ "RUN",
71
+ "AGENT",
72
+ "LLM",
73
+ "TOOL",
74
+ "CHAIN",
75
+ "RETRIEVER",
76
+ "DECISION",
77
+ "RESULT",
78
+ "ERROR",
79
+ "LOGIC",
80
+ "LOG"
81
+ ];
82
+ var ATTRIBUTION_CONFIDENCES = [
83
+ "explicit",
84
+ "correlated",
85
+ "heuristic",
86
+ "unknown"
87
+ ];
88
+ var PERSISTED_EVENT_SOURCE_TYPES = [
89
+ "manual",
90
+ "json-log",
91
+ "log4js",
92
+ "adapter",
93
+ "ai-sdk",
94
+ "otel"
95
+ ];
96
+ var PERSISTED_EVENT_STATUSES = [
97
+ "running",
98
+ "ok",
99
+ "error",
100
+ "unknown"
101
+ ];
102
+ function isRecord2(value) {
103
+ return typeof value === "object" && value !== null && !Array.isArray(value);
104
+ }
105
+ function isString(value) {
106
+ return typeof value === "string";
107
+ }
108
+ function isNonEmptyString(value) {
109
+ return typeof value === "string" && value.length > 0;
110
+ }
111
+ function isOptionalString(value) {
112
+ return value === void 0 || isString(value);
113
+ }
114
+ function isNonNegativeNumber(value) {
115
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
116
+ }
117
+ function isOptionalNonNegativeNumber(value) {
118
+ return value === void 0 || isNonNegativeNumber(value);
119
+ }
120
+ function isInspectKind(value) {
121
+ return typeof value === "string" && INSPECT_KINDS.includes(value);
122
+ }
123
+ function isAttributionConfidence(value) {
124
+ return typeof value === "string" && ATTRIBUTION_CONFIDENCES.includes(value);
125
+ }
126
+ function isPersistedEventSourceType(value) {
127
+ return typeof value === "string" && PERSISTED_EVENT_SOURCE_TYPES.includes(value);
128
+ }
129
+ function isPersistedEventStatus(value) {
130
+ return typeof value === "string" && PERSISTED_EVENT_STATUSES.includes(value);
131
+ }
132
+ function isPersistedEventSource(value) {
133
+ if (!isRecord2(value)) return false;
134
+ if (!isPersistedEventSourceType(value.type)) return false;
135
+ if (!isOptionalString(value.name)) return false;
136
+ if (!isOptionalString(value.version)) return false;
137
+ return true;
138
+ }
139
+ function isPersistedInspectError(value) {
140
+ if (!isRecord2(value)) return false;
141
+ if (!isNonEmptyString(value.message)) return false;
142
+ if (!isOptionalString(value.name)) return false;
143
+ if (!isOptionalString(value.code)) return false;
144
+ return true;
145
+ }
146
+ function isPersistedTokenUsage(value) {
147
+ if (!isRecord2(value)) return false;
148
+ if (!isOptionalNonNegativeNumber(value.input)) return false;
149
+ if (!isOptionalNonNegativeNumber(value.output)) return false;
150
+ if (!isOptionalNonNegativeNumber(value.total)) return false;
151
+ return true;
152
+ }
153
+ function isPersistedTraceContext(value) {
154
+ if (!isRecord2(value)) return false;
155
+ if (!isOptionalString(value.traceId)) return false;
156
+ if (!isOptionalString(value.spanId)) return false;
157
+ if (!isOptionalString(value.parentSpanId)) return false;
158
+ return true;
159
+ }
160
+ function isPersistedInspectEvent(value) {
161
+ if (!isRecord2(value)) return false;
162
+ if (value.schemaVersion !== "0.2") return false;
163
+ if (!isNonEmptyString(value.eventId)) return false;
164
+ if (!isNonEmptyString(value.runId)) return false;
165
+ if (!isInspectKind(value.kind)) return false;
166
+ if (!isNonEmptyString(value.name)) return false;
167
+ if (!isNonEmptyString(value.timestamp)) return false;
168
+ if (!isAttributionConfidence(value.confidence)) return false;
169
+ if (!isPersistedEventSource(value.source)) return false;
170
+ if (value.parentId !== void 0 && !isNonEmptyString(value.parentId)) {
171
+ return false;
172
+ }
173
+ if (value.status !== void 0 && !isPersistedEventStatus(value.status)) {
174
+ return false;
175
+ }
176
+ if (!isOptionalString(value.startedAt)) return false;
177
+ if (!isOptionalString(value.endedAt)) return false;
178
+ if (value.durationMs !== void 0 && !isNonNegativeNumber(value.durationMs)) {
179
+ return false;
180
+ }
181
+ if (value.attributes !== void 0 && !isRecord2(value.attributes)) {
182
+ return false;
183
+ }
184
+ if (value.error !== void 0 && !isPersistedInspectError(value.error)) {
185
+ return false;
186
+ }
187
+ if (value.tokenUsage !== void 0 && !isPersistedTokenUsage(value.tokenUsage)) {
188
+ return false;
189
+ }
190
+ if (value.trace !== void 0 && !isPersistedTraceContext(value.trace)) {
191
+ return false;
192
+ }
193
+ return true;
194
+ }
195
+
196
+ // packages/core/src/persisted/from-trace-event.ts
197
+ function sanitizeIdPart(value) {
198
+ return value.replace(/[^a-zA-Z0-9_-]/g, "_");
199
+ }
200
+ function nodeIdForEvent(event) {
201
+ switch (event.event) {
202
+ case "run_started":
203
+ case "run_completed":
204
+ return event.runId;
205
+ case "step_started":
206
+ case "step_completed":
207
+ return event.stepId;
208
+ default:
209
+ return "unknown";
210
+ }
211
+ }
212
+ function createPersistedEventId(event, eventIndex) {
213
+ const runId = sanitizeIdPart(event.runId);
214
+ const ev = sanitizeIdPart(event.event);
215
+ const node = sanitizeIdPart(nodeIdForEvent(event));
216
+ return `manual:${runId}:${ev}:${node}:${eventIndex}`;
217
+ }
218
+ function toIsoTimestamp(ms) {
219
+ if (typeof ms !== "number" || !Number.isFinite(ms)) {
220
+ return { iso: (/* @__PURE__ */ new Date(0)).toISOString(), invalidTimestamp: true };
221
+ }
222
+ return { iso: new Date(ms).toISOString(), invalidTimestamp: false };
223
+ }
224
+ function buildSource(options) {
225
+ return {
226
+ type: "manual",
227
+ name: options?.sourceName ?? "trace-event",
228
+ version: options?.sourceVersion ?? "0.1"
229
+ };
230
+ }
231
+ function mapStepTypeToInspectKind(type) {
232
+ switch (type) {
233
+ case "run":
234
+ return "RUN";
235
+ case "llm":
236
+ return "LLM";
237
+ case "tool":
238
+ return "TOOL";
239
+ case "decision":
240
+ return "DECISION";
241
+ case "logic":
242
+ case "state":
243
+ case "custom":
244
+ return "LOGIC";
245
+ default:
246
+ return "LOGIC";
247
+ }
248
+ }
249
+ function mapRunOrStepStatus(status) {
250
+ return status === "success" ? "ok" : "error";
251
+ }
252
+ function mapErrorInfo(error) {
253
+ if (!error?.message) {
254
+ return {};
255
+ }
256
+ const out = {
257
+ persisted: {
258
+ message: error.message,
259
+ name: "Error"
260
+ }
261
+ };
262
+ if (typeof error.stack === "string" && error.stack.length > 0) {
263
+ out.errorStack = error.stack;
264
+ }
265
+ return out;
266
+ }
267
+ function mapTokenUsageFromMetadata(metadata) {
268
+ const tokens = metadata?.tokens;
269
+ if (!tokens || typeof tokens !== "object") {
270
+ return void 0;
271
+ }
272
+ const input = typeof tokens.input === "number" && Number.isFinite(tokens.input) && tokens.input >= 0 ? tokens.input : void 0;
273
+ const output = typeof tokens.output === "number" && Number.isFinite(tokens.output) && tokens.output >= 0 ? tokens.output : void 0;
274
+ if (input === void 0 && output === void 0) {
275
+ return void 0;
276
+ }
277
+ const usage = {};
278
+ if (input !== void 0) usage.input = input;
279
+ if (output !== void 0) usage.output = output;
280
+ if (input !== void 0 && output !== void 0) {
281
+ usage.total = input + output;
282
+ }
283
+ return usage;
284
+ }
285
+ function compactAttributes(entries) {
286
+ const out = {};
287
+ for (const [key, value] of Object.entries(entries)) {
288
+ if (value !== void 0) {
289
+ out[key] = value;
290
+ }
291
+ }
292
+ return Object.keys(out).length > 0 ? out : void 0;
293
+ }
294
+ function traceEventToPersistedInspectEvent(event, options) {
295
+ const eventIndex = options?.eventIndex ?? 0;
296
+ const eventId = createPersistedEventId(event, eventIndex);
297
+ const source = buildSource(options);
298
+ const tsMain = toIsoTimestamp(event.timestamp);
299
+ switch (event.event) {
300
+ case "run_started": {
301
+ const tsStart = toIsoTimestamp(event.startTime);
302
+ const attributes = compactAttributes({
303
+ legacyEvent: "run_started",
304
+ metadata: event.metadata !== void 0 ? { ...event.metadata } : void 0,
305
+ invalidTimestamp: tsMain.invalidTimestamp || tsStart.invalidTimestamp ? true : void 0
306
+ });
307
+ return {
308
+ schemaVersion: "0.2",
309
+ eventId,
310
+ runId: event.runId,
311
+ kind: "RUN",
312
+ name: event.name,
313
+ status: "running",
314
+ timestamp: tsMain.iso,
315
+ startedAt: tsStart.iso,
316
+ confidence: "explicit",
317
+ source,
318
+ attributes
319
+ };
320
+ }
321
+ case "run_completed": {
322
+ const tsEnd = toIsoTimestamp(event.endTime);
323
+ const { persisted: error, errorStack } = mapErrorInfo(event.error);
324
+ const attributes = compactAttributes({
325
+ legacyEvent: "run_completed",
326
+ errorStack,
327
+ invalidTimestamp: tsMain.invalidTimestamp || tsEnd.invalidTimestamp ? true : void 0
328
+ });
329
+ return {
330
+ schemaVersion: "0.2",
331
+ eventId,
332
+ runId: event.runId,
333
+ kind: "RUN",
334
+ name: "run",
335
+ status: mapRunOrStepStatus(event.status),
336
+ timestamp: tsMain.iso,
337
+ endedAt: tsEnd.iso,
338
+ durationMs: event.durationMs,
339
+ confidence: "explicit",
340
+ source,
341
+ attributes,
342
+ error
343
+ };
344
+ }
345
+ case "step_started": {
346
+ const tsStart = toIsoTimestamp(event.startTime);
347
+ const tokenUsage = mapTokenUsageFromMetadata(event.metadata);
348
+ const attributes = compactAttributes({
349
+ legacyEvent: "step_started",
350
+ stepId: event.stepId,
351
+ stepType: event.type,
352
+ metadata: event.metadata !== void 0 ? { ...event.metadata } : void 0,
353
+ invalidTimestamp: tsMain.invalidTimestamp || tsStart.invalidTimestamp ? true : void 0
354
+ });
355
+ const out = {
356
+ schemaVersion: "0.2",
357
+ eventId,
358
+ runId: event.runId,
359
+ kind: mapStepTypeToInspectKind(event.type),
360
+ name: event.name,
361
+ status: "running",
362
+ timestamp: tsMain.iso,
363
+ startedAt: tsStart.iso,
364
+ confidence: "explicit",
365
+ source,
366
+ attributes
367
+ };
368
+ if (event.parentId !== void 0) {
369
+ out.parentId = event.parentId;
370
+ }
371
+ if (tokenUsage !== void 0) {
372
+ out.tokenUsage = tokenUsage;
373
+ }
374
+ return out;
375
+ }
376
+ case "step_completed": {
377
+ const tsEnd = toIsoTimestamp(event.endTime);
378
+ const { persisted: error, errorStack } = mapErrorInfo(event.error);
379
+ const attributes = compactAttributes({
380
+ legacyEvent: "step_completed",
381
+ stepId: event.stepId,
382
+ errorStack,
383
+ invalidTimestamp: tsMain.invalidTimestamp || tsEnd.invalidTimestamp ? true : void 0
384
+ });
385
+ return {
386
+ schemaVersion: "0.2",
387
+ eventId,
388
+ runId: event.runId,
389
+ kind: "LOGIC",
390
+ name: event.stepId,
391
+ status: mapRunOrStepStatus(event.status),
392
+ timestamp: tsMain.iso,
393
+ endedAt: tsEnd.iso,
394
+ durationMs: event.durationMs,
395
+ confidence: "explicit",
396
+ source,
397
+ attributes,
398
+ error
399
+ };
400
+ }
401
+ default: {
402
+ const _exhaustive = event;
403
+ throw new Error(`Unsupported trace event: ${_exhaustive.event}`);
404
+ }
405
+ }
406
+ }
407
+ function traceEventsToPersistedInspectEvents(events, options) {
408
+ return events.map(
409
+ (event, index) => traceEventToPersistedInspectEvent(event, { ...options, eventIndex: index })
410
+ );
411
+ }
412
+
413
+ // packages/core/src/persisted/from-inspect-event.ts
414
+ function sanitizeIdPart2(value) {
415
+ return value.replace(/[^a-zA-Z0-9_-]/g, "_");
416
+ }
417
+ function createFallbackEventId(event, eventIndex) {
418
+ const runId = sanitizeIdPart2(event.runId);
419
+ const kind = sanitizeIdPart2(event.kind);
420
+ const name = sanitizeIdPart2(event.name);
421
+ return `inspect:${runId}:${kind}:${name}:${eventIndex}`;
422
+ }
423
+ function toIsoTimestamp2(ms) {
424
+ if (typeof ms !== "number" || !Number.isFinite(ms)) {
425
+ return { iso: (/* @__PURE__ */ new Date(0)).toISOString(), invalidTimestamp: true };
426
+ }
427
+ return { iso: new Date(ms).toISOString(), invalidTimestamp: false };
428
+ }
429
+ function compactAttributes2(entries) {
430
+ const out = {};
431
+ for (const [key, value] of Object.entries(entries)) {
432
+ if (value !== void 0) {
433
+ out[key] = value;
434
+ }
435
+ }
436
+ return Object.keys(out).length > 0 ? out : void 0;
437
+ }
438
+ function mapInspectSourceToPersisted(source, options) {
439
+ const name = options?.sourceName;
440
+ const version = options?.sourceVersion;
441
+ switch (source.type) {
442
+ case "pino":
443
+ return {
444
+ persistedSource: {
445
+ type: "json-log",
446
+ name: name ?? "pino",
447
+ version
448
+ },
449
+ originalSourceType: "pino"
450
+ };
451
+ case "winston":
452
+ return {
453
+ persistedSource: {
454
+ type: "json-log",
455
+ name: name ?? "winston",
456
+ version
457
+ },
458
+ originalSourceType: "winston"
459
+ };
460
+ case "manual":
461
+ case "json-log":
462
+ case "log4js":
463
+ case "adapter":
464
+ return {
465
+ persistedSource: {
466
+ type: source.type,
467
+ name,
468
+ version
469
+ }
470
+ };
471
+ default:
472
+ return {
473
+ persistedSource: {
474
+ type: "json-log",
475
+ name,
476
+ version
477
+ }
478
+ };
479
+ }
480
+ }
481
+ function mapTokenUsageFromAttributes(attributes) {
482
+ const tokens = attributes?.tokens;
483
+ if (!tokens || typeof tokens !== "object" || Array.isArray(tokens)) {
484
+ return void 0;
485
+ }
486
+ const rec = tokens;
487
+ const input = typeof rec.input === "number" && Number.isFinite(rec.input) && rec.input >= 0 ? rec.input : void 0;
488
+ const output = typeof rec.output === "number" && Number.isFinite(rec.output) && rec.output >= 0 ? rec.output : void 0;
489
+ if (input === void 0 && output === void 0) {
490
+ return void 0;
491
+ }
492
+ const usage = {};
493
+ if (input !== void 0) usage.input = input;
494
+ if (output !== void 0) usage.output = output;
495
+ if (input !== void 0 && output !== void 0) {
496
+ usage.total = input + output;
497
+ }
498
+ return usage;
499
+ }
500
+ function mapErrorFromAttributes(event) {
501
+ if (event.status !== "error" || !event.attributes) {
502
+ return void 0;
503
+ }
504
+ const message = event.attributes.errorMessage;
505
+ if (typeof message !== "string" || message.length === 0) {
506
+ return void 0;
507
+ }
508
+ const err = { message };
509
+ if (typeof event.attributes.errorName === "string") {
510
+ err.name = event.attributes.errorName;
511
+ }
512
+ return err;
513
+ }
514
+ function inspectEventToPersistedInspectEvent(event, options) {
515
+ const eventIndex = options?.eventIndex ?? 0;
516
+ const eventId = typeof event.eventId === "string" && event.eventId.length > 0 ? event.eventId : createFallbackEventId(event, eventIndex);
517
+ const ts = toIsoTimestamp2(event.timestamp);
518
+ const { persistedSource, originalSourceType } = mapInspectSourceToPersisted(
519
+ event.source,
520
+ options
521
+ );
522
+ const attrsBase = event.attributes !== void 0 ? { ...event.attributes } : {};
523
+ const attributes = compactAttributes2({
524
+ ...attrsBase,
525
+ sourceFile: event.source.file,
526
+ sourceLine: event.source.line,
527
+ originalSourceType,
528
+ invalidTimestamp: ts.invalidTimestamp ? true : void 0
529
+ });
530
+ const tokenUsage = mapTokenUsageFromAttributes(event.attributes);
531
+ const error = mapErrorFromAttributes(event);
532
+ const inputPreview = event.attributes?.inputPreview;
533
+ const outputPreview = event.attributes?.outputPreview;
534
+ const out = {
535
+ schemaVersion: "0.2",
536
+ eventId,
537
+ runId: event.runId,
538
+ kind: event.kind,
539
+ name: event.name,
540
+ timestamp: ts.iso,
541
+ confidence: event.confidence,
542
+ source: persistedSource,
543
+ attributes
544
+ };
545
+ if (event.parentId !== void 0) {
546
+ out.parentId = event.parentId;
547
+ }
548
+ if (event.status !== void 0) {
549
+ out.status = event.status;
550
+ }
551
+ if (event.durationMs !== void 0 && Number.isFinite(event.durationMs) && event.durationMs >= 0) {
552
+ out.durationMs = event.durationMs;
553
+ }
554
+ if (tokenUsage !== void 0) {
555
+ out.tokenUsage = tokenUsage;
556
+ }
557
+ if (error !== void 0) {
558
+ out.error = error;
559
+ }
560
+ if (inputPreview !== void 0) {
561
+ out.inputSummary = inputPreview;
562
+ }
563
+ if (outputPreview !== void 0) {
564
+ out.outputSummary = outputPreview;
565
+ }
566
+ return out;
567
+ }
568
+ function inspectEventsToPersistedInspectEvents(events, options) {
569
+ return events.map(
570
+ (event, index) => inspectEventToPersistedInspectEvent(event, { ...options, eventIndex: index })
571
+ );
572
+ }
573
+
574
+ // packages/core/src/persisted/to-inspect-event.ts
575
+ function compactAttributes3(entries) {
576
+ const out = {};
577
+ for (const [key, value] of Object.entries(entries)) {
578
+ if (value !== void 0) {
579
+ out[key] = value;
580
+ }
581
+ }
582
+ return Object.keys(out).length > 0 ? out : void 0;
583
+ }
584
+ function parseIsoToMs(iso) {
585
+ const parsed = Date.parse(iso);
586
+ if (!Number.isFinite(parsed)) {
587
+ return { ms: 0, invalidTimestamp: true };
588
+ }
589
+ return { ms: parsed, invalidTimestamp: false };
590
+ }
591
+ function mapPersistedSourceToInspect(event) {
592
+ const attrs = event.attributes ?? {};
593
+ const sourceName = event.source.name;
594
+ if (sourceName === "pino") {
595
+ return {
596
+ type: "pino",
597
+ file: typeof attrs.sourceFile === "string" ? attrs.sourceFile : void 0,
598
+ line: typeof attrs.sourceLine === "number" ? attrs.sourceLine : void 0
599
+ };
600
+ }
601
+ if (sourceName === "winston") {
602
+ return {
603
+ type: "winston",
604
+ file: typeof attrs.sourceFile === "string" ? attrs.sourceFile : void 0,
605
+ line: typeof attrs.sourceLine === "number" ? attrs.sourceLine : void 0
606
+ };
607
+ }
608
+ const mapType = (t) => {
609
+ switch (t) {
610
+ case "manual":
611
+ return "manual";
612
+ case "json-log":
613
+ return "json-log";
614
+ case "log4js":
615
+ return "log4js";
616
+ case "adapter":
617
+ case "ai-sdk":
618
+ case "otel":
619
+ return "adapter";
620
+ default:
621
+ return "json-log";
622
+ }
623
+ };
624
+ return {
625
+ type: mapType(event.source.type),
626
+ file: typeof attrs.sourceFile === "string" ? attrs.sourceFile : void 0,
627
+ line: typeof attrs.sourceLine === "number" ? attrs.sourceLine : void 0
628
+ };
629
+ }
630
+ function buildInspectAttributes(event) {
631
+ const attrs = event.attributes !== void 0 ? { ...event.attributes } : {};
632
+ if (event.inputSummary !== void 0) {
633
+ attrs.inputSummary = event.inputSummary;
634
+ }
635
+ if (event.outputSummary !== void 0) {
636
+ attrs.outputSummary = event.outputSummary;
637
+ }
638
+ if (event.error) {
639
+ if (event.error.name !== void 0) {
640
+ attrs.errorName = event.error.name;
641
+ }
642
+ attrs.errorMessage = event.error.message;
643
+ if (event.error.code !== void 0) {
644
+ attrs.errorCode = event.error.code;
645
+ }
646
+ }
647
+ if (event.tokenUsage) {
648
+ attrs.tokens = { ...event.tokenUsage };
649
+ }
650
+ if (event.source.type === "ai-sdk" || event.source.type === "otel") {
651
+ attrs.originalSourceType = event.source.type;
652
+ }
653
+ if (event.source.name !== void 0) {
654
+ attrs.sourceName = event.source.name;
655
+ }
656
+ if (event.source.version !== void 0) {
657
+ attrs.sourceVersion = event.source.version;
658
+ }
659
+ return attrs;
660
+ }
661
+ function persistedInspectEventToInspectEvent(event) {
662
+ if (!isPersistedInspectEvent(event)) {
663
+ throw new Error("Invalid PersistedInspectEvent: failed isPersistedInspectEvent");
664
+ }
665
+ const ts = parseIsoToMs(event.timestamp);
666
+ const attrs = buildInspectAttributes(event);
667
+ if (ts.invalidTimestamp) {
668
+ attrs.invalidTimestamp = true;
669
+ }
670
+ let status;
671
+ if (event.status === "running" || event.status === "ok" || event.status === "error") {
672
+ status = event.status;
673
+ } else if (event.status === "unknown") {
674
+ attrs.persistedStatus = "unknown";
675
+ }
676
+ const out = {
677
+ eventId: event.eventId,
678
+ runId: event.runId,
679
+ name: event.name,
680
+ kind: event.kind,
681
+ timestamp: ts.ms,
682
+ confidence: event.confidence,
683
+ source: mapPersistedSourceToInspect(event),
684
+ attributes: compactAttributes3(attrs)
685
+ };
686
+ if (event.parentId !== void 0) {
687
+ out.parentId = event.parentId;
688
+ }
689
+ if (status !== void 0) {
690
+ out.status = status;
691
+ }
692
+ if (event.durationMs !== void 0 && Number.isFinite(event.durationMs) && event.durationMs >= 0) {
693
+ out.durationMs = event.durationMs;
694
+ }
695
+ return out;
696
+ }
697
+ function persistedInspectEventsToInspectEvents(events, options) {
698
+ const skipInvalid = options?.skipInvalid === true;
699
+ const out = [];
700
+ for (const event of events) {
701
+ if (!isPersistedInspectEvent(event)) {
702
+ if (skipInvalid) {
703
+ continue;
704
+ }
705
+ throw new Error("Invalid PersistedInspectEvent: failed isPersistedInspectEvent");
706
+ }
707
+ out.push(persistedInspectEventToInspectEvent(event));
708
+ }
709
+ return out;
710
+ }
711
+
712
+ // packages/core/src/logs/tree-builder.ts
713
+ function inc(map, key) {
714
+ map[key] = (map[key] ?? 0) + 1;
715
+ }
716
+ function computeRunStatus(events) {
717
+ let hasRunning = false;
718
+ for (const e of events) {
719
+ if (e.status === "error") return "error";
720
+ if (e.status === "running") hasRunning = true;
721
+ }
722
+ if (hasRunning) return "running";
723
+ return "ok";
724
+ }
725
+ var TreeBuilder = class {
726
+ constructor(options) {
727
+ void options?.config;
728
+ }
729
+ build(events) {
730
+ const byRun = /* @__PURE__ */ new Map();
731
+ for (const e of events) {
732
+ if (!byRun.has(e.runId)) byRun.set(e.runId, []);
733
+ byRun.get(e.runId).push(e);
734
+ }
735
+ const out = [];
736
+ for (const [runId, runEvents] of byRun.entries()) {
737
+ const sorted = [...runEvents].sort((a, b) => a.timestamp - b.timestamp);
738
+ const nodes = /* @__PURE__ */ new Map();
739
+ for (const e of sorted) {
740
+ nodes.set(e.eventId, { event: e, children: [], depth: 0 });
741
+ }
742
+ const roots = [];
743
+ for (const node of nodes.values()) {
744
+ const parentId = node.event.parentId;
745
+ if (parentId && nodes.has(parentId)) {
746
+ nodes.get(parentId).children.push(node);
747
+ } else {
748
+ roots.push(node);
749
+ }
750
+ }
751
+ const assignDepth = (n, depth) => {
752
+ n.depth = depth;
753
+ for (const c of n.children) assignDepth(c, depth + 1);
754
+ };
755
+ for (const r of roots) assignDepth(r, 0);
756
+ const confidenceBreakdown = {
757
+ explicit: 0,
758
+ correlated: 0,
759
+ heuristic: 0,
760
+ unknown: 0
761
+ };
762
+ const kinds = {};
763
+ for (const e of sorted) {
764
+ inc(confidenceBreakdown, e.confidence);
765
+ kinds[e.kind] = (kinds[e.kind] ?? 0) + 1;
766
+ }
767
+ const startedAt = sorted.length > 0 ? sorted[0].timestamp : void 0;
768
+ const endedAt = sorted.length > 0 ? sorted[sorted.length - 1].timestamp : void 0;
769
+ const status = computeRunStatus(sorted);
770
+ const durationMs = startedAt !== void 0 && endedAt !== void 0 && Number.isFinite(startedAt) && Number.isFinite(endedAt) && endedAt >= startedAt && status !== "running" ? endedAt - startedAt : void 0;
771
+ const name = sorted.find((e) => e.kind === "RUN")?.name;
772
+ out.push({
773
+ runId,
774
+ name,
775
+ status,
776
+ startedAt,
777
+ endedAt: status === "running" ? void 0 : endedAt,
778
+ durationMs,
779
+ children: roots,
780
+ metadata: {
781
+ totalEvents: sorted.length,
782
+ confidenceBreakdown,
783
+ kinds
784
+ }
785
+ });
786
+ }
787
+ out.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));
788
+ return out;
789
+ }
790
+ };
791
+
792
+ // packages/core/src/persisted/tree-bridge.ts
793
+ function persistedInspectEventsToRunTrees(events, options) {
794
+ const inspectEvents = persistedInspectEventsToInspectEvents(events, {
795
+ skipInvalid: options?.skipInvalid
796
+ });
797
+ return new TreeBuilder().build(inspectEvents);
798
+ }
799
+ function traceEventsToPersistedRunTrees(events) {
800
+ const persisted = traceEventsToPersistedInspectEvents(events);
801
+ return persistedInspectEventsToRunTrees(persisted);
802
+ }
803
+ function isRecord3(v) {
67
804
  return typeof v === "object" && v !== null && !Array.isArray(v);
68
805
  }
69
806
  function isNonEmptyStringArray(v) {
@@ -75,7 +812,7 @@ function validateRedact(redact) {
75
812
  }
76
813
  for (const r of redact) {
77
814
  if (typeof r === "string") continue;
78
- if (!isRecord2(r)) {
815
+ if (!isRecord3(r)) {
79
816
  throw new Error("Invalid config: redact entries must be strings or objects");
80
817
  }
81
818
  if (typeof r.key !== "string" || r.key.trim() === "") {
@@ -94,7 +831,7 @@ function validateRedact(redact) {
94
831
  }
95
832
  }
96
833
  function validateMappings(mappings) {
97
- if (!isRecord2(mappings)) {
834
+ if (!isRecord3(mappings)) {
98
835
  throw new Error("Invalid config: mappings must be an object");
99
836
  }
100
837
  }
@@ -144,7 +881,7 @@ async function loadLogIngestConfig(configPath) {
144
881
  const msg = e instanceof Error ? e.message : String(e);
145
882
  throw new Error(`Invalid JSON in config file: ${configPath} (${msg})`);
146
883
  }
147
- if (!isRecord2(parsed)) {
884
+ if (!isRecord3(parsed)) {
148
885
  throw new Error("Invalid config: expected a JSON object at top-level");
149
886
  }
150
887
  const user = parsed;
@@ -181,7 +918,7 @@ async function loadLogIngestConfig(configPath) {
181
918
  }
182
919
  return mergeLogIngestConfig(DEFAULT_LOG_INGEST_CONFIG, user);
183
920
  }
184
- function isRecord3(v) {
921
+ function isRecord4(v) {
185
922
  return typeof v === "object" && v !== null && !Array.isArray(v);
186
923
  }
187
924
  var JsonLogParser = class {
@@ -206,7 +943,7 @@ var JsonLogParser = class {
206
943
  });
207
944
  continue;
208
945
  }
209
- if (!isRecord3(parsed)) {
946
+ if (!isRecord4(parsed)) {
210
947
  warnings.push({
211
948
  code: "MALFORMED_JSON",
212
949
  message: "JSON log line must be an object",
@@ -237,7 +974,7 @@ var JsonLogParser = class {
237
974
  return this.parseLines(lines, filePath);
238
975
  }
239
976
  };
240
- function isRecord4(v) {
977
+ function isRecord5(v) {
241
978
  return typeof v === "object" && v !== null && !Array.isArray(v);
242
979
  }
243
980
  function findLastJsonObjectSubstring(line) {
@@ -313,7 +1050,7 @@ var Log4jsParser = class {
313
1050
  });
314
1051
  continue;
315
1052
  }
316
- if (!isRecord4(parsed)) {
1053
+ if (!isRecord5(parsed)) {
317
1054
  warnings.push({
318
1055
  code: "UNSUPPORTED_LOG4JS_PAYLOAD",
319
1056
  message: "Embedded JSON payload must be an object",
@@ -391,7 +1128,7 @@ var DEFAULT_REDACT_KEYS = [
391
1128
  "secret",
392
1129
  "email"
393
1130
  ];
394
- function isRecord5(v) {
1131
+ function isRecord6(v) {
395
1132
  return typeof v === "object" && v !== null && !Array.isArray(v);
396
1133
  }
397
1134
  function toKey(s) {
@@ -459,7 +1196,7 @@ var Redactor = class {
459
1196
  if (Array.isArray(value)) {
460
1197
  return value.map((v) => this.#redactNested(v));
461
1198
  }
462
- if (isRecord5(value)) {
1199
+ if (isRecord6(value)) {
463
1200
  const out = {};
464
1201
  for (const [k, v] of Object.entries(value)) {
465
1202
  out[k] = this.redactValue(k, v);
@@ -469,6 +1206,36 @@ var Redactor = class {
469
1206
  return value;
470
1207
  }
471
1208
  };
1209
+
1210
+ // node_modules/.pnpm/nanoid@5.1.11/node_modules/nanoid/url-alphabet/index.js
1211
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
1212
+
1213
+ // node_modules/.pnpm/nanoid@5.1.11/node_modules/nanoid/index.js
1214
+ var POOL_SIZE_MULTIPLIER = 128;
1215
+ var pool;
1216
+ var poolOffset;
1217
+ function fillPool(bytes) {
1218
+ if (bytes < 0 || bytes > 1024) throw new RangeError("Wrong ID size");
1219
+ if (!pool || pool.length < bytes) {
1220
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
1221
+ crypto.webcrypto.getRandomValues(pool);
1222
+ poolOffset = 0;
1223
+ } else if (poolOffset + bytes > pool.length) {
1224
+ crypto.webcrypto.getRandomValues(pool);
1225
+ poolOffset = 0;
1226
+ }
1227
+ poolOffset += bytes;
1228
+ }
1229
+ function nanoid(size = 21) {
1230
+ fillPool(size |= 0);
1231
+ let id = "";
1232
+ for (let i = poolOffset - size; i < poolOffset; i++) {
1233
+ id += urlAlphabet[pool[i] & 63];
1234
+ }
1235
+ return id;
1236
+ }
1237
+
1238
+ // packages/core/src/logs/normalizer.ts
472
1239
  function isFiniteNumber(v) {
473
1240
  return typeof v === "number" && Number.isFinite(v);
474
1241
  }
@@ -603,7 +1370,7 @@ var EventNormalizer = class {
603
1370
  attributes[k] = v;
604
1371
  }
605
1372
  const event = {
606
- eventId: nanoid.nanoid(10),
1373
+ eventId: nanoid(10),
607
1374
  runId,
608
1375
  ...parentId ? { parentId } : {},
609
1376
  name,
@@ -649,86 +1416,6 @@ var EventNormalizer = class {
649
1416
  }
650
1417
  };
651
1418
 
652
- // packages/core/src/logs/tree-builder.ts
653
- function inc(map, key) {
654
- map[key] = (map[key] ?? 0) + 1;
655
- }
656
- function computeRunStatus(events) {
657
- let hasRunning = false;
658
- for (const e of events) {
659
- if (e.status === "error") return "error";
660
- if (e.status === "running") hasRunning = true;
661
- }
662
- if (hasRunning) return "running";
663
- return "ok";
664
- }
665
- var TreeBuilder = class {
666
- constructor(options) {
667
- void options?.config;
668
- }
669
- build(events) {
670
- const byRun = /* @__PURE__ */ new Map();
671
- for (const e of events) {
672
- if (!byRun.has(e.runId)) byRun.set(e.runId, []);
673
- byRun.get(e.runId).push(e);
674
- }
675
- const out = [];
676
- for (const [runId, runEvents] of byRun.entries()) {
677
- const sorted = [...runEvents].sort((a, b) => a.timestamp - b.timestamp);
678
- const nodes = /* @__PURE__ */ new Map();
679
- for (const e of sorted) {
680
- nodes.set(e.eventId, { event: e, children: [], depth: 0 });
681
- }
682
- const roots = [];
683
- for (const node of nodes.values()) {
684
- const parentId = node.event.parentId;
685
- if (parentId && nodes.has(parentId)) {
686
- nodes.get(parentId).children.push(node);
687
- } else {
688
- roots.push(node);
689
- }
690
- }
691
- const assignDepth = (n, depth) => {
692
- n.depth = depth;
693
- for (const c of n.children) assignDepth(c, depth + 1);
694
- };
695
- for (const r of roots) assignDepth(r, 0);
696
- const confidenceBreakdown = {
697
- explicit: 0,
698
- correlated: 0,
699
- heuristic: 0,
700
- unknown: 0
701
- };
702
- const kinds = {};
703
- for (const e of sorted) {
704
- inc(confidenceBreakdown, e.confidence);
705
- kinds[e.kind] = (kinds[e.kind] ?? 0) + 1;
706
- }
707
- const startedAt = sorted.length > 0 ? sorted[0].timestamp : void 0;
708
- const endedAt = sorted.length > 0 ? sorted[sorted.length - 1].timestamp : void 0;
709
- const status = computeRunStatus(sorted);
710
- const durationMs = startedAt !== void 0 && endedAt !== void 0 && Number.isFinite(startedAt) && Number.isFinite(endedAt) && endedAt >= startedAt && status !== "running" ? endedAt - startedAt : void 0;
711
- const name = sorted.find((e) => e.kind === "RUN")?.name;
712
- out.push({
713
- runId,
714
- name,
715
- status,
716
- startedAt,
717
- endedAt: status === "running" ? void 0 : endedAt,
718
- durationMs,
719
- children: roots,
720
- metadata: {
721
- totalEvents: sorted.length,
722
- confidenceBreakdown,
723
- kinds
724
- }
725
- });
726
- }
727
- out.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));
728
- return out;
729
- }
730
- };
731
-
732
1419
  // packages/core/src/logs/tree-renderer.ts
733
1420
  function truncate(v, max) {
734
1421
  if (v.length <= max) return v;
@@ -1068,10 +1755,10 @@ var FALLBACK_TRACE_DIR = path__default.default.join(
1068
1755
  );
1069
1756
  var MAX_NAME_LENGTH = 100;
1070
1757
  function createRunId() {
1071
- return `run_${nanoid.nanoid(10)}`;
1758
+ return `run_${nanoid(10)}`;
1072
1759
  }
1073
1760
  function createStepId() {
1074
- return `step_${nanoid.nanoid(10)}`;
1761
+ return `step_${nanoid(10)}`;
1075
1762
  }
1076
1763
  function formatDuration2(ms) {
1077
1764
  return formatDuration(ms);
@@ -1151,168 +1838,38 @@ function formatError(error) {
1151
1838
  return { message: "Unknown error: undefined" };
1152
1839
  }
1153
1840
  if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") {
1154
- return { message: String(error) };
1155
- }
1156
- if (typeof error === "object") {
1157
- try {
1158
- return { message: JSON.stringify(error) };
1159
- } catch {
1160
- return { message: "Unknown error" };
1161
- }
1162
- }
1163
- return { message: "Unknown error" };
1164
- }
1165
- function truncateName(name, maxLength = MAX_NAME_LENGTH) {
1166
- if (typeof name !== "string" || name.trim() === "") {
1167
- return "unnamed";
1168
- }
1169
- const trimmed = name.trim();
1170
- if (trimmed.length <= maxLength) {
1171
- return trimmed;
1172
- }
1173
- const ellipsis = "...";
1174
- const head = Math.max(0, maxLength - ellipsis.length);
1175
- return `${trimmed.slice(0, head)}${ellipsis}`;
1176
- }
1177
- function warn(message, error) {
1178
- const base = `[AgentInspect] ${message}`;
1179
- if (error === void 0) {
1180
- console.warn(base);
1181
- return;
1182
- }
1183
- console.warn(`${base}: ${formatError(error).message}`);
1184
- }
1185
- var storage = new async_hooks.AsyncLocalStorage();
1186
- function toPublicContext(ctx) {
1187
- return {
1188
- runId: ctx.runId,
1189
- runName: ctx.runName,
1190
- traceDir: ctx.traceDir,
1191
- silent: ctx.silent,
1192
- metadata: ctx.metadata
1193
- };
1194
- }
1195
- function invoke(fn) {
1196
- return new Promise((resolve, reject) => {
1197
- try {
1198
- Promise.resolve(fn()).then(resolve, reject);
1199
- } catch (e) {
1200
- reject(e);
1201
- }
1202
- });
1203
- }
1204
- function getCurrentContext() {
1205
- try {
1206
- const s = storage.getStore();
1207
- if (!s) return void 0;
1208
- return toPublicContext(s);
1209
- } catch {
1210
- return void 0;
1211
- }
1212
- }
1213
- function getCurrentRunId() {
1214
- try {
1215
- return storage.getStore()?.runId;
1216
- } catch {
1217
- return void 0;
1218
- }
1219
- }
1220
- function getCurrentRunName() {
1221
- try {
1222
- return storage.getStore()?.runName;
1223
- } catch {
1224
- return void 0;
1225
- }
1226
- }
1227
- function getCurrentStepId() {
1228
- try {
1229
- return storage.getStore()?.currentStepId;
1230
- } catch {
1231
- return void 0;
1232
- }
1233
- }
1234
- function getParentStepId() {
1235
- return getCurrentStepId();
1236
- }
1237
- function getCurrentDepth() {
1238
- try {
1239
- const d = storage.getStore()?.currentDepth;
1240
- return typeof d === "number" && Number.isFinite(d) ? d : 0;
1241
- } catch {
1242
- return 0;
1243
- }
1244
- }
1245
- function hasActiveContext() {
1246
- try {
1247
- return storage.getStore() !== void 0;
1248
- } catch {
1249
- return false;
1841
+ return { message: String(error) };
1250
1842
  }
1251
- }
1252
- function getTraceDirFromContext() {
1253
- try {
1254
- return storage.getStore()?.traceDir;
1255
- } catch {
1256
- return void 0;
1843
+ if (typeof error === "object") {
1844
+ try {
1845
+ return { message: JSON.stringify(error) };
1846
+ } catch {
1847
+ return { message: "Unknown error" };
1848
+ }
1257
1849
  }
1850
+ return { message: "Unknown error" };
1258
1851
  }
1259
- function isSilentContext() {
1260
- try {
1261
- const s = storage.getStore();
1262
- return s ? s.silent : false;
1263
- } catch {
1264
- return false;
1852
+ function truncateName(name, maxLength = MAX_NAME_LENGTH) {
1853
+ if (typeof name !== "string" || name.trim() === "") {
1854
+ return "unnamed";
1265
1855
  }
1266
- }
1267
- function runWithContext(context, fn) {
1268
- const runtime = {
1269
- runId: context.runId,
1270
- runName: context.runName,
1271
- traceDir: context.traceDir,
1272
- silent: context.silent,
1273
- metadata: context.metadata,
1274
- currentDepth: 0
1275
- };
1276
- return new Promise((resolve, reject) => {
1277
- storage.run(runtime, () => {
1278
- try {
1279
- Promise.resolve(fn()).then(resolve, reject);
1280
- } catch (e) {
1281
- reject(e);
1282
- }
1283
- });
1284
- });
1285
- }
1286
- function runWithStepContext(stepId, fn) {
1287
- let parent;
1288
- try {
1289
- parent = storage.getStore();
1290
- } catch {
1291
- parent = void 0;
1856
+ const trimmed = name.trim();
1857
+ if (trimmed.length <= maxLength) {
1858
+ return trimmed;
1292
1859
  }
1293
- if (!parent) {
1294
- return invoke(fn);
1860
+ const ellipsis = "...";
1861
+ const head = Math.max(0, maxLength - ellipsis.length);
1862
+ return `${trimmed.slice(0, head)}${ellipsis}`;
1863
+ }
1864
+ function warn(message, error) {
1865
+ const base = `[AgentInspect] ${message}`;
1866
+ if (error === void 0) {
1867
+ console.warn(base);
1868
+ return;
1295
1869
  }
1296
- const derived = {
1297
- runId: parent.runId,
1298
- runName: parent.runName,
1299
- traceDir: parent.traceDir,
1300
- silent: parent.silent,
1301
- metadata: parent.metadata,
1302
- currentStepId: stepId,
1303
- currentDepth: parent.currentDepth + 1
1304
- };
1305
- return new Promise((resolve, reject) => {
1306
- storage.run(derived, () => {
1307
- try {
1308
- Promise.resolve(fn()).then(resolve, reject);
1309
- } catch (e) {
1310
- reject(e);
1311
- }
1312
- });
1313
- });
1870
+ console.warn(`${base}: ${formatError(error).message}`);
1314
1871
  }
1315
- function isRecord6(value) {
1872
+ function isRecord7(value) {
1316
1873
  return typeof value === "object" && value !== null && !Array.isArray(value);
1317
1874
  }
1318
1875
  function nonEmptyString(value) {
@@ -1323,7 +1880,7 @@ function finiteNumber(value) {
1323
1880
  }
1324
1881
  function optionalErrorInfo(value) {
1325
1882
  if (value === void 0) return true;
1326
- if (!isRecord6(value)) return false;
1883
+ if (!isRecord7(value)) return false;
1327
1884
  if (typeof value.message !== "string") return false;
1328
1885
  if ("stack" in value && value.stack !== void 0) {
1329
1886
  if (typeof value.stack !== "string") return false;
@@ -1331,7 +1888,7 @@ function optionalErrorInfo(value) {
1331
1888
  return true;
1332
1889
  }
1333
1890
  function validateEvent(event) {
1334
- if (!isRecord6(event)) return false;
1891
+ if (!isRecord7(event)) return false;
1335
1892
  if (event.schemaVersion !== "0.1") return false;
1336
1893
  if (!finiteNumber(event.timestamp)) return false;
1337
1894
  if (typeof event.event !== "string") return false;
@@ -1340,7 +1897,7 @@ function validateEvent(event) {
1340
1897
  if (!nonEmptyString(event.runId) || !nonEmptyString(event.name) || !finiteNumber(event.startTime)) {
1341
1898
  return false;
1342
1899
  }
1343
- if (event.metadata !== void 0 && !isRecord6(event.metadata)) {
1900
+ if (event.metadata !== void 0 && !isRecord7(event.metadata)) {
1344
1901
  return false;
1345
1902
  }
1346
1903
  return true;
@@ -1355,7 +1912,7 @@ function validateEvent(event) {
1355
1912
  if (event.parentId !== void 0 && typeof event.parentId !== "string") {
1356
1913
  return false;
1357
1914
  }
1358
- if (event.metadata !== void 0 && !isRecord6(event.metadata)) {
1915
+ if (event.metadata !== void 0 && !isRecord7(event.metadata)) {
1359
1916
  return false;
1360
1917
  }
1361
1918
  return true;
@@ -1393,12 +1950,20 @@ async function initializeTraceFile(runId, traceDir) {
1393
1950
  return void 0;
1394
1951
  }
1395
1952
  }
1953
+ function ensureEventWithinBounds(event) {
1954
+ const line = serializeEvent(event);
1955
+ if (line === "") return event;
1956
+ const bytes = Buffer.byteLength(line, "utf8");
1957
+ if (bytes <= DEFAULT_MAX_EVENT_BYTES) return event;
1958
+ return prepareTraceEventForDisk(event, resolveTraceSafetyOptions());
1959
+ }
1396
1960
  async function writeTraceEvent(event, traceDir) {
1397
- if (!validateEvent(event)) {
1961
+ const bounded = ensureEventWithinBounds(event);
1962
+ if (!validateEvent(bounded)) {
1398
1963
  warn("Skipped invalid trace event (validation failed)");
1399
1964
  return;
1400
1965
  }
1401
- const line = serializeEvent(event);
1966
+ const line = serializeEvent(bounded);
1402
1967
  if (line === "") {
1403
1968
  warn("Skipped trace event (serialization failed)");
1404
1969
  return;
@@ -1418,87 +1983,432 @@ async function writeTraceEvent(event, traceDir) {
1418
1983
  if (await tryAppend(traceDir)) {
1419
1984
  return;
1420
1985
  }
1421
- warn(`Failed to append trace event for run ${event.runId}`);
1422
- if (await tryAppend(FALLBACK_TRACE_DIR)) {
1423
- return;
1986
+ warn(`Failed to append trace event for run ${event.runId}`);
1987
+ if (await tryAppend(FALLBACK_TRACE_DIR)) {
1988
+ return;
1989
+ }
1990
+ warn("Failed to append trace event to fallback directory");
1991
+ }
1992
+ async function readTraceFile(runId, traceDir) {
1993
+ try {
1994
+ const filePath = getTraceFilePath(runId, traceDir);
1995
+ return await promises.readFile(filePath, "utf-8");
1996
+ } catch (e) {
1997
+ if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") {
1998
+ return void 0;
1999
+ }
2000
+ warn("Unexpected error reading trace file", e);
2001
+ return void 0;
2002
+ }
2003
+ }
2004
+ async function readTraceEvents(runId, traceDir) {
2005
+ const out = [];
2006
+ try {
2007
+ const raw = await readTraceFile(runId, traceDir);
2008
+ if (raw === void 0) {
2009
+ return out;
2010
+ }
2011
+ const lines = raw.split("\n");
2012
+ for (const line of lines) {
2013
+ const trimmed = line.trim();
2014
+ if (trimmed === "") continue;
2015
+ let parsed;
2016
+ try {
2017
+ parsed = JSON.parse(trimmed);
2018
+ } catch {
2019
+ warn("Skipped invalid JSON line in trace file");
2020
+ continue;
2021
+ }
2022
+ if (validateEvent(parsed)) {
2023
+ out.push(parsed);
2024
+ } else {
2025
+ warn("Skipped invalid trace event line in trace file");
2026
+ }
2027
+ }
2028
+ } catch (e) {
2029
+ warn("Failed to read trace events", e);
2030
+ }
2031
+ return out;
2032
+ }
2033
+ async function listTraceFiles(traceDir) {
2034
+ try {
2035
+ const usable = path__default.default.resolve(traceDir);
2036
+ const names = await promises.readdir(usable);
2037
+ const jsonl = names.filter((n) => n.endsWith(".jsonl"));
2038
+ const withStat = await Promise.all(
2039
+ jsonl.map(async (name) => {
2040
+ try {
2041
+ const st = await promises.stat(path__default.default.join(usable, name));
2042
+ return { name, mtime: st.mtimeMs };
2043
+ } catch {
2044
+ return { name, mtime: 0 };
2045
+ }
2046
+ })
2047
+ );
2048
+ withStat.sort((a, b) => {
2049
+ if (b.mtime !== a.mtime) return b.mtime - a.mtime;
2050
+ return a.name.localeCompare(b.name);
2051
+ });
2052
+ return withStat.map((x) => x.name);
2053
+ } catch {
2054
+ return [];
2055
+ }
2056
+ }
2057
+ function getRunIdFromTraceFileName(fileName) {
2058
+ try {
2059
+ const base = path__default.default.basename(fileName);
2060
+ if (!base.endsWith(".jsonl")) return void 0;
2061
+ const id = base.slice(0, -".jsonl".length);
2062
+ return id === "" ? void 0 : id;
2063
+ } catch {
2064
+ return void 0;
2065
+ }
2066
+ }
2067
+
2068
+ // packages/core/src/trace-event-safety.ts
2069
+ var DEFAULT_MAX_METADATA_VALUE_LENGTH = 2e3;
2070
+ var DEFAULT_MAX_PREVIEW_LENGTH = 500;
2071
+ var DEFAULT_MAX_EVENT_BYTES = 65536;
2072
+ function isRecord8(value) {
2073
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2074
+ }
2075
+ function isPreviewKey(key) {
2076
+ return key.toLowerCase().includes("preview");
2077
+ }
2078
+ function truncateString(value, maxLen) {
2079
+ if (maxLen <= 0) return "\u2026";
2080
+ if (value.length <= maxLen) return value;
2081
+ return `${value.slice(0, maxLen)}\u2026`;
2082
+ }
2083
+ function byteLength(text) {
2084
+ return Buffer.byteLength(text, "utf8");
2085
+ }
2086
+ function resolveTraceSafetyOptions(options) {
2087
+ const redact = options?.redact;
2088
+ let redactEnabled = true;
2089
+ let redactionRules;
2090
+ if (redact === false) {
2091
+ redactEnabled = false;
2092
+ } else if (redact === true || redact === void 0) {
2093
+ redactEnabled = true;
2094
+ } else if (isRecord8(redact)) {
2095
+ redactEnabled = true;
2096
+ redactionRules = redact.rules;
2097
+ }
2098
+ return {
2099
+ redactEnabled,
2100
+ redactionRules,
2101
+ maxMetadataValueLength: typeof options?.maxMetadataValueLength === "number" && Number.isFinite(options.maxMetadataValueLength) && options.maxMetadataValueLength >= 0 ? Math.floor(options.maxMetadataValueLength) : DEFAULT_MAX_METADATA_VALUE_LENGTH,
2102
+ maxPreviewLength: typeof options?.maxPreviewLength === "number" && Number.isFinite(options.maxPreviewLength) && options.maxPreviewLength >= 0 ? Math.floor(options.maxPreviewLength) : DEFAULT_MAX_PREVIEW_LENGTH,
2103
+ maxEventBytes: typeof options?.maxEventBytes === "number" && Number.isFinite(options.maxEventBytes) && options.maxEventBytes > 0 ? Math.floor(options.maxEventBytes) : DEFAULT_MAX_EVENT_BYTES
2104
+ };
2105
+ }
2106
+ function boundMetadataValue(key, value, opts, seen, depth) {
2107
+ if (depth > 32) return "[MaxDepth]";
2108
+ if (value === null || typeof value !== "object") {
2109
+ if (typeof value === "string") {
2110
+ const max = isPreviewKey(key) ? opts.maxPreviewLength : opts.maxMetadataValueLength;
2111
+ return truncateString(value, max);
2112
+ }
2113
+ return value;
2114
+ }
2115
+ if (seen.has(value)) return "[Circular]";
2116
+ seen.add(value);
2117
+ if (Array.isArray(value)) {
2118
+ const maxItems = 50;
2119
+ const out2 = value.slice(0, maxItems).map(
2120
+ (item, index) => boundMetadataValue(String(index), item, opts, seen, depth + 1)
2121
+ );
2122
+ if (value.length > maxItems) {
2123
+ out2.push(`\u2026(+${value.length - maxItems} more)`);
2124
+ }
2125
+ return out2;
2126
+ }
2127
+ const record = value;
2128
+ const out = {};
2129
+ for (const [k, v] of Object.entries(record)) {
2130
+ out[k] = boundMetadataValue(k, v, opts, seen, depth + 1);
2131
+ }
2132
+ return out;
2133
+ }
2134
+ function redactMetadata(metadata, opts) {
2135
+ if (!opts.redactEnabled) return { ...metadata };
2136
+ const redactor = new Redactor({ rules: opts.redactionRules });
2137
+ return redactor.redactRecord(metadata);
2138
+ }
2139
+ function prepareMetadataForDisk(metadata, opts) {
2140
+ try {
2141
+ const redacted = redactMetadata(metadata, opts);
2142
+ const seen = /* @__PURE__ */ new WeakSet();
2143
+ const bounded = boundMetadataValue(
2144
+ "metadata",
2145
+ redacted,
2146
+ opts,
2147
+ seen,
2148
+ 0
2149
+ );
2150
+ return isRecord8(bounded) ? bounded : {};
2151
+ } catch {
2152
+ return { truncated: true, reason: "metadataPreparationFailed" };
2153
+ }
2154
+ }
2155
+ function truncateErrorStack(event, maxLen) {
2156
+ if (event.event !== "run_completed" && event.event !== "step_completed") {
2157
+ return event;
2158
+ }
2159
+ if (!event.error?.stack || typeof event.error.stack !== "string") {
2160
+ return event;
2161
+ }
2162
+ return {
2163
+ ...event,
2164
+ error: {
2165
+ ...event.error,
2166
+ stack: truncateString(event.error.stack, maxLen)
2167
+ }
2168
+ };
2169
+ }
2170
+ function replaceMetadataWithTruncationMarker(event, originalApproxBytes) {
2171
+ const marker = {
2172
+ truncated: true,
2173
+ reason: "maxEventBytes",
2174
+ originalApproxBytes
2175
+ };
2176
+ if (event.event === "run_started") {
2177
+ return { ...event, metadata: marker };
2178
+ }
2179
+ if (event.event === "step_started") {
2180
+ return { ...event, metadata: marker };
2181
+ }
2182
+ return event;
2183
+ }
2184
+ function shrinkMetadataLimits(opts, factor) {
2185
+ return {
2186
+ ...opts,
2187
+ maxMetadataValueLength: Math.max(32, Math.floor(opts.maxMetadataValueLength * factor)),
2188
+ maxPreviewLength: Math.max(16, Math.floor(opts.maxPreviewLength * factor))
2189
+ };
2190
+ }
2191
+ function applyMetadataToEvent(event, metadata) {
2192
+ if (event.event === "run_started") {
2193
+ return { ...event, metadata };
2194
+ }
2195
+ if (event.event === "step_started") {
2196
+ return { ...event, metadata };
2197
+ }
2198
+ return event;
2199
+ }
2200
+ function eventHasMetadata(event) {
2201
+ return (event.event === "run_started" || event.event === "step_started") && event.metadata !== void 0;
2202
+ }
2203
+ function getEventMetadata(event) {
2204
+ if (event.event === "run_started" || event.event === "step_started") {
2205
+ return event.metadata;
2206
+ }
2207
+ return void 0;
2208
+ }
2209
+ function prepareTraceEventForDisk(event, opts) {
2210
+ try {
2211
+ let working = { ...event };
2212
+ const rawMetadata = getEventMetadata(working);
2213
+ if (rawMetadata !== void 0) {
2214
+ const safe = prepareMetadataForDisk(rawMetadata, opts);
2215
+ working = applyMetadataToEvent(working, safe);
2216
+ }
2217
+ let serialized = serializeEvent(working);
2218
+ if (serialized === "") {
2219
+ return working;
2220
+ }
2221
+ let bytes = byteLength(serialized);
2222
+ if (bytes <= opts.maxEventBytes) {
2223
+ return working;
2224
+ }
2225
+ if (rawMetadata !== void 0) {
2226
+ for (const factor of [0.5, 0.25, 0.1]) {
2227
+ const tighter = shrinkMetadataLimits(opts, factor);
2228
+ const shrunk = prepareMetadataForDisk(rawMetadata, tighter);
2229
+ working = applyMetadataToEvent(working, shrunk);
2230
+ serialized = serializeEvent(working);
2231
+ if (serialized !== "" && byteLength(serialized) <= opts.maxEventBytes) {
2232
+ return working;
2233
+ }
2234
+ }
2235
+ working = replaceMetadataWithTruncationMarker(working, bytes);
2236
+ serialized = serializeEvent(working);
2237
+ if (serialized !== "" && byteLength(serialized) <= opts.maxEventBytes) {
2238
+ return working;
2239
+ }
2240
+ }
2241
+ working = truncateErrorStack(working, Math.min(opts.maxMetadataValueLength, 500));
2242
+ serialized = serializeEvent(working);
2243
+ if (serialized !== "" && byteLength(serialized) <= opts.maxEventBytes) {
2244
+ return working;
2245
+ }
2246
+ if (eventHasMetadata(working)) {
2247
+ working = replaceMetadataWithTruncationMarker(working, bytes);
2248
+ serialized = serializeEvent(working);
2249
+ if (serialized !== "" && byteLength(serialized) <= opts.maxEventBytes) {
2250
+ return working;
2251
+ }
2252
+ if (working.event === "run_started") {
2253
+ const { metadata: _meta, ...rest } = working;
2254
+ working = rest;
2255
+ } else if (working.event === "step_started") {
2256
+ const { metadata: _meta, ...rest } = working;
2257
+ working = rest;
2258
+ }
2259
+ }
2260
+ return working;
2261
+ } catch {
2262
+ if (event.event === "run_started" || event.event === "step_started") {
2263
+ return applyMetadataToEvent(event, {
2264
+ truncated: true,
2265
+ reason: "prepareTraceEventFailed"
2266
+ });
2267
+ }
2268
+ return event;
2269
+ }
2270
+ }
2271
+
2272
+ // packages/core/src/context.ts
2273
+ var storage = new async_hooks.AsyncLocalStorage();
2274
+ function toPublicContext(ctx) {
2275
+ return {
2276
+ runId: ctx.runId,
2277
+ runName: ctx.runName,
2278
+ traceDir: ctx.traceDir,
2279
+ silent: ctx.silent,
2280
+ metadata: ctx.metadata
2281
+ };
2282
+ }
2283
+ function invoke(fn) {
2284
+ return new Promise((resolve, reject) => {
2285
+ try {
2286
+ Promise.resolve(fn()).then(resolve, reject);
2287
+ } catch (e) {
2288
+ reject(e);
2289
+ }
2290
+ });
2291
+ }
2292
+ function getCurrentContext() {
2293
+ try {
2294
+ const s = storage.getStore();
2295
+ if (!s) return void 0;
2296
+ return toPublicContext(s);
2297
+ } catch {
2298
+ return void 0;
2299
+ }
2300
+ }
2301
+ function getCurrentRunId() {
2302
+ try {
2303
+ return storage.getStore()?.runId;
2304
+ } catch {
2305
+ return void 0;
2306
+ }
2307
+ }
2308
+ function getCurrentRunName() {
2309
+ try {
2310
+ return storage.getStore()?.runName;
2311
+ } catch {
2312
+ return void 0;
1424
2313
  }
1425
- warn("Failed to append trace event to fallback directory");
1426
2314
  }
1427
- async function readTraceFile(runId, traceDir) {
2315
+ function getCurrentStepId() {
1428
2316
  try {
1429
- const filePath = getTraceFilePath(runId, traceDir);
1430
- return await promises.readFile(filePath, "utf-8");
1431
- } catch (e) {
1432
- if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") {
1433
- return void 0;
1434
- }
1435
- warn("Unexpected error reading trace file", e);
2317
+ return storage.getStore()?.currentStepId;
2318
+ } catch {
1436
2319
  return void 0;
1437
2320
  }
1438
2321
  }
1439
- async function readTraceEvents(runId, traceDir) {
1440
- const out = [];
2322
+ function getParentStepId() {
2323
+ return getCurrentStepId();
2324
+ }
2325
+ function getCurrentDepth() {
1441
2326
  try {
1442
- const raw = await readTraceFile(runId, traceDir);
1443
- if (raw === void 0) {
1444
- return out;
1445
- }
1446
- const lines = raw.split("\n");
1447
- for (const line of lines) {
1448
- const trimmed = line.trim();
1449
- if (trimmed === "") continue;
1450
- let parsed;
1451
- try {
1452
- parsed = JSON.parse(trimmed);
1453
- } catch {
1454
- warn("Skipped invalid JSON line in trace file");
1455
- continue;
1456
- }
1457
- if (validateEvent(parsed)) {
1458
- out.push(parsed);
1459
- } else {
1460
- warn("Skipped invalid trace event line in trace file");
1461
- }
1462
- }
1463
- } catch (e) {
1464
- warn("Failed to read trace events", e);
2327
+ const d = storage.getStore()?.currentDepth;
2328
+ return typeof d === "number" && Number.isFinite(d) ? d : 0;
2329
+ } catch {
2330
+ return 0;
1465
2331
  }
1466
- return out;
1467
2332
  }
1468
- async function listTraceFiles(traceDir) {
2333
+ function hasActiveContext() {
1469
2334
  try {
1470
- const usable = path__default.default.resolve(traceDir);
1471
- const names = await promises.readdir(usable);
1472
- const jsonl = names.filter((n) => n.endsWith(".jsonl"));
1473
- const withStat = await Promise.all(
1474
- jsonl.map(async (name) => {
1475
- try {
1476
- const st = await promises.stat(path__default.default.join(usable, name));
1477
- return { name, mtime: st.mtimeMs };
1478
- } catch {
1479
- return { name, mtime: 0 };
1480
- }
1481
- })
1482
- );
1483
- withStat.sort((a, b) => {
1484
- if (b.mtime !== a.mtime) return b.mtime - a.mtime;
1485
- return a.name.localeCompare(b.name);
1486
- });
1487
- return withStat.map((x) => x.name);
2335
+ return storage.getStore() !== void 0;
1488
2336
  } catch {
1489
- return [];
2337
+ return false;
1490
2338
  }
1491
2339
  }
1492
- function getRunIdFromTraceFileName(fileName) {
2340
+ function getTraceDirFromContext() {
1493
2341
  try {
1494
- const base = path__default.default.basename(fileName);
1495
- if (!base.endsWith(".jsonl")) return void 0;
1496
- const id = base.slice(0, -".jsonl".length);
1497
- return id === "" ? void 0 : id;
2342
+ return storage.getStore()?.traceDir;
2343
+ } catch {
2344
+ return void 0;
2345
+ }
2346
+ }
2347
+ function isSilentContext() {
2348
+ try {
2349
+ const s = storage.getStore();
2350
+ return s ? s.silent : false;
2351
+ } catch {
2352
+ return false;
2353
+ }
2354
+ }
2355
+ function getTraceSafetyFromContext() {
2356
+ try {
2357
+ return storage.getStore()?.traceSafety;
1498
2358
  } catch {
1499
2359
  return void 0;
1500
2360
  }
1501
2361
  }
2362
+ function runWithContext(context, fn, traceSafety = resolveTraceSafetyOptions()) {
2363
+ const runtime = {
2364
+ runId: context.runId,
2365
+ runName: context.runName,
2366
+ traceDir: context.traceDir,
2367
+ silent: context.silent,
2368
+ metadata: context.metadata,
2369
+ traceSafety,
2370
+ currentDepth: 0
2371
+ };
2372
+ return new Promise((resolve, reject) => {
2373
+ storage.run(runtime, () => {
2374
+ try {
2375
+ Promise.resolve(fn()).then(resolve, reject);
2376
+ } catch (e) {
2377
+ reject(e);
2378
+ }
2379
+ });
2380
+ });
2381
+ }
2382
+ function runWithStepContext(stepId, fn) {
2383
+ let parent;
2384
+ try {
2385
+ parent = storage.getStore();
2386
+ } catch {
2387
+ parent = void 0;
2388
+ }
2389
+ if (!parent) {
2390
+ return invoke(fn);
2391
+ }
2392
+ const derived = {
2393
+ runId: parent.runId,
2394
+ runName: parent.runName,
2395
+ traceDir: parent.traceDir,
2396
+ silent: parent.silent,
2397
+ metadata: parent.metadata,
2398
+ traceSafety: parent.traceSafety,
2399
+ currentStepId: stepId,
2400
+ currentDepth: parent.currentDepth + 1
2401
+ };
2402
+ return new Promise((resolve, reject) => {
2403
+ storage.run(derived, () => {
2404
+ try {
2405
+ Promise.resolve(fn()).then(resolve, reject);
2406
+ } catch (e) {
2407
+ reject(e);
2408
+ }
2409
+ });
2410
+ });
2411
+ }
1502
2412
  function resolveTraceDir(options = {}) {
1503
2413
  if (typeof options.dir === "string" && options.dir.trim() !== "") {
1504
2414
  return options.dir.trim();
@@ -1763,7 +2673,7 @@ var KNOWN_EVENTS = /* @__PURE__ */ new Set([
1763
2673
  "step_started",
1764
2674
  "step_completed"
1765
2675
  ]);
1766
- function isRecord7(value) {
2676
+ function isRecord9(value) {
1767
2677
  return typeof value === "object" && value !== null && !Array.isArray(value);
1768
2678
  }
1769
2679
  function safeParse(line) {
@@ -1785,7 +2695,7 @@ async function isAgentInspectTrace(filePath) {
1785
2695
  if (trimmed === "") continue;
1786
2696
  const parsed = safeParse(trimmed);
1787
2697
  if (!parsed) continue;
1788
- if (!isRecord7(parsed)) continue;
2698
+ if (!isRecord9(parsed)) continue;
1789
2699
  checked += 1;
1790
2700
  if (isTraceEvent(parsed)) return true;
1791
2701
  const ev = parsed.event;
@@ -1948,7 +2858,7 @@ function stableJson(value, pretty) {
1948
2858
  const sorted = sortKeysDeep(value);
1949
2859
  return pretty === true ? JSON.stringify(sorted, null, 2) : JSON.stringify(sorted);
1950
2860
  }
1951
- function compactAttributes(attrs, options) {
2861
+ function compactAttributes4(attrs, options) {
1952
2862
  if (attrs === void 0) return {};
1953
2863
  const maxLen = options?.maxLength ?? 500;
1954
2864
  const redacted = options?.redacted ?? true;
@@ -2303,6 +3213,498 @@ function diffRuns(left, right, options) {
2303
3213
  };
2304
3214
  return { summary, differences };
2305
3215
  }
3216
+
3217
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
3218
+ var ANSI_BACKGROUND_OFFSET = 10;
3219
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
3220
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
3221
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
3222
+ var styles = {
3223
+ modifier: {
3224
+ reset: [0, 0],
3225
+ // 21 isn't widely supported and 22 does the same thing
3226
+ bold: [1, 22],
3227
+ dim: [2, 22],
3228
+ italic: [3, 23],
3229
+ underline: [4, 24],
3230
+ overline: [53, 55],
3231
+ inverse: [7, 27],
3232
+ hidden: [8, 28],
3233
+ strikethrough: [9, 29]
3234
+ },
3235
+ color: {
3236
+ black: [30, 39],
3237
+ red: [31, 39],
3238
+ green: [32, 39],
3239
+ yellow: [33, 39],
3240
+ blue: [34, 39],
3241
+ magenta: [35, 39],
3242
+ cyan: [36, 39],
3243
+ white: [37, 39],
3244
+ // Bright color
3245
+ blackBright: [90, 39],
3246
+ gray: [90, 39],
3247
+ // Alias of `blackBright`
3248
+ grey: [90, 39],
3249
+ // Alias of `blackBright`
3250
+ redBright: [91, 39],
3251
+ greenBright: [92, 39],
3252
+ yellowBright: [93, 39],
3253
+ blueBright: [94, 39],
3254
+ magentaBright: [95, 39],
3255
+ cyanBright: [96, 39],
3256
+ whiteBright: [97, 39]
3257
+ },
3258
+ bgColor: {
3259
+ bgBlack: [40, 49],
3260
+ bgRed: [41, 49],
3261
+ bgGreen: [42, 49],
3262
+ bgYellow: [43, 49],
3263
+ bgBlue: [44, 49],
3264
+ bgMagenta: [45, 49],
3265
+ bgCyan: [46, 49],
3266
+ bgWhite: [47, 49],
3267
+ // Bright color
3268
+ bgBlackBright: [100, 49],
3269
+ bgGray: [100, 49],
3270
+ // Alias of `bgBlackBright`
3271
+ bgGrey: [100, 49],
3272
+ // Alias of `bgBlackBright`
3273
+ bgRedBright: [101, 49],
3274
+ bgGreenBright: [102, 49],
3275
+ bgYellowBright: [103, 49],
3276
+ bgBlueBright: [104, 49],
3277
+ bgMagentaBright: [105, 49],
3278
+ bgCyanBright: [106, 49],
3279
+ bgWhiteBright: [107, 49]
3280
+ }
3281
+ };
3282
+ Object.keys(styles.modifier);
3283
+ var foregroundColorNames = Object.keys(styles.color);
3284
+ var backgroundColorNames = Object.keys(styles.bgColor);
3285
+ [...foregroundColorNames, ...backgroundColorNames];
3286
+ function assembleStyles() {
3287
+ const codes = /* @__PURE__ */ new Map();
3288
+ for (const [groupName, group] of Object.entries(styles)) {
3289
+ for (const [styleName, style] of Object.entries(group)) {
3290
+ styles[styleName] = {
3291
+ open: `\x1B[${style[0]}m`,
3292
+ close: `\x1B[${style[1]}m`
3293
+ };
3294
+ group[styleName] = styles[styleName];
3295
+ codes.set(style[0], style[1]);
3296
+ }
3297
+ Object.defineProperty(styles, groupName, {
3298
+ value: group,
3299
+ enumerable: false
3300
+ });
3301
+ }
3302
+ Object.defineProperty(styles, "codes", {
3303
+ value: codes,
3304
+ enumerable: false
3305
+ });
3306
+ styles.color.close = "\x1B[39m";
3307
+ styles.bgColor.close = "\x1B[49m";
3308
+ styles.color.ansi = wrapAnsi16();
3309
+ styles.color.ansi256 = wrapAnsi256();
3310
+ styles.color.ansi16m = wrapAnsi16m();
3311
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
3312
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
3313
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
3314
+ Object.defineProperties(styles, {
3315
+ rgbToAnsi256: {
3316
+ value(red, green, blue) {
3317
+ if (red === green && green === blue) {
3318
+ if (red < 8) {
3319
+ return 16;
3320
+ }
3321
+ if (red > 248) {
3322
+ return 231;
3323
+ }
3324
+ return Math.round((red - 8) / 247 * 24) + 232;
3325
+ }
3326
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
3327
+ },
3328
+ enumerable: false
3329
+ },
3330
+ hexToRgb: {
3331
+ value(hex) {
3332
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
3333
+ if (!matches) {
3334
+ return [0, 0, 0];
3335
+ }
3336
+ let [colorString] = matches;
3337
+ if (colorString.length === 3) {
3338
+ colorString = [...colorString].map((character) => character + character).join("");
3339
+ }
3340
+ const integer = Number.parseInt(colorString, 16);
3341
+ return [
3342
+ /* eslint-disable no-bitwise */
3343
+ integer >> 16 & 255,
3344
+ integer >> 8 & 255,
3345
+ integer & 255
3346
+ /* eslint-enable no-bitwise */
3347
+ ];
3348
+ },
3349
+ enumerable: false
3350
+ },
3351
+ hexToAnsi256: {
3352
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
3353
+ enumerable: false
3354
+ },
3355
+ ansi256ToAnsi: {
3356
+ value(code) {
3357
+ if (code < 8) {
3358
+ return 30 + code;
3359
+ }
3360
+ if (code < 16) {
3361
+ return 90 + (code - 8);
3362
+ }
3363
+ let red;
3364
+ let green;
3365
+ let blue;
3366
+ if (code >= 232) {
3367
+ red = ((code - 232) * 10 + 8) / 255;
3368
+ green = red;
3369
+ blue = red;
3370
+ } else {
3371
+ code -= 16;
3372
+ const remainder = code % 36;
3373
+ red = Math.floor(code / 36) / 5;
3374
+ green = Math.floor(remainder / 6) / 5;
3375
+ blue = remainder % 6 / 5;
3376
+ }
3377
+ const value = Math.max(red, green, blue) * 2;
3378
+ if (value === 0) {
3379
+ return 30;
3380
+ }
3381
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
3382
+ if (value === 2) {
3383
+ result += 60;
3384
+ }
3385
+ return result;
3386
+ },
3387
+ enumerable: false
3388
+ },
3389
+ rgbToAnsi: {
3390
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
3391
+ enumerable: false
3392
+ },
3393
+ hexToAnsi: {
3394
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
3395
+ enumerable: false
3396
+ }
3397
+ });
3398
+ return styles;
3399
+ }
3400
+ var ansiStyles = assembleStyles();
3401
+ var ansi_styles_default = ansiStyles;
3402
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2__default.default.argv) {
3403
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
3404
+ const position = argv.indexOf(prefix + flag);
3405
+ const terminatorPosition = argv.indexOf("--");
3406
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
3407
+ }
3408
+ var { env } = process2__default.default;
3409
+ var flagForceColor;
3410
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
3411
+ flagForceColor = 0;
3412
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
3413
+ flagForceColor = 1;
3414
+ }
3415
+ function envForceColor() {
3416
+ if ("FORCE_COLOR" in env) {
3417
+ if (env.FORCE_COLOR === "true") {
3418
+ return 1;
3419
+ }
3420
+ if (env.FORCE_COLOR === "false") {
3421
+ return 0;
3422
+ }
3423
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
3424
+ }
3425
+ }
3426
+ function translateLevel(level) {
3427
+ if (level === 0) {
3428
+ return false;
3429
+ }
3430
+ return {
3431
+ level,
3432
+ hasBasic: true,
3433
+ has256: level >= 2,
3434
+ has16m: level >= 3
3435
+ };
3436
+ }
3437
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
3438
+ const noFlagForceColor = envForceColor();
3439
+ if (noFlagForceColor !== void 0) {
3440
+ flagForceColor = noFlagForceColor;
3441
+ }
3442
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
3443
+ if (forceColor === 0) {
3444
+ return 0;
3445
+ }
3446
+ if (sniffFlags) {
3447
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
3448
+ return 3;
3449
+ }
3450
+ if (hasFlag("color=256")) {
3451
+ return 2;
3452
+ }
3453
+ }
3454
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
3455
+ return 1;
3456
+ }
3457
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
3458
+ return 0;
3459
+ }
3460
+ const min = forceColor || 0;
3461
+ if (env.TERM === "dumb") {
3462
+ return min;
3463
+ }
3464
+ if (process2__default.default.platform === "win32") {
3465
+ const osRelease = os__default.default.release().split(".");
3466
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
3467
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
3468
+ }
3469
+ return 1;
3470
+ }
3471
+ if ("CI" in env) {
3472
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
3473
+ return 3;
3474
+ }
3475
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
3476
+ return 1;
3477
+ }
3478
+ return min;
3479
+ }
3480
+ if ("TEAMCITY_VERSION" in env) {
3481
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
3482
+ }
3483
+ if (env.COLORTERM === "truecolor") {
3484
+ return 3;
3485
+ }
3486
+ if (env.TERM === "xterm-kitty") {
3487
+ return 3;
3488
+ }
3489
+ if (env.TERM === "xterm-ghostty") {
3490
+ return 3;
3491
+ }
3492
+ if (env.TERM === "wezterm") {
3493
+ return 3;
3494
+ }
3495
+ if ("TERM_PROGRAM" in env) {
3496
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
3497
+ switch (env.TERM_PROGRAM) {
3498
+ case "iTerm.app": {
3499
+ return version >= 3 ? 3 : 2;
3500
+ }
3501
+ case "Apple_Terminal": {
3502
+ return 2;
3503
+ }
3504
+ }
3505
+ }
3506
+ if (/-256(color)?$/i.test(env.TERM)) {
3507
+ return 2;
3508
+ }
3509
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
3510
+ return 1;
3511
+ }
3512
+ if ("COLORTERM" in env) {
3513
+ return 1;
3514
+ }
3515
+ return min;
3516
+ }
3517
+ function createSupportsColor(stream, options = {}) {
3518
+ const level = _supportsColor(stream, {
3519
+ streamIsTTY: stream && stream.isTTY,
3520
+ ...options
3521
+ });
3522
+ return translateLevel(level);
3523
+ }
3524
+ var supportsColor = {
3525
+ stdout: createSupportsColor({ isTTY: tty__default.default.isatty(1) }),
3526
+ stderr: createSupportsColor({ isTTY: tty__default.default.isatty(2) })
3527
+ };
3528
+ var supports_color_default = supportsColor;
3529
+
3530
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
3531
+ function stringReplaceAll(string, substring, replacer) {
3532
+ let index = string.indexOf(substring);
3533
+ if (index === -1) {
3534
+ return string;
3535
+ }
3536
+ const substringLength = substring.length;
3537
+ let endIndex = 0;
3538
+ let returnValue = "";
3539
+ do {
3540
+ returnValue += string.slice(endIndex, index) + substring + replacer;
3541
+ endIndex = index + substringLength;
3542
+ index = string.indexOf(substring, endIndex);
3543
+ } while (index !== -1);
3544
+ returnValue += string.slice(endIndex);
3545
+ return returnValue;
3546
+ }
3547
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
3548
+ let endIndex = 0;
3549
+ let returnValue = "";
3550
+ do {
3551
+ const gotCR = string[index - 1] === "\r";
3552
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
3553
+ endIndex = index + 1;
3554
+ index = string.indexOf("\n", endIndex);
3555
+ } while (index !== -1);
3556
+ returnValue += string.slice(endIndex);
3557
+ return returnValue;
3558
+ }
3559
+
3560
+ // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
3561
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
3562
+ var GENERATOR = /* @__PURE__ */ Symbol("GENERATOR");
3563
+ var STYLER = /* @__PURE__ */ Symbol("STYLER");
3564
+ var IS_EMPTY = /* @__PURE__ */ Symbol("IS_EMPTY");
3565
+ var levelMapping = [
3566
+ "ansi",
3567
+ "ansi",
3568
+ "ansi256",
3569
+ "ansi16m"
3570
+ ];
3571
+ var styles2 = /* @__PURE__ */ Object.create(null);
3572
+ var applyOptions = (object, options = {}) => {
3573
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
3574
+ throw new Error("The `level` option should be an integer from 0 to 3");
3575
+ }
3576
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
3577
+ object.level = options.level === void 0 ? colorLevel : options.level;
3578
+ };
3579
+ var chalkFactory = (options) => {
3580
+ const chalk2 = (...strings) => strings.join(" ");
3581
+ applyOptions(chalk2, options);
3582
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
3583
+ return chalk2;
3584
+ };
3585
+ function createChalk(options) {
3586
+ return chalkFactory(options);
3587
+ }
3588
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
3589
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
3590
+ styles2[styleName] = {
3591
+ get() {
3592
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
3593
+ Object.defineProperty(this, styleName, { value: builder });
3594
+ return builder;
3595
+ }
3596
+ };
3597
+ }
3598
+ styles2.visible = {
3599
+ get() {
3600
+ const builder = createBuilder(this, this[STYLER], true);
3601
+ Object.defineProperty(this, "visible", { value: builder });
3602
+ return builder;
3603
+ }
3604
+ };
3605
+ var getModelAnsi = (model, level, type, ...arguments_) => {
3606
+ if (model === "rgb") {
3607
+ if (level === "ansi16m") {
3608
+ return ansi_styles_default[type].ansi16m(...arguments_);
3609
+ }
3610
+ if (level === "ansi256") {
3611
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
3612
+ }
3613
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
3614
+ }
3615
+ if (model === "hex") {
3616
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
3617
+ }
3618
+ return ansi_styles_default[type][model](...arguments_);
3619
+ };
3620
+ var usedModels = ["rgb", "hex", "ansi256"];
3621
+ for (const model of usedModels) {
3622
+ styles2[model] = {
3623
+ get() {
3624
+ const { level } = this;
3625
+ return function(...arguments_) {
3626
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
3627
+ return createBuilder(this, styler, this[IS_EMPTY]);
3628
+ };
3629
+ }
3630
+ };
3631
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
3632
+ styles2[bgModel] = {
3633
+ get() {
3634
+ const { level } = this;
3635
+ return function(...arguments_) {
3636
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
3637
+ return createBuilder(this, styler, this[IS_EMPTY]);
3638
+ };
3639
+ }
3640
+ };
3641
+ }
3642
+ var proto = Object.defineProperties(() => {
3643
+ }, {
3644
+ ...styles2,
3645
+ level: {
3646
+ enumerable: true,
3647
+ get() {
3648
+ return this[GENERATOR].level;
3649
+ },
3650
+ set(level) {
3651
+ this[GENERATOR].level = level;
3652
+ }
3653
+ }
3654
+ });
3655
+ var createStyler = (open, close, parent) => {
3656
+ let openAll;
3657
+ let closeAll;
3658
+ if (parent === void 0) {
3659
+ openAll = open;
3660
+ closeAll = close;
3661
+ } else {
3662
+ openAll = parent.openAll + open;
3663
+ closeAll = close + parent.closeAll;
3664
+ }
3665
+ return {
3666
+ open,
3667
+ close,
3668
+ openAll,
3669
+ closeAll,
3670
+ parent
3671
+ };
3672
+ };
3673
+ var createBuilder = (self, _styler, _isEmpty) => {
3674
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
3675
+ Object.setPrototypeOf(builder, proto);
3676
+ builder[GENERATOR] = self;
3677
+ builder[STYLER] = _styler;
3678
+ builder[IS_EMPTY] = _isEmpty;
3679
+ return builder;
3680
+ };
3681
+ var applyStyle = (self, string) => {
3682
+ if (self.level <= 0 || !string) {
3683
+ return self[IS_EMPTY] ? "" : string;
3684
+ }
3685
+ let styler = self[STYLER];
3686
+ if (styler === void 0) {
3687
+ return string;
3688
+ }
3689
+ const { openAll, closeAll } = styler;
3690
+ if (string.includes("\x1B")) {
3691
+ while (styler !== void 0) {
3692
+ string = stringReplaceAll(string, styler.close, styler.open);
3693
+ styler = styler.parent;
3694
+ }
3695
+ }
3696
+ const lfIndex = string.indexOf("\n");
3697
+ if (lfIndex !== -1) {
3698
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
3699
+ }
3700
+ return openAll + string + closeAll;
3701
+ };
3702
+ Object.defineProperties(createChalk.prototype, styles2);
3703
+ var chalk = createChalk();
3704
+ createChalk({ level: stderrColor ? stderrColor.level : 0 });
3705
+ var source_default = chalk;
3706
+
3707
+ // packages/core/src/diff/renderer.ts
2306
3708
  function formatPath(path5) {
2307
3709
  if (path5 === void 0 || path5.path.length === 0) {
2308
3710
  return "(run)";
@@ -2326,9 +3728,9 @@ function renderRunDiff(result, options) {
2326
3728
  }
2327
3729
  const sev = (s, level) => {
2328
3730
  if (!color) return s;
2329
- if (level === "error") return chalk2__default.default.red(s);
2330
- if (level === "warning") return chalk2__default.default.yellow(s);
2331
- return chalk2__default.default.gray(s);
3731
+ if (level === "error") return source_default.red(s);
3732
+ if (level === "warning") return source_default.yellow(s);
3733
+ return source_default.gray(s);
2332
3734
  };
2333
3735
  const lines = [];
2334
3736
  const { summary } = result;
@@ -2391,6 +3793,8 @@ function diffTraceEvents(leftEvents, rightEvents, options) {
2391
3793
  const right = manualTraceEventsToComparableRun(rightEvents);
2392
3794
  return diffRuns(left, right, options);
2393
3795
  }
3796
+
3797
+ // packages/core/src/terminal.ts
2394
3798
  var TERMINAL_INDENT = " ";
2395
3799
  var MAX_TERMINAL_NAME_LENGTH = 80;
2396
3800
  var MAX_TERMINAL_DEPTH = 10;
@@ -2416,24 +3820,24 @@ function formatTerminalName(name) {
2416
3820
  return truncateName(name, MAX_TERMINAL_NAME_LENGTH);
2417
3821
  }
2418
3822
  function getStatusIcon(status) {
2419
- if (status === "success") return chalk2__default.default.green("\u2714");
2420
- if (status === "error") return chalk2__default.default.red("\u2716");
2421
- return chalk2__default.default.yellow("\u23F3");
3823
+ if (status === "success") return source_default.green("\u2714");
3824
+ if (status === "error") return source_default.red("\u2716");
3825
+ return source_default.yellow("\u23F3");
2422
3826
  }
2423
3827
  function renderStepLine(name, durationMs, status, depth) {
2424
3828
  try {
2425
3829
  const nm = formatTerminalName(name);
2426
3830
  const ind = getIndent(depth ?? 0);
2427
3831
  if (status === "running" && durationMs === void 0) {
2428
- return `${ind}${chalk2__default.default.yellow("\u23F3")} ${nm}`;
3832
+ return `${ind}${source_default.yellow("\u23F3")} ${nm}`;
2429
3833
  }
2430
3834
  const hasDur = durationMs !== void 0 && Number.isFinite(durationMs);
2431
3835
  const dur = hasDur ? formatDuration2(durationMs) : void 0;
2432
3836
  if (status === "running") {
2433
- return dur !== void 0 ? `${ind}${chalk2__default.default.yellow("\u23F3")} ${nm} (${dur})` : `${ind}${chalk2__default.default.yellow("\u23F3")} ${nm}`;
3837
+ return dur !== void 0 ? `${ind}${source_default.yellow("\u23F3")} ${nm} (${dur})` : `${ind}${source_default.yellow("\u23F3")} ${nm}`;
2434
3838
  }
2435
3839
  if (!hasDur || dur === void 0) {
2436
- return `${ind}${chalk2__default.default.yellow("\u23F3")} ${nm}`;
3840
+ return `${ind}${source_default.yellow("\u23F3")} ${nm}`;
2437
3841
  }
2438
3842
  if (status === "success") {
2439
3843
  return `${ind}${getStatusIcon("success")} ${nm} (${dur})`;
@@ -2469,7 +3873,7 @@ function printRunStart(runId, name) {
2469
3873
  if (isSilentContext()) return;
2470
3874
  try {
2471
3875
  safePrint("");
2472
- const header = `${chalk2__default.default.cyan.bold("\u{1F50D} AgentInspect:")} ${formatTerminalName(name)} ${chalk2__default.default.dim(`(${runId})`)}`;
3876
+ const header = `${source_default.cyan.bold("\u{1F50D} AgentInspect:")} ${formatTerminalName(name)} ${source_default.dim(`(${runId})`)}`;
2473
3877
  safePrint(header);
2474
3878
  } catch {
2475
3879
  }
@@ -2502,10 +3906,10 @@ function printRunComplete(_name, _runId, durationMs, status, traceFilePath) {
2502
3906
  for (let i = 0; i < lines.length; i++) {
2503
3907
  const line = lines[i];
2504
3908
  if (i === 0) {
2505
- const color = status === "error" ? chalk2__default.default.red : status === "running" ? chalk2__default.default.yellow : chalk2__default.default.green;
3909
+ const color = status === "error" ? source_default.red : status === "running" ? source_default.yellow : source_default.green;
2506
3910
  safePrint(color(line));
2507
3911
  } else {
2508
- safePrint(chalk2__default.default.dim(line));
3912
+ safePrint(source_default.dim(line));
2509
3913
  }
2510
3914
  }
2511
3915
  } catch {
@@ -2543,6 +3947,7 @@ async function inspectRun(name, fn, options) {
2543
3947
  const runName = normalizeRunName(name);
2544
3948
  const runId = createRunId();
2545
3949
  const traceDir = resolveTraceDir({ dir: options?.traceDir });
3950
+ const traceSafety = resolveTraceSafetyOptions(options);
2546
3951
  const context = {
2547
3952
  runId,
2548
3953
  runName,
@@ -2566,7 +3971,10 @@ async function inspectRun(name, fn, options) {
2566
3971
  startTime,
2567
3972
  ...options?.metadata !== void 0 ? { metadata: options.metadata } : {}
2568
3973
  };
2569
- await writeTraceEvent(started, traceDir);
3974
+ await writeTraceEvent(
3975
+ prepareTraceEventForDisk(started, traceSafety),
3976
+ traceDir
3977
+ );
2570
3978
  });
2571
3979
  await safeInstrumentation("printRunStart", () => {
2572
3980
  printRunStart(runId, runName);
@@ -2590,7 +3998,10 @@ async function inspectRun(name, fn, options) {
2590
3998
  durationMs: durationMs2,
2591
3999
  error: formatted
2592
4000
  };
2593
- await writeTraceEvent(completed, traceDir);
4001
+ await writeTraceEvent(
4002
+ prepareTraceEventForDisk(completed, traceSafety),
4003
+ traceDir
4004
+ );
2594
4005
  });
2595
4006
  await safeInstrumentation("printRunComplete(error)", () => {
2596
4007
  printRunComplete(runName, runId, durationMs2, "error", printPath2);
@@ -2610,13 +4021,16 @@ async function inspectRun(name, fn, options) {
2610
4021
  endTime,
2611
4022
  durationMs
2612
4023
  };
2613
- await writeTraceEvent(completed, traceDir);
4024
+ await writeTraceEvent(
4025
+ prepareTraceEventForDisk(completed, traceSafety),
4026
+ traceDir
4027
+ );
2614
4028
  });
2615
4029
  await safeInstrumentation("printRunComplete(success)", () => {
2616
4030
  printRunComplete(runName, runId, durationMs, "success", printPath);
2617
4031
  });
2618
4032
  return result;
2619
- });
4033
+ }, traceSafety);
2620
4034
  }
2621
4035
 
2622
4036
  // packages/core/src/maybe-inspect-run.ts
@@ -2667,6 +4081,7 @@ async function stepImpl(name, fn, options) {
2667
4081
  const parentId = getParentStepId();
2668
4082
  const stepType = options?.type ?? "logic";
2669
4083
  const metadata = options?.metadata;
4084
+ const traceSafety = getTraceSafetyFromContext();
2670
4085
  const startTime = Date.now();
2671
4086
  await safeInstrumentation2("writeTraceEvent(step_started)", async () => {
2672
4087
  const started = {
@@ -2681,7 +4096,8 @@ async function stepImpl(name, fn, options) {
2681
4096
  startTime,
2682
4097
  ...metadata !== void 0 ? { metadata } : {}
2683
4098
  };
2684
- await writeTraceEvent(started, context.traceDir);
4099
+ const safe = traceSafety !== void 0 ? prepareTraceEventForDisk(started, traceSafety) : started;
4100
+ await writeTraceEvent(safe, context.traceDir);
2685
4101
  });
2686
4102
  await safeInstrumentation2("printStepStart", () => {
2687
4103
  printStepStart(stepName, renderDepth);
@@ -2707,7 +4123,8 @@ async function stepImpl(name, fn, options) {
2707
4123
  durationMs: durationMs2,
2708
4124
  error: formatted
2709
4125
  };
2710
- await writeTraceEvent(completed, context.traceDir);
4126
+ const safe = traceSafety !== void 0 ? prepareTraceEventForDisk(completed, traceSafety) : completed;
4127
+ await writeTraceEvent(safe, context.traceDir);
2711
4128
  });
2712
4129
  await safeInstrumentation2("printStepComplete(error)", () => {
2713
4130
  printStepComplete(stepName, durationMs2, "error", renderDepth);
@@ -2733,7 +4150,8 @@ async function stepImpl(name, fn, options) {
2733
4150
  endTime,
2734
4151
  durationMs
2735
4152
  };
2736
- await writeTraceEvent(completed, context.traceDir);
4153
+ const safe = traceSafety !== void 0 ? prepareTraceEventForDisk(completed, traceSafety) : completed;
4154
+ await writeTraceEvent(safe, context.traceDir);
2737
4155
  });
2738
4156
  await safeInstrumentation2("printStepComplete(success)", () => {
2739
4157
  printStepComplete(stepName, durationMs, "success", renderDepth);
@@ -2922,7 +4340,7 @@ function exportHtml(tree, options) {
2922
4340
  attrsHtml += "<h2>Attributes (bounded)</h2>";
2923
4341
  for (const n of flat) {
2924
4342
  if (!n.event.attributes || Object.keys(n.event.attributes).length === 0) continue;
2925
- const compact = compactAttributes(n.event.attributes, {
4343
+ const compact = compactAttributes4(n.event.attributes, {
2926
4344
  maxLength: maxLen,
2927
4345
  redacted
2928
4346
  });
@@ -3073,7 +4491,7 @@ function exportMarkdown(tree, options) {
3073
4491
  lines.push("");
3074
4492
  for (const n of flat) {
3075
4493
  if (!n.event.attributes || Object.keys(n.event.attributes).length === 0) continue;
3076
- const compact = compactAttributes(n.event.attributes, {
4494
+ const compact = compactAttributes4(n.event.attributes, {
3077
4495
  maxLength: maxLen,
3078
4496
  redacted
3079
4497
  });
@@ -3603,6 +5021,9 @@ function validateExport(result) {
3603
5021
  }
3604
5022
 
3605
5023
  exports.DEFAULT_LOG_INGEST_CONFIG = DEFAULT_LOG_INGEST_CONFIG;
5024
+ exports.DEFAULT_MAX_EVENT_BYTES = DEFAULT_MAX_EVENT_BYTES;
5025
+ exports.DEFAULT_MAX_METADATA_VALUE_LENGTH = DEFAULT_MAX_METADATA_VALUE_LENGTH;
5026
+ exports.DEFAULT_MAX_PREVIEW_LENGTH = DEFAULT_MAX_PREVIEW_LENGTH;
3606
5027
  exports.DEFAULT_REDACT_KEYS = DEFAULT_REDACT_KEYS;
3607
5028
  exports.DEFAULT_TRACE_DIR_NAME = DEFAULT_TRACE_DIR_NAME;
3608
5029
  exports.EXPORT_PAYLOAD_VERSION = EXPORT_PAYLOAD_VERSION;
@@ -3620,7 +5041,7 @@ exports.TERMINAL_INDENT = TERMINAL_INDENT;
3620
5041
  exports.TraceDirectory = TraceDirectory;
3621
5042
  exports.TreeBuilder = TreeBuilder;
3622
5043
  exports.buildRunSummary = buildRunSummary;
3623
- exports.compactAttributes = compactAttributes;
5044
+ exports.compactAttributes = compactAttributes4;
3624
5045
  exports.createRunId = createRunId;
3625
5046
  exports.createStepId = createStepId;
3626
5047
  exports.diffRuns = diffRuns;
@@ -3651,11 +5072,15 @@ exports.getParentStepId = getParentStepId;
3651
5072
  exports.getRunIdFromTraceFileName = getRunIdFromTraceFileName;
3652
5073
  exports.getTraceDirFromContext = getTraceDirFromContext;
3653
5074
  exports.getTraceFilePath = getTraceFilePath;
5075
+ exports.getTraceSafetyFromContext = getTraceSafetyFromContext;
3654
5076
  exports.hasActiveContext = hasActiveContext;
3655
5077
  exports.initializeTraceFile = initializeTraceFile;
5078
+ exports.inspectEventToPersistedInspectEvent = inspectEventToPersistedInspectEvent;
5079
+ exports.inspectEventsToPersistedInspectEvents = inspectEventsToPersistedInspectEvents;
3656
5080
  exports.inspectRun = inspectRun;
3657
5081
  exports.isAgentInspectEnabled = isAgentInspectEnabled;
3658
5082
  exports.isAgentInspectTrace = isAgentInspectTrace;
5083
+ exports.isPersistedInspectEvent = isPersistedInspectEvent;
3659
5084
  exports.isSilentContext = isSilentContext;
3660
5085
  exports.isStepStatus = isStepStatus;
3661
5086
  exports.isStepType = isStepType;
@@ -3672,6 +5097,11 @@ exports.observe = observe;
3672
5097
  exports.parseDuration = parseDuration;
3673
5098
  exports.parseLogLine = parseLogLine;
3674
5099
  exports.parseLogsToTrees = parseLogsToTrees;
5100
+ exports.persistedInspectEventToInspectEvent = persistedInspectEventToInspectEvent;
5101
+ exports.persistedInspectEventsToInspectEvents = persistedInspectEventsToInspectEvents;
5102
+ exports.persistedInspectEventsToRunTrees = persistedInspectEventsToRunTrees;
5103
+ exports.prepareMetadataForDisk = prepareMetadataForDisk;
5104
+ exports.prepareTraceEventForDisk = prepareTraceEventForDisk;
3675
5105
  exports.printError = printError;
3676
5106
  exports.printFailedAt = printFailedAt;
3677
5107
  exports.printRunComplete = printRunComplete;
@@ -3687,6 +5117,7 @@ exports.renderRunTree = renderRunTree;
3687
5117
  exports.renderRunTrees = renderRunTrees;
3688
5118
  exports.renderStepLine = renderStepLine;
3689
5119
  exports.resolveTraceDir = resolveTraceDir;
5120
+ exports.resolveTraceSafetyOptions = resolveTraceSafetyOptions;
3690
5121
  exports.runWithContext = runWithContext;
3691
5122
  exports.runWithStepContext = runWithStepContext;
3692
5123
  exports.safeString = safeString2;
@@ -3694,6 +5125,9 @@ exports.serializeEvent = serializeEvent;
3694
5125
  exports.stableJson = stableJson;
3695
5126
  exports.step = step;
3696
5127
  exports.summarizeTree = summarizeTree;
5128
+ exports.traceEventToPersistedInspectEvent = traceEventToPersistedInspectEvent;
5129
+ exports.traceEventsToPersistedInspectEvents = traceEventsToPersistedInspectEvents;
5130
+ exports.traceEventsToPersistedRunTrees = traceEventsToPersistedRunTrees;
3697
5131
  exports.truncateName = truncateName;
3698
5132
  exports.validateEvent = validateEvent;
3699
5133
  exports.validateExport = validateExport;