@agent-inspect/langchain 6.31.35 → 6.31.36

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.
package/dist/index.cjs DELETED
@@ -1,1995 +0,0 @@
1
- 'use strict';
2
-
3
- var path = require('path');
4
- var base = require('@langchain/core/callbacks/base');
5
- var advanced = require('agent-inspect/advanced');
6
- var logs = require('agent-inspect/logs');
7
-
8
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
-
10
- var path__default = /*#__PURE__*/_interopDefault(path);
11
-
12
- // packages/langchain/src/agent-inspect-callback.ts
13
- function isRecord(v) {
14
- return typeof v === "object" && v !== null && !Array.isArray(v);
15
- }
16
- function num(v) {
17
- if (typeof v === "number" && Number.isFinite(v)) return v;
18
- if (typeof v === "string" && v.trim() !== "") {
19
- const n = Number(v);
20
- if (Number.isFinite(n)) return n;
21
- }
22
- return void 0;
23
- }
24
- function normalizeTokenShape(raw) {
25
- const input = num(raw.promptTokens) ?? num(raw.inputTokens) ?? num(raw.input_tokens) ?? num(raw.prompt_tokens);
26
- const output = num(raw.completionTokens) ?? num(raw.outputTokens) ?? num(raw.output_tokens) ?? num(raw.completion_tokens);
27
- let total = num(raw.totalTokens) ?? num(raw.total_tokens);
28
- if (total === void 0 && input !== void 0 && output !== void 0) {
29
- total = input + output;
30
- }
31
- const inputDetails = isRecord(raw.input_token_details) ? raw.input_token_details : isRecord(raw.inputTokenDetails) ? raw.inputTokenDetails : void 0;
32
- const outputDetails = isRecord(raw.output_token_details) ? raw.output_token_details : isRecord(raw.outputTokenDetails) ? raw.outputTokenDetails : void 0;
33
- const cached = num(raw.cached) ?? num(raw.cache_read) ?? num(raw.cacheRead) ?? (inputDetails ? num(inputDetails.cache_read) ?? num(inputDetails.cacheRead) : void 0);
34
- const cacheWrite = num(raw.cacheWrite) ?? num(raw.cache_write) ?? num(raw.cache_creation) ?? (inputDetails ? num(inputDetails.cache_creation) ?? num(inputDetails.cache_write) ?? num(inputDetails.cacheWrite) : void 0);
35
- const reasoning = num(raw.reasoning) ?? num(raw.reasoning_tokens) ?? (outputDetails ? num(outputDetails.reasoning) ?? num(outputDetails.reasoning_tokens) : void 0);
36
- if (input === void 0 && output === void 0 && total === void 0 && cached === void 0 && cacheWrite === void 0 && reasoning === void 0) {
37
- return void 0;
38
- }
39
- const out = {};
40
- if (input !== void 0) out.input = input;
41
- if (output !== void 0) out.output = output;
42
- if (total !== void 0) out.total = total;
43
- if (cached !== void 0) out.cached = cached;
44
- if (cacheWrite !== void 0) out.cacheWrite = cacheWrite;
45
- if (reasoning !== void 0) out.reasoning = reasoning;
46
- return out;
47
- }
48
- function extractTokenUsage(output) {
49
- try {
50
- if (!isRecord(output)) return void 0;
51
- const candidates = [
52
- isRecord(output.llmOutput) ? output.llmOutput.tokenUsage : void 0,
53
- isRecord(output.llmOutput) ? output.llmOutput.estimatedTokenUsage : void 0,
54
- output.usage_metadata,
55
- isRecord(output.response_metadata) ? output.response_metadata.tokenUsage : void 0,
56
- isRecord(output.response_metadata) ? output.response_metadata.token_usage : void 0
57
- ];
58
- for (const c of candidates) {
59
- if (!isRecord(c)) continue;
60
- const norm = normalizeTokenShape(c);
61
- if (norm) return norm;
62
- }
63
- return void 0;
64
- } catch {
65
- return void 0;
66
- }
67
- }
68
- function readLcKwargs(serializedOrOutput) {
69
- if (!isRecord(serializedOrOutput)) return void 0;
70
- const lc = serializedOrOutput.lc_kwargs ?? serializedOrOutput.kwargs;
71
- return isRecord(lc) ? lc : void 0;
72
- }
73
- function extractModelName(serializedOrOutput) {
74
- try {
75
- const lc = readLcKwargs(serializedOrOutput);
76
- const fromLc = lc?.model ?? lc?.modelName ?? lc?.model_name;
77
- if (typeof fromLc === "string" && fromLc.trim()) return fromLc;
78
- if (isRecord(serializedOrOutput)) {
79
- for (const k of ["model", "modelName", "model_name"]) {
80
- const v = serializedOrOutput[k];
81
- if (typeof v === "string" && v.trim()) return v;
82
- }
83
- const rm = serializedOrOutput.response_metadata;
84
- if (isRecord(rm)) {
85
- const m = rm.model_name ?? rm.model;
86
- if (typeof m === "string" && m.trim()) return m;
87
- }
88
- const lo = serializedOrOutput.llmOutput;
89
- if (isRecord(lo)) {
90
- const m = lo.model_name;
91
- if (typeof m === "string" && m.trim()) return m;
92
- }
93
- }
94
- return void 0;
95
- } catch {
96
- return void 0;
97
- }
98
- }
99
- function safePreview(value, maxChars) {
100
- return advanced.serializeAdapterPreview(value, maxChars);
101
- }
102
- var MAX_METADATA_KEYS = 40;
103
- var LANGGRAPH_ALIASES = [
104
- { out: "graphId", aliases: ["graphId", "graph_id", "langgraph_graph_id"] },
105
- { out: "graphName", aliases: ["graphName", "graph_name", "langgraph_graph_name"] },
106
- { out: "nodeId", aliases: ["nodeId", "node_id", "langgraph_node_id"] },
107
- { out: "nodeName", aliases: ["nodeName", "node_name", "langgraph_node"] },
108
- { out: "subgraphId", aliases: ["subgraphId", "subgraph_id", "langgraph_subgraph_id"] },
109
- { out: "subgraphName", aliases: ["subgraphName", "subgraph_name", "langgraph_subgraph"] },
110
- { out: "taskId", aliases: ["taskId", "task_id", "langgraph_task_id"] },
111
- { out: "taskName", aliases: ["taskName", "task_name", "langgraph_task"] },
112
- { out: "graphStep", aliases: ["graphStep", "graph_step", "langgraph_step"] },
113
- { out: "streamMode", aliases: ["streamMode", "stream_mode", "langgraph_stream_mode"] },
114
- { out: "branch", aliases: ["branch", "branchName", "branch_name", "langgraph_branch"] },
115
- { out: "branchPath", aliases: ["branchPath", "branch_path", "langgraph_path"] },
116
- { out: "branchIndex", aliases: ["branchIndex", "branch_index", "langgraph_branch_index"] },
117
- {
118
- out: "parallelGroupId",
119
- aliases: ["parallelGroupId", "parallel_group_id", "langgraph_parallel_group_id"]
120
- },
121
- { out: "checkpointId", aliases: ["checkpointId", "checkpoint_id", "langgraph_checkpoint_id"] },
122
- {
123
- out: "checkpointNamespace",
124
- aliases: ["checkpointNamespace", "checkpoint_ns", "langgraph_checkpoint_ns"]
125
- },
126
- { out: "threadId", aliases: ["threadId", "thread_id", "langgraph_thread_id"] },
127
- { out: "sessionId", aliases: ["sessionId", "session_id", "langgraph_session_id"] },
128
- { out: "retryAttempt", aliases: ["retryAttempt", "retry_attempt", "attempt"] },
129
- { out: "handoffFrom", aliases: ["handoffFrom", "handoff_from", "langgraph_handoff_from"] },
130
- { out: "handoffTo", aliases: ["handoffTo", "handoff_to", "langgraph_handoff_to"] }
131
- ];
132
- var LANGGRAPH_SUMMARY_ALIASES = [
133
- { out: "checkpointSummary", aliases: ["checkpoint", "langgraph_checkpoint"] },
134
- { out: "branchSummary", aliases: ["branches", "langgraph_branches", "langgraph_triggers"] },
135
- { out: "subgraphSummary", aliases: ["subgraphs", "langgraph_subgraphs"] },
136
- { out: "taskSummary", aliases: ["tasks", "langgraph_tasks"] }
137
- ];
138
- function boundedValue(value) {
139
- if (value === null) return null;
140
- if (typeof value === "string") return value.length <= 200 ? value : `${value.slice(0, 200)}\u2026`;
141
- if (typeof value === "number" || typeof value === "boolean") return value;
142
- if (typeof value === "bigint") return value.toString();
143
- if (Array.isArray(value)) {
144
- const items = value.slice(0, 10).map((item) => {
145
- if (item === null) return null;
146
- if (typeof item === "string" || typeof item === "number" || typeof item === "boolean") {
147
- return item;
148
- }
149
- if (typeof item === "bigint") return item.toString();
150
- return summarizeValue(item);
151
- });
152
- return {
153
- type: "array",
154
- itemCount: value.length,
155
- items,
156
- truncated: value.length > items.length ? true : void 0
157
- };
158
- }
159
- return summarizeValue(value);
160
- }
161
- function summarizeValue(value) {
162
- if (Array.isArray(value)) return { type: "array", itemCount: value.length };
163
- if (isRecord(value)) return { type: "object", keyCount: Object.keys(value).length };
164
- return { type: typeof value };
165
- }
166
- function getAliasValue(sources, aliases) {
167
- for (const source of sources) {
168
- for (const alias of aliases) {
169
- if (Object.prototype.hasOwnProperty.call(source, alias)) {
170
- return source[alias];
171
- }
172
- }
173
- }
174
- return void 0;
175
- }
176
- function toPlainMetadata(value) {
177
- try {
178
- if (!isRecord(value)) return {};
179
- const out = {};
180
- let n = 0;
181
- for (const [k, v] of Object.entries(value)) {
182
- if (n >= MAX_METADATA_KEYS) break;
183
- if (typeof v === "function" || typeof v === "symbol") continue;
184
- if (v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
185
- out[k] = v;
186
- n++;
187
- continue;
188
- }
189
- if (typeof v === "bigint") {
190
- out[k] = v.toString();
191
- n++;
192
- continue;
193
- }
194
- if (Array.isArray(v)) {
195
- out[k] = `array(${v.length})`;
196
- n++;
197
- continue;
198
- }
199
- if (isRecord(v)) {
200
- out[k] = "[object]";
201
- n++;
202
- continue;
203
- }
204
- out[k] = String(v);
205
- n++;
206
- }
207
- return out;
208
- } catch {
209
- return {};
210
- }
211
- }
212
- function extractLangGraphMetadata(value) {
213
- try {
214
- if (!isRecord(value)) return void 0;
215
- const sources = [value];
216
- for (const key of ["langgraph", "configurable"]) {
217
- const nested = value[key];
218
- if (isRecord(nested)) sources.push(nested);
219
- }
220
- const langGraph = value.langgraph;
221
- if (isRecord(langGraph)) {
222
- const configurable = langGraph.configurable;
223
- if (isRecord(configurable)) sources.push(configurable);
224
- const nestedConfig = langGraph.config;
225
- if (isRecord(nestedConfig) && isRecord(nestedConfig.configurable)) {
226
- sources.push(nestedConfig.configurable);
227
- }
228
- }
229
- const config = value.config;
230
- if (isRecord(config) && isRecord(config.configurable)) {
231
- sources.push(config.configurable);
232
- }
233
- const out = {};
234
- for (const { out: outKey, aliases } of LANGGRAPH_ALIASES) {
235
- const raw = getAliasValue(sources, aliases);
236
- if (raw !== void 0) out[outKey] = boundedValue(raw);
237
- }
238
- for (const { out: outKey, aliases } of LANGGRAPH_SUMMARY_ALIASES) {
239
- const raw = getAliasValue(sources, aliases);
240
- if (raw !== void 0) out[outKey] = summarizeValue(raw);
241
- }
242
- return Object.keys(out).length > 0 ? out : void 0;
243
- } catch {
244
- return void 0;
245
- }
246
- }
247
-
248
- // packages/langchain/src/streaming-metadata.ts
249
- function createLlmStreamState() {
250
- return {
251
- chunkCount: 0,
252
- streamedCharCount: 0,
253
- previewChars: "",
254
- previewTruncated: false
255
- };
256
- }
257
- function recordLlmStreamToken(state, token, now, maxPreviewChars) {
258
- state.chunkCount += 1;
259
- if (state.firstChunkAt === void 0) {
260
- state.firstChunkAt = now;
261
- }
262
- state.lastChunkAt = now;
263
- if (typeof token === "string" && token.length > 0) {
264
- state.streamedCharCount += token.length;
265
- if (maxPreviewChars > 0) {
266
- const remaining = maxPreviewChars - state.previewChars.length;
267
- if (remaining > 0) {
268
- const slice = token.slice(0, remaining);
269
- state.previewChars += slice;
270
- if (token.length > remaining) {
271
- state.previewTruncated = true;
272
- }
273
- } else {
274
- state.previewTruncated = true;
275
- }
276
- }
277
- }
278
- }
279
- function streamMetadataFromState(state, options) {
280
- if (!state || state.chunkCount === 0) {
281
- return void 0;
282
- }
283
- const out = {
284
- stream: true,
285
- chunkCount: state.chunkCount,
286
- streamedCharCount: state.streamedCharCount
287
- };
288
- if (state.firstChunkAt !== void 0) {
289
- out.firstChunkAt = state.firstChunkAt;
290
- }
291
- if (state.lastChunkAt !== void 0) {
292
- out.lastChunkAt = state.lastChunkAt;
293
- }
294
- if (state.firstChunkAt !== void 0 && state.lastChunkAt !== void 0 && state.lastChunkAt >= state.firstChunkAt) {
295
- out.streamDurationMs = state.lastChunkAt - state.firstChunkAt;
296
- }
297
- if (state.previewTruncated) {
298
- out.previewTruncated = true;
299
- }
300
- if (options.capturePreview && state.previewChars.length > 0) {
301
- const preview = state.previewChars.length <= options.maxPreviewChars ? state.previewChars : `${state.previewChars.slice(0, options.maxPreviewChars)}\u2026`;
302
- out.streamPreview = preview;
303
- if (state.previewChars.length > options.maxPreviewChars) {
304
- out.previewTruncated = true;
305
- }
306
- }
307
- return out;
308
- }
309
-
310
- // packages/langchain/src/tool-identity.ts
311
- function serializedLabel(s) {
312
- if (typeof s.name === "string" && s.name.trim()) return s.name.trim();
313
- if (Array.isArray(s.id) && s.id.length > 0) {
314
- const last = s.id[s.id.length - 1];
315
- if (typeof last === "string" && last.trim()) return last.trim();
316
- }
317
- return typeof s.type === "string" && s.type.trim() ? s.type.trim() : void 0;
318
- }
319
- function nonEmpty(value) {
320
- if (typeof value !== "string") return void 0;
321
- const trimmed = value.trim();
322
- return trimmed.length > 0 ? trimmed : void 0;
323
- }
324
- function resolveToolIdentity(tool, runName, metadata, toolCallId) {
325
- const frameworkRunName = nonEmpty(runName);
326
- const metaToolName = nonEmpty(metadata?.toolName);
327
- const metaTool = nonEmpty(metadata?.tool);
328
- const classLabel = serializedLabel(tool);
329
- const callId = nonEmpty(toolCallId) ?? nonEmpty(metadata?.toolCallId) ?? nonEmpty(metadata?.tool_call_id);
330
- const displayName = frameworkRunName ?? metaToolName ?? metaTool ?? classLabel ?? "unknown-tool";
331
- return {
332
- displayName,
333
- toolName: displayName,
334
- ...classLabel && classLabel !== displayName ? { toolClass: classLabel } : {},
335
- ...callId ? { toolCallId: callId } : {},
336
- ...frameworkRunName ? { frameworkRunName } : {}
337
- };
338
- }
339
- function applyToolIdentityAttributes(attrs, identity) {
340
- attrs.tool = identity.displayName;
341
- attrs.toolName = identity.toolName;
342
- if (identity.toolClass) attrs.toolClass = identity.toolClass;
343
- if (identity.toolCallId) attrs.toolCallId = identity.toolCallId;
344
- if (identity.frameworkRunName) attrs.frameworkRunName = identity.frameworkRunName;
345
- }
346
-
347
- // packages/langchain/src/persist-intent.ts
348
- function resolvePersistIntent(input) {
349
- const hasTraceDir = typeof input.traceDir === "string" && input.traceDir.trim().length > 0;
350
- const explicit = input.persist;
351
- if (explicit === false) {
352
- return { persist: false, contradictory: hasTraceDir };
353
- }
354
- if (explicit === true) {
355
- return { persist: true, contradictory: false };
356
- }
357
- return { persist: hasTraceDir, contradictory: false };
358
- }
359
-
360
- // packages/langchain/src/invocation-state.ts
361
- function createInvocationState(envelopeRunId) {
362
- return {
363
- envelopeRunId,
364
- activeRuns: /* @__PURE__ */ new Map(),
365
- endedRuns: /* @__PURE__ */ new Set(),
366
- knownRelationships: /* @__PURE__ */ new Map(),
367
- pendingRelationships: [],
368
- completionGeneration: 0,
369
- envelopeStarted: false,
370
- finalized: false
371
- };
372
- }
373
- function isObservedCallbackRun(state, parentLcRunId) {
374
- return state.activeRuns.has(parentLcRunId) || state.endedRuns.has(parentLcRunId);
375
- }
376
- function beginCallbackRun(state, input) {
377
- state.completionGeneration += 1;
378
- const run = {
379
- lcRunId: input.lcRunId,
380
- ...input.parentLcRunId !== void 0 ? { parentLcRunId: input.parentLcRunId } : {},
381
- startedAt: input.startedAt,
382
- ...input.kind !== void 0 ? { kind: input.kind } : {},
383
- ...input.stepId !== void 0 ? { stepId: input.stepId } : {}
384
- };
385
- state.activeRuns.set(input.lcRunId, run);
386
- if (input.parentLcRunId !== void 0) {
387
- if (isObservedCallbackRun(state, input.parentLcRunId)) {
388
- state.knownRelationships.set(input.lcRunId, input.parentLcRunId);
389
- } else {
390
- state.pendingRelationships.push({
391
- childLcRunId: input.lcRunId,
392
- parentLcRunId: input.parentLcRunId,
393
- reason: "unobserved-parent"
394
- });
395
- }
396
- }
397
- return run;
398
- }
399
- function endCallbackRun(state, lcRunId) {
400
- const active = state.activeRuns.get(lcRunId);
401
- if (active === void 0) {
402
- if (state.endedRuns.has(lcRunId) || state.finalized) {
403
- return { ended: false, late: true };
404
- }
405
- return { ended: false, late: true };
406
- }
407
- state.completionGeneration += 1;
408
- state.activeRuns.delete(lcRunId);
409
- state.endedRuns.add(lcRunId);
410
- return { ended: true, late: false };
411
- }
412
- function markEnvelopeStarted(state, startTime) {
413
- if (state.envelopeStarted) return false;
414
- state.envelopeStarted = true;
415
- state.runStartTime = startTime;
416
- return true;
417
- }
418
- function markFinalized(state) {
419
- if (state.finalized) return false;
420
- if (!state.envelopeStarted) return false;
421
- state.finalized = true;
422
- return true;
423
- }
424
- function noteTerminalError(state, message) {
425
- state.terminalError = { message };
426
- }
427
- function canScheduleFinalize(state) {
428
- return state.envelopeStarted && !state.finalized && state.activeRuns.size === 0;
429
- }
430
- function bumpCompletionGeneration(state) {
431
- state.completionGeneration += 1;
432
- return state.completionGeneration;
433
- }
434
- function resetInvocationState(state, nextEnvelopeRunId) {
435
- state.activeRuns.clear();
436
- state.endedRuns.clear();
437
- state.knownRelationships.clear();
438
- state.pendingRelationships.length = 0;
439
- state.terminalError = void 0;
440
- state.completionGeneration += 1;
441
- state.envelopeStarted = false;
442
- state.finalized = false;
443
- state.runStartTime = void 0;
444
- if (nextEnvelopeRunId !== void 0) {
445
- state.envelopeRunId = nextEnvelopeRunId;
446
- }
447
- }
448
-
449
- // packages/langchain/src/parent-reconciliation.ts
450
- var WELL_KNOWN_SEMANTIC_PARENTS = /* @__PURE__ */ new Set([
451
- "LangGraph",
452
- "__start__",
453
- "__end__"
454
- ]);
455
- function isSemanticParentLabel(parentLcRunId) {
456
- if (WELL_KNOWN_SEMANTIC_PARENTS.has(parentLcRunId)) return true;
457
- return parentLcRunId.startsWith("__") && parentLcRunId.endsWith("__");
458
- }
459
- function excludeSelf(stepId, excludeStepId) {
460
- if (!stepId) return void 0;
461
- if (excludeStepId && stepId === excludeStepId) return void 0;
462
- return stepId;
463
- }
464
- var LANGGRAPH_PARENT_KEYS = [
465
- "handoffFrom",
466
- "taskId",
467
- "nodeId",
468
- "nodeName",
469
- "checkpointNamespace"
470
- ];
471
- function langGraphRecord(attributes) {
472
- const lg = attributes?.langGraph;
473
- if (typeof lg !== "object" || lg === null || Array.isArray(lg)) return void 0;
474
- return lg;
475
- }
476
- function resolveParentRelationship(input, lookup, context = {}) {
477
- const parentLcRunId = input.parentLcRunId;
478
- const excludeStepId = context.excludeStepId;
479
- if (parentLcRunId) {
480
- const exact = excludeSelf(lookup.exactStepByLcRunId(parentLcRunId), excludeStepId);
481
- if (exact) {
482
- return {
483
- parentStepId: exact,
484
- confidence: "explicit",
485
- parentMapping: "exact"
486
- };
487
- }
488
- }
489
- const lg = langGraphRecord(input.attributes);
490
- if (lg) {
491
- for (const key of LANGGRAPH_PARENT_KEYS) {
492
- if (key !== "handoffFrom" && key !== "checkpointNamespace") continue;
493
- const raw = lg[key];
494
- if (typeof raw !== "string" || !raw.trim()) continue;
495
- const stepId = excludeSelf(
496
- lookup.uniqueStepByLangGraphKey(key === "handoffFrom" ? "taskId" : key, raw),
497
- excludeStepId
498
- );
499
- const matched = stepId ?? excludeSelf(
500
- key === "handoffFrom" ? lookup.uniqueStepByLangGraphKey("nodeName", raw) ?? lookup.uniqueStepByLangGraphKey("nodeId", raw) : void 0,
501
- excludeStepId
502
- );
503
- if (matched) {
504
- return {
505
- parentStepId: matched,
506
- confidence: "correlated",
507
- parentMapping: "langgraph-metadata",
508
- correlatedVia: key
509
- };
510
- }
511
- }
512
- }
513
- if (parentLcRunId && isSemanticParentLabel(parentLcRunId)) {
514
- const semantic = excludeSelf(
515
- lookup.uniqueStepBySemanticLabel(parentLcRunId),
516
- excludeStepId
517
- );
518
- if (semantic) {
519
- return {
520
- parentStepId: semantic,
521
- confidence: "correlated",
522
- parentMapping: "semantic-name",
523
- semanticParentLabel: parentLcRunId
524
- };
525
- }
526
- return {
527
- confidence: "unresolved",
528
- parentMapping: "unresolved",
529
- semanticParentLabel: parentLcRunId,
530
- unresolvedParentRunId: parentLcRunId
531
- };
532
- }
533
- if (parentLcRunId) {
534
- return {
535
- confidence: "unresolved",
536
- parentMapping: "unresolved",
537
- unresolvedParentRunId: parentLcRunId
538
- };
539
- }
540
- return {
541
- confidence: "explicit",
542
- parentMapping: "exact"
543
- };
544
- }
545
- function rejectSelfParentResolution(resolution, stepId, parentLcRunId) {
546
- if (resolution.parentStepId !== stepId) return resolution;
547
- return {
548
- confidence: "unresolved",
549
- parentMapping: "unresolved",
550
- unresolvedParentRunId: parentLcRunId ?? resolution.unresolvedParentRunId,
551
- ...resolution.semanticParentLabel ? { semanticParentLabel: resolution.semanticParentLabel } : {}
552
- };
553
- }
554
- var AI_LANGGRAPH_SELF_PARENT_REJECTED = "AI_LANGGRAPH_SELF_PARENT_REJECTED";
555
- var AI_LANGGRAPH_RELATIONSHIP_AMBIGUOUS = "AI_LANGGRAPH_RELATIONSHIP_AMBIGUOUS";
556
- function applySelfParentCaptureInvariant(stepId, parentStepId, metadata, originalParentRunId) {
557
- if (!parentStepId || parentStepId !== stepId) {
558
- return { parentStepId, rejected: false };
559
- }
560
- metadata.parentMapping = "self-parent-rejected";
561
- metadata.parentConfidence = "unresolved";
562
- metadata.relationshipWarning = "self-parent";
563
- metadata.diagnosticCode = AI_LANGGRAPH_SELF_PARENT_REJECTED;
564
- if (originalParentRunId && originalParentRunId.trim()) {
565
- metadata.originalParentRunId = originalParentRunId.slice(0, 128);
566
- }
567
- delete metadata.parentCorrelatedVia;
568
- return { parentStepId: void 0, rejected: true };
569
- }
570
- function applyAmbiguousScaffoldingDiagnostic(resolution, metadata) {
571
- if (resolution.parentStepId) return false;
572
- if (resolution.parentMapping !== "unresolved") return false;
573
- if (metadata.diagnosticCode === AI_LANGGRAPH_SELF_PARENT_REJECTED) return false;
574
- metadata.diagnosticCode = AI_LANGGRAPH_RELATIONSHIP_AMBIGUOUS;
575
- if (typeof metadata.relationshipWarning !== "string") {
576
- metadata.relationshipWarning = "ambiguous-root";
577
- }
578
- return true;
579
- }
580
- function applyParentResolutionMetadata(metadata, resolution) {
581
- const hasParentSignal = Boolean(resolution.parentStepId) || Boolean(resolution.unresolvedParentRunId) || Boolean(resolution.semanticParentLabel) || Boolean(resolution.correlatedVia);
582
- if (!hasParentSignal) return;
583
- metadata.parentMapping = resolution.parentMapping;
584
- metadata.parentConfidence = resolution.confidence;
585
- if (resolution.semanticParentLabel) {
586
- metadata.semanticParentLabel = resolution.semanticParentLabel;
587
- }
588
- if (resolution.unresolvedParentRunId) {
589
- metadata.unresolvedParentRunId = resolution.unresolvedParentRunId;
590
- }
591
- if (resolution.correlatedVia) {
592
- metadata.parentCorrelatedVia = resolution.correlatedVia;
593
- }
594
- if (resolution.parentMapping === "synthetic-group") {
595
- metadata.synthetic = true;
596
- }
597
- }
598
-
599
- // packages/langchain/src/trace-persistence.ts
600
- function kindToStepType(kind) {
601
- switch (kind) {
602
- case "LLM":
603
- return "llm";
604
- case "TOOL":
605
- return "tool";
606
- case "DECISION":
607
- return "decision";
608
- default:
609
- return "logic";
610
- }
611
- }
612
- function toStepMetadata(attrs) {
613
- const out = {
614
- adapter: "langchain",
615
- confidence: "explicit"
616
- };
617
- for (const [k, v] of Object.entries(attrs)) {
618
- out[k] = v;
619
- }
620
- return out;
621
- }
622
- var LangChainTracePersistence = class {
623
- #traceDir;
624
- #runId;
625
- #runName;
626
- #standalone;
627
- #silent;
628
- #safety;
629
- #lifecycle;
630
- #lcToStepId = /* @__PURE__ */ new Map();
631
- /** `${field}\0${value}` → stepId, or null when ambiguous. */
632
- #langGraphIndex = /* @__PURE__ */ new Map();
633
- /** Semantic / display label → stepId, or null when ambiguous. */
634
- #semanticLabelIndex = /* @__PURE__ */ new Map();
635
- /** Semantic label → synthetic step id (created once ≥2 siblings share the label). */
636
- #syntheticByLabel = /* @__PURE__ */ new Map();
637
- /** Count of unresolved semantic-parent children seen per label (this invocation). */
638
- #semanticParentCounts = /* @__PURE__ */ new Map();
639
- #lateEventCount = 0;
640
- #selfParentRejectedCount = 0;
641
- #ambiguousRelationshipCount = 0;
642
- constructor(options = {}) {
643
- const inContext = advanced.hasActiveContext();
644
- this.#standalone = !inContext;
645
- this.#silent = options.silent ?? false;
646
- this.#traceDir = inContext ? advanced.getTraceDirFromContext() ?? advanced.resolveTraceDir({ dir: options.traceDir }) : advanced.resolveTraceDir({ dir: options.traceDir });
647
- const contextRunId = inContext ? advanced.getCurrentRunId() : void 0;
648
- this.#runId = contextRunId ?? options.runId ?? advanced.createRunId();
649
- this.#runName = options.runName ?? "langchain-agent";
650
- this.#safety = advanced.resolveTraceSafetyOptions({
651
- redact: options.redact ? { rules: options.redact } : true,
652
- maxPreviewLength: options.maxPreviewChars,
653
- ...options.redactionProfile ? { redactionProfile: options.redactionProfile } : {}
654
- });
655
- this.#lifecycle = createInvocationState(this.#runId);
656
- }
657
- get runId() {
658
- return this.#runId;
659
- }
660
- get traceDir() {
661
- return this.#traceDir;
662
- }
663
- /** @internal Test / diagnostics access to per-invocation lifecycle. */
664
- get lifecycle() {
665
- return this.#lifecycle;
666
- }
667
- /** Count of end/start events ignored after finalize (diagnostics). */
668
- get lateEventCount() {
669
- return this.#lateEventCount;
670
- }
671
- /** Bounded adapter diagnostics for CLI/MCP summaries (no filesystem paths). */
672
- getDiagnostics() {
673
- return {
674
- lateEventCount: this.#lateEventCount,
675
- activeRunCount: this.#lifecycle.activeRuns.size,
676
- endedRunCount: this.#lifecycle.endedRuns.size,
677
- pendingRelationshipCount: this.#lifecycle.pendingRelationships.length,
678
- knownRelationshipCount: this.#lifecycle.knownRelationships.size,
679
- syntheticGroupCount: this.#syntheticByLabel.size,
680
- selfParentRejectedCount: this.#selfParentRejectedCount,
681
- ambiguousRelationshipCount: this.#ambiguousRelationshipCount,
682
- envelopeStarted: this.#lifecycle.envelopeStarted,
683
- finalized: this.#lifecycle.finalized,
684
- completionGeneration: this.#lifecycle.completionGeneration,
685
- hasTerminalError: Boolean(this.#lifecycle.terminalError)
686
- };
687
- }
688
- #parentIdForPersist(stepId, resolution, metadata, originalParentRunId) {
689
- const guarded = applySelfParentCaptureInvariant(
690
- stepId,
691
- resolution.parentStepId,
692
- metadata,
693
- originalParentRunId ?? resolution.unresolvedParentRunId
694
- );
695
- if (guarded.rejected) {
696
- this.#selfParentRejectedCount += 1;
697
- } else if (applyAmbiguousScaffoldingDiagnostic(resolution, metadata)) {
698
- this.#ambiguousRelationshipCount += 1;
699
- }
700
- return guarded.parentStepId;
701
- }
702
- /**
703
- * Start a fresh envelope after a prior invocation finalized (callback reuse).
704
- * Allocates a new run id unless still nested in an inspectRun context.
705
- */
706
- beginNewInvocation() {
707
- if (advanced.hasActiveContext()) {
708
- const ctxId = advanced.getCurrentRunId();
709
- if (ctxId) {
710
- this.#runId = ctxId;
711
- resetInvocationState(this.#lifecycle, this.#runId);
712
- this.#clearStepIndexes();
713
- this.#lateEventCount = 0;
714
- this.#selfParentRejectedCount = 0;
715
- this.#ambiguousRelationshipCount = 0;
716
- return;
717
- }
718
- }
719
- this.#runId = advanced.createRunId();
720
- resetInvocationState(this.#lifecycle, this.#runId);
721
- this.#clearStepIndexes();
722
- this.#lateEventCount = 0;
723
- this.#selfParentRejectedCount = 0;
724
- this.#ambiguousRelationshipCount = 0;
725
- }
726
- reset() {
727
- resetInvocationState(this.#lifecycle);
728
- this.#clearStepIndexes();
729
- this.#lateEventCount = 0;
730
- this.#selfParentRejectedCount = 0;
731
- this.#ambiguousRelationshipCount = 0;
732
- }
733
- #clearStepIndexes() {
734
- this.#lcToStepId.clear();
735
- this.#langGraphIndex.clear();
736
- this.#semanticLabelIndex.clear();
737
- this.#syntheticByLabel.clear();
738
- this.#semanticParentCounts.clear();
739
- }
740
- #registerUnique(index, key, stepId) {
741
- if (!index.has(key)) {
742
- index.set(key, stepId);
743
- return;
744
- }
745
- if (index.get(key) !== stepId) {
746
- index.set(key, null);
747
- }
748
- }
749
- #langGraphIndexKey(field, value) {
750
- return `${field}\0${value}`;
751
- }
752
- #registerStepIndexes(stepId, name, attributes) {
753
- const labels = /* @__PURE__ */ new Set([name]);
754
- const stripped = name.replace(/^(chain|tool|llm|retriever|agent):/, "");
755
- if (stripped) labels.add(stripped);
756
- for (const label of labels) {
757
- this.#registerUnique(this.#semanticLabelIndex, label, stepId);
758
- }
759
- const lg = attributes.langGraph;
760
- if (typeof lg === "object" && lg !== null && !Array.isArray(lg)) {
761
- const record = lg;
762
- for (const field of [
763
- "taskId",
764
- "nodeId",
765
- "nodeName",
766
- "checkpointNamespace"
767
- ]) {
768
- const raw = record[field];
769
- if (typeof raw === "string" && raw.trim()) {
770
- this.#registerUnique(
771
- this.#langGraphIndex,
772
- this.#langGraphIndexKey(field, raw),
773
- stepId
774
- );
775
- }
776
- }
777
- }
778
- }
779
- #resolveParent(parentLcRunId, attributes, excludeStepId) {
780
- const resolution = resolveParentRelationship(
781
- { parentLcRunId, attributes },
782
- {
783
- exactStepByLcRunId: (lcRunId) => this.#lcToStepId.get(lcRunId),
784
- uniqueStepByLangGraphKey: (key, value) => {
785
- const hit = this.#langGraphIndex.get(this.#langGraphIndexKey(key, value));
786
- return hit === null || hit === void 0 ? void 0 : hit;
787
- },
788
- uniqueStepBySemanticLabel: (label) => {
789
- const hit = this.#semanticLabelIndex.get(label);
790
- return hit === null || hit === void 0 ? void 0 : hit;
791
- }
792
- },
793
- excludeStepId ? { excludeStepId } : {}
794
- );
795
- return excludeStepId ? rejectSelfParentResolution(resolution, excludeStepId, parentLcRunId) : resolution;
796
- }
797
- /**
798
- * When ≥2 steps share the same unresolved semantic parent label, emit one
799
- * synthetic grouping node and attach this (and later) siblings under it.
800
- * The first sibling remains unresolved (append-only JSONL cannot rewrite it).
801
- */
802
- async #maybeAttachSyntheticGroup(resolution, startTime) {
803
- const label = resolution.semanticParentLabel;
804
- if (resolution.parentMapping !== "unresolved" || !label || resolution.parentStepId) {
805
- return resolution;
806
- }
807
- const existing = this.#syntheticByLabel.get(label);
808
- if (existing) {
809
- return {
810
- parentStepId: existing,
811
- confidence: "synthetic",
812
- parentMapping: "synthetic-group",
813
- semanticParentLabel: label,
814
- unresolvedParentRunId: label
815
- };
816
- }
817
- const nextCount = (this.#semanticParentCounts.get(label) ?? 0) + 1;
818
- this.#semanticParentCounts.set(label, nextCount);
819
- if (nextCount < 2) {
820
- return resolution;
821
- }
822
- const syntheticStepId = advanced.createStepId();
823
- this.#syntheticByLabel.set(label, syntheticStepId);
824
- const metadata = {
825
- adapter: "langchain",
826
- confidence: "synthetic",
827
- synthetic: true,
828
- parentMapping: "synthetic-group",
829
- parentConfidence: "synthetic",
830
- semanticParentLabel: label,
831
- unresolvedParentRunId: label
832
- };
833
- const event = {
834
- schemaVersion: "0.1",
835
- event: "step_started",
836
- timestamp: startTime,
837
- runId: this.#runId,
838
- stepId: syntheticStepId,
839
- name: `synthetic:${label}`,
840
- type: "logic",
841
- startTime,
842
- metadata
843
- };
844
- await this.#write(event);
845
- return {
846
- parentStepId: syntheticStepId,
847
- confidence: "synthetic",
848
- parentMapping: "synthetic-group",
849
- semanticParentLabel: label,
850
- unresolvedParentRunId: label
851
- };
852
- }
853
- /** Rotate when a prior standalone invocation already finalized. */
854
- #prepareForStart() {
855
- if (this.#standalone && this.#lifecycle.finalized) {
856
- this.beginNewInvocation();
857
- }
858
- }
859
- /**
860
- * @deprecated Root-ID heuristics are no longer used for envelope completion.
861
- * Retained as a no-op for call-site compatibility during the v6.8 train.
862
- */
863
- noteRoot(_lcRunId, _parentRunId) {
864
- }
865
- resolveParentId(lcParentRunId) {
866
- if (!lcParentRunId) return void 0;
867
- return this.#lcToStepId.get(lcParentRunId);
868
- }
869
- async onStepStart(params) {
870
- try {
871
- this.#prepareForStart();
872
- const stepId = advanced.createStepId();
873
- const resolution = await this.#maybeAttachSyntheticGroup(
874
- this.#resolveParent(params.lcParentRunId, params.attributes, stepId),
875
- params.startTime
876
- );
877
- beginCallbackRun(this.#lifecycle, {
878
- lcRunId: params.lcRunId,
879
- parentLcRunId: params.lcParentRunId,
880
- startedAt: params.startTime,
881
- kind: params.kind,
882
- stepId
883
- });
884
- if (this.#standalone && !this.#lifecycle.envelopeStarted) {
885
- await this.#ensureRunStarted(params.startTime, params.attributes);
886
- }
887
- const metadata = toStepMetadata(params.attributes);
888
- applyParentResolutionMetadata(metadata, resolution);
889
- const parentId = this.#parentIdForPersist(
890
- stepId,
891
- resolution,
892
- metadata,
893
- params.lcParentRunId
894
- );
895
- const event = {
896
- schemaVersion: "0.1",
897
- event: "step_started",
898
- timestamp: params.startTime,
899
- runId: this.#runId,
900
- stepId,
901
- ...parentId ? { parentId } : {},
902
- name: params.name,
903
- type: kindToStepType(params.kind),
904
- startTime: params.startTime,
905
- metadata
906
- };
907
- this.#lcToStepId.set(params.lcRunId, stepId);
908
- await this.#write(event);
909
- this.#registerStepIndexes(stepId, params.name, params.attributes);
910
- } catch (err) {
911
- this.#warn(err);
912
- }
913
- }
914
- async onStepEnd(params) {
915
- try {
916
- if (this.#lifecycle.finalized && !this.#lifecycle.activeRuns.has(params.lcRunId) && !this.#lcToStepId.has(params.lcRunId)) {
917
- this.#lateEventCount += 1;
918
- return;
919
- }
920
- let stepId = this.#lcToStepId.get(params.lcRunId);
921
- if (!stepId && params.completionAttributes) {
922
- if (this.#lifecycle.finalized) {
923
- this.#lateEventCount += 1;
924
- return;
925
- }
926
- stepId = advanced.createStepId();
927
- const synthName = String(params.completionAttributes.name ?? "llm:llm");
928
- const startTime = params.endTime - (params.durationMs ?? 0);
929
- const resolution = await this.#maybeAttachSyntheticGroup(
930
- this.#resolveParent(
931
- params.lcParentRunId,
932
- params.completionAttributes,
933
- stepId
934
- ),
935
- startTime
936
- );
937
- beginCallbackRun(this.#lifecycle, {
938
- lcRunId: params.lcRunId,
939
- parentLcRunId: params.lcParentRunId,
940
- startedAt: startTime,
941
- kind: params.completionAttributes.kind ?? "LLM",
942
- stepId
943
- });
944
- const metadata = toStepMetadata(params.completionAttributes);
945
- applyParentResolutionMetadata(metadata, resolution);
946
- const parentId = this.#parentIdForPersist(
947
- stepId,
948
- resolution,
949
- metadata,
950
- params.lcParentRunId
951
- );
952
- const started = {
953
- schemaVersion: "0.1",
954
- event: "step_started",
955
- timestamp: startTime,
956
- runId: this.#runId,
957
- stepId,
958
- ...parentId ? { parentId } : {},
959
- name: synthName,
960
- type: kindToStepType(
961
- params.completionAttributes.kind ?? "LLM"
962
- ),
963
- startTime,
964
- metadata
965
- };
966
- if (this.#standalone && !this.#lifecycle.envelopeStarted) {
967
- await this.#ensureRunStarted(startTime, params.completionAttributes);
968
- }
969
- this.#lcToStepId.set(params.lcRunId, stepId);
970
- await this.#write(started);
971
- this.#registerStepIndexes(stepId, synthName, params.completionAttributes);
972
- }
973
- if (!stepId) return;
974
- const durationMs = typeof params.durationMs === "number" && Number.isFinite(params.durationMs) ? Math.max(0, Math.floor(params.durationMs)) : Math.max(
975
- 0,
976
- params.endTime - (this.#lifecycle.runStartTime ?? params.endTime)
977
- );
978
- const event = {
979
- schemaVersion: "0.1",
980
- event: "step_completed",
981
- timestamp: params.endTime,
982
- runId: this.#runId,
983
- stepId,
984
- status: params.status,
985
- endTime: params.endTime,
986
- durationMs,
987
- ...params.status === "error" && params.errorMessage ? { error: { message: params.errorMessage } } : {}
988
- };
989
- await this.#write(event);
990
- if (params.status === "error") {
991
- noteTerminalError(
992
- this.#lifecycle,
993
- params.errorMessage ?? "adapter step error"
994
- );
995
- }
996
- endCallbackRun(this.#lifecycle, params.lcRunId);
997
- await this.#scheduleStandaloneFinalization(params.endTime);
998
- } catch (err) {
999
- this.#warn(err);
1000
- }
1001
- }
1002
- /** Point-in-time adapter events (e.g. agent action) — writes start + completed pair. */
1003
- async onInstantStep(params) {
1004
- try {
1005
- this.#prepareForStart();
1006
- const stepId = advanced.createStepId();
1007
- const resolution = await this.#maybeAttachSyntheticGroup(
1008
- this.#resolveParent(params.lcParentRunId, params.attributes, stepId),
1009
- params.timestamp
1010
- );
1011
- beginCallbackRun(this.#lifecycle, {
1012
- lcRunId: params.lcRunId,
1013
- parentLcRunId: params.lcParentRunId,
1014
- startedAt: params.timestamp,
1015
- kind: params.kind,
1016
- stepId
1017
- });
1018
- if (this.#standalone && !this.#lifecycle.envelopeStarted) {
1019
- await this.#ensureRunStarted(params.timestamp, params.attributes);
1020
- }
1021
- const metadata = toStepMetadata(params.attributes);
1022
- applyParentResolutionMetadata(metadata, resolution);
1023
- const parentId = this.#parentIdForPersist(
1024
- stepId,
1025
- resolution,
1026
- metadata,
1027
- params.lcParentRunId
1028
- );
1029
- const started = {
1030
- schemaVersion: "0.1",
1031
- event: "step_started",
1032
- timestamp: params.timestamp,
1033
- runId: this.#runId,
1034
- stepId,
1035
- ...parentId ? { parentId } : {},
1036
- name: params.name,
1037
- type: kindToStepType(params.kind),
1038
- startTime: params.timestamp,
1039
- metadata
1040
- };
1041
- this.#lcToStepId.set(params.lcRunId, stepId);
1042
- await this.#write(started);
1043
- this.#registerStepIndexes(stepId, params.name, params.attributes);
1044
- const completed = {
1045
- schemaVersion: "0.1",
1046
- event: "step_completed",
1047
- timestamp: params.timestamp,
1048
- runId: this.#runId,
1049
- stepId,
1050
- status: params.status,
1051
- endTime: params.timestamp,
1052
- durationMs: 0,
1053
- ...params.status === "error" && params.errorMessage ? { error: { message: params.errorMessage } } : {}
1054
- };
1055
- await this.#write(completed);
1056
- if (params.status === "error") {
1057
- noteTerminalError(
1058
- this.#lifecycle,
1059
- params.errorMessage ?? "adapter step error"
1060
- );
1061
- }
1062
- endCallbackRun(this.#lifecycle, params.lcRunId);
1063
- await this.#scheduleStandaloneFinalization(params.timestamp);
1064
- } catch (err) {
1065
- this.#warn(err);
1066
- }
1067
- }
1068
- /**
1069
- * Drain deferred microtask finalization. Idempotent; never throws to callers.
1070
- * @experimental
1071
- */
1072
- async flush() {
1073
- try {
1074
- await Promise.resolve();
1075
- await Promise.resolve();
1076
- } catch (err) {
1077
- this.#warn(err);
1078
- }
1079
- }
1080
- /**
1081
- * Force-complete the standalone envelope when safe/started.
1082
- * Works even if active callback runs remain (unusual framework shapes / serverless).
1083
- * Idempotent; never throws to callers.
1084
- * @experimental
1085
- */
1086
- async finalize(options = {}) {
1087
- try {
1088
- if (!this.#standalone) return false;
1089
- if (this.#lifecycle.finalized) return false;
1090
- if (!this.#lifecycle.envelopeStarted) return false;
1091
- bumpCompletionGeneration(this.#lifecycle);
1092
- const status = options.status ?? (this.#lifecycle.terminalError ? "error" : "success");
1093
- if (status === "error") {
1094
- noteTerminalError(
1095
- this.#lifecycle,
1096
- options.errorMessage ?? this.#lifecycle.terminalError?.message ?? "adapter finalize error"
1097
- );
1098
- }
1099
- await this.#ensureRunCompleted(
1100
- options.endTime ?? Date.now(),
1101
- status,
1102
- status === "error" ? options.errorMessage ?? this.#lifecycle.terminalError?.message : void 0
1103
- );
1104
- return this.#lifecycle.finalized;
1105
- } catch (err) {
1106
- this.#warn(err);
1107
- return false;
1108
- }
1109
- }
1110
- /**
1111
- * Flush + finalize. Idempotent; never throws to callers.
1112
- * @experimental
1113
- */
1114
- async close() {
1115
- try {
1116
- await this.flush();
1117
- await this.finalize();
1118
- } catch (err) {
1119
- this.#warn(err);
1120
- }
1121
- }
1122
- /**
1123
- * When the last active LangChain callback ends, yield one microtask so a
1124
- * same-turn sibling start can cancel finalization, then write run_completed
1125
- * before the callback promise settles. Unresolved external parents do not
1126
- * block the envelope.
1127
- */
1128
- async #scheduleStandaloneFinalization(endTime) {
1129
- if (!this.#standalone || !canScheduleFinalize(this.#lifecycle)) return;
1130
- const generation = this.#lifecycle.completionGeneration;
1131
- await Promise.resolve();
1132
- if (this.#lifecycle.completionGeneration !== generation) return;
1133
- if (!this.#standalone || !canScheduleFinalize(this.#lifecycle)) return;
1134
- const status = this.#lifecycle.terminalError ? "error" : "success";
1135
- await this.#ensureRunCompleted(
1136
- endTime,
1137
- status,
1138
- status === "error" ? this.#lifecycle.terminalError?.message : void 0
1139
- );
1140
- }
1141
- async #ensureRunStarted(startTime, attrs) {
1142
- if (!markEnvelopeStarted(this.#lifecycle, startTime)) return;
1143
- await advanced.initializeTraceFile(this.#runId, this.#traceDir);
1144
- const metadata = {
1145
- adapter: "langchain",
1146
- confidence: "explicit"
1147
- };
1148
- if (attrs.langchainRunId) metadata.langchainRunId = attrs.langchainRunId;
1149
- if (attrs.adapterRunName) metadata.adapterRunName = attrs.adapterRunName;
1150
- const event = {
1151
- schemaVersion: "0.1",
1152
- event: "run_started",
1153
- timestamp: startTime,
1154
- runId: this.#runId,
1155
- name: this.#runName,
1156
- startTime,
1157
- metadata
1158
- };
1159
- await this.#write(event);
1160
- }
1161
- async #ensureRunCompleted(endTime, stepStatus, errorMessage) {
1162
- if (!markFinalized(this.#lifecycle)) return;
1163
- for (const [, syntheticStepId] of this.#syntheticByLabel) {
1164
- const completed = {
1165
- schemaVersion: "0.1",
1166
- event: "step_completed",
1167
- timestamp: endTime,
1168
- runId: this.#runId,
1169
- stepId: syntheticStepId,
1170
- status: "success",
1171
- endTime,
1172
- durationMs: Math.max(0, endTime - (this.#lifecycle.runStartTime ?? endTime))
1173
- };
1174
- await this.#write(completed);
1175
- }
1176
- const startTime = this.#lifecycle.runStartTime ?? endTime;
1177
- const durationMs = Math.max(0, endTime - startTime);
1178
- const runStatus = stepStatus === "error" ? "error" : "success";
1179
- const event = {
1180
- schemaVersion: "0.1",
1181
- event: "run_completed",
1182
- timestamp: endTime,
1183
- runId: this.#runId,
1184
- status: runStatus,
1185
- endTime,
1186
- durationMs,
1187
- ...runStatus === "error" && errorMessage ? { error: { message: errorMessage } } : {}
1188
- };
1189
- await this.#write(event);
1190
- }
1191
- async #write(event) {
1192
- const safe = advanced.prepareTraceEventForDisk(event, this.#safety);
1193
- await advanced.writeTraceEvent(safe, this.#traceDir);
1194
- }
1195
- #warn(err) {
1196
- if (!this.#silent) {
1197
- console.error("[agent-inspect:langchain]", err);
1198
- }
1199
- }
1200
- };
1201
-
1202
- // packages/langchain/src/agent-inspect-callback.ts
1203
- function isRecord2(v) {
1204
- return typeof v === "object" && v !== null && !Array.isArray(v);
1205
- }
1206
- function serializedLabel2(s) {
1207
- if (typeof s.name === "string" && s.name.trim()) return s.name;
1208
- if (Array.isArray(s.id) && s.id.length > 0) return s.id[s.id.length - 1];
1209
- return s.type;
1210
- }
1211
- function errorShape(err) {
1212
- if (err instanceof Error) {
1213
- return { errorName: err.name, errorMessage: err.message };
1214
- }
1215
- return { errorMessage: String(err) };
1216
- }
1217
- var AgentInspectCallback = class extends base.BaseCallbackHandler {
1218
- name = "agent-inspect";
1219
- /**
1220
- * Ensure LangGraph/LangChain awaits async handler work (persistence) before
1221
- * invoke/stream settles. Required for deterministic standalone envelopes.
1222
- */
1223
- awaitHandlers = true;
1224
- #opts;
1225
- #redactor;
1226
- #capture;
1227
- #persistence;
1228
- #events = [];
1229
- #starts = /* @__PURE__ */ new Map();
1230
- #streamState = /* @__PURE__ */ new Map();
1231
- #deferredPersistStart = /* @__PURE__ */ new Map();
1232
- #rootRunId;
1233
- constructor(options = {}) {
1234
- super({});
1235
- const intent = resolvePersistIntent(options);
1236
- this.#opts = {
1237
- capture: options.capture ?? "metadata-only",
1238
- silent: options.silent ?? false,
1239
- maxPreviewChars: options.maxPreviewChars ?? 200,
1240
- runName: options.runName ?? "langchain-agent",
1241
- ...options,
1242
- persist: intent.persist
1243
- };
1244
- this.#redactor = new logs.Redactor({ rules: this.#opts.redact });
1245
- this.#capture = advanced.createAdapterPreviewCapture({
1246
- capture: this.#opts.capture === "preview" ? "preview" : "metadata-only",
1247
- redactionProfile: this.#opts.redactionProfile,
1248
- maxPreviewChars: this.#opts.maxPreviewChars,
1249
- redact: this.#opts.redact,
1250
- onDiagnostic: this.#opts.onDiagnostic
1251
- });
1252
- if (intent.contradictory && !this.#opts.silent) {
1253
- console.error(
1254
- "[agent-inspect:langchain] persist:false with traceDir set \u2014 traces stay in-memory; remove traceDir or set persist:true"
1255
- );
1256
- }
1257
- if (intent.persist) {
1258
- this.#persistence = new LangChainTracePersistence({
1259
- runName: this.#opts.runName,
1260
- traceDir: this.#opts.traceDir,
1261
- runId: this.#opts.runId,
1262
- redact: this.#opts.redact,
1263
- silent: this.#opts.silent,
1264
- maxPreviewChars: this.#capture.maxPreviewChars,
1265
- redactionProfile: this.#opts.redactionProfile
1266
- });
1267
- }
1268
- }
1269
- getEvents() {
1270
- return this.#events.map((e) => ({
1271
- ...e,
1272
- attributes: e.attributes ? { ...e.attributes } : void 0,
1273
- source: { ...e.source }
1274
- }));
1275
- }
1276
- clear() {
1277
- this.#events = [];
1278
- this.#starts.clear();
1279
- this.#streamState.clear();
1280
- this.#deferredPersistStart.clear();
1281
- this.#rootRunId = void 0;
1282
- this.#persistence?.reset();
1283
- }
1284
- /**
1285
- * Bounded adapter diagnostics for the current invocation (counts only).
1286
- * Safe for CLI/MCP summaries — no absolute paths or payloads.
1287
- *
1288
- * @experimental
1289
- */
1290
- getDiagnostics() {
1291
- const base = this.#persistence?.getDiagnostics() ?? {
1292
- lateEventCount: 0,
1293
- activeRunCount: 0,
1294
- endedRunCount: 0,
1295
- pendingRelationshipCount: 0,
1296
- knownRelationshipCount: 0,
1297
- syntheticGroupCount: 0,
1298
- selfParentRejectedCount: 0,
1299
- ambiguousRelationshipCount: 0,
1300
- envelopeStarted: false,
1301
- finalized: false,
1302
- completionGeneration: 0,
1303
- hasTerminalError: false
1304
- };
1305
- return {
1306
- ...base,
1307
- inMemoryEventCount: this.#events.length,
1308
- deferredPersistStartCount: this.#deferredPersistStart.size,
1309
- capture: this.#capture.getDiagnostics()
1310
- };
1311
- }
1312
- /**
1313
- * Drain deferred completion work (microtask finalization).
1314
- * Idempotent. Failures are isolated and never thrown to user code.
1315
- *
1316
- * @experimental Additive finalization API for serverless / unusual callback shapes.
1317
- */
1318
- async flush() {
1319
- try {
1320
- await this.#persistence?.flush();
1321
- } catch (err) {
1322
- if (!this.#opts.silent) {
1323
- console.error("[agent-inspect:langchain]", err);
1324
- }
1325
- }
1326
- }
1327
- /**
1328
- * Complete the standalone envelope when started. Fallback when automatic
1329
- * completion cannot run (e.g. process shutdown). Idempotent.
1330
- * Failures are isolated and never thrown to user code.
1331
- *
1332
- * @experimental Additive finalization API for serverless / unusual callback shapes.
1333
- */
1334
- async finalize(options) {
1335
- try {
1336
- await this.#persistence?.finalize(options);
1337
- } catch (err) {
1338
- if (!this.#opts.silent) {
1339
- console.error("[agent-inspect:langchain]", err);
1340
- }
1341
- }
1342
- }
1343
- /**
1344
- * `flush()` then `finalize()`. Idempotent. Failures are isolated.
1345
- *
1346
- * @experimental Additive finalization API for serverless / unusual callback shapes.
1347
- */
1348
- async close() {
1349
- try {
1350
- await this.flush();
1351
- await this.finalize();
1352
- } catch (err) {
1353
- if (!this.#opts.silent) {
1354
- console.error("[agent-inspect:langchain]", err);
1355
- }
1356
- }
1357
- }
1358
- /**
1359
- * When persist mode has already finalized an envelope, rotate to a new
1360
- * invocation before the next start so reused handlers do not mix runs.
1361
- */
1362
- #prepareCallbackInvocation() {
1363
- const persistence = this.#persistence;
1364
- if (!persistence?.lifecycle.finalized) return;
1365
- this.#events = [];
1366
- this.#starts.clear();
1367
- this.#streamState.clear();
1368
- this.#deferredPersistStart.clear();
1369
- this.#rootRunId = void 0;
1370
- persistence.beginNewInvocation();
1371
- }
1372
- #streamPreviewLimit() {
1373
- if (!this.#capture.previewEnabled) return 0;
1374
- return this.#opts.maxStreamPreviewChars ?? this.#capture.maxPreviewChars;
1375
- }
1376
- #attachStreamMetadata(attrs, lcRunId) {
1377
- const meta = streamMetadataFromState(this.#streamState.get(lcRunId), {
1378
- capturePreview: this.#opts.capture === "preview",
1379
- maxPreviewChars: this.#streamPreviewLimit()
1380
- });
1381
- if (meta) {
1382
- Object.assign(attrs, meta);
1383
- }
1384
- }
1385
- #clearStreamState(lcRunId) {
1386
- this.#streamState.delete(lcRunId);
1387
- this.#deferredPersistStart.delete(lcRunId);
1388
- }
1389
- #mergeCorrelation(attrs) {
1390
- if (this.#opts.capture === "none") return;
1391
- try {
1392
- const corr = advanced.getCurrentCorrelationMetadata();
1393
- if (!corr) return;
1394
- for (const [key, value] of Object.entries(corr)) {
1395
- if (typeof value === "string" && value.length > 0) {
1396
- attrs[key] = value;
1397
- }
1398
- }
1399
- } catch {
1400
- }
1401
- }
1402
- async #persistLlmStepStart(lcRunId, lcParentRunId, name, kind, startTime, attributes) {
1403
- if (this.#opts.stream && this.#opts.persist) {
1404
- this.#deferredPersistStart.set(lcRunId, {
1405
- lcParentRunId,
1406
- name,
1407
- kind,
1408
- startTime,
1409
- attributes: { ...attributes }
1410
- });
1411
- return;
1412
- }
1413
- await this.#persistStepStart(lcRunId, lcParentRunId, name, kind, attributes, startTime);
1414
- }
1415
- async #flushDeferredPersistStart(lcRunId, completionAttributes) {
1416
- const pending = this.#deferredPersistStart.get(lcRunId);
1417
- if (!pending || !this.#opts.persist) return;
1418
- const merged = {
1419
- ...pending.attributes,
1420
- ...completionAttributes
1421
- };
1422
- await this.#persistStepStart(
1423
- lcRunId,
1424
- pending.lcParentRunId,
1425
- pending.name,
1426
- pending.kind,
1427
- merged,
1428
- pending.startTime
1429
- );
1430
- this.#deferredPersistStart.delete(lcRunId);
1431
- }
1432
- #ensureRoot(lcRunId, parentRunId) {
1433
- if (parentRunId) return;
1434
- if (!this.#rootRunId) this.#rootRunId = lcRunId;
1435
- }
1436
- #traceRunId(lcRunId) {
1437
- return this.#rootRunId ?? lcRunId;
1438
- }
1439
- #durationFor(lcRunId) {
1440
- const s = this.#starts.get(lcRunId);
1441
- if (!s) return void 0;
1442
- return Date.now() - s.ts;
1443
- }
1444
- #rememberStart(lcRunId, kind) {
1445
- this.#starts.set(lcRunId, { ts: Date.now(), kind });
1446
- }
1447
- #rememberStartMetadata(lcRunId, attrs) {
1448
- const start = this.#starts.get(lcRunId);
1449
- if (!start || !isRecord2(attrs.langGraph)) return;
1450
- this.#starts.set(lcRunId, { ...start, langGraph: { ...attrs.langGraph } });
1451
- }
1452
- #attachStartMetadata(attrs, lcRunId) {
1453
- const langGraph = this.#starts.get(lcRunId)?.langGraph;
1454
- if (langGraph && !attrs.langGraph) attrs.langGraph = { ...langGraph };
1455
- }
1456
- #clearStart(lcRunId) {
1457
- this.#starts.delete(lcRunId);
1458
- }
1459
- #baseAttrs(lcRunId, parentRunId, tags, runNameArg) {
1460
- const out = {
1461
- langchainRunId: lcRunId
1462
- };
1463
- if (parentRunId) out.parentRunId = parentRunId;
1464
- if (this.#opts.runName) out.adapterRunName = this.#opts.runName;
1465
- if (runNameArg) out.runName = runNameArg;
1466
- if (this.#opts.persist) out.traceStorage = "local";
1467
- const configuredTraceDir = this.#opts.traceDir?.trim();
1468
- if (configuredTraceDir && !path__default.default.isAbsolute(configuredTraceDir) && !/^[A-Za-z]:[\\/]/.test(configuredTraceDir)) {
1469
- out.workspaceRelativeTraceDir = configuredTraceDir;
1470
- }
1471
- const cap = this.#opts.capture;
1472
- if (cap !== "none" && tags?.length) out.tags = [...tags];
1473
- return out;
1474
- }
1475
- #mergeMetadata(attrs, metadata) {
1476
- if (this.#opts.capture === "none" || !metadata) return;
1477
- attrs.metadata = this.#redactor.redactRecord(toPlainMetadata(metadata));
1478
- const langGraph = extractLangGraphMetadata(metadata);
1479
- if (langGraph) attrs.langGraph = this.#redactor.redactRecord(langGraph);
1480
- }
1481
- #applyPreview(attrs, previews) {
1482
- this.#capture.applyPreviewFields(attrs, previews);
1483
- }
1484
- #pushEvent(ev) {
1485
- try {
1486
- const attributes = ev.attributes ? this.#redactor.redactRecord({ ...ev.attributes }) : void 0;
1487
- this.#events.push({ ...ev, attributes });
1488
- } catch (err) {
1489
- if (!this.#opts.silent) {
1490
- console.error("[agent-inspect:langchain]", err);
1491
- }
1492
- }
1493
- }
1494
- async #persistStepStart(lcRunId, lcParentRunId, name, kind, attrs, startTime) {
1495
- await this.#persistence?.onStepStart({
1496
- lcRunId,
1497
- lcParentRunId,
1498
- name,
1499
- kind,
1500
- startTime,
1501
- attributes: attrs
1502
- });
1503
- }
1504
- async #persistStepEnd(lcRunId, lcParentRunId, status, endTime, durationMs, errorMessage, completionAttributes) {
1505
- await this.#persistence?.onStepEnd({
1506
- lcRunId,
1507
- lcParentRunId,
1508
- endTime,
1509
- durationMs,
1510
- status,
1511
- errorMessage,
1512
- completionAttributes
1513
- });
1514
- }
1515
- async #persistInstant(lcRunId, lcParentRunId, name, kind, attrs, status, errorMessage) {
1516
- await this.#persistence?.onInstantStep({
1517
- lcRunId,
1518
- lcParentRunId,
1519
- name,
1520
- kind,
1521
- timestamp: Date.now(),
1522
- attributes: attrs,
1523
- status,
1524
- errorMessage
1525
- });
1526
- }
1527
- /**
1528
- * Match CallbackManager's runtime call order (parentRunId 4th), same as
1529
- * handleLLMStart / handleToolStart — not the declared CallbackHandlerMethods
1530
- * TypeScript order that puts runType 4th and parentRunId 8th.
1531
- */
1532
- async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, runName, _extra) {
1533
- this.#prepareCallbackInvocation();
1534
- this.#ensureRoot(runId, parentRunId);
1535
- this.#rememberStart(runId, "CHAIN");
1536
- const label = serializedLabel2(chain) ?? "chain";
1537
- const previews = {};
1538
- if (this.#opts.capture === "preview") previews.inputPreview = inputs;
1539
- const attrs = {
1540
- ...this.#baseAttrs(runId, parentRunId, tags, runName)
1541
- };
1542
- this.#mergeMetadata(attrs, metadata);
1543
- this.#applyPreview(attrs, previews);
1544
- this.#rememberStartMetadata(runId, attrs);
1545
- const ts = Date.now();
1546
- this.#pushEvent({
1547
- eventId: `${runId}:CHAIN:start`,
1548
- runId: this.#traceRunId(runId),
1549
- parentId: parentRunId,
1550
- name: `chain:${runName ?? label}`,
1551
- kind: "CHAIN",
1552
- timestamp: ts,
1553
- status: "running",
1554
- attributes: attrs,
1555
- confidence: "explicit",
1556
- source: { type: "adapter" }
1557
- });
1558
- await this.#persistStepStart(runId, parentRunId, `chain:${runName ?? label}`, "CHAIN", attrs, ts);
1559
- }
1560
- async handleChainEnd(outputs, runId, parentRunId, tags, _kwargs) {
1561
- this.#ensureRoot(runId, parentRunId);
1562
- const durationMs = this.#durationFor(runId);
1563
- const previews = {};
1564
- if (this.#opts.capture === "preview") previews.outputPreview = outputs;
1565
- const attrs = {
1566
- ...this.#baseAttrs(runId, parentRunId, tags, void 0)
1567
- };
1568
- this.#attachStartMetadata(attrs, runId);
1569
- this.#clearStart(runId);
1570
- this.#applyPreview(attrs, previews);
1571
- const ts = Date.now();
1572
- this.#pushEvent({
1573
- eventId: `${runId}:CHAIN:end`,
1574
- runId: this.#traceRunId(runId),
1575
- parentId: parentRunId,
1576
- name: "chain:end",
1577
- kind: "CHAIN",
1578
- timestamp: ts,
1579
- status: "ok",
1580
- durationMs,
1581
- attributes: attrs,
1582
- confidence: "explicit",
1583
- source: { type: "adapter" }
1584
- });
1585
- await this.#persistStepEnd(runId, parentRunId, "success", ts, durationMs);
1586
- }
1587
- async handleChainError(err, runId, parentRunId, tags, _kwargs) {
1588
- this.#ensureRoot(runId, parentRunId);
1589
- const durationMs = this.#durationFor(runId);
1590
- const { errorName, errorMessage } = errorShape(err);
1591
- const attrs = {
1592
- ...this.#baseAttrs(runId, parentRunId, tags, void 0),
1593
- errorName,
1594
- errorMessage
1595
- };
1596
- this.#attachStartMetadata(attrs, runId);
1597
- this.#clearStart(runId);
1598
- const ts = Date.now();
1599
- this.#pushEvent({
1600
- eventId: `${runId}:CHAIN:error`,
1601
- runId: this.#traceRunId(runId),
1602
- parentId: parentRunId,
1603
- name: "chain:error",
1604
- kind: "CHAIN",
1605
- timestamp: ts,
1606
- status: "error",
1607
- durationMs,
1608
- attributes: attrs,
1609
- confidence: "explicit",
1610
- source: { type: "adapter" }
1611
- });
1612
- await this.#persistStepEnd(runId, parentRunId, "error", ts, durationMs, errorMessage);
1613
- }
1614
- async handleLLMStart(llm, prompts, runId, parentRunId, _extraParams, tags, metadata, runName) {
1615
- this.#prepareCallbackInvocation();
1616
- this.#ensureRoot(runId, parentRunId);
1617
- this.#rememberStart(runId, "LLM");
1618
- const model = extractModelName(llm);
1619
- const previews = {};
1620
- if (this.#opts.capture === "preview") {
1621
- previews.promptPreview = prompts.length === 1 ? prompts[0] : prompts;
1622
- }
1623
- const attrs = {
1624
- ...this.#baseAttrs(runId, parentRunId, tags, runName)
1625
- };
1626
- if (model && this.#opts.capture !== "none") attrs.model = model;
1627
- this.#mergeMetadata(attrs, metadata);
1628
- this.#mergeCorrelation(attrs);
1629
- this.#applyPreview(attrs, previews);
1630
- this.#rememberStartMetadata(runId, attrs);
1631
- const ts = Date.now();
1632
- const stepName = `llm:${model ?? "llm"}`;
1633
- this.#pushEvent({
1634
- eventId: `${runId}:LLM:start`,
1635
- runId: this.#traceRunId(runId),
1636
- parentId: parentRunId,
1637
- name: stepName,
1638
- kind: "LLM",
1639
- timestamp: ts,
1640
- status: "running",
1641
- attributes: attrs,
1642
- confidence: "explicit",
1643
- source: { type: "adapter" }
1644
- });
1645
- await this.#persistLlmStepStart(runId, parentRunId, stepName, "LLM", ts, attrs);
1646
- }
1647
- async handleChatModelStart(llm, messages, runId, parentRunId, _extraParams, tags, metadata, runName) {
1648
- this.#prepareCallbackInvocation();
1649
- this.#ensureRoot(runId, parentRunId);
1650
- this.#rememberStart(runId, "LLM");
1651
- const model = extractModelName(llm);
1652
- const previews = {};
1653
- if (this.#opts.capture === "preview") previews.inputPreview = messages;
1654
- const attrs = {
1655
- ...this.#baseAttrs(runId, parentRunId, tags, runName)
1656
- };
1657
- if (model && this.#opts.capture !== "none") attrs.model = model;
1658
- this.#mergeMetadata(attrs, metadata);
1659
- this.#mergeCorrelation(attrs);
1660
- this.#applyPreview(attrs, previews);
1661
- this.#rememberStartMetadata(runId, attrs);
1662
- const ts = Date.now();
1663
- const stepName = `llm:${model ?? "llm"}`;
1664
- this.#pushEvent({
1665
- eventId: `${runId}:CHAT:start`,
1666
- runId: this.#traceRunId(runId),
1667
- parentId: parentRunId,
1668
- name: stepName,
1669
- kind: "LLM",
1670
- timestamp: ts,
1671
- status: "running",
1672
- attributes: attrs,
1673
- confidence: "explicit",
1674
- source: { type: "adapter" }
1675
- });
1676
- await this.#persistLlmStepStart(runId, parentRunId, stepName, "LLM", ts, attrs);
1677
- }
1678
- handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, _fields) {
1679
- try {
1680
- if (!this.#opts.stream) return;
1681
- let state = this.#streamState.get(runId);
1682
- if (!state) {
1683
- state = createLlmStreamState();
1684
- this.#streamState.set(runId, state);
1685
- }
1686
- recordLlmStreamToken(state, token, Date.now(), this.#streamPreviewLimit());
1687
- } catch (err) {
1688
- if (!this.#opts.silent) {
1689
- console.error("[agent-inspect:langchain]", err);
1690
- }
1691
- }
1692
- }
1693
- async handleLLMEnd(output, runId, parentRunId, tags, _extraParams) {
1694
- this.#ensureRoot(runId, parentRunId);
1695
- const durationMs = this.#durationFor(runId);
1696
- const tokens = extractTokenUsage(output);
1697
- const model = extractModelName(output);
1698
- const previews = {};
1699
- if (this.#opts.capture === "preview") previews.outputPreview = output;
1700
- const attrs = {
1701
- ...this.#baseAttrs(runId, parentRunId, tags, void 0)
1702
- };
1703
- if (model && this.#opts.capture !== "none") attrs.model = model;
1704
- if (tokens && this.#opts.capture !== "none") attrs.tokens = tokens;
1705
- this.#attachStartMetadata(attrs, runId);
1706
- this.#clearStart(runId);
1707
- this.#attachStreamMetadata(attrs, runId);
1708
- this.#mergeCorrelation(attrs);
1709
- this.#applyPreview(attrs, previews);
1710
- const ts = Date.now();
1711
- this.#pushEvent({
1712
- eventId: `${runId}:LLM:end`,
1713
- runId: this.#traceRunId(runId),
1714
- parentId: parentRunId,
1715
- name: `llm:${model ?? "llm"}`,
1716
- kind: "LLM",
1717
- timestamp: ts,
1718
- status: "ok",
1719
- durationMs,
1720
- attributes: attrs,
1721
- confidence: "explicit",
1722
- source: { type: "adapter" }
1723
- });
1724
- await this.#flushDeferredPersistStart(runId, attrs);
1725
- await this.#persistStepEnd(runId, parentRunId, "success", ts, durationMs, void 0, {
1726
- ...attrs,
1727
- name: `llm:${model ?? "llm"}`,
1728
- kind: "LLM"
1729
- });
1730
- this.#clearStreamState(runId);
1731
- }
1732
- async handleLLMError(err, runId, parentRunId, tags, _extraParams) {
1733
- this.#ensureRoot(runId, parentRunId);
1734
- const durationMs = this.#durationFor(runId);
1735
- const { errorName, errorMessage } = errorShape(err);
1736
- const attrs = {
1737
- ...this.#baseAttrs(runId, parentRunId, tags, void 0),
1738
- errorName,
1739
- errorMessage
1740
- };
1741
- this.#attachStartMetadata(attrs, runId);
1742
- this.#clearStart(runId);
1743
- this.#attachStreamMetadata(attrs, runId);
1744
- this.#mergeCorrelation(attrs);
1745
- const ts = Date.now();
1746
- this.#pushEvent({
1747
- eventId: `${runId}:LLM:error`,
1748
- runId: this.#traceRunId(runId),
1749
- parentId: parentRunId,
1750
- name: "llm:error",
1751
- kind: "LLM",
1752
- timestamp: ts,
1753
- status: "error",
1754
- durationMs,
1755
- attributes: attrs,
1756
- confidence: "explicit",
1757
- source: { type: "adapter" }
1758
- });
1759
- await this.#flushDeferredPersistStart(runId, attrs);
1760
- await this.#persistStepEnd(runId, parentRunId, "error", ts, durationMs, errorMessage, {
1761
- ...attrs,
1762
- name: "llm:error",
1763
- kind: "LLM"
1764
- });
1765
- this.#clearStreamState(runId);
1766
- }
1767
- async handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName, toolCallId) {
1768
- this.#prepareCallbackInvocation();
1769
- this.#ensureRoot(runId, parentRunId);
1770
- this.#rememberStart(runId, "TOOL");
1771
- const identity = resolveToolIdentity(tool, runName, metadata, toolCallId);
1772
- const previews = {};
1773
- if (this.#opts.capture === "preview") previews.inputPreview = input;
1774
- const attrs = {
1775
- ...this.#baseAttrs(runId, parentRunId, tags, runName)
1776
- };
1777
- applyToolIdentityAttributes(attrs, identity);
1778
- this.#mergeMetadata(attrs, metadata);
1779
- this.#applyPreview(attrs, previews);
1780
- this.#rememberStartMetadata(runId, attrs);
1781
- const ts = Date.now();
1782
- const stepName = `tool:${identity.displayName}`;
1783
- this.#pushEvent({
1784
- eventId: `${runId}:TOOL:start`,
1785
- runId: this.#traceRunId(runId),
1786
- parentId: parentRunId,
1787
- name: stepName,
1788
- kind: "TOOL",
1789
- timestamp: ts,
1790
- status: "running",
1791
- attributes: attrs,
1792
- confidence: "explicit",
1793
- source: { type: "adapter" }
1794
- });
1795
- await this.#persistStepStart(runId, parentRunId, stepName, "TOOL", attrs, ts);
1796
- }
1797
- async handleToolEnd(output, runId, parentRunId, tags) {
1798
- this.#ensureRoot(runId, parentRunId);
1799
- const durationMs = this.#durationFor(runId);
1800
- const previews = {};
1801
- if (this.#opts.capture === "preview") previews.outputPreview = output;
1802
- const attrs = {
1803
- ...this.#baseAttrs(runId, parentRunId, tags, void 0)
1804
- };
1805
- this.#attachStartMetadata(attrs, runId);
1806
- this.#clearStart(runId);
1807
- this.#applyPreview(attrs, previews);
1808
- const ts = Date.now();
1809
- this.#pushEvent({
1810
- eventId: `${runId}:TOOL:end`,
1811
- runId: this.#traceRunId(runId),
1812
- parentId: parentRunId,
1813
- name: "tool:end",
1814
- kind: "TOOL",
1815
- timestamp: ts,
1816
- status: "ok",
1817
- durationMs,
1818
- attributes: attrs,
1819
- confidence: "explicit",
1820
- source: { type: "adapter" }
1821
- });
1822
- await this.#persistStepEnd(runId, parentRunId, "success", ts, durationMs);
1823
- }
1824
- async handleToolError(err, runId, parentRunId, tags) {
1825
- this.#ensureRoot(runId, parentRunId);
1826
- const durationMs = this.#durationFor(runId);
1827
- const { errorName, errorMessage } = errorShape(err);
1828
- const attrs = {
1829
- ...this.#baseAttrs(runId, parentRunId, tags, void 0),
1830
- errorName,
1831
- errorMessage
1832
- };
1833
- this.#attachStartMetadata(attrs, runId);
1834
- this.#clearStart(runId);
1835
- const ts = Date.now();
1836
- this.#pushEvent({
1837
- eventId: `${runId}:TOOL:error`,
1838
- runId: this.#traceRunId(runId),
1839
- parentId: parentRunId,
1840
- name: "tool:error",
1841
- kind: "TOOL",
1842
- timestamp: ts,
1843
- status: "error",
1844
- durationMs,
1845
- attributes: attrs,
1846
- confidence: "explicit",
1847
- source: { type: "adapter" }
1848
- });
1849
- await this.#persistStepEnd(runId, parentRunId, "error", ts, durationMs, errorMessage);
1850
- }
1851
- async handleRetrieverStart(retriever, _query, runId, parentRunId, tags, metadata, name) {
1852
- this.#prepareCallbackInvocation();
1853
- this.#ensureRoot(runId, parentRunId);
1854
- this.#rememberStart(runId, "RETRIEVER");
1855
- const rname = name ?? serializedLabel2(retriever) ?? "retriever";
1856
- const attrs = {
1857
- ...this.#baseAttrs(runId, parentRunId, tags, void 0),
1858
- retriever: rname
1859
- };
1860
- this.#mergeMetadata(attrs, metadata);
1861
- this.#rememberStartMetadata(runId, attrs);
1862
- const ts = Date.now();
1863
- const stepName = `retriever:${rname}`;
1864
- this.#pushEvent({
1865
- eventId: `${runId}:RETRIEVER:start`,
1866
- runId: this.#traceRunId(runId),
1867
- parentId: parentRunId,
1868
- name: stepName,
1869
- kind: "RETRIEVER",
1870
- timestamp: ts,
1871
- status: "running",
1872
- attributes: attrs,
1873
- confidence: "explicit",
1874
- source: { type: "adapter" }
1875
- });
1876
- await this.#persistStepStart(runId, parentRunId, stepName, "RETRIEVER", attrs, ts);
1877
- }
1878
- async handleRetrieverEnd(documents, runId, parentRunId, tags) {
1879
- this.#ensureRoot(runId, parentRunId);
1880
- const durationMs = this.#durationFor(runId);
1881
- const previews = {};
1882
- if (this.#opts.capture === "preview" && documents.length > 0) {
1883
- previews.documentPreview = documents.slice(0, 3);
1884
- }
1885
- const attrs = {
1886
- ...this.#baseAttrs(runId, parentRunId, tags, void 0),
1887
- documentCount: documents.length
1888
- };
1889
- this.#attachStartMetadata(attrs, runId);
1890
- this.#clearStart(runId);
1891
- this.#applyPreview(attrs, previews);
1892
- const ts = Date.now();
1893
- this.#pushEvent({
1894
- eventId: `${runId}:RETRIEVER:end`,
1895
- runId: this.#traceRunId(runId),
1896
- parentId: parentRunId,
1897
- name: "retriever:end",
1898
- kind: "RETRIEVER",
1899
- timestamp: ts,
1900
- status: "ok",
1901
- durationMs,
1902
- attributes: attrs,
1903
- confidence: "explicit",
1904
- source: { type: "adapter" }
1905
- });
1906
- await this.#persistStepEnd(runId, parentRunId, "success", ts, durationMs);
1907
- }
1908
- async handleRetrieverError(err, runId, parentRunId, tags) {
1909
- this.#ensureRoot(runId, parentRunId);
1910
- const durationMs = this.#durationFor(runId);
1911
- const { errorName, errorMessage } = errorShape(err);
1912
- const attrs = {
1913
- ...this.#baseAttrs(runId, parentRunId, tags, void 0),
1914
- errorName,
1915
- errorMessage
1916
- };
1917
- this.#attachStartMetadata(attrs, runId);
1918
- this.#clearStart(runId);
1919
- const ts = Date.now();
1920
- this.#pushEvent({
1921
- eventId: `${runId}:RETRIEVER:error`,
1922
- runId: this.#traceRunId(runId),
1923
- parentId: parentRunId,
1924
- name: "retriever:error",
1925
- kind: "RETRIEVER",
1926
- timestamp: ts,
1927
- status: "error",
1928
- durationMs,
1929
- attributes: attrs,
1930
- confidence: "explicit",
1931
- source: { type: "adapter" }
1932
- });
1933
- await this.#persistStepEnd(runId, parentRunId, "error", ts, durationMs, errorMessage);
1934
- }
1935
- async handleAgentAction(action, runId, parentRunId, tags) {
1936
- this.#prepareCallbackInvocation();
1937
- this.#ensureRoot(runId, parentRunId);
1938
- const attrs = {
1939
- ...this.#baseAttrs(runId, parentRunId, tags, void 0),
1940
- tool: action.tool
1941
- };
1942
- if (this.#opts.capture === "preview") {
1943
- this.#applyPreview(attrs, {
1944
- toolInputPreview: action.toolInput,
1945
- logPreview: action.log
1946
- });
1947
- }
1948
- this.#pushEvent({
1949
- eventId: `${runId}:AGENT:action:${Date.now()}`,
1950
- runId: this.#traceRunId(runId),
1951
- parentId: parentRunId,
1952
- name: "agent:action",
1953
- kind: "DECISION",
1954
- timestamp: Date.now(),
1955
- status: "ok",
1956
- attributes: attrs,
1957
- confidence: "explicit",
1958
- source: { type: "adapter" }
1959
- });
1960
- await this.#persistInstant(runId, parentRunId, "agent:action", "DECISION", attrs, "success");
1961
- }
1962
- async handleAgentEnd(finish, runId, parentRunId, tags) {
1963
- this.#ensureRoot(runId, parentRunId);
1964
- const attrs = {
1965
- ...this.#baseAttrs(runId, parentRunId, tags, void 0)
1966
- };
1967
- if (this.#opts.capture === "preview") {
1968
- this.#applyPreview(attrs, {
1969
- outputPreview: finish.returnValues,
1970
- logPreview: finish.log
1971
- });
1972
- }
1973
- this.#pushEvent({
1974
- eventId: `${runId}:AGENT:end:${Date.now()}`,
1975
- runId: this.#traceRunId(runId),
1976
- parentId: parentRunId,
1977
- name: "agent:end",
1978
- kind: "AGENT",
1979
- timestamp: Date.now(),
1980
- status: "ok",
1981
- attributes: attrs,
1982
- confidence: "explicit",
1983
- source: { type: "adapter" }
1984
- });
1985
- await this.#persistInstant(runId, parentRunId, "agent:end", "AGENT", attrs, "success");
1986
- }
1987
- };
1988
-
1989
- exports.AgentInspectCallback = AgentInspectCallback;
1990
- exports.extractModelName = extractModelName;
1991
- exports.extractTokenUsage = extractTokenUsage;
1992
- exports.safePreview = safePreview;
1993
- exports.toPlainMetadata = toPlainMetadata;
1994
- //# sourceMappingURL=index.cjs.map
1995
- //# sourceMappingURL=index.cjs.map