@ai-sdk/otel 1.0.160 → 1.0.162

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,110 @@
1
- import { SpanKind, SpanStatusCode, context, metrics, trace } from "@opentelemetry/api";
1
+ import { SpanKind, SpanStatusCode, TraceFlags, context, createTraceState, isSpanContextValid, metrics, trace } from "@opentelemetry/api";
2
2
  import { RetryError, convertDataContentToBase64String } from "ai";
3
3
  import { APICallError } from "@ai-sdk/provider";
4
+ //#region src/durable-span-ids.ts
5
+ /**
6
+ * Instance-scoped SDK bridge for durable tracing. Pass the same instance as
7
+ * the SDK's idGenerator and sampler, and as OpenTelemetry's durable option.
8
+ * Without a custom sampler, uses parent-based sampling with roots enabled.
9
+ */
10
+ var OpenTelemetryIdGenerator = class {
11
+ constructor(options = {}) {
12
+ this.options = options;
13
+ }
14
+ generateTraceId() {
15
+ const requested = this.requested?.traceId;
16
+ if (requested == null) return randomHex(16);
17
+ this.requested.traceId = void 0;
18
+ return requested;
19
+ }
20
+ generateSpanId() {
21
+ const requested = this.requested?.spanId;
22
+ if (requested == null) return randomHex(8);
23
+ this.requested.spanId = void 0;
24
+ return requested;
25
+ }
26
+ shouldSample(...args) {
27
+ if (this.requested?.samplingDecision != null) return {
28
+ decision: this.requested.samplingDecision,
29
+ traceState: this.requested.traceState == null ? trace.getSpanContext(args[0])?.traceState : createTraceState(this.requested.traceState)
30
+ };
31
+ if (this.options.sampler != null) return this.options.sampler.shouldSample(...args);
32
+ const parent = trace.getSpanContext(args[0]);
33
+ return {
34
+ decision: parent == null || !isSpanContextValid(parent) || (parent.traceFlags & TraceFlags.SAMPLED) !== 0 ? 2 : 0,
35
+ traceState: parent?.traceState
36
+ };
37
+ }
38
+ toString() {
39
+ return "AiSdkDurableSampler";
40
+ }
41
+ captureContext(callId, name, kind, attributes) {
42
+ const activeParent = trace.getSpanContext(context.active());
43
+ const parent = activeParent != null && isSpanContextValid(activeParent) ? activeParent : void 0;
44
+ const traceId = parent?.traceId ?? deriveTraceId(callId);
45
+ const sampling = this.shouldSample(context.active(), traceId, name, kind, attributes, []);
46
+ return {
47
+ traceId,
48
+ rootSpanId: deriveSpanId(callId, "root"),
49
+ traceFlags: sampling.decision === 2 ? TraceFlags.SAMPLED : TraceFlags.NONE,
50
+ samplingDecision: sampling.decision,
51
+ rootAttributes: {
52
+ ...attributes,
53
+ ...sampling.attributes
54
+ },
55
+ traceState: sampling.traceState?.serialize() ?? parent?.traceState?.serialize(),
56
+ ...parent == null ? {} : { parentSpanContext: {
57
+ traceId: parent.traceId,
58
+ spanId: parent.spanId,
59
+ traceFlags: parent.traceFlags,
60
+ traceState: parent.traceState?.serialize()
61
+ } }
62
+ };
63
+ }
64
+ /** Scope requested IDs to this bridge and restore nested requests. */
65
+ withIds(ids, startSpan) {
66
+ const previous = this.requested;
67
+ this.requested = { ...ids };
68
+ try {
69
+ return startSpan();
70
+ } finally {
71
+ this.requested = previous;
72
+ }
73
+ }
74
+ };
75
+ /** Derives the trace ID of a durable run from its telemetry call ID. */
76
+ function deriveTraceId(callId) {
77
+ return deriveHex(`${callId}:trace`, 4);
78
+ }
79
+ /** Derives a span ID of a durable run from its telemetry call ID. */
80
+ function deriveSpanId(callId, ...path) {
81
+ return deriveHex([callId, ...path].join(":"), 2);
82
+ }
83
+ function randomHex(bytes) {
84
+ const values = crypto.getRandomValues(new Uint8Array(bytes));
85
+ return nonZero(Array.from(values, (value) => value.toString(16).padStart(2, "0")).join(""));
86
+ }
87
+ /**
88
+ * Non-cryptographic hash (FNV-1a with one seed per 32-bit word). Collisions
89
+ * only matter between spans of the same run.
90
+ */
91
+ function deriveHex(input, words) {
92
+ let hex = "";
93
+ for (let word = 0; word < words; word++) {
94
+ let hash = (2166136261 ^ Math.imul(word + 1, 2654435761)) >>> 0;
95
+ for (let index = 0; index < input.length; index++) {
96
+ hash ^= input.charCodeAt(index);
97
+ hash = Math.imul(hash, 16777619) >>> 0;
98
+ }
99
+ hex += hash.toString(16).padStart(8, "0");
100
+ }
101
+ return nonZero(hex);
102
+ }
103
+ /** All-zero IDs are invalid in OpenTelemetry. */
104
+ function nonZero(hex) {
105
+ return /^0+$/.test(hex) ? `${hex.slice(0, -1)}1` : hex;
106
+ }
107
+ //#endregion
4
108
  //#region src/gen-ai-format-messages.ts
