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