@uselemma/tracing 7.15.3 → 7.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/client.d.ts +129 -56
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +596 -200
  4. package/dist/client.js.map +1 -1
  5. package/dist/coding-agent.d.ts +4 -1
  6. package/dist/coding-agent.d.ts.map +1 -1
  7. package/dist/coding-agent.js +73 -31
  8. package/dist/coding-agent.js.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +16 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/integration-client.d.ts +1 -1
  14. package/dist/integration-client.d.ts.map +1 -1
  15. package/dist/integration-client.js.map +1 -1
  16. package/dist/langchain.d.ts +15 -17
  17. package/dist/langchain.d.ts.map +1 -1
  18. package/dist/langchain.js +327 -87
  19. package/dist/langchain.js.map +1 -1
  20. package/dist/mastra.d.ts.map +1 -1
  21. package/dist/mastra.js +225 -24
  22. package/dist/mastra.js.map +1 -1
  23. package/dist/messages.d.ts +84 -0
  24. package/dist/messages.d.ts.map +1 -0
  25. package/dist/messages.js +1102 -0
  26. package/dist/messages.js.map +1 -0
  27. package/dist/openai-agents-containers.d.ts +1 -0
  28. package/dist/openai-agents-containers.d.ts.map +1 -1
  29. package/dist/openai-agents-containers.js.map +1 -1
  30. package/dist/openai-agents-generation.d.ts +8 -5
  31. package/dist/openai-agents-generation.d.ts.map +1 -1
  32. package/dist/openai-agents-generation.js +92 -44
  33. package/dist/openai-agents-generation.js.map +1 -1
  34. package/dist/openai-agents-tool-calls.d.ts +24 -0
  35. package/dist/openai-agents-tool-calls.d.ts.map +1 -0
  36. package/dist/openai-agents-tool-calls.js +207 -0
  37. package/dist/openai-agents-tool-calls.js.map +1 -0
  38. package/dist/openai-agents.d.ts +2 -7
  39. package/dist/openai-agents.d.ts.map +1 -1
  40. package/dist/openai-agents.js +259 -20
  41. package/dist/openai-agents.js.map +1 -1
  42. package/dist/payload.d.ts +30 -0
  43. package/dist/payload.d.ts.map +1 -0
  44. package/dist/payload.js +413 -0
  45. package/dist/payload.js.map +1 -0
  46. package/dist/release.d.ts +12 -0
  47. package/dist/release.d.ts.map +1 -1
  48. package/dist/release.js +41 -7
  49. package/dist/release.js.map +1 -1
  50. package/dist/tool-call-id.d.ts +14 -0
  51. package/dist/tool-call-id.d.ts.map +1 -0
  52. package/dist/tool-call-id.js +56 -0
  53. package/dist/tool-call-id.js.map +1 -0
  54. package/dist/turn.d.ts +25 -1
  55. package/dist/turn.d.ts.map +1 -1
  56. package/dist/turn.js +97 -14
  57. package/dist/turn.js.map +1 -1
  58. package/dist/usage.d.ts +5 -3
  59. package/dist/usage.d.ts.map +1 -1
  60. package/dist/usage.js +38 -35
  61. package/dist/usage.js.map +1 -1
  62. package/dist/vercel-ai-events.d.ts +46 -9
  63. package/dist/vercel-ai-events.d.ts.map +1 -1
  64. package/dist/vercel-ai-events.js +81 -7
  65. package/dist/vercel-ai-events.js.map +1 -1
  66. package/dist/vercel-ai-run.d.ts +7 -0
  67. package/dist/vercel-ai-run.d.ts.map +1 -1
  68. package/dist/vercel-ai-run.js +191 -47
  69. package/dist/vercel-ai-run.js.map +1 -1
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/package.json +2 -2
package/dist/langchain.js CHANGED
@@ -7,42 +7,50 @@ const client_1 = require("./client");
7
7
  const error_message_1 = require("./error-message");
8
8
  const langchain_context_1 = require("./langchain-context");
9
9
  const langchain_eviction_1 = require("./langchain-eviction");
10
- const schedule_1 = require("./schedule");
11
- const tool_result_1 = require("./tool-result");
10
+ const messages_1 = require("./messages");
12
11
  const model_1 = require("./model");
13
12
  const reply_text_1 = require("./reply-text");
13
+ const schedule_1 = require("./schedule");
14
+ const tool_call_id_1 = require("./tool-call-id");
15
+ const tool_result_1 = require("./tool-result");
14
16
  const usage_1 = require("./usage");
15
17
  const INTEGRATION_ATTRS = {
16
18
  "lemma.sdk.integration": "langchain",
17
19
  };
20
+ function monotonicNow() {
21
+ return typeof performance !== "undefined" &&
22
+ typeof performance.now === "function"
23
+ ? performance.now()
24
+ : Date.now();
25
+ }
18
26
  const KNOWN_PROVIDERS = [
27
+ "azure_openai",
28
+ "azure",
19
29
  "openai",
20
30
  "anthropic",
21
- "azure",
22
- "azure_openai",
23
- "google",
24
31
  "google_genai",
25
32
  "google_vertexai",
26
33
  "vertexai",
27
- "bedrock",
34
+ "google",
28
35
  "amazon_bedrock",
36
+ "bedrock",
29
37
  "cohere",
30
- "mistral",
31
38
  "mistralai",
39
+ "mistral",
32
40
  "groq",
33
41
  "fireworks",
34
42
  "together",
35
43
  "ollama",
36
- "huggingface",
37
44
  "huggingface_hub",
45
+ "huggingface",
38
46
  "deepseek",
39
47
  "xai",
40
48
  "perplexity",
41
49
  ];