5
109
  /**
6
110
  * Maps an AI SDK provider string (e.g. "anthropic.messages", "openai.chat")
@@ -44,6 +148,7 @@ function mapOperationName(operationId) {
44
148
  "ai.streamText": "invoke_agent",
45
149
  "ai.generateObject": "invoke_agent",
46
150
  "ai.streamObject": "invoke_agent",
151
+ "ai.workflowAgent.stream": "invoke_agent",
47
152
  "ai.embed": "embeddings",
48
153
  "ai.embedMany": "embeddings",
49
154
  "ai.rerank": "rerank",
@@ -669,6 +774,19 @@ function selectSupplementalAttributes(telemetry, enabledAttributes, attributes)
669
774
  }
670
775
  //#endregion
671
776
  //#region src/open-telemetry.ts
777
+ /**
778
+ * Returns the time an event occurred when it is reported after the fact.
779
+ * A `Date` is used because OpenTelemetry treats numbers smaller than the
780
+ * process time origin as `performance.now()` values.
781
+ */
782
+ function getEventTime(event) {
783
+ const timestamp = getEventTimestamp(event);
784
+ return timestamp == null ? void 0 : new Date(timestamp);
785
+ }
786
+ function getEventTimestamp(event) {
787
+ const timestamp = event != null && typeof event === "object" && "timestamp" in event ? event.timestamp : void 0;
788
+ return typeof timestamp === "number" ? timestamp : void 0;
789
+ }
672
790
  function msToSeconds(durationMs) {
673
791
  return durationMs == null ? void 0 : durationMs / 1e3;
674
792
  }
