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
@@ -0,0 +1,743 @@
1
+ import { source_default } from './chunk-BT7CATSD.mjs';
2
+ import { resolveTraceSafetyOptions, preparePersistedInspectEventForWrite } from './chunk-57S5D6HR.mjs';
3
+ import { extractCorrelationMetadata } from './chunk-S4YWKV4G.mjs';
4
+ import { truncateName, formatDuration, createRunId, getDefaultTraceDir, createStepId } from './chunk-VTIB5MDK.mjs';
5
+ import { AsyncLocalStorage } from 'async_hooks';
6
+
7
+ var storage = new AsyncLocalStorage();
8
+ function toPublicContext(ctx) {
9
+ return {
10
+ runId: ctx.runId,
11
+ runName: ctx.runName,
12
+ traceDir: ctx.traceDir,
13
+ silent: ctx.silent,
14
+ metadata: ctx.metadata
15
+ };
16
+ }
17
+ function invoke(fn) {
18
+ return new Promise((resolve, reject) => {
19
+ try {
20
+ Promise.resolve(fn()).then(resolve, reject);
21
+ } catch (e) {
22
+ reject(e);
23
+ }
24
+ });
25
+ }
26
+ function getCurrentContext() {
27
+ try {
28
+ const s = storage.getStore();
29
+ if (!s) return void 0;
30
+ return toPublicContext(s);
31
+ } catch {
32
+ return void 0;
33
+ }
34
+ }
35
+ function getCurrentRunId() {
36
+ try {
37
+ return storage.getStore()?.runId;
38
+ } catch {
39
+ return void 0;
40
+ }
41
+ }
42
+ function getCurrentCorrelationMetadata() {
43
+ try {
44
+ return extractCorrelationMetadata(storage.getStore()?.metadata);
45
+ } catch {
46
+ return void 0;
47
+ }
48
+ }
49
+ function getCurrentRunName() {
50
+ try {
51
+ return storage.getStore()?.runName;
52
+ } catch {
53
+ return void 0;
54
+ }
55
+ }
56
+ function getCurrentStepId() {
57
+ try {
58
+ return storage.getStore()?.currentStepId;
59
+ } catch {
60
+ return void 0;
61
+ }
62
+ }
63
+ function getParentStepId() {
64
+ return getCurrentStepId();
65
+ }
66
+ function getCurrentDepth() {
67
+ try {
68
+ const d = storage.getStore()?.currentDepth;
69
+ return typeof d === "number" && Number.isFinite(d) ? d : 0;
70
+ } catch {
71
+ return 0;
72
+ }
73
+ }
74
+ function hasActiveContext() {
75
+ try {
76
+ return storage.getStore() !== void 0;
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+ function getTraceDirFromContext() {
82
+ try {
83
+ return storage.getStore()?.traceDir;
84
+ } catch {
85
+ return void 0;
86
+ }
87
+ }
88
+ function isSilentContext() {
89
+ try {
90
+ const s = storage.getStore();
91
+ return s ? s.silent : false;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+ function getTraceSafetyFromContext() {
97
+ try {
98
+ return storage.getStore()?.traceSafety;
99
+ } catch {
100
+ return void 0;
101
+ }
102
+ }
103
+ function runWithContext(context, fn, traceSafety = resolveTraceSafetyOptions()) {
104
+ const runtime = {
105
+ runId: context.runId,
106
+ runName: context.runName,
107
+ traceDir: context.traceDir,
108
+ silent: context.silent,
109
+ metadata: context.metadata,
110
+ traceSafety,
111
+ currentDepth: 0
112
+ };
113
+ return new Promise((resolve, reject) => {
114
+ storage.run(runtime, () => {
115
+ try {
116
+ Promise.resolve(fn()).then(resolve, reject);
117
+ } catch (e) {
118
+ reject(e);
119
+ }
120
+ });
121
+ });
122
+ }
123
+ function runWithStepContext(stepId, fn) {
124
+ let parent;
125
+ try {
126
+ parent = storage.getStore();
127
+ } catch {
128
+ parent = void 0;
129
+ }
130
+ if (!parent) {
131
+ return invoke(fn);
132
+ }
133
+ const derived = {
134
+ runId: parent.runId,
135
+ runName: parent.runName,
136
+ traceDir: parent.traceDir,
137
+ silent: parent.silent,
138
+ metadata: parent.metadata,
139
+ traceSafety: parent.traceSafety,
140
+ currentStepId: stepId,
141
+ currentDepth: parent.currentDepth + 1
142
+ };
143
+ return new Promise((resolve, reject) => {
144
+ storage.run(derived, () => {
145
+ try {
146
+ Promise.resolve(fn()).then(resolve, reject);
147
+ } catch (e) {
148
+ reject(e);
149
+ }
150
+ });
151
+ });
152
+ }
153
+ function invoke2(fn) {
154
+ return new Promise((resolve, reject) => {
155
+ try {
156
+ Promise.resolve(fn()).then(resolve, reject);
157
+ } catch (error) {
158
+ reject(error);
159
+ }
160
+ });
161
+ }
162
+ function normalizeError(error) {
163
+ if (error instanceof Error && error.message.trim() !== "") {
164
+ return error.message;
165
+ }
166
+ if (typeof error === "string" && error.trim() !== "") {
167
+ return error;
168
+ }
169
+ return "Unknown inspector runtime error";
170
+ }
171
+ var runtimeSequence = 0;
172
+ function createRuntimeId() {
173
+ runtimeSequence += 1;
174
+ return `runtime_${runtimeSequence.toString(36)}`;
175
+ }
176
+ function publicContext(store) {
177
+ return {
178
+ runtimeId: store.runtimeId,
179
+ runId: store.runId,
180
+ runName: store.runName,
181
+ traceDir: store.traceDir,
182
+ silent: store.silent,
183
+ metadata: store.metadata
184
+ };
185
+ }
186
+ function createInspectorRuntime(options = {}) {
187
+ const storage2 = new AsyncLocalStorage();
188
+ const enabled = options.enabled ?? true;
189
+ const runtimeId = createRuntimeId();
190
+ const traceSafety = options.traceSafety ?? resolveTraceSafetyOptions();
191
+ let closed = false;
192
+ let instrumentationErrors = 0;
193
+ let lastInstrumentationError;
194
+ function recordInstrumentationError(error) {
195
+ instrumentationErrors += 1;
196
+ lastInstrumentationError = normalizeError(error);
197
+ }
198
+ function currentStore() {
199
+ try {
200
+ return storage2.getStore();
201
+ } catch (error) {
202
+ recordInstrumentationError(error);
203
+ return void 0;
204
+ }
205
+ }
206
+ const runtime = {
207
+ runtimeId,
208
+ enabled,
209
+ runWithContext(context, fn) {
210
+ if (!enabled) return invoke2(fn);
211
+ const store = {
212
+ runtimeId,
213
+ runId: context.runId,
214
+ runName: context.runName,
215
+ traceDir: context.traceDir,
216
+ silent: context.silent,
217
+ metadata: context.metadata,
218
+ traceSafety,
219
+ currentDepth: 0
220
+ };
221
+ return new Promise((resolve, reject) => {
222
+ storage2.run(store, () => {
223
+ invoke2(fn).then(resolve, reject);
224
+ });
225
+ });
226
+ },
227
+ runWithStepContext(stepId, fn) {
228
+ if (!enabled) return invoke2(fn);
229
+ const parent = currentStore();
230
+ if (!parent) return invoke2(fn);
231
+ const store = {
232
+ runtimeId,
233
+ runId: parent.runId,
234
+ runName: parent.runName,
235
+ traceDir: parent.traceDir,
236
+ silent: parent.silent,
237
+ metadata: parent.metadata,
238
+ traceSafety: parent.traceSafety,
239
+ currentStepId: stepId,
240
+ currentDepth: parent.currentDepth + 1
241
+ };
242
+ return new Promise((resolve, reject) => {
243
+ storage2.run(store, () => {
244
+ invoke2(fn).then(resolve, reject);
245
+ });
246
+ });
247
+ },
248
+ getCurrentContext() {
249
+ const store = currentStore();
250
+ return store ? publicContext(store) : void 0;
251
+ },
252
+ getCurrentCorrelationMetadata() {
253
+ return extractCorrelationMetadata(currentStore()?.metadata);
254
+ },
255
+ getCurrentStepId() {
256
+ return currentStore()?.currentStepId;
257
+ },
258
+ getCurrentDepth() {
259
+ const depth = currentStore()?.currentDepth;
260
+ return typeof depth === "number" && Number.isFinite(depth) ? depth : 0;
261
+ },
262
+ getTraceSafety() {
263
+ return traceSafety;
264
+ },
265
+ async write(event) {
266
+ if (!enabled || closed || !options.writer) return;
267
+ try {
268
+ const safe = preparePersistedInspectEventForWrite(event, traceSafety);
269
+ if (safe === void 0) {
270
+ recordInstrumentationError("Invalid persisted inspect event");
271
+ return;
272
+ }
273
+ await options.writer.write(safe);
274
+ } catch (error) {
275
+ recordInstrumentationError(error);
276
+ }
277
+ },
278
+ async flush() {
279
+ if (!options.writer) return;
280
+ try {
281
+ await options.writer.flush?.();
282
+ } catch (error) {
283
+ recordInstrumentationError(error);
284
+ }
285
+ },
286
+ async close() {
287
+ if (closed) return;
288
+ try {
289
+ await options.writer?.close?.();
290
+ } catch (error) {
291
+ recordInstrumentationError(error);
292
+ } finally {
293
+ closed = true;
294
+ }
295
+ },
296
+ getDiagnostics() {
297
+ const diagnostics = {
298
+ instrumentationErrors
299
+ };
300
+ if (lastInstrumentationError !== void 0) {
301
+ diagnostics.lastInstrumentationError = lastInstrumentationError;
302
+ }
303
+ const writerStats = options.writer?.getStats?.();
304
+ if (writerStats !== void 0) {
305
+ diagnostics.writerStats = writerStats;
306
+ }
307
+ return diagnostics;
308
+ }
309
+ };
310
+ return runtime;
311
+ }
312
+
313
+ // packages/core/src/inspector.ts
314
+ function normalizeName(name, fallback) {
315
+ if (typeof name !== "string" || name.trim() === "") return fallback;
316
+ return truncateName(name.trim(), 100);
317
+ }
318
+ function nowIso() {
319
+ return (/* @__PURE__ */ new Date()).toISOString();
320
+ }
321
+ function durationMs(startedAt, endedAt) {
322
+ return Math.max(0, Date.parse(endedAt) - Date.parse(startedAt));
323
+ }
324
+ function mergeMetadata(base, override) {
325
+ if (base === void 0 && override === void 0) return void 0;
326
+ return {
327
+ ...base ?? {},
328
+ ...override ?? {}
329
+ };
330
+ }
331
+ function toPersistedError(error) {
332
+ if (error instanceof Error) {
333
+ return {
334
+ name: error.name,
335
+ message: error.message
336
+ };
337
+ }
338
+ if (typeof error === "string") {
339
+ return { message: error };
340
+ }
341
+ return { message: "Unknown error" };
342
+ }
343
+ function summarizeValue(value) {
344
+ if (value === null) return { type: "null" };
345
+ if (Array.isArray(value)) return { type: "array", length: value.length };
346
+ if (typeof value === "string") return { type: "string", length: value.length };
347
+ if (typeof value === "number") {
348
+ return { type: "number", finite: Number.isFinite(value) };
349
+ }
350
+ if (typeof value === "bigint") return { type: "bigint" };
351
+ if (typeof value === "boolean") return { type: "boolean" };
352
+ if (typeof value === "undefined") return { type: "undefined" };
353
+ if (typeof value === "symbol") return { type: "symbol" };
354
+ if (typeof value === "function") {
355
+ return { type: "function", name: value.name || void 0 };
356
+ }
357
+ if (typeof value === "object") {
358
+ const record = value;
359
+ let keyCount;
360
+ try {
361
+ keyCount = Object.keys(record).length;
362
+ } catch {
363
+ keyCount = void 0;
364
+ }
365
+ return {
366
+ type: "object",
367
+ constructorName: value?.constructor?.name,
368
+ ...keyCount !== void 0 ? { keyCount } : {}
369
+ };
370
+ }
371
+ return { type: typeof value };
372
+ }
373
+ function summarizeCapturedError(error) {
374
+ if (error instanceof Error) {
375
+ return { type: "error", name: error.name };
376
+ }
377
+ return summarizeValue(error);
378
+ }
379
+ function stepTypeToKind(type) {
380
+ switch (type) {
381
+ case "llm":
382
+ return "LLM";
383
+ case "tool":
384
+ return "TOOL";
385
+ case "decision":
386
+ return "DECISION";
387
+ case "run":
388
+ return "RUN";
389
+ default:
390
+ return "LOGIC";
391
+ }
392
+ }
393
+ function createInspector(options = {}) {
394
+ const traceSafety = options.traceSafety ?? resolveTraceSafetyOptions({
395
+ redactionProfile: options.redactionProfile
396
+ });
397
+ const runtime = createInspectorRuntime({
398
+ enabled: options.enabled,
399
+ writer: options.writer,
400
+ traceSafety
401
+ });
402
+ async function write(event) {
403
+ const safe = preparePersistedInspectEventForWrite(event, traceSafety);
404
+ if (safe !== void 0) {
405
+ await runtime.write(safe);
406
+ }
407
+ }
408
+ async function run(name, fn, runOptions = {}) {
409
+ if (typeof fn !== "function") {
410
+ throw new TypeError("inspector.run requires `fn` to be a function");
411
+ }
412
+ if (options.enabled === false) {
413
+ return Promise.resolve(fn());
414
+ }
415
+ const runName = normalizeName(name, "unnamed-run");
416
+ const runId = runOptions.runId ?? createRunId();
417
+ const traceDir = runOptions.traceDir ?? options.traceDir ?? getDefaultTraceDir();
418
+ const metadata = mergeMetadata(options.metadata, runOptions.metadata);
419
+ const startedAt = nowIso();
420
+ return runtime.runWithContext(
421
+ {
422
+ runId,
423
+ runName,
424
+ traceDir,
425
+ silent: runOptions.silent ?? options.silent ?? true,
426
+ metadata
427
+ },
428
+ async () => {
429
+ await write({
430
+ schemaVersion: "0.2",
431
+ eventId: `${runId}_started`,
432
+ runId,
433
+ kind: "RUN",
434
+ name: runName,
435
+ status: "running",
436
+ timestamp: startedAt,
437
+ startedAt,
438
+ confidence: "explicit",
439
+ source: { type: "manual", name: "createInspector" },
440
+ attributes: {
441
+ legacyEvent: "run_started",
442
+ ...metadata !== void 0 ? { metadata } : {}
443
+ }
444
+ });
445
+ try {
446
+ const result = await Promise.resolve(fn());
447
+ const endedAt = nowIso();
448
+ await write({
449
+ schemaVersion: "0.2",
450
+ eventId: `${runId}_completed`,
451
+ runId,
452
+ kind: "RUN",
453
+ name: runName,
454
+ status: "ok",
455
+ timestamp: endedAt,
456
+ endedAt,
457
+ durationMs: durationMs(startedAt, endedAt),
458
+ confidence: "explicit",
459
+ source: { type: "manual", name: "createInspector" },
460
+ attributes: { legacyEvent: "run_completed" },
461
+ ...options.capture?.onSuccess === "metadata-only" ? { outputSummary: summarizeValue(result) } : {}
462
+ });
463
+ return result;
464
+ } catch (error) {
465
+ const endedAt = nowIso();
466
+ await write({
467
+ schemaVersion: "0.2",
468
+ eventId: `${runId}_completed`,
469
+ runId,
470
+ kind: "RUN",
471
+ name: runName,
472
+ status: "error",
473
+ timestamp: endedAt,
474
+ endedAt,
475
+ durationMs: durationMs(startedAt, endedAt),
476
+ confidence: "explicit",
477
+ source: { type: "manual", name: "createInspector" },
478
+ attributes: { legacyEvent: "run_completed" },
479
+ ...options.capture?.onError === "metadata-only" ? { outputSummary: summarizeCapturedError(error) } : {},
480
+ error: toPersistedError(error)
481
+ });
482
+ throw error;
483
+ }
484
+ }
485
+ );
486
+ }
487
+ async function step(name, fn, stepOptions = {}) {
488
+ if (typeof fn !== "function") {
489
+ throw new TypeError("inspector.step requires `fn` to be a function");
490
+ }
491
+ if (options.enabled === false || !runtime.getCurrentContext()) {
492
+ return Promise.resolve(fn());
493
+ }
494
+ const context = runtime.getCurrentContext();
495
+ const stepName = normalizeName(name, "unnamed-step");
496
+ const stepId = createStepId();
497
+ const parentId = runtime.getCurrentStepId();
498
+ const stepType = stepOptions.type ?? "logic";
499
+ const startedAt = nowIso();
500
+ const attributes = {
501
+ legacyEvent: "step_started",
502
+ stepId,
503
+ stepType,
504
+ ...stepOptions.metadata !== void 0 ? { metadata: stepOptions.metadata } : {}
505
+ };
506
+ await write({
507
+ schemaVersion: "0.2",
508
+ eventId: `${stepId}_started`,
509
+ runId: context.runId,
510
+ ...parentId !== void 0 ? { parentId } : {},
511
+ kind: stepTypeToKind(stepType),
512
+ name: stepName,
513
+ status: "running",
514
+ timestamp: startedAt,
515
+ startedAt,
516
+ confidence: "explicit",
517
+ source: { type: "manual", name: "createInspector" },
518
+ attributes
519
+ });
520
+ return runtime.runWithStepContext(stepId, async () => {
521
+ try {
522
+ const result = await Promise.resolve(fn());
523
+ const endedAt = nowIso();
524
+ await write({
525
+ schemaVersion: "0.2",
526
+ eventId: `${stepId}_completed`,
527
+ runId: context.runId,
528
+ kind: stepTypeToKind(stepType),
529
+ name: stepName,
530
+ status: "ok",
531
+ timestamp: endedAt,
532
+ endedAt,
533
+ durationMs: durationMs(startedAt, endedAt),
534
+ confidence: "explicit",
535
+ source: { type: "manual", name: "createInspector" },
536
+ attributes: {
537
+ legacyEvent: "step_completed",
538
+ stepId,
539
+ stepType
540
+ },
541
+ ...options.capture?.onSuccess === "metadata-only" ? { outputSummary: summarizeValue(result) } : {}
542
+ });
543
+ return result;
544
+ } catch (error) {
545
+ const endedAt = nowIso();
546
+ await write({
547
+ schemaVersion: "0.2",
548
+ eventId: `${stepId}_completed`,
549
+ runId: context.runId,
550
+ kind: stepTypeToKind(stepType),
551
+ name: stepName,
552
+ status: "error",
553
+ timestamp: endedAt,
554
+ endedAt,
555
+ durationMs: durationMs(startedAt, endedAt),
556
+ confidence: "explicit",
557
+ source: { type: "manual", name: "createInspector" },
558
+ attributes: {
559
+ legacyEvent: "step_completed",
560
+ stepId,
561
+ stepType
562
+ },
563
+ ...options.capture?.onError === "metadata-only" ? { outputSummary: summarizeCapturedError(error) } : {},
564
+ error: toPersistedError(error)
565
+ });
566
+ throw error;
567
+ }
568
+ });
569
+ }
570
+ const inspector = {
571
+ runtime,
572
+ run,
573
+ step,
574
+ tool(name, fn, toolOptions) {
575
+ const toolName = normalizeName(name, "unknown-tool");
576
+ return step(`tool:${toolName}`, fn, {
577
+ ...toolOptions,
578
+ type: "tool",
579
+ metadata: {
580
+ ...toolOptions?.metadata ?? {},
581
+ toolName
582
+ }
583
+ });
584
+ },
585
+ llm(name, fn, llmOptions) {
586
+ const model = normalizeName(name, "unknown-model");
587
+ return step(`llm:${model}`, fn, {
588
+ ...llmOptions,
589
+ type: "llm",
590
+ metadata: {
591
+ ...llmOptions?.metadata ?? {},
592
+ model
593
+ }
594
+ });
595
+ },
596
+ observe(name, fn, observeOptions) {
597
+ return async (...args) => step(name, () => Promise.resolve(fn(...args)), observeOptions);
598
+ },
599
+ getDiagnostics() {
600
+ return runtime.getDiagnostics();
601
+ },
602
+ flush() {
603
+ return runtime.flush();
604
+ },
605
+ close() {
606
+ return runtime.close();
607
+ }
608
+ };
609
+ return inspector;
610
+ }
611
+
612
+ // packages/core/src/terminal.ts
613
+ var TERMINAL_INDENT = " ";
614
+ var MAX_TERMINAL_NAME_LENGTH = 80;
615
+ var MAX_TERMINAL_DEPTH = 10;
616
+ function normalizeDepth(depth) {
617
+ if (!Number.isFinite(depth) || depth < 0) {
618
+ return 0;
619
+ }
620
+ return Math.min(Math.floor(depth), MAX_TERMINAL_DEPTH);
621
+ }
622
+ function safePrint(line = "") {
623
+ try {
624
+ console.log(line);
625
+ } catch {
626
+ }
627
+ }
628
+ function getIndent(depth) {
629
+ return TERMINAL_INDENT.repeat(normalizeDepth(depth));
630
+ }
631
+ function formatTerminalName(name) {
632
+ if (typeof name !== "string" || name.trim() === "") {
633
+ return "unnamed";
634
+ }
635
+ return truncateName(name, MAX_TERMINAL_NAME_LENGTH);
636
+ }
637
+ function getStatusIcon(status) {
638
+ if (status === "success") return source_default.green("\u2714");
639
+ if (status === "error") return source_default.red("\u2716");
640
+ return source_default.yellow("\u23F3");
641
+ }
642
+ function renderStepLine(name, durationMs2, status, depth) {
643
+ try {
644
+ const nm = formatTerminalName(name);
645
+ const ind = getIndent(depth ?? 0);
646
+ if (status === "running" && durationMs2 === void 0) {
647
+ return `${ind}${source_default.yellow("\u23F3")} ${nm}`;
648
+ }
649
+ const hasDur = durationMs2 !== void 0 && Number.isFinite(durationMs2);
650
+ const dur = hasDur ? formatDuration(durationMs2) : void 0;
651
+ if (status === "running") {
652
+ return dur !== void 0 ? `${ind}${source_default.yellow("\u23F3")} ${nm} (${dur})` : `${ind}${source_default.yellow("\u23F3")} ${nm}`;
653
+ }
654
+ if (!hasDur || dur === void 0) {
655
+ return `${ind}${source_default.yellow("\u23F3")} ${nm}`;
656
+ }
657
+ if (status === "success") {
658
+ return `${ind}${getStatusIcon("success")} ${nm} (${dur})`;
659
+ }
660
+ return `${ind}${getStatusIcon("error")} ${nm} (${dur})`;
661
+ } catch {
662
+ return "";
663
+ }
664
+ }
665
+ function renderErrorLine(error, depth) {
666
+ try {
667
+ const msg = typeof error.message === "string" ? error.message : "";
668
+ const ind = getIndent((depth ?? 0) + 1);
669
+ return `${ind}Error: ${msg}`;
670
+ } catch {
671
+ return "";
672
+ }
673
+ }
674
+ function renderRunSummary(durationMs2, status, traceFilePath) {
675
+ try {
676
+ const dur = Number.isFinite(durationMs2) ? formatDuration(durationMs2) : formatDuration(0);
677
+ const head = status === "error" ? `Failed in ${dur}` : `Completed in ${dur}`;
678
+ const lines = [head];
679
+ if (traceFilePath !== void 0 && traceFilePath.trim() !== "") {
680
+ lines.push(`Trace: ${traceFilePath}`);
681
+ }
682
+ return lines;
683
+ } catch {
684
+ return [];
685
+ }
686
+ }
687
+ function printRunStart(runId, name) {
688
+ if (isSilentContext()) return;
689
+ try {
690
+ safePrint("");
691
+ const header = `${source_default.cyan.bold("\u{1F50D} AgentInspect:")} ${formatTerminalName(name)} ${source_default.dim(`(${runId})`)}`;
692
+ safePrint(header);
693
+ } catch {
694
+ }
695
+ }
696
+ function printStepStart(name, depth = 0) {
697
+ if (isSilentContext()) return;
698
+ try {
699
+ safePrint(renderStepLine(name, void 0, "running", depth));
700
+ } catch {
701
+ }
702
+ }
703
+ function printStepComplete(name, durationMs2, status, depth = 0) {
704
+ if (isSilentContext()) return;
705
+ try {
706
+ safePrint(renderStepLine(name, durationMs2, status, depth));
707
+ } catch {
708
+ }
709
+ }
710
+ function printError(error, depth = 0) {
711
+ if (isSilentContext()) return;
712
+ try {
713
+ safePrint(renderErrorLine(error, depth));
714
+ } catch {
715
+ }
716
+ }
717
+ function printRunComplete(_name, _runId, durationMs2, status, traceFilePath) {
718
+ if (isSilentContext()) return;
719
+ try {
720
+ const lines = renderRunSummary(durationMs2, status, traceFilePath);
721
+ for (let i = 0; i < lines.length; i++) {
722
+ const line = lines[i];
723
+ if (i === 0) {
724
+ const color = status === "error" ? source_default.red : status === "running" ? source_default.yellow : source_default.green;
725
+ safePrint(color(line));
726
+ } else {
727
+ safePrint(source_default.dim(line));
728
+ }
729
+ }
730
+ } catch {
731
+ }
732
+ }
733
+ function printFailedAt(stepName) {
734
+ if (isSilentContext()) return;
735
+ try {
736
+ safePrint(`Failed at: ${formatTerminalName(stepName)}`);
737
+ } catch {
738
+ }
739
+ }
740
+
741
+ export { MAX_TERMINAL_DEPTH, MAX_TERMINAL_NAME_LENGTH, TERMINAL_INDENT, createInspector, createInspectorRuntime, formatTerminalName, getCurrentContext, getCurrentCorrelationMetadata, getCurrentDepth, getCurrentRunId, getCurrentRunName, getCurrentStepId, getIndent, getParentStepId, getTraceDirFromContext, getTraceSafetyFromContext, hasActiveContext, isSilentContext, printError, printFailedAt, printRunComplete, printRunStart, printStepComplete, printStepStart, renderErrorLine, renderRunSummary, renderStepLine, runWithContext, runWithStepContext };
742
+ //# sourceMappingURL=chunk-6QSLZCBJ.mjs.map
743
+ //# sourceMappingURL=chunk-6QSLZCBJ.mjs.map