42
50
  const CLASS_PROVIDER_HINTS = [
51
+ [/azure/i, "azure"],
43
52
  [/openai/i, "openai"],
44
53
  [/anthropic|claude/i, "anthropic"],
45
- [/azure/i, "azure"],
46
54
  [/vertex/i, "google"],
47
55
  [/google|gemini/i, "google"],
48
56
  [/bedrock|amazon/i, "bedrock"],
@@ -57,6 +65,12 @@ const CLASS_PROVIDER_HINTS = [
57
65
  [/xai|grok/i, "xai"],
58
66
  [/perplexity/i, "perplexity"],
59
67
  ];
68
+ function asRecord(value) {
69
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
70
+ return undefined;
71
+ }
72
+ return value;
73
+ }
60
74
  function serializedName(serialized, fallback) {
61
75
  if (typeof serialized?.name === "string" && serialized.name) {
62
76
  return serialized.name;
@@ -115,12 +129,21 @@ function messageRole(message) {
115
129
  const record = message;
116
130
  if (typeof record.role === "string" && record.role)
117
131
  return record.role;
118
- const type = (typeof record.type === "string" && record.type) ||
132
+ const rawType = (typeof record.type === "string" && record.type) ||
119
133
  (typeof record._type === "string" && record._type) ||
120
134
  (typeof record.getType === "function"
121
135
  ? record.getType()
122
136
  : undefined);
137
+ // Serialized LangChain messages use `{ lc: 1, type: "constructor", id: [..., "AIMessage"] }`.
138
+ const type = rawType === "constructor" || rawType === "message" ? undefined : rawType;
123
139
  if (!type) {
140
+ const kwargs = asRecord(record.kwargs);
141
+ if (kwargs && typeof kwargs.role === "string" && kwargs.role) {
142
+ return kwargs.role;
143
+ }
144
+ if (kwargs && typeof kwargs.type === "string" && kwargs.type) {
145
+ return roleFromClassName(kwargs.type) ?? kwargs.type;
146
+ }
124
147
  const id = record.id;
125
148
  if (Array.isArray(id) && id.length > 0) {
126
149
  return roleFromClassName(String(id[id.length - 1]));
@@ -189,8 +212,8 @@ function toolCallsFromMessage(record) {
189
212
  }
190
213
  return undefined;
191
214
  }
192
- /** Normalize LangChain message classes / dicts to `{ role, content, ... }`. */
193
- function normalizeMessage(message) {
215
+ /** Normalize LangChain message classes / dicts to a plain intermediate object. */
216
+ function unpackLangChainMessage(message) {
194
217
  if (typeof message === "string") {
195
218
  return { role: "user", content: message };
196
219
  }
@@ -199,39 +222,42 @@ function normalizeMessage(message) {
199
222
  }
200
223
  const record = message;
201
224
  // Serialized LangChain messages often nest fields under `kwargs`.
202
- const kwargs = record.kwargs && typeof record.kwargs === "object"
203
- ? record.kwargs
204
- : undefined;
225
+ const kwargs = asRecord(record.kwargs);
205
226
  const content = "content" in record
206
227
  ? record.content
207
228
  : kwargs && "content" in kwargs
208
229
  ? kwargs.content
209
230
  : messageContent(message);
210
231
  const role = messageRole(message) ?? messageRole(kwargs) ?? "user";
211
- const normalized = {
232
+ const unpacked = {
212
233
  role,
213
234
  content,
214
235
  };
215
236
  const toolCalls = toolCallsFromMessage(record) ??
216
237
  (kwargs ? toolCallsFromMessage(kwargs) : undefined);
217
238
  if (toolCalls)
218
- normalized.tool_calls = toolCalls;
219
- const toolCallId = (typeof record.tool_call_id === "string" && record.tool_call_id) ||
220
- (typeof record.toolCallId === "string" && record.toolCallId) ||
221
- (kwargs && typeof kwargs.tool_call_id === "string"
222
- ? kwargs.tool_call_id
239
+ unpacked.tool_calls = toolCalls;
240
+ const toolCallId = (0, tool_call_id_1.normalizeToolCallId)(record.tool_call_id) ??
241
+ (0, tool_call_id_1.normalizeToolCallId)(record.toolCallId) ??
242
+ (kwargs
243
+ ? ((0, tool_call_id_1.normalizeToolCallId)(kwargs.tool_call_id) ??
244
+ (0, tool_call_id_1.normalizeToolCallId)(kwargs.toolCallId))
223
245
  : undefined);
224
246
  if (toolCallId)
225
- normalized.tool_call_id = toolCallId;
247
+ unpacked.tool_call_id = toolCallId;
226
248
  const name = (typeof record.name === "string" && record.name) ||
227
249
  (kwargs && typeof kwargs.name === "string" ? kwargs.name : undefined);
228
250
  if (name && (role === "tool" || role === "function")) {
229
- normalized.name = name;
251
+ unpacked.name = name;
230
252
  }
231
- return normalized;
232
- }
233
- function normalizeMessages(messages) {
234
- return messages.map(normalizeMessage);
253
+ const status = (typeof record.status === "string" && record.status) ||
254
+ (kwargs && typeof kwargs.status === "string" ? kwargs.status : undefined);
255
+ if (status)
256
+ unpacked.status = status;
257
+ if (record.is_error === true || kwargs?.is_error === true) {
258
+ unpacked.is_error = true;
259
+ }
260
+ return unpacked;
235
261
  }
236
262
  function asMessageList(input) {
237
263
  if (Array.isArray(input))
@@ -252,11 +278,11 @@ function rootTraceInput(input) {
252
278
  const messages = asMessageList(input);
253
279
  if (messages && messages.length > 0) {
254
280
  for (let i = messages.length - 1; i >= 0; i--) {
255
- const normalized = normalizeMessage(messages[i]);
281
+ const normalized = unpackLangChainMessage(messages[i]);
256
282
  if (normalized.role === "user")
257
283
  return normalized.content;
258
284
  }
259
- return normalizeMessage(messages[messages.length - 1]).content;
285
+ return unpackLangChainMessage(messages[messages.length - 1]).content;
260
286
  }
261
287
  if (input && typeof input === "object" && !Array.isArray(input)) {
262
288
  const record = input;
@@ -305,12 +331,12 @@ function rootTraceOutput(output) {
305
331
  const messages = asMessageList(output);
306
332
  if (messages && messages.length > 0) {
307
333
  for (let i = messages.length - 1; i >= 0; i--) {
308
- const normalized = normalizeMessage(messages[i]);
334
+ const normalized = unpackLangChainMessage(messages[i]);
309
335
  if (normalized.role === "assistant") {
310
336
  return flattenRootDisplay(structuredAssistantOutput(normalized));
311
337
  }
312
338
  }
313
- return flattenRootDisplay(structuredAssistantOutput(normalizeMessage(messages[messages.length - 1])));
339
+ return flattenRootDisplay(structuredAssistantOutput(unpackLangChainMessage(messages[messages.length - 1])));
314
340
  }
315
341
  if (output && typeof output === "object" && !Array.isArray(output)) {
316
342
  const record = output;
@@ -387,7 +413,7 @@ function llmStructuredOutput(result) {
387
413
  for (const item of group) {
388
414
  const message = generationMessage(item);
389
415
  if (message != null) {
390
- messages.push(normalizeMessage(message));
416
+ messages.push(unpackLangChainMessage(message));
391
417
  continue;
392
418
  }
393
419
  const text = firstText(item);
@@ -404,31 +430,126 @@ function llmStructuredOutput(result) {
404
430
  const text = generations.flat().map(firstText).filter(Boolean).join("");
405
431
  return text || generations;
406
432
  }
407
- function llmOutputMessages(result) {
433
+ function llmOutputMessages(result, options) {
408
434
  const generations = result.generations;
409
435
  if (!Array.isArray(generations))
410
436
  return undefined;
411
- const messages = [];
437
+ const rawMessages = [];
412
438
  for (const group of generations) {
413
439
  if (!Array.isArray(group))
414
440
  continue;
415
441
  for (const item of group) {
416
442
  const message = generationMessage(item);
417
443
  if (message != null) {
418
- messages.push(normalizeMessage(message));
444
+ rawMessages.push(unpackLangChainMessage(message));
419
445
  continue;
420
446
  }
421
447
  const text = firstText(item);
422
448
  if (text != null)
423
- messages.push({ role: "assistant", content: text });
449
+ rawMessages.push({ role: "assistant", content: text });
450
+ }
451
+ }
452
+ if (rawMessages.length === 0)
453
+ return undefined;
454
+ const canonical = (0, messages_1.normalizeMessages)(rawMessages, {
455
+ ...options,
456
+ defaultRole: "assistant",
457
+ });
458
+ return canonical.length > 0 ? canonical : undefined;
459
+ }
460
+ function llmFinishReason(result) {
461
+ const llmOutput = result.llmOutput;
462
+ if (llmOutput) {
463
+ const direct = (0, messages_1.normalizeFinishReason)(llmOutput.finish_reason ??
464
+ llmOutput.finishReason ??
465
+ llmOutput.stop_reason);
466
+ if (direct)
467
+ return direct;
468
+ }
469
+ const generations = result.generations;
470
+ if (!Array.isArray(generations))
471
+ return undefined;
472
+ for (const group of generations) {
473
+ if (!Array.isArray(group))
474
+ continue;
475
+ for (const item of group) {
476
+ const record = asRecord(item);
477
+ if (!record)
478
+ continue;
479
+ const genInfo = asRecord(record.generationInfo ?? record.generation_info);
480
+ const fromGenInfo = (0, messages_1.normalizeFinishReason)(genInfo?.finish_reason ??
481
+ genInfo?.finishReason ??
482
+ genInfo?.stop_reason);
483
+ if (fromGenInfo)
484
+ return fromGenInfo;
485
+ const message = asRecord(record.message);
486
+ const responseMeta = asRecord(message?.response_metadata ?? message?.responseMetadata);
487
+ const fromMeta = (0, messages_1.normalizeFinishReason)(responseMeta?.finish_reason ??
488
+ responseMeta?.finishReason ??
489
+ responseMeta?.stop_reason);
490
+ if (fromMeta)
491
+ return fromMeta;
492
+ }
493
+ }
494
+ return undefined;
495
+ }
496
+ function extractLangChainTools(serialized, extraParams) {
497
+ const invocationParams = asRecord(extraParams?.invocation_params);
498
+ const rawTools = invocationParams?.tools ??
499
+ extraParams?.tools ??
500
+ serialized?.kwargs?.tools ??
501
+ invocationParams?.functions ??
502
+ extraParams?.functions;
503
+ return (0, messages_1.normalizeToolDefinitions)(rawTools);
504
+ }
505
+ function extractLangChainInvocationParameters(extraParams) {
506
+ if (!extraParams)
507
+ return undefined;
508
+ const result = {};
509
+ const nested = asRecord(extraParams.invocation_params);
510
+ for (const [key, value] of Object.entries(extraParams)) {
511
+ if (key === "tools" ||
512
+ key === "functions" ||
513
+ key === "invocation_params") {
514
+ continue;
515
+ }
516
+ if (value !== undefined)
517
+ result[key] = value;
518
+ }
519
+ if (nested) {
520
+ for (const [key, value] of Object.entries(nested)) {
521
+ if (key === "tools" || key === "functions")
522
+ continue;
523
+ if (value !== undefined)
524
+ result[key] = value;
424
525
  }
425
526
  }
426
- return messages.length ? messages : undefined;
527
+ return Object.keys(result).length > 0 ? result : undefined;
528
+ }
529
+ function toolMessageStatusError(output) {
530
+ const record = asRecord(output);
531
+ if (!record)
532
+ return undefined;
533
+ const kwargs = asRecord(record.kwargs);
534
+ const status = record.status ?? kwargs?.status;
535
+ if (typeof status === "string" && status.toLowerCase() === "error") {
536
+ const content = record.content ?? kwargs?.content;
537
+ if (typeof content === "string" && content.trim())
538
+ return content.trim();
539
+ return "Tool execution failed";
540
+ }
541
+ return undefined;
542
+ }
543
+ function resolveToolCallId(explicit, sources) {
544
+ return ((0, tool_call_id_1.normalizeToolCallId)(explicit) ??
545
+ (0, tool_call_id_1.resolveToolCallIdFromSources)(sources, tool_call_id_1.TOOL_CALL_ID_KEYS));
427
546
  }
428
547
  function providerFromId(id) {
429
548
  if (!Array.isArray(id))
430
549
  return undefined;
431
- for (const part of id) {
550
+ // Walk from most-specific segment (class name, e.g. AzureChatOpenAI) to package name (e.g. langchain_openai).
551
+ for (let index = id.length - 1; index >= 0; index -= 1) {
552
+ const part = id[index];
432
553
  if (typeof part !== "string")
433
554
  continue;
434
555
  const lower = part.toLowerCase().replace(/-/g, "_");
@@ -481,8 +602,11 @@ function llmProvider(serialized, extraParams, metadata) {
481
602
  "llmProvider",
482
603
  ]) {
483
604
  const value = source[key];
484
- if (typeof value === "string" && value && value !== "langchain") {
485
- return value;
605
+ if (typeof value === "string") {
606
+ const trimmed = value.trim();
607
+ if (trimmed && trimmed !== "langchain") {
608
+ return trimmed;
609
+ }
486
610
  }
487
611
  }
488
612
  }
@@ -515,8 +639,17 @@ function durationMs(start, end) {
515
639
  return Math.max(0, end.getTime() - start.getTime());
516
640
  }
517
641
  const NO_OUTPUT = { result: "none" };
518
- function recordedSpanOutput(output, ownsTrace, status) {
519
- if (output == null && !ownsTrace && status !== "ERROR") {
642
+ function recordedSpanOutput(output, run, options) {
643
+ if (options.status === "ERROR" || options.error !== undefined) {
644
+ return undefined;
645
+ }
646
+ if (run.kind === "llm" && options.llmOutputMessages?.length) {
647
+ return undefined;
648
+ }
649
+ if (run.kind === "retriever" && options.retrievalDocuments?.length) {
650
+ return undefined;
651
+ }
652
+ if (output == null && !run.ownsTrace) {
520
653
  return { ...NO_OUTPUT };
521
654
  }
522
655
  return output;
@@ -604,6 +737,12 @@ class LemmaLangChainCallbackHandler {
604
737
  baseUrl: this.options.baseUrl,
605
738
  fetch: this.options.fetch,
606
739
  release: this.options.release,
740
+ environment: this.options.environment,
741
+ tags: this.options.tags,
742
+ gzip: this.options.gzip,
743
+ beforeSend: this.options.beforeSend,
744
+ maxPayloadBytes: this.options.maxPayloadBytes,
745
+ deduplicateSpanInputs: this.options.deduplicateSpanInputs,
607
746
  });
608
747
  return this.lemma;
609
748
  }
@@ -689,6 +828,8 @@ class LemmaLangChainCallbackHandler {
689
828
  earliestStart: startedAt,
690
829
  hasRootInput: input != null,
691
830
  rootInput: rootTraceInput(input),
831
+ failedToolCallIds: new Set(),
832
+ toolNamesByCallId: new Map(),
692
833
  };
693
834
  this.traces.set(runId, stored);
694
835
  const run = {
@@ -711,8 +852,8 @@ class LemmaLangChainCallbackHandler {
711
852
  }
712
853
  /**
713
854
  * Resolve the parent attachment target.
714
- * - Known parent → attach under that parent's owning trace.
715
- * - Missing / unknown parent → create a NEW owned trace for this run
855
+ * - Known parent -> attach under that parent's owning trace.
856
+ * - Missing / unknown parent -> create a NEW owned trace for this run
716
857
  * (never overwrite another concurrent trace's state).
717
858
  */
718
859
  resolveAttachment(runId, parentRunId, createRoot) {
@@ -761,7 +902,7 @@ class LemmaLangChainCallbackHandler {
761
902
  return;
762
903
  run.handle.end({
763
904
  ...options,
764
- output: recordedSpanOutput(options.output, run.ownsTrace, options.status),
905
+ output: recordedSpanOutput(options.output, run, options),
765
906
  });
766
907
  }
767
908
  async finalizeTrace(owningTraceId, stored) {
@@ -771,11 +912,28 @@ class LemmaLangChainCallbackHandler {
771
912
  if (ownsRuns)
772
913
  this.traces.delete(owningTraceId);
773
914
  if (!stored.ended && ownsRuns) {
774
- // LangChain can report a failed run on the chain while a model call
775
- // still in flight has reported nothing.
776
- (0, error_message_1.failOpenGenerations)([...this.runs.values()]
777
- .filter((run) => run.owningTraceId === owningTraceId && run.kind === "llm")
778
- .map((run) => run.handle), stored.rootError, stored.latestEnd ?? new Date());
915
+ // LangChain can report a failed run on the chain (or finalize on
916
+ // shutdown/eviction) while child llm/tool/chain/retriever spans are
917
+ // still in flight and have reported nothing.
918
+ const closeAt = stored.latestEnd ?? new Date();
919
+ const openRuns = [...this.runs.values()].filter((run) => run.owningTraceId === owningTraceId && run.handle !== undefined);
920
+ if (stored.rootError) {
921
+ (0, error_message_1.failOpenGenerations)(openRuns.map((run) => run.handle), stored.rootError, closeAt);
922
+ for (const run of openRuns) {
923
+ const closedAt = run.startedAt > closeAt ? run.startedAt : closeAt;
924
+ this.noteBounds(stored, run.startedAt, closedAt);
925
+ }
926
+ }
927
+ else {
928
+ for (const run of openRuns) {
929
+ const closedAt = run.startedAt > closeAt ? run.startedAt : closeAt;
930
+ run.handle?.end({
931
+ endedAt: closedAt,
932
+ durationMs: durationMs(run.startedAt, closedAt),
933
+ });
934
+ this.noteBounds(stored, run.startedAt, closedAt);
935
+ }
936
+ }
779
937
  }
780
938
  if (ownsRuns)
781
939
  this.forgetTraceRuns(owningTraceId);
@@ -837,6 +995,19 @@ class LemmaLangChainCallbackHandler {
837
995
  traceName(serialized, fallback) {
838
996
  return this.options.agentName ?? serializedName(serialized, fallback);
839
997
  }
998
+ noteToolCallsFromCanonical(stored, messages) {
999
+ if (!messages)
1000
+ return;
1001
+ for (const msg of messages) {
1002
+ if (msg.role === "assistant" && Array.isArray(msg.tool_calls)) {
1003
+ for (const call of msg.tool_calls) {
1004
+ if (call.id && call.name) {
1005
+ stored.toolNamesByCallId.set(call.id, call.name);
1006
+ }
1007
+ }
1008
+ }
1009
+ }
1010
+ }
840
1011
  handleChainStart(serialized, inputs, runId, parentRunId, tags, metadata, runType, name) {
841
1012
  this.evictIdleTraces();
842
1013
  const startedAt = new Date();
@@ -873,7 +1044,7 @@ class LemmaLangChainCallbackHandler {
873
1044
  ownsTrace: false,
874
1045
  });
875
1046
  }
876
- handleChainEnd(outputs, runId) {
1047
+ handleChainEnd(outputs, runId, _parentRunId) {
877
1048
  const run = this.runs.get(runId);
878
1049
  if (!run)
879
1050
  return;
@@ -893,7 +1064,7 @@ class LemmaLangChainCallbackHandler {
893
1064
  this.runs.delete(runId);
894
1065
  this.maybeFinalizeOwner(run);
895
1066
  }
896
- handleChainError(error, runId) {
1067
+ handleChainError(error, runId, _parentRunId) {
897
1068
  const run = this.runs.get(runId);
898
1069
  if (!run)
899
1070
  return;
@@ -918,23 +1089,26 @@ class LemmaLangChainCallbackHandler {
918
1089
  handleLLMStart(serialized, prompts, runId, parentRunId, extraParams, tags, metadata, _runName) {
919
1090
  this.evictIdleTraces();
920
1091
  const startedAt = new Date();
1092
+ const startedMonoMs = monotonicNow();
921
1093
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-llm"), prompts, "llm", metadata, tags));
922
- // createOwnedTrace already registered the run when ownsTrace; update it.
923
1094
  if (attachment.ownsTrace) {
924
1095
  this.noteRootInput(attachment.stored, prompts);
925
1096
  }
926
1097
  this.applyIdentity(attachment.stored, metadata, tags);
927
1098
  this.noteBounds(attachment.stored, startedAt, undefined);
928
1099
  const { provider, model } = resolveGenerationIdentity(serialized, extraParams, metadata);
1100
+ const llmInputMessages = (0, messages_1.normalizeMessages)(prompts.map((content) => ({ role: "user", content })));
1101
+ const tools = extractLangChainTools(serialized, extraParams);
1102
+ const invocationParameters = extractLangChainInvocationParameters(extraParams);
929
1103
  const handle = attachment.stored.handle.startGeneration({
930
1104
  name: serializedName(serialized, "langchain-llm"),
931
1105
  parentId: attachment.parentId,
932
- input: prompts,
933
1106
  metadata: this.options.metadata,
934
1107
  model,
935
- llmProvider: provider,
936
- llmInputMessages: prompts.map((content) => ({ role: "user", content })),
937
- llmInvocationParameters: extraParams,
1108
+ provider,
1109
+ llmInputMessages,
1110
+ ...(invocationParameters ? { invocationParameters } : {}),
1111
+ ...(tools ? { tools } : {}),
938
1112
  attributes: langchainAttributes(runId, parentRunId, "llm"),
939
1113
  startedAt,
940
1114
  });
@@ -944,6 +1118,7 @@ class LemmaLangChainCallbackHandler {
944
1118
  handle,
945
1119
  kind: "llm",
946
1120
  startedAt,
1121
+ startedMonoMs,
947
1122
  parentRunId,
948
1123
  ownsTrace: attachment.ownsTrace,
949
1124
  });
@@ -951,24 +1126,32 @@ class LemmaLangChainCallbackHandler {
951
1126
  handleChatModelStart(serialized, messages, runId, parentRunId, extraParams, tags, metadata, _runName) {
952
1127
  this.evictIdleTraces();
953
1128
  const startedAt = new Date();
1129
+ const startedMonoMs = monotonicNow();
954
1130
  const flatMessages = messages.flat();
955
- const normalized = normalizeMessages(flatMessages);
956
1131
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-chat-model"), flatMessages, "llm", metadata, tags));
957
1132
  if (attachment.ownsTrace) {
958
1133
  this.noteRootInput(attachment.stored, flatMessages);
959
1134
  }
960
1135
  this.applyIdentity(attachment.stored, metadata, tags);
961
1136
  this.noteBounds(attachment.stored, startedAt, undefined);
1137
+ const unpacked = flatMessages.map(unpackLangChainMessage);
1138
+ const canonicalInput = (0, messages_1.normalizeMessages)(unpacked, {
1139
+ failedToolCallIds: attachment.stored.failedToolCallIds,
1140
+ toolNamesByCallId: attachment.stored.toolNamesByCallId,
1141
+ });
1142
+ this.noteToolCallsFromCanonical(attachment.stored, canonicalInput);
962
1143
  const { provider, model } = resolveGenerationIdentity(serialized, extraParams, metadata);
1144
+ const tools = extractLangChainTools(serialized, extraParams);
1145
+ const invocationParameters = extractLangChainInvocationParameters(extraParams);
963
1146
  const handle = attachment.stored.handle.startGeneration({
964
1147
  name: serializedName(serialized, "langchain-chat-model"),
965
1148
  parentId: attachment.parentId,
966
- input: normalized,
967
1149
  metadata: this.options.metadata,
968
1150
  model,
969
- llmProvider: provider,
970
- llmInputMessages: normalized,
971
- llmInvocationParameters: extraParams,
1151
+ provider,
1152
+ llmInputMessages: canonicalInput,
1153
+ ...(invocationParameters ? { invocationParameters } : {}),
1154
+ ...(tools ? { tools } : {}),
972
1155
  attributes: langchainAttributes(runId, parentRunId, "llm"),
973
1156
  startedAt,
974
1157
  });
@@ -978,39 +1161,58 @@ class LemmaLangChainCallbackHandler {
978
1161
  handle,
979
1162
  kind: "llm",
980
1163
  startedAt,
1164
+ startedMonoMs,
981
1165
  parentRunId,
982
1166
  ownsTrace: attachment.ownsTrace,
983
1167
  });
984
1168
  }
985
- handleLLMEnd(output, runId) {
1169
+ handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, _fields) {
1170
+ if (!runId || typeof token !== "string" || token.length === 0)
1171
+ return;
1172
+ const run = this.runs.get(runId);
1173
+ if (!run || run.kind !== "llm" || run.firstTokenMonoMs !== undefined) {
1174
+ return;
1175
+ }
1176
+ run.firstTokenMonoMs = monotonicNow();
1177
+ }
1178
+ handleLLMEnd(output, runId, _parentRunId) {
986
1179
  const run = this.runs.get(runId);
987
1180
  if (!run?.handle)
988
1181
  return;
989
1182
  const endedAt = new Date();
1183
+ const stored = this.storedTrace(run.owningTraceId);
990
1184
  const structured = llmStructuredOutput(output);
991
- const outputMessages = llmOutputMessages(output);
992
- const softError = (0, tool_result_1.toolResultError)(structured);
1185
+ const outputMessages = llmOutputMessages(output, stored
1186
+ ? {
1187
+ failedToolCallIds: stored.failedToolCallIds,
1188
+ toolNamesByCallId: stored.toolNamesByCallId,
1189
+ }
1190
+ : undefined);
1191
+ if (stored) {
1192
+ this.noteToolCallsFromCanonical(stored, outputMessages);
1193
+ }
1194
+ const finishReason = llmFinishReason(output);
993
1195
  const model = (0, model_1.pickGenerationModelIdentity)(output);
1196
+ const spanDurationMs = durationMs(run.startedAt, endedAt);
1197
+ const timeToFirstTokenMs = run.firstTokenMonoMs !== undefined && run.startedMonoMs !== undefined
1198
+ ? Math.min(Math.max(0, run.firstTokenMonoMs - run.startedMonoMs), spanDurationMs)
1199
+ : undefined;
994
1200
  this.endStoredRun(run, {
995
- output: softError ? undefined : structured,
996
- error: softError ?? undefined,
997
- status: softError ? "ERROR" : undefined,
1201
+ output: outputMessages ? undefined : structured,
998
1202
  endedAt,
999
- durationMs: durationMs(run.startedAt, endedAt),
1000
- llmOutputMessages: softError ? undefined : outputMessages,
1203
+ durationMs: spanDurationMs,
1204
+ llmOutputMessages: outputMessages,
1205
+ ...(finishReason ? { finishReason } : {}),
1206
+ ...(timeToFirstTokenMs !== undefined ? { timeToFirstTokenMs } : {}),
1001
1207
  usage: llmTokenUsage(output),
1002
1208
  ...(model ? { model } : {}),
1003
1209
  });
1004
- const stored = this.storedTrace(run.owningTraceId);
1005
1210
  if (stored) {
1006
1211
  this.noteBounds(stored, run.startedAt, endedAt);
1007
1212
  if (run.ownsTrace) {
1008
- if (softError)
1009
- this.noteRootError(stored, softError);
1010
- else
1011
- this.noteRootOutput(stored, structured);
1213
+ this.noteRootOutput(stored, structured);
1012
1214
  }
1013
- else if (!softError) {
1215
+ else {
1014
1216
  // Prefer chain-level root output; refresh from later generations.
1015
1217
  this.noteRootOutput(stored, structured);
1016
1218
  }
@@ -1018,7 +1220,7 @@ class LemmaLangChainCallbackHandler {
1018
1220
  this.runs.delete(runId);
1019
1221
  this.maybeFinalizeOwner(run);
1020
1222
  }
1021
- handleLLMError(error, runId) {
1223
+ handleLLMError(error, runId, _parentRunId) {
1022
1224
  const run = this.runs.get(runId);
1023
1225
  if (!run)
1024
1226
  return;
@@ -1039,7 +1241,7 @@ class LemmaLangChainCallbackHandler {
1039
1241
  this.runs.delete(runId);
1040
1242
  this.maybeFinalizeOwner(run);
1041
1243
  }
1042
- handleToolStart(serialized, input, runId, parentRunId, tags, metadata, _runName, _toolCallId) {
1244
+ handleToolStart(serialized, input, runId, parentRunId, tags, metadata, _runName, toolCallId) {
1043
1245
  this.evictIdleTraces();
1044
1246
  const startedAt = new Date();
1045
1247
  const attachment = this.resolveAttachment(runId, parentRunId, () => this.createOwnedTrace(runId, this.traceName(serialized, "langchain-tool"), input, "tool", metadata, tags));
@@ -1049,10 +1251,19 @@ class LemmaLangChainCallbackHandler {
1049
1251
  this.applyIdentity(attachment.stored, metadata, tags);
1050
1252
  this.noteBounds(attachment.stored, startedAt, undefined);
1051
1253
  const name = serializedName(serialized, "langchain-tool");
1254
+ const resolvedCallId = resolveToolCallId(toolCallId, [
1255
+ metadata,
1256
+ serialized?.kwargs,
1257
+ asRecord(input),
1258
+ ]);
1259
+ if (resolvedCallId && name) {
1260
+ attachment.stored.toolNamesByCallId.set(resolvedCallId, name);
1261
+ }
1052
1262
  const handle = attachment.stored.handle.startTool({
1053
1263
  name,
1054
1264
  parentId: attachment.parentId,
1055
1265
  toolName: name,
1266
+ toolCallId: resolvedCallId,
1056
1267
  input,
1057
1268
  metadata: this.options.metadata,
1058
1269
  attributes: langchainAttributes(runId, parentRunId, "tool"),
@@ -1065,19 +1276,42 @@ class LemmaLangChainCallbackHandler {
1065
1276
  kind: "tool",
1066
1277
  startedAt,
1067
1278
  parentRunId,
1279
+ toolCallId: resolvedCallId,
1280
+ toolName: name,
1068
1281
  ownsTrace: attachment.ownsTrace,
1069
1282
  });
1070
1283
  }
1071
- handleToolEnd(output, runId) {
1284
+ handleToolEnd(output, runId, _parentRunId) {
1072
1285
  const run = this.runs.get(runId);
1073
1286
  if (!run)
1074
1287
  return;
1075
1288
  const endedAt = new Date();
1076
- const softError = (0, tool_result_1.toolResultError)(output);
1289
+ const outputRecord = asRecord(output);
1290
+ const outputKwargs = asRecord(outputRecord?.kwargs);
1291
+ const resolvedCallId = run.toolCallId ??
1292
+ resolveToolCallId(undefined, [outputRecord, outputKwargs]);
1293
+ const toolContent = outputRecord && "content" in outputRecord
1294
+ ? outputRecord.content
1295
+ : outputKwargs && "content" in outputKwargs
1296
+ ? outputKwargs.content
1297
+ : undefined;
1298
+ const softError = toolMessageStatusError(output) ??
1299
+ (0, tool_result_1.toolResultError)(output) ??
1300
+ (toolContent !== undefined ? (0, tool_result_1.toolResultError)(toolContent) : null);
1301
+ const stored = this.storedTrace(run.owningTraceId);
1302
+ if (stored && resolvedCallId) {
1303
+ if (run.toolName) {
1304
+ stored.toolNamesByCallId.set(resolvedCallId, run.toolName);
1305
+ }
1306
+ if (softError) {
1307
+ stored.failedToolCallIds.add(resolvedCallId);
1308
+ }
1309
+ }
1077
1310
  if (softError) {
1078
1311
  this.endStoredRun(run, {
1079
1312
  status: "ERROR",
1080
1313
  error: softError,
1314
+ toolCallId: resolvedCallId,
1081
1315
  endedAt,
1082
1316
  durationMs: durationMs(run.startedAt, endedAt),
1083
1317
  });
@@ -1085,11 +1319,11 @@ class LemmaLangChainCallbackHandler {
1085
1319
  else {
1086
1320
  this.endStoredRun(run, {
1087
1321
  output,
1322
+ toolCallId: resolvedCallId,
1088
1323
  endedAt,
1089
1324
  durationMs: durationMs(run.startedAt, endedAt),
1090
1325
  });
1091
1326
  }
1092
- const stored = this.storedTrace(run.owningTraceId);
1093
1327
  if (stored) {
1094
1328
  this.noteBounds(stored, run.startedAt, endedAt);
1095
1329
  if (run.ownsTrace) {
@@ -1102,19 +1336,23 @@ class LemmaLangChainCallbackHandler {
1102
1336
  this.runs.delete(runId);
1103
1337
  this.maybeFinalizeOwner(run);
1104
1338
  }
1105
- handleToolError(error, runId) {
1339
+ handleToolError(error, runId, _parentRunId) {
1106
1340
  const run = this.runs.get(runId);
1107
1341
  if (!run)
1108
1342
  return;
1109
1343
  const endedAt = new Date();
1110
1344
  const message = (0, error_message_1.describeError)(error);
1345
+ const stored = this.storedTrace(run.owningTraceId);
1346
+ if (stored && run.toolCallId) {
1347
+ stored.failedToolCallIds.add(run.toolCallId);
1348
+ }
1111
1349
  this.endStoredRun(run, {
1112
1350
  status: "ERROR",
1113
1351
  error: message,
1352
+ toolCallId: run.toolCallId,
1114
1353
  endedAt,
1115
1354
  durationMs: durationMs(run.startedAt, endedAt),
1116
1355
  });
1117
- const stored = this.storedTrace(run.owningTraceId);
1118
1356
  if (stored) {
1119
1357
  this.noteBounds(stored, run.startedAt, endedAt);
1120
1358
  if (run.ownsTrace)
@@ -1132,7 +1370,7 @@ class LemmaLangChainCallbackHandler {
1132
1370
  }
1133
1371
  this.applyIdentity(attachment.stored, metadata, tags);
1134
1372
  this.noteBounds(attachment.stored, startedAt, undefined);
1135
- const handle = attachment.stored.handle.startSpan({
1373
+ const handle = attachment.stored.handle.startRetrieval({
1136
1374
  name: serializedName(serialized, "langchain-retriever"),
1137
1375
  parentId: attachment.parentId,
1138
1376
  input: query,
@@ -1150,13 +1388,15 @@ class LemmaLangChainCallbackHandler {
1150
1388
  ownsTrace: attachment.ownsTrace,
1151
1389
  });
1152
1390
  }
1153
- handleRetrieverEnd(documents, runId) {
1391
+ handleRetrieverEnd(documents, runId, _parentRunId) {
1154
1392
  const run = this.runs.get(runId);
1155
1393
  if (!run)
1156
1394
  return;
1157
1395
  const endedAt = new Date();
1396
+ const retrievalDocuments = (0, messages_1.normalizeDocuments)(documents);
1158
1397
  this.endStoredRun(run, {
1159
- output: documents,
1398
+ retrievalDocuments,
1399
+ ...(retrievalDocuments ? {} : { output: documents }),
1160
1400
  endedAt,
1161
1401
  durationMs: durationMs(run.startedAt, endedAt),
1162
1402
  });
@@ -1169,7 +1409,7 @@ class LemmaLangChainCallbackHandler {
1169
1409
  this.runs.delete(runId);
1170
1410
  this.maybeFinalizeOwner(run);
1171
1411
  }
1172
- handleRetrieverError(error, runId) {
1412
+ handleRetrieverError(error, runId, _parentRunId) {
1173
1413
  const run = this.runs.get(runId);
1174
1414
  if (!run)
1175
1415
  return;