agent-inspect 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +12 -4
  3. package/docs/API.md +124 -9
  4. package/docs/ARCHITECTURE.md +4 -0
  5. package/docs/CLI.md +41 -12
  6. package/docs/KNOWN-ISSUES.md +8 -1
  7. package/docs/LIMITATIONS.md +11 -2
  8. package/docs/SCHEMA.md +16 -6
  9. package/package.json +21 -1
  10. package/packages/cli/dist/index.cjs +2449 -157
  11. package/packages/cli/dist/index.cjs.map +1 -1
  12. package/packages/cli/dist/index.mjs +2450 -158
  13. package/packages/cli/dist/index.mjs.map +1 -1
  14. package/packages/core/dist/advanced.cjs +839 -18
  15. package/packages/core/dist/advanced.cjs.map +1 -1
  16. package/packages/core/dist/advanced.d.cts +98 -3
  17. package/packages/core/dist/advanced.d.ts +98 -3
  18. package/packages/core/dist/advanced.mjs +7 -4
  19. package/packages/core/dist/chunk-57S5D6HR.mjs +655 -0
  20. package/packages/core/dist/chunk-57S5D6HR.mjs.map +1 -0
  21. package/packages/core/dist/chunk-6QSLZCBJ.mjs +743 -0
  22. package/packages/core/dist/chunk-6QSLZCBJ.mjs.map +1 -0
  23. package/packages/core/dist/chunk-6SZPTECC.mjs +342 -0
  24. package/packages/core/dist/chunk-6SZPTECC.mjs.map +1 -0
  25. package/packages/core/dist/{chunk-QX3ZMPUF.mjs → chunk-74XZ6N7Q.mjs} +13 -55
  26. package/packages/core/dist/chunk-74XZ6N7Q.mjs.map +1 -0
  27. package/packages/core/dist/{chunk-QPAU2TPA.mjs → chunk-HR7G62IE.mjs} +4 -4
  28. package/packages/core/dist/{chunk-QPAU2TPA.mjs.map → chunk-HR7G62IE.mjs.map} +1 -1
  29. package/packages/core/dist/chunk-S4YWKV4G.mjs +48 -0
  30. package/packages/core/dist/chunk-S4YWKV4G.mjs.map +1 -0
  31. package/packages/core/dist/chunk-TFLPUZ56.mjs +1571 -0
  32. package/packages/core/dist/chunk-TFLPUZ56.mjs.map +1 -0
  33. package/packages/core/dist/{chunk-Q6EPNB3V.mjs → chunk-TZISEVLQ.mjs} +34 -183
  34. package/packages/core/dist/chunk-TZISEVLQ.mjs.map +1 -0
  35. package/packages/core/dist/chunk-U2BGPESY.mjs +150 -0
  36. package/packages/core/dist/chunk-U2BGPESY.mjs.map +1 -0
  37. package/packages/core/dist/chunk-VTIB5MDK.mjs +304 -0
  38. package/packages/core/dist/chunk-VTIB5MDK.mjs.map +1 -0
  39. package/packages/core/dist/{chunk-5EMIZZXD.mjs → chunk-Y56BPA3B.mjs} +87 -4
  40. package/packages/core/dist/chunk-Y56BPA3B.mjs.map +1 -0
  41. package/packages/core/dist/diff.d.cts +3 -2
  42. package/packages/core/dist/diff.d.ts +3 -2
  43. package/packages/core/dist/exporters.cjs.map +1 -1
  44. package/packages/core/dist/exporters.d.cts +3 -2
  45. package/packages/core/dist/exporters.d.ts +3 -2
  46. package/packages/core/dist/exporters.mjs +2 -2
  47. package/packages/core/dist/index.cjs +2975 -229
  48. package/packages/core/dist/index.cjs.map +1 -1
  49. package/packages/core/dist/index.d.cts +27 -6
  50. package/packages/core/dist/index.d.ts +27 -6
  51. package/packages/core/dist/index.mjs +113 -60
  52. package/packages/core/dist/index.mjs.map +1 -1
  53. package/packages/core/dist/{log-config-BzGmDYum.d.cts → inspect-event-Des4JDHo.d.cts} +1 -31
  54. package/packages/core/dist/{log-config-BzGmDYum.d.ts → inspect-event-Des4JDHo.d.ts} +1 -31
  55. package/packages/core/dist/log-config-BnH8Ykcb.d.cts +33 -0
  56. package/packages/core/dist/log-config-C1GcJPIM.d.ts +33 -0
  57. package/packages/core/dist/logs.d.cts +3 -2
  58. package/packages/core/dist/logs.d.ts +3 -2
  59. package/packages/core/dist/logs.mjs +3 -3
  60. package/packages/core/dist/persisted-inspect-event-0kaRADsp.d.cts +56 -0
  61. package/packages/core/dist/persisted-inspect-event-DiFto0K2.d.ts +56 -0
  62. package/packages/core/dist/persisted.cjs +38 -40
  63. package/packages/core/dist/persisted.cjs.map +1 -1
  64. package/packages/core/dist/persisted.d.cts +6 -55
  65. package/packages/core/dist/persisted.d.ts +6 -55
  66. package/packages/core/dist/persisted.mjs +4 -2
  67. package/packages/core/dist/readers.cjs +2590 -0
  68. package/packages/core/dist/readers.cjs.map +1 -0
  69. package/packages/core/dist/readers.d.cts +80 -0
  70. package/packages/core/dist/readers.d.ts +80 -0
  71. package/packages/core/dist/readers.mjs +9 -0
  72. package/packages/core/dist/readers.mjs.map +1 -0
  73. package/packages/core/dist/{types-CNbheSdk.d.cts → types-DB8jB6Jg.d.cts} +7 -1
  74. package/packages/core/dist/{types-Bkt7LS01.d.ts → types-tSix7tfv.d.ts} +7 -1
  75. package/packages/core/dist/writers.cjs +997 -0
  76. package/packages/core/dist/writers.cjs.map +1 -0
  77. package/packages/core/dist/writers.d.cts +62 -0
  78. package/packages/core/dist/writers.d.ts +62 -0
  79. package/packages/core/dist/writers.mjs +9 -0
  80. package/packages/core/dist/writers.mjs.map +1 -0
  81. package/packages/core/dist/chunk-5EMIZZXD.mjs.map +0 -1
  82. package/packages/core/dist/chunk-Q6EPNB3V.mjs.map +0 -1
  83. package/packages/core/dist/chunk-QX3ZMPUF.mjs.map +0 -1
  84. package/packages/core/dist/chunk-XDBND27A.mjs +0 -975
  85. package/packages/core/dist/chunk-XDBND27A.mjs.map +0 -1
