@ai-sdk/otel 1.0.161 → 1.0.163

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.
@@ -4,12 +4,14 @@ import {
4
4
  SpanKind,
5
5
  SpanStatusCode,
6
6
  trace,
7
+ createTraceState,
7
8
  type Attributes,
8
9
  type Context as OpenTelemetryContext,
9
10
  type Span,
10
11
  type Tracer,
11
12
  } from '@opentelemetry/api';
12
13
  import type {
14
+ DurableTelemetryContext,
13
15
  EmbeddingModelCallEndEvent,
14
16
  EmbedEndEvent,
15
17
  EmbedStartEvent,
@@ -58,7 +60,9 @@ import {
58
60
  } from './gen-ai-format-messages';
59
61
  import { stringifyDecisionStateForTelemetry } from './stringify-for-telemetry';
60
62
  import { recordErrorOnSpan } from './record-span';
63
+ import { redactToolDefinition } from './redact-tool-definition';
61
64
  import { getProviderUsageAttributes } from './provider-usage-attributes';
65
+ import { getServerAttributes } from './server-attributes';
62
66
  import { sanitizeAttributes } from './sanitize-attribute-value';
63
67
  import { selectAttributes } from './select-attributes';
64
68
  import {
@@ -72,6 +76,10 @@ import {
72
76
  type OpenTelemetrySpanType,
73
77
  type SupplementalAttributeOptions,
74
78
  } from './supplemental-attributes';
79
+ import {
80
+ deriveSpanId,
81
+ type OpenTelemetryIdGenerator,
82
+ } from './durable-span-ids';
75
83
 
76
84
  export type {
77
85
  EnrichSpan,
@@ -94,6 +102,8 @@ interface CallState {
94
102
  inferenceContext: OpenTelemetryContext | undefined;
95
103
  inferenceMetrics?: {
96
104
  startTime: number;
105
+ /** Epoch milliseconds when the call was reported after the fact. */
106
+ startTimestamp?: number;
97
107
  provider: string;
98
108
  modelId: string;
99
109
  };
@@ -108,6 +118,31 @@ interface CallState {
108
118
  runtimeContext: Record<string, unknown> | undefined;
109
119
  baseSupplementalAttributes: Attributes;
110
120
  objectSystemInstructions?: GenerateObjectStartEvent['system'];
121
+ /**
122
+ * The root and step spans of a durable run use derived IDs; its model calls
123
+ * were reported live from the durable steps.
124
+ */
125
+ durableContext?: DurableTelemetryContext;
126
+ /** A model call reported live from a durable step, without a root span. */
127
+ liveDurableContext?: DurableTelemetryContext;
128
+ }
129
+
130
+ /**
131
+ * Returns the time an event occurred when it is reported after the fact.
132
+ * A `Date` is used because OpenTelemetry treats numbers smaller than the
133
+ * process time origin as `performance.now()` values.
134
+ */
135
+ function getEventTime(event: unknown): Date | undefined {
136
+ const timestamp = getEventTimestamp(event);
137
+ return timestamp == null ? undefined : new Date(timestamp);
138
+ }
139
+
140
+ function getEventTimestamp(event: unknown): number | undefined {
141
+ const timestamp =
142
+ event != null && typeof event === 'object' && 'timestamp' in event
143
+ ? event.timestamp
144
+ : undefined;
145
+ return typeof timestamp === 'number' ? timestamp : undefined;
111
146
  }
112
147
 
113
148
  function msToSeconds(durationMs: number | undefined): number | undefined {
@@ -132,17 +167,50 @@ export class OpenTelemetry implements Telemetry {
132
167
  private readonly callStates = new Map<string, CallState>();
133
168
 
134
169
  private readonly tracer: Tracer;
170
+ private readonly durable: OpenTelemetryIdGenerator | undefined;
135
171
  private readonly agentSpanName: OpenTelemetryOptions['agentSpanName'];
136
172
  private readonly supplementalAttributes: SupplementalAttributeOptions;
137
173
  private readonly enrichSpan: EnrichSpan | undefined;
138
174
 
139
175
  constructor(options: OpenTelemetryOptions = {}) {
140
176
  this.tracer = options.tracer ?? trace.getTracer('gen_ai');
177
+ this.durable = options.durable;
141
178
  this.agentSpanName = options.agentSpanName;
142
179
  this.supplementalAttributes = normalizeSupplementalAttributes(options);
143
180
  this.enrichSpan = options.enrichSpan;
144
181
  }
145
182
 
183
+ readonly experimental_durable: NonNullable<
184
+ Telemetry['experimental_durable']
185
+ > = {
186
+ captureContext: event => {
187
+ if (this.durable == null) return undefined;
188
+ const { spanName, rootSpanOptions } = this.prepareGenerateStart(event);
189
+ return {
190
+ ...this.durable.captureContext(
191
+ event.callId,
192
+ spanName,
193
+ SpanKind.INTERNAL,
194
+ rootSpanOptions.attributes,
195
+ ),
196
+ rootSpanName: spanName,
197
+ };
198
+ },
199
+ };
200
+
201
+ private withDurableSampling<T>(state: CallState, startSpan: () => T): T {
202
+ const run = state.durableContext ?? state.liveDurableContext;
203
+ return run != null && this.durable != null
204
+ ? this.durable.withIds(
205
+ {
206
+ samplingDecision: run.samplingDecision,
207
+ traceState: run.traceState,
208
+ },
209
+ startSpan,
210
+ )
211
+ : startSpan();
212
+ }
213
+
146
214
  private getCallState(callId: string): CallState | undefined {
147
215
  return this.callStates.get(callId);
148
216
  }
@@ -158,17 +226,26 @@ export class OpenTelemetry implements Telemetry {
158
226
  provider,
159
227
  responseModelId,
160
228
  errorType,
229
+ endTimestamp,
161
230
  }: {
162
231
  responseTimeMs?: number;
163
232
  provider?: string;
164
233
  responseModelId?: string;
165
234
  errorType?: string;
235
+ /** Epoch milliseconds of the event that ends the call, if reported. */
236
+ endTimestamp?: number;
166
237
  } = {},
167
238
  ): void {
168
239
  const inference = state.inferenceMetrics;
169
240
  if (inference == null) return;
170
241
  state.inferenceMetrics = undefined;
171
242
 
243
+ const durationMs =
244
+ responseTimeMs ??
245
+ (inference.startTimestamp != null && endTimestamp != null
246
+ ? Math.max(0, endTimestamp - inference.startTimestamp)
247
+ : performance.now() - inference.startTime);
248
+
172
249
  // Resolve the meter when recording so a provider registered after this
173
250
  // integration is constructed can still receive metrics.
174
251
  const histogram = metrics
@@ -185,7 +262,7 @@ export class OpenTelemetry implements Telemetry {
185
262
  });
186
263
 
187
264
  histogram.record(
188
- (responseTimeMs ?? performance.now() - inference.startTime) / 1000,
265
+ durationMs / 1000,
189
266
  selectAttributes(state.telemetry, {
190
267
  'gen_ai.operation.name': 'chat',
191
268
  'gen_ai.provider.name': mapProviderName(provider ?? inference.provider),
@@ -446,9 +523,9 @@ export class OpenTelemetry implements Telemetry {
446
523
  });
447
524
  }
448
525
 
449
- private onGenerateStart(
526
+ private prepareGenerateStart(
450
527
  event: InferTelemetryEvent<GenerateTextStartEvent>,
451
- ): void {
528
+ ) {
452
529
  const telemetry: TelemetryOptions = {
453
530
  recordInputs: event.recordInputs,
454
531
  recordOutputs: event.recordOutputs,
@@ -515,22 +592,83 @@ export class OpenTelemetry implements Telemetry {
515
592
  ...baseSupplementalAttributes,
516
593
  });
517
594
 
518
- const spanName = this.getAgentSpanName({
519
- operationName,
520
- modelId: event.modelId,
521
- functionId: telemetry.functionId,
522
- });
523
- const rootSpan = this.tracer.startSpan(spanName, {
524
- attributes: this.getSpanAttributes({
525
- attributes,
526
- spanType: 'operation',
527
- operationId: event.operationId,
528
- callId: event.callId,
529
- runtimeContext,
530
- }),
595
+ const spanName =
596
+ event.durableContext?.run.rootSpanName ??
597
+ this.getAgentSpanName({
598
+ operationName,
599
+ modelId: event.modelId,
600
+ functionId: telemetry.functionId,
601
+ });
602
+ const rootSpanOptions = {
603
+ attributes:
604
+ event.durableContext?.run.rootAttributes ??
605
+ this.getSpanAttributes({
606
+ attributes,
607
+ spanType: 'operation',
608
+ operationId: event.operationId,
609
+ callId: event.callId,
610
+ runtimeContext,
611
+ }),
531
612
  kind: SpanKind.INTERNAL,
532
- });
533
- const rootContext = trace.setSpan(context.active(), rootSpan);
613
+ startTime: getEventTime(event),
614
+ };
615
+
616
+ return {
617
+ spanName,
618
+ rootSpanOptions,
619
+ telemetry,
620
+ settings,
621
+ runtimeContext,
622
+ baseSupplementalAttributes,
623
+ };
624
+ }
625
+
626
+ private onGenerateStart(
627
+ event: InferTelemetryEvent<GenerateTextStartEvent>,
628
+ ): void {
629
+ const {
630
+ spanName,
631
+ rootSpanOptions,
632
+ telemetry,
633
+ settings,
634
+ runtimeContext,
635
+ baseSupplementalAttributes,
636
+ } = this.prepareGenerateStart(event);
637
+ const run = event.durableContext?.run;
638
+ let parentContext = context.active();
639
+ let rootSpan: Span;
640
+ if (run != null && this.durable != null) {
641
+ parentContext = trace.deleteSpan(parentContext);
642
+ if (run.parentSpanContext != null) {
643
+ parentContext = trace.setSpanContext(parentContext, {
644
+ ...run.parentSpanContext,
645
+ traceState:
646
+ run.parentSpanContext.traceState == null
647
+ ? undefined
648
+ : createTraceState(run.parentSpanContext.traceState),
649
+ isRemote: true,
650
+ });
651
+ }
652
+ rootSpan = this.durable.withIds(
653
+ {
654
+ traceId: run.traceId,
655
+ spanId: run.rootSpanId,
656
+ samplingDecision: run.samplingDecision,
657
+ traceState: run.traceState,
658
+ },
659
+ () => this.tracer.startSpan(spanName, rootSpanOptions, parentContext),
660
+ );
661
+ } else {
662
+ rootSpan = this.tracer.startSpan(spanName, rootSpanOptions);
663
+ }
664
+ const actual = rootSpan.spanContext();
665
+ const durableContext =
666
+ run != null &&
667
+ actual.traceId === run.traceId &&
668
+ actual.spanId === run.rootSpanId
669
+ ? run
670
+ : undefined;
671
+ const rootContext = trace.setSpan(parentContext, rootSpan);
534
672
 
535
673
  this.callStates.set(event.callId, {
536
674
  operationId: event.operationId,
@@ -550,6 +688,7 @@ export class OpenTelemetry implements Telemetry {
550
688
  modelId: event.modelId,
551
689
  runtimeContext,
552
690
  baseSupplementalAttributes,
691
+ durableContext,
553
692
  });
554
693
  }
555
694
 
@@ -749,6 +888,7 @@ export class OpenTelemetry implements Telemetry {
749
888
 
750
889
  state.inferenceSpan.setAttributes(
751
890
  selectAttributes(telemetry, {
891
+ ...getServerAttributes(event.request.url),
752
892
  'gen_ai.response.finish_reasons': [event.finishReason],
753
893
  'gen_ai.response.id': event.response.id,
754
894
  'gen_ai.response.model': event.response.modelId,
@@ -890,41 +1030,74 @@ export class OpenTelemetry implements Telemetry {
890
1030
  }),
891
1031
  });
892
1032
 
893
- state.stepSpan = this.tracer.startSpan(
894
- `step ${event.steps.length + 1}`,
895
- {
896
- attributes: this.getSpanAttributes({
897
- attributes: stepAttributes,
898
- spanType: 'step',
899
- operationId: state.operationId,
900
- callId: event.callId,
901
- runtimeContext: state.runtimeContext,
902
- }),
903
- kind: SpanKind.INTERNAL,
904
- },
905
- state.rootContext,
906
- );
907
- state.stepContext = trace.setSpan(state.rootContext, state.stepSpan);
1033
+ const rootContext = state.rootContext;
1034
+ const options = {
1035
+ attributes: this.getSpanAttributes({
1036
+ attributes: stepAttributes,
1037
+ spanType: 'step',
1038
+ operationId: state.operationId,
1039
+ callId: event.callId,
1040
+ runtimeContext: state.runtimeContext,
1041
+ }),
1042
+ kind: SpanKind.INTERNAL,
1043
+ startTime: getEventTime(event),
1044
+ };
1045
+ const startStepSpan = () =>
1046
+ this.tracer.startSpan(
1047
+ `step ${event.steps.length + 1}`,
1048
+ options,
1049
+ rootContext,
1050
+ );
1051
+ state.stepSpan =
1052
+ state.durableContext != null && this.durable != null
1053
+ ? this.durable.withIds(
1054
+ {
1055
+ spanId: deriveSpanId(event.callId, 'step', event.stepNumber),
1056
+ samplingDecision: state.durableContext.samplingDecision,
1057
+ traceState: state.durableContext.traceState,
1058
+ },
1059
+ startStepSpan,
1060
+ )
1061
+ : startStepSpan();
1062
+ state.stepContext = trace.setSpan(rootContext, state.stepSpan);
908
1063
  }
909
1064
 
910
- onLanguageModelCallStart(event: LanguageModelCallStartEvent): void {
911
- const state = this.getCallState(event.callId);
1065
+ onLanguageModelCallStart(
1066
+ event: InferTelemetryEvent<LanguageModelCallStartEvent>,
1067
+ ): void {
1068
+ const existingState = this.getCallState(event.callId);
1069
+ // The durable steps already reported the run's model calls live.
1070
+ if (existingState?.durableContext) return;
1071
+
1072
+ const state = existingState ?? this.startDurableModelCall(event);
912
1073
  if (!state?.stepContext) return;
913
1074
 
914
1075
  // A retried stream may start a new attempt without ending the failed one.
915
- this.recordInferenceDuration(state, { errorType: '_OTHER' });
1076
+ if (state.liveDurableContext && state.inferenceSpan != null) {
1077
+ state.inferenceSpan.setStatus({ code: SpanStatusCode.ERROR });
1078
+ state.inferenceSpan.end(getEventTime(event));
1079
+ state.inferenceSpan = undefined;
1080
+ state.inferenceContext = undefined;
1081
+ }
1082
+ this.recordInferenceDuration(state, {
1083
+ errorType: '_OTHER',
1084
+ endTimestamp: getEventTimestamp(event),
1085
+ });
916
1086
 
917
1087
  const { telemetry } = state;
918
1088
  const providerName = mapProviderName(event.provider);
919
- state.inferenceToolDefinitions = event.tools;
1089
+ const toolDefinitions = event.tools?.map(redactToolDefinition);
1090
+ state.inferenceToolDefinitions = toolDefinitions;
920
1091
  state.inferenceMetrics = {
921
1092
  startTime: performance.now(),
1093
+ startTimestamp: getEventTimestamp(event),
922
1094
  provider: event.provider,
923
1095
  modelId: event.modelId,
924
1096
  };
925
1097
 
926
1098
  const inferenceAttributes = selectAttributes(telemetry, {
927
1099
  'gen_ai.operation.name': 'chat',
1100
+ ...(state.liveDurableContext ? state.baseSupplementalAttributes : {}),
928
1101
  'gen_ai.provider.name': providerName,
929
1102
  'gen_ai.request.model': event.modelId,
930
1103
  'gen_ai.request.frequency_penalty': state.settings.frequencyPenalty as
@@ -964,24 +1137,29 @@ export class OpenTelemetry implements Telemetry {
964
1137
  },
965
1138
  },
966
1139
  'gen_ai.tool.definitions': {
967
- input: () => (event.tools ? JSON.stringify(event.tools) : undefined),
1140
+ input: () =>
1141
+ toolDefinitions ? JSON.stringify(toolDefinitions) : undefined,
968
1142
  },
969
1143
  });
970
1144
 
971
- state.inferenceSpan = this.tracer.startSpan(
972
- `chat ${event.modelId}`,
973
- {
974
- attributes: this.getSpanAttributes({
975
- attributes: inferenceAttributes,
976
- spanType: 'languageModel',
977
- operationId: state.operationId,
978
- callId: event.callId,
979
- runtimeContext: state.runtimeContext,
980
- }),
981
- kind: SpanKind.CLIENT,
982
- },
983
- state.stepContext,
984
- );
1145
+ const inferenceSpanAttributes = this.getSpanAttributes({
1146
+ attributes: inferenceAttributes,
1147
+ spanType: 'languageModel',
1148
+ operationId: state.operationId,
1149
+ callId: event.callId,
1150
+ runtimeContext: state.runtimeContext,
1151
+ });
1152
+ const startInferenceSpan = () =>
1153
+ this.tracer.startSpan(
1154
+ `chat ${event.modelId}`,
1155
+ {
1156
+ attributes: inferenceSpanAttributes,
1157
+ kind: SpanKind.CLIENT,
1158
+ startTime: getEventTime(event),
1159
+ },
1160
+ state.stepContext,
1161
+ );
1162
+ state.inferenceSpan = this.withDurableSampling(state, startInferenceSpan);
985
1163
  state.inferenceContext = trace.setSpan(
986
1164
  state.stepContext,
987
1165
  state.inferenceSpan,
@@ -990,13 +1168,14 @@ export class OpenTelemetry implements Telemetry {
990
1168
 
991
1169
  onLanguageModelCallEnd(event: LanguageModelCallEndEvent<ToolSet>): void {
992
1170
  const state = this.getCallState(event.callId);
993
- if (!state?.inferenceSpan) return;
1171
+ if (state?.durableContext || !state?.inferenceSpan) return;
994
1172
 
995
1173
  this.recordInferenceDuration(state, {
996
1174
  responseTimeMs: event.performance.responseTimeMs,
997
1175
  provider: event.provider,
998
1176
  responseModelId: event.modelId,
999
1177
  errorType: event.finishReason === 'error' ? '_OTHER' : undefined,
1178
+ endTimestamp: getEventTimestamp(event),
1000
1179
  });
1001
1180
 
1002
1181
  if (event.finishReason === 'error') {
@@ -1033,6 +1212,7 @@ export class OpenTelemetry implements Telemetry {
1033
1212
  state.inferenceSpan.setAttributes(
1034
1213
  selectAttributes(telemetry, {
1035
1214
  ...getGenAIClientPerformanceAttributes(event.performance),
1215
+ ...getServerAttributes(event.request?.url),
1036
1216
  'gen_ai.provider.name': providerName,
1037
1217
  'gen_ai.response.finish_reasons': [event.finishReason],
1038
1218
  'gen_ai.response.id': event.responseId,
@@ -1100,6 +1280,7 @@ export class OpenTelemetry implements Telemetry {
1100
1280
  }
1101
1281
  }
1102
1282
 
1283
+ const endTime = getEventTime(event);
1103
1284
  const recordedToolCallIds = new Set<string>();
1104
1285
  for (const part of event.content) {
1105
1286
  if (
@@ -1111,27 +1292,31 @@ export class OpenTelemetry implements Telemetry {
1111
1292
  }
1112
1293
  recordedToolCallIds.add(part.toolCallId);
1113
1294
 
1114
- const toolSpan = this.tracer.startSpan(
1115
- `execute_tool ${part.toolName}`,
1116
- {
1117
- attributes: this.getSpanAttributes({
1118
- attributes: selectAttributes(telemetry, {
1119
- 'gen_ai.operation.name': 'execute_tool',
1120
- 'gen_ai.tool.name': part.toolName,
1121
- 'gen_ai.tool.call.id': part.toolCallId,
1122
- 'gen_ai.tool.type': 'extension',
1123
- 'gen_ai.tool.call.arguments': {
1124
- input: () => JSON.stringify(part.input),
1125
- },
1126
- }),
1127
- spanType: 'tool',
1128
- operationId: state.operationId,
1129
- callId: event.callId,
1130
- runtimeContext: state.runtimeContext,
1295
+ const toolSpanOptions = {
1296
+ attributes: this.getSpanAttributes({
1297
+ attributes: selectAttributes(telemetry, {
1298
+ 'gen_ai.operation.name': 'execute_tool',
1299
+ 'gen_ai.tool.name': part.toolName,
1300
+ 'gen_ai.tool.call.id': part.toolCallId,
1301
+ 'gen_ai.tool.type': 'extension',
1302
+ 'gen_ai.tool.call.arguments': {
1303
+ input: () => JSON.stringify(part.input),
1304
+ },
1131
1305
  }),
1132
- kind: SpanKind.INTERNAL,
1133
- },
1134
- state.inferenceContext,
1306
+ spanType: 'tool',
1307
+ operationId: state.operationId,
1308
+ callId: event.callId,
1309
+ runtimeContext: state.runtimeContext,
1310
+ }),
1311
+ kind: SpanKind.INTERNAL,
1312
+ startTime: endTime,
1313
+ };
1314
+ const toolSpan = this.withDurableSampling(state, () =>
1315
+ this.tracer.startSpan(
1316
+ `execute_tool ${part.toolName}`,
1317
+ toolSpanOptions,
1318
+ state.inferenceContext,
1319
+ ),
1135
1320
  );
1136
1321
 
1137
1322
  const toolOutput = finalToolOutputs.get(part.toolCallId);
@@ -1151,13 +1336,121 @@ export class OpenTelemetry implements Telemetry {
1151
1336
  recordErrorOnSpan(toolSpan, toolOutput.error);
1152
1337
  }
1153
1338
 
1154
- toolSpan.end();
1339
+ toolSpan.end(endTime);
1155
1340
  }
1156
1341
 
1157
- state.inferenceSpan.end();
1342
+ state.inferenceSpan.end(endTime);
1158
1343
  state.inferenceSpan = undefined;
1159
1344
  state.inferenceContext = undefined;
1160
1345
  state.inferenceToolDefinitions = undefined;
1346
+
1347
+ if (state.liveDurableContext) {
1348
+ this.cleanupCallState(event.callId);
1349
+ }
1350
+ }
1351
+
1352
+ /**
1353
+ * Starts a model call reported live from a durable step. The run's root and
1354
+ * step spans are reported when the run ends, so the model call is parented
1355
+ * to the step span's derived ID.
1356
+ */
1357
+ private startDurableModelCall(
1358
+ event: InferTelemetryEvent<LanguageModelCallStartEvent>,
1359
+ ): CallState | undefined {
1360
+ const durable = event.durableContext;
1361
+ if (
1362
+ durable?.phase !== 'live' ||
1363
+ durable.stepNumber == null ||
1364
+ this.durable == null
1365
+ )
1366
+ return undefined;
1367
+ const run = durable.run;
1368
+ const stepContext = trace.setSpanContext(context.active(), {
1369
+ traceId: run.traceId,
1370
+ spanId: deriveSpanId(event.callId, 'step', durable.stepNumber),
1371
+ traceFlags: run.traceFlags,
1372
+ traceState:
1373
+ run.traceState == null ? undefined : createTraceState(run.traceState),
1374
+ isRemote: true,
1375
+ });
1376
+ const telemetryEvent =
1377
+ event as InferTelemetryEvent<LanguageModelCallStartEvent>;
1378
+ const state: CallState = {
1379
+ operationId: 'ai.workflowAgent.stream',
1380
+ telemetry: {
1381
+ recordInputs: telemetryEvent.recordInputs,
1382
+ recordOutputs: telemetryEvent.recordOutputs,
1383
+ functionId: telemetryEvent.functionId,
1384
+ },
1385
+ rootSpan: undefined,
1386
+ rootContext: undefined,
1387
+ stepSpan: undefined,
1388
+ stepContext,
1389
+ inferenceSpan: undefined,
1390
+ inferenceContext: undefined,
1391
+ embedSpans: new Map(),
1392
+ rerankSpan: undefined,
1393
+ decisionSpan: undefined,
1394
+ toolSpans: new Map(),
1395
+ settings: {
1396
+ maxOutputTokens: event.maxOutputTokens,
1397
+ temperature: event.temperature,
1398
+ topP: event.topP,
1399
+ topK: event.topK,
1400
+ presencePenalty: event.presencePenalty,
1401
+ frequencyPenalty: event.frequencyPenalty,
1402
+ stopSequences: event.stopSequences,
1403
+ seed: event.seed,
1404
+ },
1405
+ provider: event.provider,
1406
+ modelId: event.modelId,
1407
+ runtimeContext: durable.runtimeContext,
1408
+ baseSupplementalAttributes: selectSupplementalAttributes(
1409
+ {
1410
+ recordInputs: telemetryEvent.recordInputs,
1411
+ recordOutputs: telemetryEvent.recordOutputs,
1412
+ },
1413
+ this.supplementalAttributes,
1414
+ {
1415
+ runtimeContext: getRuntimeContextAttributes(durable.runtimeContext),
1416
+ headers: getHeaderAttributes(durable.headers),
1417
+ },
1418
+ ),
1419
+ liveDurableContext: run,
1420
+ };
1421
+ this.callStates.set(event.callId, state);
1422
+ return state;
1423
+ }
1424
+
1425
+ /**
1426
+ * Ends a model call reported live from a durable step that failed or was
1427
+ * aborted before its end event.
1428
+ */
1429
+ private endDurableModelCall(
1430
+ callId: string,
1431
+ {
1432
+ error,
1433
+ errorType,
1434
+ endTimestamp,
1435
+ }: {
1436
+ error?: unknown;
1437
+ errorType: string;
1438
+ endTimestamp: number | undefined;
1439
+ },
1440
+ ): void {
1441
+ const state = this.getCallState(callId);
1442
+ if (!state?.liveDurableContext) return;
1443
+
1444
+ this.recordInferenceDuration(state, { errorType, endTimestamp });
1445
+ if (state.inferenceSpan) {
1446
+ if (error !== undefined) {
1447
+ recordErrorOnSpan(state.inferenceSpan, error);
1448
+ }
1449
+ state.inferenceSpan.end(
1450
+ endTimestamp == null ? undefined : new Date(endTimestamp),
1451
+ );
1452
+ }
1453
+ this.cleanupCallState(callId);
1161
1454
  }
1162
1455
 
1163
1456
  onToolExecutionStart(event: ToolExecutionStartEvent<ToolSet>): void {
@@ -1179,19 +1472,19 @@ export class OpenTelemetry implements Telemetry {
1179
1472
  });
1180
1473
 
1181
1474
  const spanName = `execute_tool ${toolCall.toolName}`;
1182
- const toolSpan = this.tracer.startSpan(
1183
- spanName,
1184
- {
1185
- attributes: this.getSpanAttributes({
1186
- attributes,
1187
- spanType: 'tool',
1188
- operationId: state.operationId,
1189
- callId: event.callId,
1190
- runtimeContext: state.runtimeContext,
1191
- }),
1192
- kind: SpanKind.INTERNAL,
1193
- },
1194
- parentContext,
1475
+ const toolSpanOptions = {
1476
+ attributes: this.getSpanAttributes({
1477
+ attributes,
1478
+ spanType: 'tool',
1479
+ operationId: state.operationId,
1480
+ callId: event.callId,
1481
+ runtimeContext: state.runtimeContext,
1482
+ }),
1483
+ kind: SpanKind.INTERNAL,
1484
+ startTime: getEventTime(event),
1485
+ };
1486
+ const toolSpan = this.withDurableSampling(state, () =>
1487
+ this.tracer.startSpan(spanName, toolSpanOptions, parentContext),
1195
1488
  );
1196
1489
  const toolContext = trace.setSpan(parentContext, toolSpan);
1197
1490
 
@@ -1234,7 +1527,7 @@ export class OpenTelemetry implements Telemetry {
1234
1527
  recordErrorOnSpan(span, toolOutput.error);
1235
1528
  }
1236
1529
 
1237
- span.end();
1530
+ span.end(getEventTime(event));
1238
1531
  state.toolSpans.delete(event.toolCall.toolCallId);
1239
1532
  }
1240
1533
 
@@ -1245,6 +1538,7 @@ export class OpenTelemetry implements Telemetry {
1245
1538
  // Streams can close after an error chunk without a model-call end event.
1246
1539
  this.recordInferenceDuration(state, {
1247
1540
  errorType: event.finishReason === 'error' ? '_OTHER' : undefined,
1541
+ endTimestamp: getEventTimestamp(event),
1248
1542
  });
1249
1543
 
1250
1544
  if (event.finishReason === 'error') {
@@ -1264,7 +1558,7 @@ export class OpenTelemetry implements Telemetry {
1264
1558
  }),
1265
1559
  );
1266
1560
 
1267
- state.stepSpan.end();
1561
+ state.stepSpan.end(getEventTime(event));
1268
1562
  state.stepSpan = undefined;
1269
1563
  state.stepContext = undefined;
1270
1564
  }
@@ -1280,17 +1574,18 @@ export class OpenTelemetry implements Telemetry {
1280
1574
 
1281
1575
  this.recordInferenceDuration(state, {
1282
1576
  errorType: event.error instanceof Error ? event.error.name : '_OTHER',
1577
+ endTimestamp: getEventTimestamp(event),
1283
1578
  });
1284
1579
 
1285
1580
  if (state.inferenceSpan) {
1286
1581
  recordErrorOnSpan(state.inferenceSpan, event.error);
1287
- state.inferenceSpan.end();
1582
+ state.inferenceSpan.end(getEventTime(event));
1288
1583
  state.inferenceSpan = undefined;
1289
1584
  state.inferenceContext = undefined;
1290
1585
  }
1291
1586
 
1292
1587
  recordErrorOnSpan(state.stepSpan, event.error);
1293
- state.stepSpan.end();
1588
+ state.stepSpan.end(getEventTime(event));
1294
1589
  state.stepSpan = undefined;
1295
1590
  state.stepContext = undefined;
1296
1591
  }
@@ -1474,7 +1769,7 @@ export class OpenTelemetry implements Telemetry {
1474
1769
  }),
1475
1770
  );
1476
1771
 
1477
- state.rootSpan.end();
1772
+ state.rootSpan.end(getEventTime(event));
1478
1773
  this.cleanupCallState(event.callId);
1479
1774
  }
1480
1775
 
@@ -1981,43 +2276,55 @@ export class OpenTelemetry implements Telemetry {
1981
2276
 
1982
2277
  onAbort(event: GenerateTextAbortEvent<ToolSet>): void {
1983
2278
  const state = this.getCallState(event.callId);
2279
+ if (state?.liveDurableContext) {
2280
+ this.endDurableModelCall(event.callId, {
2281
+ errorType: 'AbortError',
2282
+ endTimestamp: getEventTimestamp(event),
2283
+ });
2284
+ return;
2285
+ }
1984
2286
  if (!state?.rootSpan) return;
1985
2287
 
1986
- this.recordInferenceDuration(state, { errorType: 'AbortError' });
2288
+ const endTime = getEventTime(event);
2289
+
2290
+ this.recordInferenceDuration(state, {
2291
+ errorType: 'AbortError',
2292
+ endTimestamp: getEventTimestamp(event),
2293
+ });
1987
2294
 
1988
2295
  for (const { span: toolSpan } of state.toolSpans.values()) {
1989
- toolSpan.end();
2296
+ toolSpan.end(endTime);
1990
2297
  }
1991
2298
  state.toolSpans.clear();
1992
2299
 
1993
2300
  if (state.inferenceSpan) {
1994
- state.inferenceSpan.end();
2301
+ state.inferenceSpan.end(endTime);
1995
2302
  state.inferenceSpan = undefined;
1996
2303
  state.inferenceContext = undefined;
1997
2304
  }
1998
2305
 
1999
2306
  if (state.stepSpan) {
2000
- state.stepSpan.end();
2307
+ state.stepSpan.end(endTime);
2001
2308
  state.stepSpan = undefined;
2002
2309
  state.stepContext = undefined;
2003
2310
  }
2004
2311
 
2005
2312
  for (const { span: embedSpan } of state.embedSpans.values()) {
2006
- embedSpan.end();
2313
+ embedSpan.end(endTime);
2007
2314
  }
2008
2315
  state.embedSpans.clear();
2009
2316
 
2010
2317
  if (state.rerankSpan) {
2011
- state.rerankSpan.span.end();
2318
+ state.rerankSpan.span.end(endTime);
2012
2319
  state.rerankSpan = undefined;
2013
2320
  }
2014
2321
 
2015
2322
  if (state.decisionSpan) {
2016
- state.decisionSpan.span.end();
2323
+ state.decisionSpan.span.end(endTime);
2017
2324
  state.decisionSpan = undefined;
2018
2325
  }
2019
2326
 
2020
- state.rootSpan.end();
2327
+ state.rootSpan.end(endTime);
2021
2328
  this.cleanupCallState(event.callId);
2022
2329
  }
2023
2330
 
@@ -2026,55 +2333,65 @@ export class OpenTelemetry implements Telemetry {
2026
2333
  if (!event?.callId) return;
2027
2334
 
2028
2335
  const state = this.getCallState(event.callId);
2336
+ const actualError = event.error ?? error;
2337
+ if (state?.liveDurableContext) {
2338
+ this.endDurableModelCall(event.callId, {
2339
+ error: actualError,
2340
+ errorType: actualError instanceof Error ? actualError.name : '_OTHER',
2341
+ endTimestamp: getEventTimestamp(event),
2342
+ });
2343
+ return;
2344
+ }
2029
2345
  if (!state?.rootSpan) return;
2030
2346
 
2031
- const actualError = event.error ?? error;
2347
+ const endTime = getEventTime(event);
2032
2348
 
2033
2349
  this.recordInferenceDuration(state, {
2034
2350
  errorType: actualError instanceof Error ? actualError.name : '_OTHER',
2351
+ endTimestamp: getEventTimestamp(event),
2035
2352
  });
2036
2353
 
2037
2354
  for (const { span: toolSpan } of state.toolSpans.values()) {
2038
2355
  recordErrorOnSpan(toolSpan, actualError);
2039
- toolSpan.end();
2356
+ toolSpan.end(endTime);
2040
2357
  }
2041
2358
  state.toolSpans.clear();
2042
2359
 
2043
2360
  if (state.inferenceSpan) {
2044
2361
  recordErrorOnSpan(state.inferenceSpan, actualError);
2045
- state.inferenceSpan.end();
2362
+ state.inferenceSpan.end(endTime);
2046
2363
  state.inferenceSpan = undefined;
2047
2364
  state.inferenceContext = undefined;
2048
2365
  }
2049
2366
 
2050
2367
  if (state.stepSpan) {
2051
2368
  recordErrorOnSpan(state.stepSpan, actualError);
2052
- state.stepSpan.end();
2369
+ state.stepSpan.end(endTime);
2053
2370
  state.stepSpan = undefined;
2054
2371
  state.stepContext = undefined;
2055
2372
  }
2056
2373
 
2057
2374
  for (const { span: embedSpan } of state.embedSpans.values()) {
2058
2375
  recordErrorOnSpan(embedSpan, actualError);
2059
- embedSpan.end();
2376
+ embedSpan.end(endTime);
2060
2377
  }
2061
2378
  state.embedSpans.clear();
2062
2379
 
2063
2380
  if (state.rerankSpan) {
2064
2381
  recordErrorOnSpan(state.rerankSpan.span, actualError);
2065
- state.rerankSpan.span.end();
2382
+ state.rerankSpan.span.end(endTime);
2066
2383
  state.rerankSpan = undefined;
2067
2384
  }
2068
2385
 
2069
2386
  if (state.decisionSpan) {
2070
2387
  recordErrorOnSpan(state.decisionSpan.span, actualError);
2071
- state.decisionSpan.span.end();
2388
+ state.decisionSpan.span.end(endTime);
2072
2389
  state.decisionSpan = undefined;
2073
2390
  }
2074
2391
 
2075
2392
  recordErrorOnSpan(state.rootSpan, actualError);
2076
2393
 
2077
- state.rootSpan.end();
2394
+ state.rootSpan.end(endTime);
2078
2395
  this.cleanupCallState(event.callId);
2079
2396
  }
2080
2397
  }