@@ -682,21 +800,38 @@ function getGenAIClientPerformanceAttributes(performance) {
682
800
  var OpenTelemetry = class {
683
801
  constructor(options = {}) {
684
802
  this.callStates = /* @__PURE__ */ new Map();
803
+ this.experimental_durable = { captureContext: (event) => {
804
+ if (this.durable == null) return void 0;
805
+ const { spanName, rootSpanOptions } = this.prepareGenerateStart(event);
806
+ return {
807
+ ...this.durable.captureContext(event.callId, spanName, SpanKind.INTERNAL, rootSpanOptions.attributes),
808
+ rootSpanName: spanName
809
+ };
810
+ } };
685
811
  this.tracer = options.tracer ?? trace.getTracer("gen_ai");
812
+ this.durable = options.durable;
686
813
  this.agentSpanName = options.agentSpanName;
687
814
  this.supplementalAttributes = normalizeSupplementalAttributes(options);
688
815
  this.enrichSpan = options.enrichSpan;
689
816
  }
817
+ withDurableSampling(state, startSpan) {
818
+ const run = state.durableContext ?? state.liveDurableContext;
819
+ return run != null && this.durable != null ? this.durable.withIds({
820
+ samplingDecision: run.samplingDecision,
821
+ traceState: run.traceState
822
+ }, startSpan) : startSpan();
823
+ }
690
824
  getCallState(callId) {
691
825
  return this.callStates.get(callId);
692
826
  }
693
827
  cleanupCallState(callId) {
694
828
  this.callStates.delete(callId);
695
829
  }
696
- recordInferenceDuration(state, { responseTimeMs, provider, responseModelId, errorType } = {}) {
830
+ recordInferenceDuration(state, { responseTimeMs, provider, responseModelId, errorType, endTimestamp } = {}) {
697
831
  const inference = state.inferenceMetrics;
698
832
  if (inference == null) return;
699
833
  state.inferenceMetrics = void 0;
834
+ const durationMs = responseTimeMs ?? (inference.startTimestamp != null && endTimestamp != null ? Math.max(0, endTimestamp - inference.startTimestamp) : performance.now() - inference.startTime);
700
835
  metrics.getMeter("gen_ai").createHistogram("gen_ai.client.inference.duration", {
701
836
  description: "GenAI client inference operation duration.",
702
837
  unit: "s",
@@ -716,7 +851,7 @@ var OpenTelemetry = class {
716
851
  40.96,
717
852
  81.92
718
853
  ] }
719
- }).record((responseTimeMs ?? performance.now() - inference.startTime) / 1e3, selectAttributes$1(state.telemetry, {
854
+ }).record(durationMs / 1e3, selectAttributes$1(state.telemetry, {
720
855
  "gen_ai.operation.name": "chat",
721
856
  "gen_ai.provider.name": mapProviderName(provider ?? inference.provider),
722
857
  "gen_ai.request.model": inference.modelId,
@@ -857,7 +992,7 @@ var OpenTelemetry = class {
857
992
  baseSupplementalAttributes
858
993
  });
859
994
  }
860
- onGenerateStart(event) {
995
+ prepareGenerateStart(event) {
861
996
  const telemetry = {
862
997
  recordInputs: event.recordInputs,
863
998
  recordOutputs: event.recordOutputs,
@@ -901,22 +1036,51 @@ var OpenTelemetry = class {
901
1036
  })) },
902
1037
  ...baseSupplementalAttributes
903
1038
  });
904
- const spanName = this.getAgentSpanName({
905
- operationName,
906
- modelId: event.modelId,
907
- functionId: telemetry.functionId
908
- });
909
- const rootSpan = this.tracer.startSpan(spanName, {
910
- attributes: this.getSpanAttributes({
911
- attributes,
912
- spanType: "operation",
913
- operationId: event.operationId,
914
- callId: event.callId,
915
- runtimeContext
1039
+ return {
1040
+ spanName: event.durableContext?.run.rootSpanName ?? this.getAgentSpanName({
1041
+ operationName,
1042
+ modelId: event.modelId,
1043
+ functionId: telemetry.functionId
916
1044
  }),
917
- kind: SpanKind.INTERNAL
918
- });
919
- const rootContext = trace.setSpan(context.active(), rootSpan);
1045
+ rootSpanOptions: {
1046
+ attributes: event.durableContext?.run.rootAttributes ?? this.getSpanAttributes({
1047
+ attributes,
1048
+ spanType: "operation",
1049
+ operationId: event.operationId,
1050
+ callId: event.callId,
1051
+ runtimeContext
1052
+ }),
1053
+ kind: SpanKind.INTERNAL,
1054
+ startTime: getEventTime(event)
1055
+ },
1056
+ telemetry,
1057
+ settings,
1058
+ runtimeContext,
1059
+ baseSupplementalAttributes
1060
+ };
1061
+ }
1062
+ onGenerateStart(event) {
1063
+ const { spanName, rootSpanOptions, telemetry, settings, runtimeContext, baseSupplementalAttributes } = this.prepareGenerateStart(event);
1064
+ const run = event.durableContext?.run;
1065
+ let parentContext = context.active();
1066
+ let rootSpan;
1067
+ if (run != null && this.durable != null) {
1068
+ parentContext = trace.deleteSpan(parentContext);
1069
+ if (run.parentSpanContext != null) parentContext = trace.setSpanContext(parentContext, {
1070
+ ...run.parentSpanContext,
1071
+ traceState: run.parentSpanContext.traceState == null ? void 0 : createTraceState(run.parentSpanContext.traceState),
1072
+ isRemote: true
1073
+ });
1074
+ rootSpan = this.durable.withIds({
1075
+ traceId: run.traceId,
1076
+ spanId: run.rootSpanId,
1077
+ samplingDecision: run.samplingDecision,
1078
+ traceState: run.traceState
1079
+ }, () => this.tracer.startSpan(spanName, rootSpanOptions, parentContext));
1080
+ } else rootSpan = this.tracer.startSpan(spanName, rootSpanOptions);
1081
+ const actual = rootSpan.spanContext();
1082
+ const durableContext = run != null && actual.traceId === run.traceId && actual.spanId === run.rootSpanId ? run : void 0;
1083
+ const rootContext = trace.setSpan(parentContext, rootSpan);
920
1084
  this.callStates.set(event.callId, {
921
1085
  operationId: event.operationId,
922
1086
  telemetry,
@@ -934,7 +1098,8 @@ var OpenTelemetry = class {
934
1098
  provider: event.provider,
935
1099
  modelId: event.modelId,
936
1100
  runtimeContext,
937
- baseSupplementalAttributes
1101
+ baseSupplementalAttributes,
1102
+ durableContext
938
1103
  });
939
1104
  }
940
1105
  onObjectOperationStart(event) {
@@ -1151,7 +1316,8 @@ var OpenTelemetry = class {
1151
1316
  ...state.baseSupplementalAttributes,
1152
1317
  ...selectSupplementalAttributes(telemetry, this.supplementalAttributes, { toolChoice: { "ai.prompt.toolChoice": { input: () => event.stepToolChoice != null ? JSON.stringify(event.stepToolChoice) : void 0 } } })
1153
1318
  });
1154
- state.stepSpan = this.tracer.startSpan(`step ${event.steps.length + 1}`, {
1319
+ const rootContext = state.rootContext;
1320
+ const options = {
1155
1321
  attributes: this.getSpanAttributes({
1156
1322
  attributes: stepAttributes,
1157
1323
  spanType: "step",
@@ -1159,24 +1325,44 @@ var OpenTelemetry = class {
1159
1325
  callId: event.callId,
1160
1326
  runtimeContext: state.runtimeContext
1161
1327
  }),
1162
- kind: SpanKind.INTERNAL
1163
- }, state.rootContext);
1164
- state.stepContext = trace.setSpan(state.rootContext, state.stepSpan);
1328
+ kind: SpanKind.INTERNAL,
1329
+ startTime: getEventTime(event)
1330
+ };
1331
+ const startStepSpan = () => this.tracer.startSpan(`step ${event.steps.length + 1}`, options, rootContext);
1332
+ state.stepSpan = state.durableContext != null && this.durable != null ? this.durable.withIds({
1333
+ spanId: deriveSpanId(event.callId, "step", event.stepNumber),
1334
+ samplingDecision: state.durableContext.samplingDecision,
1335
+ traceState: state.durableContext.traceState
1336
+ }, startStepSpan) : startStepSpan();
1337
+ state.stepContext = trace.setSpan(rootContext, state.stepSpan);
1165
1338
  }
1166
1339
  onLanguageModelCallStart(event) {
1167
- const state = this.getCallState(event.callId);
1340
+ const existingState = this.getCallState(event.callId);
1341
+ if (existingState?.durableContext) return;
1342
+ const state = existingState ?? this.startDurableModelCall(event);
1168
1343
  if (!state?.stepContext) return;
1169
- this.recordInferenceDuration(state, { errorType: "_OTHER" });
1344
+ if (state.liveDurableContext && state.inferenceSpan != null) {
1345
+ state.inferenceSpan.setStatus({ code: SpanStatusCode.ERROR });
1346
+ state.inferenceSpan.end(getEventTime(event));
1347
+ state.inferenceSpan = void 0;
1348
+ state.inferenceContext = void 0;
1349
+ }
1350
+ this.recordInferenceDuration(state, {
1351
+ errorType: "_OTHER",
1352
+ endTimestamp: getEventTimestamp(event)
1353
+ });
1170
1354
  const { telemetry } = state;
1171
1355
  const providerName = mapProviderName(event.provider);
1172
1356
  state.inferenceToolDefinitions = event.tools;
1173
1357
  state.inferenceMetrics = {
1174
1358
  startTime: performance.now(),
1359
+ startTimestamp: getEventTimestamp(event),
1175
1360
  provider: event.provider,
1176
1361
  modelId: event.modelId
1177
1362
  };
1178
1363
  const inferenceAttributes = selectAttributes$1(telemetry, {
1179
1364
  "gen_ai.operation.name": "chat",
1365
+ ...state.liveDurableContext ? state.baseSupplementalAttributes : {},
1180
1366
  "gen_ai.provider.name": providerName,
1181
1367
  "gen_ai.request.model": event.modelId,
1182
1368
  "gen_ai.request.frequency_penalty": state.settings.frequencyPenalty,
@@ -1196,26 +1382,30 @@ var OpenTelemetry = class {
1196
1382
  } },
1197
1383
  "gen_ai.tool.definitions": { input: () => event.tools ? JSON.stringify(event.tools) : void 0 }
1198
1384
  });
1199
- state.inferenceSpan = this.tracer.startSpan(`chat ${event.modelId}`, {
1200
- attributes: this.getSpanAttributes({
1201
- attributes: inferenceAttributes,
1202
- spanType: "languageModel",
1203
- operationId: state.operationId,
1204
- callId: event.callId,
1205
- runtimeContext: state.runtimeContext
1206
- }),
1207
- kind: SpanKind.CLIENT
1385
+ const inferenceSpanAttributes = this.getSpanAttributes({
1386
+ attributes: inferenceAttributes,
1387
+ spanType: "languageModel",
1388
+ operationId: state.operationId,
1389
+ callId: event.callId,
1390
+ runtimeContext: state.runtimeContext
1391
+ });
1392
+ const startInferenceSpan = () => this.tracer.startSpan(`chat ${event.modelId}`, {
1393
+ attributes: inferenceSpanAttributes,
1394
+ kind: SpanKind.CLIENT,
1395
+ startTime: getEventTime(event)
1208
1396
  }, state.stepContext);
1397
+ state.inferenceSpan = this.withDurableSampling(state, startInferenceSpan);
1209
1398
  state.inferenceContext = trace.setSpan(state.stepContext, state.inferenceSpan);
1210
1399
  }
1211
1400
  onLanguageModelCallEnd(event) {
1212
1401
  const state = this.getCallState(event.callId);
1213
- if (!state?.inferenceSpan) return;
1402
+ if (state?.durableContext || !state?.inferenceSpan) return;
1214
1403
  this.recordInferenceDuration(state, {
1215
1404
  responseTimeMs: event.performance.responseTimeMs,
1216
1405
  provider: event.provider,
1217
1406
  responseModelId: event.modelId,
1218
- errorType: event.finishReason === "error" ? "_OTHER" : void 0
1407
+ errorType: event.finishReason === "error" ? "_OTHER" : void 0,
1408
+ endTimestamp: getEventTimestamp(event)
1219
1409
  });
1220
1410
  if (event.finishReason === "error") state.inferenceSpan.setStatus({ code: SpanStatusCode.ERROR });
1221
1411
  const { telemetry } = state;
@@ -1258,11 +1448,12 @@ var OpenTelemetry = class {
1258
1448
  }));
1259
1449
  const finalToolOutputs = /* @__PURE__ */ new Map();
1260
1450
  for (const part of event.content) if (part.type === "tool-error" || part.type === "tool-result" && part.preliminary !== true) finalToolOutputs.set(part.toolCallId, part);
1451
+ const endTime = getEventTime(event);
1261
1452
  const recordedToolCallIds = /* @__PURE__ */ new Set();
1262
1453
  for (const part of event.content) {
1263
1454
  if (part.type !== "tool-call" || !part.providerExecuted || recordedToolCallIds.has(part.toolCallId)) continue;
1264
1455
  recordedToolCallIds.add(part.toolCallId);
1265
- const toolSpan = this.tracer.startSpan(`execute_tool ${part.toolName}`, {
1456
+ const toolSpanOptions = {
1266
1457
  attributes: this.getSpanAttributes({
1267
1458
  attributes: selectAttributes$1(telemetry, {
1268
1459
  "gen_ai.operation.name": "execute_tool",
@@ -1276,19 +1467,98 @@ var OpenTelemetry = class {
1276
1467
  callId: event.callId,
1277
1468
  runtimeContext: state.runtimeContext
1278
1469
  }),
1279
- kind: SpanKind.INTERNAL
1280
- }, state.inferenceContext);
1470
+ kind: SpanKind.INTERNAL,
1471
+ startTime: endTime
1472
+ };
1473
+ const toolSpan = this.withDurableSampling(state, () => this.tracer.startSpan(`execute_tool ${part.toolName}`, toolSpanOptions, state.inferenceContext));
1281
1474
  const toolOutput = finalToolOutputs.get(part.toolCallId);
1282
1475
  if (toolOutput?.type === "tool-result") try {
1283
1476
  toolSpan.setAttributes(selectAttributes$1(telemetry, { "gen_ai.tool.call.result": { output: () => JSON.stringify(toolOutput.output) } }));
1284
1477
  } catch {}
1285
1478
  else if (toolOutput?.type === "tool-error") recordErrorOnSpan(toolSpan, toolOutput.error);
1286
- toolSpan.end();
1479
+ toolSpan.end(endTime);
1287
1480
  }
1288
- state.inferenceSpan.end();
1481
+ state.inferenceSpan.end(endTime);
1289
1482
  state.inferenceSpan = void 0;
1290
1483
  state.inferenceContext = void 0;
1291
1484
  state.inferenceToolDefinitions = void 0;
1485
+ if (state.liveDurableContext) this.cleanupCallState(event.callId);
1486
+ }
1487
+ /**
1488
+ * Starts a model call reported live from a durable step. The run's root and
1489
+ * step spans are reported when the run ends, so the model call is parented
1490
+ * to the step span's derived ID.
1491
+ */
1492
+ startDurableModelCall(event) {
1493
+ const durable = event.durableContext;
1494
+ if (durable?.phase !== "live" || durable.stepNumber == null || this.durable == null) return void 0;
1495
+ const run = durable.run;
1496
+ const stepContext = trace.setSpanContext(context.active(), {
1497
+ traceId: run.traceId,
1498
+ spanId: deriveSpanId(event.callId, "step", durable.stepNumber),
1499
+ traceFlags: run.traceFlags,
1500
+ traceState: run.traceState == null ? void 0 : createTraceState(run.traceState),
1501
+ isRemote: true
1502
+ });
1503
+ const telemetryEvent = event;
1504
+ const state = {
1505
+ operationId: "ai.workflowAgent.stream",
1506
+ telemetry: {
1507
+ recordInputs: telemetryEvent.recordInputs,
1508
+ recordOutputs: telemetryEvent.recordOutputs,
1509
+ functionId: telemetryEvent.functionId
1510
+ },
1511
+ rootSpan: void 0,
1512
+ rootContext: void 0,
1513
+ stepSpan: void 0,
1514
+ stepContext,
1515
+ inferenceSpan: void 0,
1516
+ inferenceContext: void 0,
1517
+ embedSpans: /* @__PURE__ */ new Map(),
1518
+ rerankSpan: void 0,
1519
+ decisionSpan: void 0,
1520
+ toolSpans: /* @__PURE__ */ new Map(),
1521
+ settings: {
1522
+ maxOutputTokens: event.maxOutputTokens,
1523
+ temperature: event.temperature,
1524
+ topP: event.topP,
1525
+ topK: event.topK,
1526
+ presencePenalty: event.presencePenalty,
1527
+ frequencyPenalty: event.frequencyPenalty,
1528
+ stopSequences: event.stopSequences,
1529
+ seed: event.seed
1530
+ },
1531
+ provider: event.provider,
1532
+ modelId: event.modelId,
1533
+ runtimeContext: durable.runtimeContext,
1534
+ baseSupplementalAttributes: selectSupplementalAttributes({
1535
+ recordInputs: telemetryEvent.recordInputs,
1536
+ recordOutputs: telemetryEvent.recordOutputs
1537
+ }, this.supplementalAttributes, {
1538
+ runtimeContext: getRuntimeContextAttributes(durable.runtimeContext),
1539
+ headers: getHeaderAttributes(durable.headers)
1540
+ }),
1541
+ liveDurableContext: run
1542
+ };
1543
+ this.callStates.set(event.callId, state);
1544
+ return state;
1545
+ }
1546
+ /**
1547
+ * Ends a model call reported live from a durable step that failed or was
1548
+ * aborted before its end event.
1549
+ */
1550
+ endDurableModelCall(callId, { error, errorType, endTimestamp }) {
1551
+ const state = this.getCallState(callId);
1552
+ if (!state?.liveDurableContext) return;
1553
+ this.recordInferenceDuration(state, {
1554
+ errorType,
1555
+ endTimestamp
1556
+ });
1557
+ if (state.inferenceSpan) {
1558
+ if (error !== void 0) recordErrorOnSpan(state.inferenceSpan, error);
1559
+ state.inferenceSpan.end(endTimestamp == null ? void 0 : new Date(endTimestamp));
1560
+ }
1561
+ this.cleanupCallState(callId);
1292
1562
  }
1293
1563
  onToolExecutionStart(event) {
1294
1564
  const state = this.getCallState(event.callId);
@@ -1304,7 +1574,7 @@ var OpenTelemetry = class {
1304
1574
  "gen_ai.tool.call.arguments": { input: () => JSON.stringify(toolCall.input) }
1305
1575
  });
1306
1576
  const spanName = `execute_tool ${toolCall.toolName}`;
1307
- const toolSpan = this.tracer.startSpan(spanName, {
1577
+ const toolSpanOptions = {
1308
1578
  attributes: this.getSpanAttributes({
1309
1579
  attributes,
1310
1580
  spanType: "tool",
@@ -1312,8 +1582,10 @@ var OpenTelemetry = class {
1312
1582
  callId: event.callId,
1313
1583
  runtimeContext: state.runtimeContext
1314
1584
  }),
1315
- kind: SpanKind.INTERNAL
1316
- }, parentContext);
1585
+ kind: SpanKind.INTERNAL,
1586
+ startTime: getEventTime(event)
1587
+ };
1588
+ const toolSpan = this.withDurableSampling(state, () => this.tracer.startSpan(spanName, toolSpanOptions, parentContext));
1317
1589
  const toolContext = trace.setSpan(parentContext, toolSpan);
1318
1590
  state.toolSpans.set(toolCall.toolCallId, {
1319
1591
  span: toolSpan,
@@ -1333,20 +1605,23 @@ var OpenTelemetry = class {
1333
1605
  span.setAttributes(selectAttributes$1(telemetry, { "gen_ai.tool.call.result": { output: () => JSON.stringify(toolOutput.output) } }));
1334
1606
  } catch {}
1335
1607
  else recordErrorOnSpan(span, toolOutput.error);
1336
- span.end();
1608
+ span.end(getEventTime(event));
1337
1609
  state.toolSpans.delete(event.toolCall.toolCallId);
1338
1610
  }
1339
1611
  onStepEnd(event) {
1340
1612
  const state = this.getCallState(event.callId);
1341
1613
  if (!state?.stepSpan) return;
1342
- this.recordInferenceDuration(state, { errorType: event.finishReason === "error" ? "_OTHER" : void 0 });
1614
+ this.recordInferenceDuration(state, {
1615
+ errorType: event.finishReason === "error" ? "_OTHER" : void 0,
1616
+ endTimestamp: getEventTimestamp(event)
1617
+ });
1343
1618
  if (event.finishReason === "error") state.stepSpan.setStatus({ code: SpanStatusCode.ERROR });
1344
1619
  const { telemetry } = state;
1345
1620
  state.stepSpan.setAttributes(selectSupplementalAttributes(telemetry, this.supplementalAttributes, {
1346
1621
  providerMetadata: { "ai.response.providerMetadata": event.providerMetadata ? JSON.stringify(event.providerMetadata) : void 0 },
1347
1622
  usage: getDetailedUsageAttributes(event.usage)
1348
1623
  }));
1349
- state.stepSpan.end();
1624
+ state.stepSpan.end(getEventTime(event));
1350
1625
  state.stepSpan = void 0;
1351
1626
  state.stepContext = void 0;
1352
1627
  }
@@ -1357,15 +1632,18 @@ var OpenTelemetry = class {
1357
1632
  onStepError(event) {
1358
1633
  const state = this.getCallState(event.callId);
1359
1634
  if (!state?.stepSpan) return;
1360
- this.recordInferenceDuration(state, { errorType: event.error instanceof Error ? event.error.name : "_OTHER" });
1635
+ this.recordInferenceDuration(state, {
1636
+ errorType: event.error instanceof Error ? event.error.name : "_OTHER",
1637
+ endTimestamp: getEventTimestamp(event)
1638
+ });
1361
1639
  if (state.inferenceSpan) {
1362
1640
  recordErrorOnSpan(state.inferenceSpan, event.error);
1363
- state.inferenceSpan.end();
1641
+ state.inferenceSpan.end(getEventTime(event));
1364
1642
  state.inferenceSpan = void 0;
1365
1643
  state.inferenceContext = void 0;
1366
1644
  }
1367
1645
  recordErrorOnSpan(state.stepSpan, event.error);
1368
- state.stepSpan.end();
1646
+ state.stepSpan.end(getEventTime(event));
1369
1647
  state.stepSpan = void 0;
1370
1648
  state.stepContext = void 0;
1371
1649
  }
@@ -1449,7 +1727,7 @@ var OpenTelemetry = class {
1449
1727
  usage: getDetailedUsageAttributes(event.usage)
1450
1728
  })
1451
1729
  }));
1452
- state.rootSpan.end();
1730
+ state.rootSpan.end(getEventTime(event));
1453
1731
  this.cleanupCallState(event.callId);
1454
1732
  }
1455
1733
  onObjectOperationEnd(event) {
@@ -1748,74 +2026,97 @@ var OpenTelemetry = class {
1748
2026
  }
1749
2027
  onAbort(event) {
1750
2028
  const state = this.getCallState(event.callId);
2029
+ if (state?.liveDurableContext) {
2030
+ this.endDurableModelCall(event.callId, {
2031
+ errorType: "AbortError",
2032
+ endTimestamp: getEventTimestamp(event)
2033
+ });
2034
+ return;
2035
+ }
1751
2036
  if (!state?.rootSpan) return;
1752
- this.recordInferenceDuration(state, { errorType: "AbortError" });
1753
- for (const { span: toolSpan } of state.toolSpans.values()) toolSpan.end();
2037
+ const endTime = getEventTime(event);
2038
+ this.recordInferenceDuration(state, {
2039
+ errorType: "AbortError",
2040
+ endTimestamp: getEventTimestamp(event)
2041
+ });
2042
+ for (const { span: toolSpan } of state.toolSpans.values()) toolSpan.end(endTime);
1754
2043
  state.toolSpans.clear();
1755
2044
  if (state.inferenceSpan) {
1756
- state.inferenceSpan.end();
2045
+ state.inferenceSpan.end(endTime);
1757
2046
  state.inferenceSpan = void 0;
1758
2047
  state.inferenceContext = void 0;
1759
2048
  }
1760
2049
  if (state.stepSpan) {
1761
- state.stepSpan.end();
2050
+ state.stepSpan.end(endTime);
1762
2051
  state.stepSpan = void 0;
1763
2052
  state.stepContext = void 0;
1764
2053
  }
1765
- for (const { span: embedSpan } of state.embedSpans.values()) embedSpan.end();
2054
+ for (const { span: embedSpan } of state.embedSpans.values()) embedSpan.end(endTime);
1766
2055
  state.embedSpans.clear();
1767
2056
  if (state.rerankSpan) {
1768
- state.rerankSpan.span.end();
2057
+ state.rerankSpan.span.end(endTime);
1769
2058
  state.rerankSpan = void 0;
1770
2059
  }
1771
2060
  if (state.decisionSpan) {
1772
- state.decisionSpan.span.end();
2061
+ state.decisionSpan.span.end(endTime);
1773
2062
  state.decisionSpan = void 0;
1774
2063
  }
1775
- state.rootSpan.end();
2064
+ state.rootSpan.end(endTime);
1776
2065
  this.cleanupCallState(event.callId);
1777
2066
  }
1778
2067
  onError(error) {
1779
2068
  const event = error;
1780
2069
  if (!event?.callId) return;
1781
2070
  const state = this.getCallState(event.callId);
1782
- if (!state?.rootSpan) return;
1783
2071
  const actualError = event.error ?? error;
1784
- this.recordInferenceDuration(state, { errorType: actualError instanceof Error ? actualError.name : "_OTHER" });
2072
+ if (state?.liveDurableContext) {
2073
+ this.endDurableModelCall(event.callId, {
2074
+ error: actualError,
2075
+ errorType: actualError instanceof Error ? actualError.name : "_OTHER",
2076
+ endTimestamp: getEventTimestamp(event)
2077
+ });
2078
+ return;
2079
+ }
2080
+ if (!state?.rootSpan) return;
2081
+ const endTime = getEventTime(event);
2082
+ this.recordInferenceDuration(state, {
2083
+ errorType: actualError instanceof Error ? actualError.name : "_OTHER",
2084
+ endTimestamp: getEventTimestamp(event)
2085
+ });
1785
2086
  for (const { span: toolSpan } of state.toolSpans.values()) {
1786
2087
  recordErrorOnSpan(toolSpan, actualError);
1787
- toolSpan.end();
2088
+ toolSpan.end(endTime);
1788
2089
  }
1789
2090
  state.toolSpans.clear();
1790
2091
  if (state.inferenceSpan) {
1791
2092
  recordErrorOnSpan(state.inferenceSpan, actualError);
1792
- state.inferenceSpan.end();
2093
+ state.inferenceSpan.end(endTime);
1793
2094
  state.inferenceSpan = void 0;
1794
2095
  state.inferenceContext = void 0;
1795
2096
  }
1796
2097
  if (state.stepSpan) {
1797
2098
  recordErrorOnSpan(state.stepSpan, actualError);
1798
- state.stepSpan.end();
2099
+ state.stepSpan.end(endTime);
1799
2100
  state.stepSpan = void 0;
1800
2101
  state.stepContext = void 0;
1801
2102
  }
1802
2103
  for (const { span: embedSpan } of state.embedSpans.values()) {
1803
2104
  recordErrorOnSpan(embedSpan, actualError);
1804
- embedSpan.end();
2105
+ embedSpan.end(endTime);
1805
2106
  }
1806
2107
  state.embedSpans.clear();
1807
2108
  if (state.rerankSpan) {
1808
2109
  recordErrorOnSpan(state.rerankSpan.span, actualError);
1809
- state.rerankSpan.span.end();
2110
+ state.rerankSpan.span.end(endTime);
1810
2111
  state.rerankSpan = void 0;
1811
2112
  }
1812
2113
  if (state.decisionSpan) {
1813
2114
  recordErrorOnSpan(state.decisionSpan.span, actualError);
1814
- state.decisionSpan.span.end();
2115
+ state.decisionSpan.span.end(endTime);
1815
2116
  state.decisionSpan = void 0;
1816
2117
  }
1817
2118
  recordErrorOnSpan(state.rootSpan, actualError);
1818
- state.rootSpan.end();
2119
+ state.rootSpan.end(endTime);
1819
2120
  this.cleanupCallState(event.callId);
1820
2121
  }
1821
2122
  };
@@ -2708,6 +3009,6 @@ var LegacyOpenTelemetry = class {
2708
3009
  }
2709
3010
  };
2710
3011
  //#endregion
2711
- export { LegacyOpenTelemetry, OpenTelemetry };
3012
+ export { LegacyOpenTelemetry, OpenTelemetry, OpenTelemetryIdGenerator };
2712
3013
 
2713
3014
  //# sourceMappingURL=index.js.map