@@ -212,6 +212,135 @@ function applyProfileMetadataCaps(maxMetadataValueLength, maxPreviewLength, reso
212
212
  return { maxMetadataValueLength: meta, maxPreviewLength: preview };
213
213
  }
214
214
 
215
+ // packages/core/src/types/persisted-inspect-event.ts
216
+ var INSPECT_KINDS = [
217
+ "RUN",
218
+ "AGENT",
219
+ "LLM",
220
+ "TOOL",
221
+ "CHAIN",
222
+ "RETRIEVER",
223
+ "DECISION",
224
+ "RESULT",
225
+ "ERROR",
226
+ "LOGIC",
227
+ "LOG"
228
+ ];
229
+ var ATTRIBUTION_CONFIDENCES = [
230
+ "explicit",
231
+ "correlated",
232
+ "heuristic",
233
+ "unknown"
234
+ ];
235
+ var PERSISTED_EVENT_SOURCE_TYPES = [
236
+ "manual",
237
+ "json-log",
238
+ "log4js",
239
+ "adapter",
240
+ "ai-sdk",
241
+ "otel"
242
+ ];
243
+ var PERSISTED_EVENT_STATUSES = [
244
+ "running",
245
+ "ok",
246
+ "error",
247
+ "unknown"
248
+ ];
249
+ function isRecord2(value) {
250
+ return typeof value === "object" && value !== null && !Array.isArray(value);
251
+ }
252
+ function isString(value) {
253
+ return typeof value === "string";
254
+ }
255
+ function isNonEmptyString2(value) {
256
+ return typeof value === "string" && value.length > 0;
257
+ }
258
+ function isOptionalString(value) {
259
+ return value === void 0 || isString(value);
260
+ }
261
+ function isNonNegativeNumber(value) {
262
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
263
+ }
264
+ function isOptionalNonNegativeNumber(value) {
265
+ return value === void 0 || isNonNegativeNumber(value);
266
+ }
267
+ function isInspectKind(value) {
268
+ return typeof value === "string" && INSPECT_KINDS.includes(value);
269
+ }
270
+ function isAttributionConfidence(value) {
271
+ return typeof value === "string" && ATTRIBUTION_CONFIDENCES.includes(value);
272
+ }
273
+ function isPersistedEventSourceType(value) {
274
+ return typeof value === "string" && PERSISTED_EVENT_SOURCE_TYPES.includes(value);
275
+ }
276
+ function isPersistedEventStatus(value) {
277
+ return typeof value === "string" && PERSISTED_EVENT_STATUSES.includes(value);
278
+ }
279
+ function isPersistedEventSource(value) {
280
+ if (!isRecord2(value)) return false;
281
+ if (!isPersistedEventSourceType(value.type)) return false;
282
+ if (!isOptionalString(value.name)) return false;
283
+ if (!isOptionalString(value.version)) return false;
284
+ return true;
285
+ }
286
+ function isPersistedInspectError(value) {
287
+ if (!isRecord2(value)) return false;
288
+ if (!isNonEmptyString2(value.message)) return false;
289
+ if (!isOptionalString(value.name)) return false;
290
+ if (!isOptionalString(value.code)) return false;
291
+ return true;
292
+ }
293
+ function isPersistedTokenUsage(value) {
294
+ if (!isRecord2(value)) return false;
295
+ if (!isOptionalNonNegativeNumber(value.input)) return false;
296
+ if (!isOptionalNonNegativeNumber(value.output)) return false;
297
+ if (!isOptionalNonNegativeNumber(value.total)) return false;
298
+ if (!isOptionalNonNegativeNumber(value.cached)) return false;
299
+ return true;
300
+ }
301
+ function isPersistedTraceContext(value) {
302
+ if (!isRecord2(value)) return false;
303
+ if (!isOptionalString(value.traceId)) return false;
304
+ if (!isOptionalString(value.spanId)) return false;
305
+ if (!isOptionalString(value.parentSpanId)) return false;
306
+ return true;
307
+ }
308
+ function isPersistedInspectEvent(value) {
309
+ if (!isRecord2(value)) return false;
310
+ if (value.schemaVersion !== "0.2") return false;
311
+ if (!isNonEmptyString2(value.eventId)) return false;
312
+ if (!isNonEmptyString2(value.runId)) return false;
313
+ if (!isInspectKind(value.kind)) return false;
314
+ if (!isNonEmptyString2(value.name)) return false;
315
+ if (!isNonEmptyString2(value.timestamp)) return false;
316
+ if (!isAttributionConfidence(value.confidence)) return false;
317
+ if (!isPersistedEventSource(value.source)) return false;
318
+ if (value.parentId !== void 0 && !isNonEmptyString2(value.parentId)) {
319
+ return false;
320
+ }
321
+ if (value.status !== void 0 && !isPersistedEventStatus(value.status)) {
322
+ return false;
323
+ }
324
+ if (!isOptionalString(value.startedAt)) return false;
325
+ if (!isOptionalString(value.endedAt)) return false;
326
+ if (value.durationMs !== void 0 && !isNonNegativeNumber(value.durationMs)) {
327
+ return false;
328
+ }
329
+ if (value.attributes !== void 0 && !isRecord2(value.attributes)) {
330
+ return false;
331
+ }
332
+ if (value.error !== void 0 && !isPersistedInspectError(value.error)) {
333
+ return false;
334
+ }
335
+ if (value.tokenUsage !== void 0 && !isPersistedTokenUsage(value.tokenUsage)) {
336
+ return false;
337
+ }
338
+ if (value.trace !== void 0 && !isPersistedTraceContext(value.trace)) {
339
+ return false;
340
+ }
341
+ return true;
342
+ }
343
+
215
344
  // node_modules/.pnpm/nanoid@5.1.11/node_modules/nanoid/url-alphabet/index.js
216
345
  var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
217
346
 
@@ -398,7 +527,7 @@ function serializeEvent(event) {
398
527
  var DEFAULT_MAX_METADATA_VALUE_LENGTH = 2e3;
399
528
  var DEFAULT_MAX_PREVIEW_LENGTH = 500;
400
529
  var DEFAULT_MAX_EVENT_BYTES = 65536;
401
- function isRecord2(value) {
530
+ function isRecord3(value) {
402
531
  return typeof value === "object" && value !== null && !Array.isArray(value);
403
532
  }
404
533
  function isPreviewKey(key) {
@@ -420,7 +549,7 @@ function resolveTraceSafetyOptions(options) {
420
549
  redactEnabled = false;
421
550
  } else if (redact === true || redact === void 0) {
422
551
  redactEnabled = true;
423
- } else if (isRecord2(redact)) {
552
+ } else if (isRecord3(redact)) {
424
553
  redactEnabled = true;
425
554
  redactionRules = redact.rules;
426
555
  }
@@ -451,6 +580,21 @@ function resolveTraceSafetyOptions(options) {
451
580
  }
452
581
  function boundMetadataValue(key, value, opts, seen, depth) {
453
582
  if (depth > 32) return "[MaxDepth]";
583
+ if (typeof value === "bigint") {
584
+ return `${value.toString()}n`;
585
+ }
586
+ if (typeof value === "function") {
587
+ return "[Function]";
588
+ }
589
+ if (typeof value === "symbol") {
590
+ return "[Symbol]";
591
+ }
592
+ if (typeof value === "number" && !Number.isFinite(value)) {
593
+ return String(value);
594
+ }
595
+ if (value === void 0) {
596
+ return null;
597
+ }
454
598
  if (value === null || typeof value !== "object") {
455
599
  if (typeof value === "string") {
456
600
  const max = isPreviewKey(key) ? opts.maxPreviewLength : opts.maxMetadataValueLength;
@@ -472,8 +616,12 @@ function boundMetadataValue(key, value, opts, seen, depth) {
472
616
  }
473
617
  const record = value;
474
618
  const out = {};
475
- for (const [k, v] of Object.entries(record)) {
476
- out[k] = boundMetadataValue(k, v, opts, seen, depth + 1);
619
+ try {
620
+ for (const [k, v] of Object.entries(record)) {
621
+ out[k] = boundMetadataValue(k, v, opts, seen, depth + 1);
622
+ }
623
+ } catch {
624
+ return { truncated: true, reason: "metadataEnumerationFailed" };
477
625
  }
478
626
  return out;
479
627
  }
@@ -487,16 +635,25 @@ function redactMetadata(metadata, opts) {
487
635
  }
488
636
  function prepareMetadataForDisk(metadata, opts) {
489
637
  try {
490
- const redacted = redactMetadata(metadata, opts);
491
- const seen = /* @__PURE__ */ new WeakSet();
638
+ const preBounded = boundMetadataValue(
639
+ "metadata",
640
+ metadata,
641
+ opts,
642
+ /* @__PURE__ */ new WeakSet(),
643
+ 0
644
+ );
645
+ const redacted = redactMetadata(
646
+ isRecord3(preBounded) ? preBounded : {},
647
+ opts
648
+ );
492
649
  const bounded = boundMetadataValue(
493
650
  "metadata",
494
651
  redacted,
495
652
  opts,
496
- seen,
653
+ /* @__PURE__ */ new WeakSet(),
497
654
  0
498
655
  );
499
- return isRecord2(bounded) ? bounded : {};
656
+ return isRecord3(bounded) ? bounded : {};
500
657
  } catch {
501
658
  return { truncated: true, reason: "metadataPreparationFailed" };
502
659
  }
@@ -617,6 +774,210 @@ function prepareTraceEventForDisk(event, opts) {
617
774
  return event;
618
775
  }
619
776
  }
777
+ function safeGet(record, key) {
778
+ try {
779
+ return record[key];
780
+ } catch {
781
+ return void 0;
782
+ }
783
+ }
784
+ function optionalBoundedString(value, _key, opts) {
785
+ if (typeof value !== "string") return void 0;
786
+ return truncateString(value, opts.maxMetadataValueLength);
787
+ }
788
+ function requiredBoundedString(value, key, opts) {
789
+ const out = optionalBoundedString(value, key, opts);
790
+ return out && out.length > 0 ? out : void 0;
791
+ }
792
+ function preparePersistedSummaryForDisk(key, value, opts) {
793
+ try {
794
+ const redactor = new Redactor({
795
+ rules: opts.redactionRules,
796
+ extraKeys: opts.profileExtraKeys
797
+ });
798
+ const redacted = opts.redactEnabled ? redactor.redactValue(key, value) : value;
799
+ return boundMetadataValue(key, redacted, opts, /* @__PURE__ */ new WeakSet(), 0);
800
+ } catch {
801
+ return { truncated: true, reason: "summaryPreparationFailed" };
802
+ }
803
+ }
804
+ function preparePersistedErrorForDisk(value, opts) {
805
+ if (!isRecord3(value)) return void 0;
806
+ try {
807
+ const redactor = new Redactor({
808
+ rules: opts.redactionRules,
809
+ extraKeys: opts.profileExtraKeys
810
+ });
811
+ const rawMessage = safeGet(value, "message");
812
+ const redactedMessage = opts.redactEnabled ? redactor.redactValue("message", rawMessage) : rawMessage;
813
+ const boundedMessage = boundMetadataValue(
814
+ "message",
815
+ redactedMessage,
816
+ opts,
817
+ /* @__PURE__ */ new WeakSet(),
818
+ 0
819
+ );
820
+ const message = typeof boundedMessage === "string" && boundedMessage.length > 0 ? boundedMessage : "Unknown error";
821
+ const out = { message };
822
+ const name = optionalBoundedString(safeGet(value, "name"), "name", opts);
823
+ const code = optionalBoundedString(safeGet(value, "code"), "code", opts);
824
+ if (name !== void 0) out.name = name;
825
+ if (code !== void 0) out.code = code;
826
+ return out;
827
+ } catch {
828
+ return { message: "Error preparation failed" };
829
+ }
830
+ }
831
+ function prepareTokenUsage(value) {
832
+ if (!isRecord3(value)) return void 0;
833
+ const out = {};
834
+ for (const key of ["input", "output", "total", "cached"]) {
835
+ const item = safeGet(value, key);
836
+ if (typeof item === "number" && Number.isFinite(item) && item >= 0) {
837
+ out[key] = item;
838
+ }
839
+ }
840
+ return Object.keys(out).length > 0 ? out : void 0;
841
+ }
842
+ function prepareTraceContext(value, opts) {
843
+ if (!isRecord3(value)) return void 0;
844
+ const out = {};
845
+ const traceId = optionalBoundedString(safeGet(value, "traceId"), "traceId", opts);
846
+ const spanId = optionalBoundedString(safeGet(value, "spanId"), "spanId", opts);
847
+ const parentSpanId = optionalBoundedString(
848
+ safeGet(value, "parentSpanId"),
849
+ "parentSpanId",
850
+ opts
851
+ );
852
+ if (traceId !== void 0) out.traceId = traceId;
853
+ if (spanId !== void 0) out.spanId = spanId;
854
+ if (parentSpanId !== void 0) out.parentSpanId = parentSpanId;
855
+ return Object.keys(out).length > 0 ? out : void 0;
856
+ }
857
+ function serializedPersistedEvent(event) {
858
+ try {
859
+ return JSON.stringify(event);
860
+ } catch {
861
+ return void 0;
862
+ }
863
+ }
864
+ function persistedEventByteLength(event) {
865
+ const serialized = serializedPersistedEvent(event);
866
+ return serialized === void 0 ? void 0 : byteLength(serialized);
867
+ }
868
+ function minimalPersistedEvent(event, opts, originalApproxBytes) {
869
+ return {
870
+ schemaVersion: "0.2",
871
+ eventId: truncateString(event.eventId, 128),
872
+ runId: truncateString(event.runId, 128),
873
+ kind: event.kind,
874
+ name: truncateString(event.name, 128),
875
+ ...event.status !== void 0 ? { status: event.status } : {},
876
+ timestamp: truncateString(event.timestamp, 128),
877
+ confidence: event.confidence,
878
+ source: {
879
+ type: event.source.type,
880
+ ...event.source.name !== void 0 ? { name: truncateString(event.source.name, 128) } : {},
881
+ ...event.source.version !== void 0 ? { version: truncateString(event.source.version, 128) } : {}
882
+ },
883
+ attributes: {
884
+ truncated: true,
885
+ reason: "maxEventBytes",
886
+ originalApproxBytes,
887
+ maxEventBytes: opts.maxEventBytes
888
+ }
889
+ };
890
+ }
891
+ function tinyPersistedEvent(event) {
892
+ return {
893
+ schemaVersion: "0.2",
894
+ eventId: truncateString(event.eventId, 32),
895
+ runId: truncateString(event.runId, 32),
896
+ kind: event.kind,
897
+ name: truncateString(event.name, 32),
898
+ timestamp: truncateString(event.timestamp, 32),
899
+ confidence: event.confidence,
900
+ source: { type: event.source.type },
901
+ attributes: { truncated: true, reason: "maxEventBytes" }
902
+ };
903
+ }
904
+ function enforcePersistedEventSize(event, opts) {
905
+ const bytes = persistedEventByteLength(event);
906
+ if (bytes === void 0) return void 0;
907
+ if (bytes <= opts.maxEventBytes) return event;
908
+ const minimal = minimalPersistedEvent(event, opts, bytes);
909
+ const minimalBytes = persistedEventByteLength(minimal);
910
+ if (minimalBytes !== void 0 && minimalBytes <= opts.maxEventBytes) {
911
+ return minimal;
912
+ }
913
+ const tiny = tinyPersistedEvent(event);
914
+ return isPersistedInspectEvent(tiny) ? tiny : void 0;
915
+ }
916
+ function preparePersistedInspectEventForWrite(value, opts = resolveTraceSafetyOptions()) {
917
+ try {
918
+ if (!isRecord3(value)) return void 0;
919
+ const source = safeGet(value, "source");
920
+ if (!isRecord3(source)) return void 0;
921
+ const candidate = {
922
+ schemaVersion: safeGet(value, "schemaVersion"),
923
+ eventId: requiredBoundedString(safeGet(value, "eventId"), "eventId", opts) ?? "",
924
+ runId: requiredBoundedString(safeGet(value, "runId"), "runId", opts) ?? "",
925
+ kind: safeGet(value, "kind"),
926
+ name: requiredBoundedString(safeGet(value, "name"), "name", opts) ?? "",
927
+ timestamp: requiredBoundedString(safeGet(value, "timestamp"), "timestamp", opts) ?? "",
928
+ confidence: safeGet(value, "confidence"),
929
+ source: {
930
+ type: safeGet(source, "type")
931
+ }
932
+ };
933
+ const parentId = requiredBoundedString(safeGet(value, "parentId"), "parentId", opts);
934
+ const status = safeGet(value, "status");
935
+ const startedAt = optionalBoundedString(safeGet(value, "startedAt"), "startedAt", opts);
936
+ const endedAt = optionalBoundedString(safeGet(value, "endedAt"), "endedAt", opts);
937
+ const durationMs2 = safeGet(value, "durationMs");
938
+ const sourceName = optionalBoundedString(safeGet(source, "name"), "name", opts);
939
+ const sourceVersion = optionalBoundedString(safeGet(source, "version"), "version", opts);
940
+ if (parentId !== void 0) candidate.parentId = parentId;
941
+ if (status === "running" || status === "ok" || status === "error" || status === "unknown") {
942
+ candidate.status = status;
943
+ }
944
+ if (startedAt !== void 0) candidate.startedAt = startedAt;
945
+ if (endedAt !== void 0) candidate.endedAt = endedAt;
946
+ if (typeof durationMs2 === "number" && Number.isFinite(durationMs2) && durationMs2 >= 0) {
947
+ candidate.durationMs = durationMs2;
948
+ }
949
+ if (sourceName !== void 0) candidate.source.name = sourceName;
950
+ if (sourceVersion !== void 0) candidate.source.version = sourceVersion;
951
+ const attributes = safeGet(value, "attributes");
952
+ if (isRecord3(attributes)) {
953
+ candidate.attributes = prepareMetadataForDisk(attributes, opts);
954
+ }
955
+ if (safeGet(value, "inputSummary") !== void 0) {
956
+ candidate.inputSummary = preparePersistedSummaryForDisk(
957
+ "input",
958
+ safeGet(value, "inputSummary"),
959
+ opts
960
+ );
961
+ }
962
+ if (safeGet(value, "outputSummary") !== void 0) {
963
+ candidate.outputSummary = preparePersistedSummaryForDisk(
964
+ "output",
965
+ safeGet(value, "outputSummary"),
966
+ opts
967
+ );
968
+ }
969
+ const error = preparePersistedErrorForDisk(safeGet(value, "error"), opts);
970
+ if (error !== void 0) candidate.error = error;
971
+ const tokenUsage = prepareTokenUsage(safeGet(value, "tokenUsage"));
972
+ if (tokenUsage !== void 0) candidate.tokenUsage = tokenUsage;
973
+ const trace = prepareTraceContext(safeGet(value, "trace"), opts);
974
+ if (trace !== void 0) candidate.trace = trace;
975
+ if (!isPersistedInspectEvent(candidate)) return void 0;
976
+ return enforcePersistedEventSize(candidate, opts);
977
+ } catch {
978
+ return void 0;
979
+ }
980
+ }
620
981
 
621
982
  // packages/core/src/context.ts
622
983
  var storage = new async_hooks.AsyncLocalStorage();
@@ -765,6 +1126,464 @@ function runWithStepContext(stepId, fn) {
765
1126
  });
766
1127
  });
767
1128
  }
1129
+ function invoke2(fn) {
1130
+ return new Promise((resolve, reject) => {
1131
+ try {
1132
+ Promise.resolve(fn()).then(resolve, reject);
1133
+ } catch (error) {
1134
+ reject(error);
1135
+ }
1136
+ });
1137
+ }
1138
+ function normalizeError(error) {
1139
+ if (error instanceof Error && error.message.trim() !== "") {
1140
+ return error.message;
1141
+ }
1142
+ if (typeof error === "string" && error.trim() !== "") {
1143
+ return error;
1144
+ }
1145
+ return "Unknown inspector runtime error";
1146
+ }
1147
+ var runtimeSequence = 0;
1148
+ function createRuntimeId() {
1149
+ runtimeSequence += 1;
1150
+ return `runtime_${runtimeSequence.toString(36)}`;
1151
+ }
1152
+ function publicContext(store) {
1153
+ return {
1154
+ runtimeId: store.runtimeId,
1155
+ runId: store.runId,
1156
+ runName: store.runName,
1157
+ traceDir: store.traceDir,
1158
+ silent: store.silent,
1159
+ metadata: store.metadata
1160
+ };
1161
+ }
1162
+ function createInspectorRuntime(options = {}) {
1163
+ const storage2 = new async_hooks.AsyncLocalStorage();
1164
+ const enabled = options.enabled ?? true;
1165
+ const runtimeId = createRuntimeId();
1166
+ const traceSafety = options.traceSafety ?? resolveTraceSafetyOptions();
1167
+ let closed = false;
1168
+ let instrumentationErrors = 0;
1169
+ let lastInstrumentationError;
1170
+ function recordInstrumentationError(error) {
1171
+ instrumentationErrors += 1;
1172
+ lastInstrumentationError = normalizeError(error);
1173
+ }
1174
+ function currentStore() {
1175
+ try {
1176
+ return storage2.getStore();
1177
+ } catch (error) {
1178
+ recordInstrumentationError(error);
1179
+ return void 0;
1180
+ }
1181
+ }
1182
+ const runtime = {
1183
+ runtimeId,
1184
+ enabled,
1185
+ runWithContext(context, fn) {
1186
+ if (!enabled) return invoke2(fn);
1187
+ const store = {
1188
+ runtimeId,
1189
+ runId: context.runId,
1190
+ runName: context.runName,
1191
+ traceDir: context.traceDir,
1192
+ silent: context.silent,
1193
+ metadata: context.metadata,
1194
+ traceSafety,
1195
+ currentDepth: 0
1196
+ };
1197
+ return new Promise((resolve, reject) => {
1198
+ storage2.run(store, () => {
1199
+ invoke2(fn).then(resolve, reject);
1200
+ });
1201
+ });
1202
+ },
1203
+ runWithStepContext(stepId, fn) {
1204
+ if (!enabled) return invoke2(fn);
1205
+ const parent = currentStore();
1206
+ if (!parent) return invoke2(fn);
1207
+ const store = {
1208
+ runtimeId,
1209
+ runId: parent.runId,
1210
+ runName: parent.runName,
1211
+ traceDir: parent.traceDir,
1212
+ silent: parent.silent,
1213
+ metadata: parent.metadata,
1214
+ traceSafety: parent.traceSafety,
1215
+ currentStepId: stepId,
1216
+ currentDepth: parent.currentDepth + 1
1217
+ };
1218
+ return new Promise((resolve, reject) => {
1219
+ storage2.run(store, () => {
1220
+ invoke2(fn).then(resolve, reject);
1221
+ });
1222
+ });
1223
+ },
1224
+ getCurrentContext() {
1225
+ const store = currentStore();
1226
+ return store ? publicContext(store) : void 0;
1227
+ },
1228
+ getCurrentCorrelationMetadata() {
1229
+ return extractCorrelationMetadata(currentStore()?.metadata);
1230
+ },
1231
+ getCurrentStepId() {
1232
+ return currentStore()?.currentStepId;
1233
+ },
1234
+ getCurrentDepth() {
1235
+ const depth = currentStore()?.currentDepth;
1236
+ return typeof depth === "number" && Number.isFinite(depth) ? depth : 0;
1237
+ },
1238
+ getTraceSafety() {
1239
+ return traceSafety;
1240
+ },
1241
+ async write(event) {
1242
+ if (!enabled || closed || !options.writer) return;
1243
+ try {
1244
+ const safe = preparePersistedInspectEventForWrite(event, traceSafety);
1245
+ if (safe === void 0) {
1246
+ recordInstrumentationError("Invalid persisted inspect event");
1247
+ return;
1248
+ }
1249
+ await options.writer.write(safe);
1250
+ } catch (error) {
1251
+ recordInstrumentationError(error);
1252
+ }
1253
+ },
1254
+ async flush() {
1255
+ if (!options.writer) return;
1256
+ try {
1257
+ await options.writer.flush?.();
1258
+ } catch (error) {
1259
+ recordInstrumentationError(error);
1260
+ }
1261
+ },
1262
+ async close() {
1263
+ if (closed) return;
1264
+ try {
1265
+ await options.writer?.close?.();
1266
+ } catch (error) {
1267
+ recordInstrumentationError(error);
1268
+ } finally {
1269
+ closed = true;
1270
+ }
1271
+ },
1272
+ getDiagnostics() {
1273
+ const diagnostics = {
1274
+ instrumentationErrors
1275
+ };
1276
+ if (lastInstrumentationError !== void 0) {
1277
+ diagnostics.lastInstrumentationError = lastInstrumentationError;
1278
+ }
1279
+ const writerStats = options.writer?.getStats?.();
1280
+ if (writerStats !== void 0) {
1281
+ diagnostics.writerStats = writerStats;
1282
+ }
1283
+ return diagnostics;
1284
+ }
1285
+ };
1286
+ return runtime;
1287
+ }
1288
+
1289
+ // packages/core/src/inspector.ts
1290
+ function normalizeName(name, fallback) {
1291
+ if (typeof name !== "string" || name.trim() === "") return fallback;
1292
+ return truncateName(name.trim(), 100);
1293
+ }
1294
+ function nowIso() {
1295
+ return (/* @__PURE__ */ new Date()).toISOString();
1296
+ }
1297
+ function durationMs(startedAt, endedAt) {
1298
+ return Math.max(0, Date.parse(endedAt) - Date.parse(startedAt));
1299
+ }
1300
+ function mergeMetadata(base, override) {
1301
+ if (base === void 0 && override === void 0) return void 0;
1302
+ return {
1303
+ ...base ?? {},
1304
+ ...override ?? {}
1305
+ };
1306
+ }
1307
+ function toPersistedError(error) {
1308
+ if (error instanceof Error) {
1309
+ return {
1310
+ name: error.name,
1311
+ message: error.message
1312
+ };
1313
+ }
1314
+ if (typeof error === "string") {
1315
+ return { message: error };
1316
+ }
1317
+ return { message: "Unknown error" };
1318
+ }
1319
+ function summarizeValue(value) {
1320
+ if (value === null) return { type: "null" };
1321
+ if (Array.isArray(value)) return { type: "array", length: value.length };
1322
+ if (typeof value === "string") return { type: "string", length: value.length };
1323
+ if (typeof value === "number") {
1324
+ return { type: "number", finite: Number.isFinite(value) };
1325
+ }
1326
+ if (typeof value === "bigint") return { type: "bigint" };
1327
+ if (typeof value === "boolean") return { type: "boolean" };
1328
+ if (typeof value === "undefined") return { type: "undefined" };
1329
+ if (typeof value === "symbol") return { type: "symbol" };
1330
+ if (typeof value === "function") {
1331
+ return { type: "function", name: value.name || void 0 };
1332
+ }
1333
+ if (typeof value === "object") {
1334
+ const record = value;
1335
+ let keyCount;
1336
+ try {
1337
+ keyCount = Object.keys(record).length;
1338
+ } catch {
1339
+ keyCount = void 0;
1340
+ }
1341
+ return {
1342
+ type: "object",
1343
+ constructorName: value?.constructor?.name,
1344
+ ...keyCount !== void 0 ? { keyCount } : {}
1345
+ };
1346
+ }
1347
+ return { type: typeof value };
1348
+ }
1349
+ function summarizeCapturedError(error) {
1350
+ if (error instanceof Error) {
1351
+ return { type: "error", name: error.name };
1352
+ }
1353
+ return summarizeValue(error);
1354
+ }
1355
+ function stepTypeToKind(type) {
1356
+ switch (type) {
1357
+ case "llm":
1358
+ return "LLM";
1359
+ case "tool":
1360
+ return "TOOL";
1361
+ case "decision":
1362
+ return "DECISION";
1363
+ case "run":
1364
+ return "RUN";
1365
+ default:
1366
+ return "LOGIC";
1367
+ }
1368
+ }
1369
+ function createInspector(options = {}) {
1370
+ const traceSafety = options.traceSafety ?? resolveTraceSafetyOptions({
1371
+ redactionProfile: options.redactionProfile
1372
+ });
1373
+ const runtime = createInspectorRuntime({
1374
+ enabled: options.enabled,
1375
+ writer: options.writer,
1376
+ traceSafety
1377
+ });
1378
+ async function write(event) {
1379
+ const safe = preparePersistedInspectEventForWrite(event, traceSafety);
1380
+ if (safe !== void 0) {
1381
+ await runtime.write(safe);
1382
+ }
1383
+ }
1384
+ async function run(name, fn, runOptions = {}) {
1385
+ if (typeof fn !== "function") {
1386
+ throw new TypeError("inspector.run requires `fn` to be a function");
1387
+ }
1388
+ if (options.enabled === false) {
1389
+ return Promise.resolve(fn());
1390
+ }
1391
+ const runName = normalizeName(name, "unnamed-run");
1392
+ const runId = runOptions.runId ?? createRunId();
1393
+ const traceDir = runOptions.traceDir ?? options.traceDir ?? getDefaultTraceDir();
1394
+ const metadata = mergeMetadata(options.metadata, runOptions.metadata);
1395
+ const startedAt = nowIso();
1396
+ return runtime.runWithContext(
1397
+ {
1398
+ runId,
1399
+ runName,
1400
+ traceDir,
1401
+ silent: runOptions.silent ?? options.silent ?? true,
1402
+ metadata
1403
+ },
1404
+ async () => {
1405
+ await write({
1406
+ schemaVersion: "0.2",
1407
+ eventId: `${runId}_started`,
1408
+ runId,
1409
+ kind: "RUN",
1410
+ name: runName,
1411
+ status: "running",
1412
+ timestamp: startedAt,
1413
+ startedAt,
1414
+ confidence: "explicit",
1415
+ source: { type: "manual", name: "createInspector" },
1416
+ attributes: {
1417
+ legacyEvent: "run_started",
1418
+ ...metadata !== void 0 ? { metadata } : {}
1419
+ }
1420
+ });
1421
+ try {
1422
+ const result = await Promise.resolve(fn());
1423
+ const endedAt = nowIso();
1424
+ await write({
1425
+ schemaVersion: "0.2",
1426
+ eventId: `${runId}_completed`,
1427
+ runId,
1428
+ kind: "RUN",
1429
+ name: runName,
1430
+ status: "ok",
1431
+ timestamp: endedAt,
1432
+ endedAt,
1433
+ durationMs: durationMs(startedAt, endedAt),
1434
+ confidence: "explicit",
1435
+ source: { type: "manual", name: "createInspector" },
1436
+ attributes: { legacyEvent: "run_completed" },
1437
+ ...options.capture?.onSuccess === "metadata-only" ? { outputSummary: summarizeValue(result) } : {}
1438
+ });
1439
+ return result;
1440
+ } catch (error) {
1441
+ const endedAt = nowIso();
1442
+ await write({
1443
+ schemaVersion: "0.2",
1444
+ eventId: `${runId}_completed`,
1445
+ runId,
1446
+ kind: "RUN",
1447
+ name: runName,
1448
+ status: "error",
1449
+ timestamp: endedAt,
1450
+ endedAt,
1451
+ durationMs: durationMs(startedAt, endedAt),
1452
+ confidence: "explicit",
1453
+ source: { type: "manual", name: "createInspector" },
1454
+ attributes: { legacyEvent: "run_completed" },
1455
+ ...options.capture?.onError === "metadata-only" ? { outputSummary: summarizeCapturedError(error) } : {},
1456
+ error: toPersistedError(error)
1457
+ });
1458
+ throw error;
1459
+ }
1460
+ }
1461
+ );
1462
+ }
1463
+ async function step(name, fn, stepOptions = {}) {
1464
+ if (typeof fn !== "function") {
1465
+ throw new TypeError("inspector.step requires `fn` to be a function");
1466
+ }
1467
+ if (options.enabled === false || !runtime.getCurrentContext()) {
1468
+ return Promise.resolve(fn());
1469
+ }
1470
+ const context = runtime.getCurrentContext();
1471
+ const stepName = normalizeName(name, "unnamed-step");
1472
+ const stepId = createStepId();
1473
+ const parentId = runtime.getCurrentStepId();
1474
+ const stepType = stepOptions.type ?? "logic";
1475
+ const startedAt = nowIso();
1476
+ const attributes = {
1477
+ legacyEvent: "step_started",
1478
+ stepId,
1479
+ stepType,
1480
+ ...stepOptions.metadata !== void 0 ? { metadata: stepOptions.metadata } : {}
1481
+ };
1482
+ await write({
1483
+ schemaVersion: "0.2",
1484
+ eventId: `${stepId}_started`,
1485
+ runId: context.runId,
1486
+ ...parentId !== void 0 ? { parentId } : {},
1487
+ kind: stepTypeToKind(stepType),
1488
+ name: stepName,
1489
+ status: "running",
1490
+ timestamp: startedAt,
1491
+ startedAt,
1492
+ confidence: "explicit",
1493
+ source: { type: "manual", name: "createInspector" },
1494
+ attributes
1495
+ });
1496
+ return runtime.runWithStepContext(stepId, async () => {
1497
+ try {
1498
+ const result = await Promise.resolve(fn());
1499
+ const endedAt = nowIso();
1500
+ await write({
1501
+ schemaVersion: "0.2",
1502
+ eventId: `${stepId}_completed`,
1503
+ runId: context.runId,
1504
+ kind: stepTypeToKind(stepType),
1505
+ name: stepName,
1506
+ status: "ok",
1507
+ timestamp: endedAt,
1508
+ endedAt,
1509
+ durationMs: durationMs(startedAt, endedAt),
1510
+ confidence: "explicit",
1511
+ source: { type: "manual", name: "createInspector" },
1512
+ attributes: {
1513
+ legacyEvent: "step_completed",
1514
+ stepId,
1515
+ stepType
1516
+ },
1517
+ ...options.capture?.onSuccess === "metadata-only" ? { outputSummary: summarizeValue(result) } : {}
1518
+ });
1519
+ return result;
1520
+ } catch (error) {
1521
+ const endedAt = nowIso();
1522
+ await write({
1523
+ schemaVersion: "0.2",
1524
+ eventId: `${stepId}_completed`,
1525
+ runId: context.runId,
1526
+ kind: stepTypeToKind(stepType),
1527
+ name: stepName,
1528
+ status: "error",
1529
+ timestamp: endedAt,
1530
+ endedAt,
1531
+ durationMs: durationMs(startedAt, endedAt),
1532
+ confidence: "explicit",
1533
+ source: { type: "manual", name: "createInspector" },
1534
+ attributes: {
1535
+ legacyEvent: "step_completed",
1536
+ stepId,
1537
+ stepType
1538
+ },
1539
+ ...options.capture?.onError === "metadata-only" ? { outputSummary: summarizeCapturedError(error) } : {},
1540
+ error: toPersistedError(error)
1541
+ });
1542
+ throw error;
1543
+ }
1544
+ });
1545
+ }
1546
+ const inspector = {
1547
+ runtime,
1548
+ run,
1549
+ step,
1550
+ tool(name, fn, toolOptions) {
1551
+ const toolName = normalizeName(name, "unknown-tool");
1552
+ return step(`tool:${toolName}`, fn, {
1553
+ ...toolOptions,
1554
+ type: "tool",
1555
+ metadata: {
1556
+ ...toolOptions?.metadata ?? {},
1557
+ toolName
1558
+ }
1559
+ });
1560
+ },
1561
+ llm(name, fn, llmOptions) {
1562
+ const model = normalizeName(name, "unknown-model");
1563
+ return step(`llm:${model}`, fn, {
1564
+ ...llmOptions,
1565
+ type: "llm",
1566
+ metadata: {
1567
+ ...llmOptions?.metadata ?? {},
1568
+ model
1569
+ }
1570
+ });
1571
+ },
1572
+ observe(name, fn, observeOptions) {
1573
+ return async (...args) => step(name, () => Promise.resolve(fn(...args)), observeOptions);
1574
+ },
1575
+ getDiagnostics() {
1576
+ return runtime.getDiagnostics();
1577
+ },
1578
+ flush() {
1579
+ return runtime.flush();
1580
+ },
1581
+ close() {
1582
+ return runtime.close();
1583
+ }
1584
+ };
1585
+ return inspector;
1586
+ }
768
1587
 
769
1588
  // node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
770
1589
  var ANSI_BACKGROUND_OFFSET = 10;
@@ -1286,15 +2105,15 @@ function getStatusIcon(status) {
1286
2105
  if (status === "error") return source_default.red("\u2716");
1287
2106
  return source_default.yellow("\u23F3");
1288
2107
  }
1289
- function renderStepLine(name, durationMs, status, depth) {
2108
+ function renderStepLine(name, durationMs2, status, depth) {
1290
2109
  try {
1291
2110
  const nm = formatTerminalName(name);
1292
2111
  const ind = getIndent(depth ?? 0);
1293
- if (status === "running" && durationMs === void 0) {
2112
+ if (status === "running" && durationMs2 === void 0) {
1294
2113
  return `${ind}${source_default.yellow("\u23F3")} ${nm}`;
1295
2114
  }
1296
- const hasDur = durationMs !== void 0 && Number.isFinite(durationMs);
1297
- const dur = hasDur ? formatDuration2(durationMs) : void 0;
2115
+ const hasDur = durationMs2 !== void 0 && Number.isFinite(durationMs2);
2116
+ const dur = hasDur ? formatDuration2(durationMs2) : void 0;
1298
2117
  if (status === "running") {
1299
2118
  return dur !== void 0 ? `${ind}${source_default.yellow("\u23F3")} ${nm} (${dur})` : `${ind}${source_default.yellow("\u23F3")} ${nm}`;
1300
2119
  }
@@ -1318,9 +2137,9 @@ function renderErrorLine(error, depth) {
1318
2137
  return "";
1319
2138
  }
1320
2139
  }
1321
- function renderRunSummary(durationMs, status, traceFilePath) {
2140
+ function renderRunSummary(durationMs2, status, traceFilePath) {
1322
2141
  try {
1323
- const dur = Number.isFinite(durationMs) ? formatDuration2(durationMs) : formatDuration2(0);
2142
+ const dur = Number.isFinite(durationMs2) ? formatDuration2(durationMs2) : formatDuration2(0);
1324
2143
  const head = status === "error" ? `Failed in ${dur}` : `Completed in ${dur}`;
1325
2144
  const lines = [head];
1326
2145
  if (traceFilePath !== void 0 && traceFilePath.trim() !== "") {
@@ -1347,10 +2166,10 @@ function printStepStart(name, depth = 0) {
1347
2166
  } catch {
1348
2167
  }
1349
2168
  }
1350
- function printStepComplete(name, durationMs, status, depth = 0) {
2169
+ function printStepComplete(name, durationMs2, status, depth = 0) {
1351
2170
  if (isSilentContext()) return;
1352
2171
  try {
1353
- safePrint(renderStepLine(name, durationMs, status, depth));
2172
+ safePrint(renderStepLine(name, durationMs2, status, depth));
1354
2173
  } catch {
1355
2174
  }
1356
2175
  }
@@ -1361,10 +2180,10 @@ function printError(error, depth = 0) {
1361
2180
  } catch {
1362
2181
  }
1363
2182
  }
1364
- function printRunComplete(_name, _runId, durationMs, status, traceFilePath) {
2183
+ function printRunComplete(_name, _runId, durationMs2, status, traceFilePath) {
1365
2184
  if (isSilentContext()) return;
1366
2185
  try {
1367
- const lines = renderRunSummary(durationMs, status, traceFilePath);
2186
+ const lines = renderRunSummary(durationMs2, status, traceFilePath);
1368
2187
  for (let i = 0; i < lines.length; i++) {
1369
2188
  const line = lines[i];
1370
2189
  if (i === 0) {
@@ -1395,6 +2214,8 @@ exports.MAX_TERMINAL_DEPTH = MAX_TERMINAL_DEPTH;
1395
2214
  exports.MAX_TERMINAL_NAME_LENGTH = MAX_TERMINAL_NAME_LENGTH;
1396
2215
  exports.RUNS_DIR_NAME = RUNS_DIR_NAME;
1397
2216
  exports.TERMINAL_INDENT = TERMINAL_INDENT;
2217
+ exports.createInspector = createInspector;
2218
+ exports.createInspectorRuntime = createInspectorRuntime;
1398
2219
  exports.createRunId = createRunId;
1399
2220
  exports.createStepId = createStepId;
1400
2221
  exports.ensureTraceDir = ensureTraceDir;