@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.
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",
@@ -502,6 +607,47 @@ function recordErrorOnSpan(span, error) {
502
607
  } else span.setStatus({ code: SpanStatusCode.ERROR });
503
608
  }
504
609
  //#endregion
610
+ //#region src/redact-tool-definition.ts
611
+ /** Remove provider credentials from a telemetry-only copy of a tool definition. */
612
+ function redactToolDefinition(tool) {
613
+ if (tool.type !== "provider") return tool;
614
+ const args = tool.args;
615
+ if (!isRecord(args)) return tool;
616
+ if (tool.id === "openai.mcp") return {
617
+ ...tool,
618
+ args: {
619
+ ...args,
620
+ ...args.authorization != null ? { authorization: "[redacted]" } : {},
621
+ ...isRecord(args.headers) ? { headers: Object.fromEntries(Object.keys(args.headers).map((name) => [name, "[redacted]"])) } : {}
622
+ }
623
+ };
624
+ const containerKey = tool.id === "openai.code_interpreter" ? "container" : tool.id === "openai.shell" ? "environment" : void 0;
625
+ if (containerKey == null) return tool;
626
+ const container = args[containerKey];
627
+ if (!isRecord(container)) return tool;
628
+ const networkPolicy = container.networkPolicy;
629
+ if (!isRecord(networkPolicy) || !Array.isArray(networkPolicy.domainSecrets)) return tool;
630
+ return {
631
+ ...tool,
632
+ args: {
633
+ ...args,
634
+ [containerKey]: {
635
+ ...container,
636
+ networkPolicy: {
637
+ ...networkPolicy,
638
+ domainSecrets: networkPolicy.domainSecrets.map((secret) => isRecord(secret) && "value" in secret ? {
639
+ ...secret,
640
+ value: "[redacted]"
641
+ } : secret)
642
+ }
643
+ }
644
+ }
645
+ };
646
+ }
647
+ function isRecord(value) {
648
+ return value != null && typeof value === "object" && !Array.isArray(value);
649
+ }
650
+ //#endregion
505
651
  //#region src/provider-usage-attributes.ts
506
652
  const usageKeyAliases = {
507
653
  inputtokens: "input_tokens",
@@ -544,6 +690,22 @@ function getProviderUsageAttributes({ usage, prefix }) {
544
690
  return attributes;
545
691
  }
546
692
  //#endregion
693
+ //#region src/server-attributes.ts
694
+ /** Only record the known transport destination, never infer a provider backend. */
695
+ function getServerAttributes(url) {
696
+ if (url == null) return {};
697
+ try {
698
+ const endpoint = new URL(url);
699
+ if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") return {};
700
+ return {
701
+ "server.address": endpoint.hostname.replace(/^\[|\]$/g, ""),
702
+ "server.port": endpoint.port !== "" ? Number(endpoint.port) : endpoint.protocol === "https:" ? 443 : 80
703
+ };
704
+ } catch {
705
+ return {};
706
+ }
707
+ }
708
+ //#endregion
547
709
  //#region src/sanitize-attribute-value.ts
548
710
  function isPrimitiveAttributeValue(value) {
549
711
  return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
@@ -669,6 +831,19 @@ function selectSupplementalAttributes(telemetry, enabledAttributes, attributes)
669
831
  }
670
832
  //#endregion
671
833
  //#region src/open-telemetry.ts
834
+ /**
835
+ * Returns the time an event occurred when it is reported after the fact.
836
+ * A `Date` is used because OpenTelemetry treats numbers smaller than the
837
+ * process time origin as `performance.now()` values.
838
+ */
839
+ function getEventTime(event) {
840
+ const timestamp = getEventTimestamp(event);
841
+ return timestamp == null ? void 0 : new Date(timestamp);
842
+ }
843
+ function getEventTimestamp(event) {
844
+ const timestamp = event != null && typeof event === "object" && "timestamp" in event ? event.timestamp : void 0;
845
+ return typeof timestamp === "number" ? timestamp : void 0;
846
+ }
672
847
  function msToSeconds(durationMs) {
673
848
  return durationMs == null ? void 0 : durationMs / 1e3;
674
849
  }
@@ -682,21 +857,38 @@ function getGenAIClientPerformanceAttributes(performance) {
682
857
  var OpenTelemetry = class {
683
858
  constructor(options = {}) {
684
859
  this.callStates = /* @__PURE__ */ new Map();
860
+ this.experimental_durable = { captureContext: (event) => {
861
+ if (this.durable == null) return void 0;
862
+ const { spanName, rootSpanOptions } = this.prepareGenerateStart(event);
863
+ return {
864
+ ...this.durable.captureContext(event.callId, spanName, SpanKind.INTERNAL, rootSpanOptions.attributes),
865
+ rootSpanName: spanName
866
+ };
867
+ } };
685
868
  this.tracer = options.tracer ?? trace.getTracer("gen_ai");
869
+ this.durable = options.durable;
686
870
  this.agentSpanName = options.agentSpanName;
687
871
  this.supplementalAttributes = normalizeSupplementalAttributes(options);
688
872
  this.enrichSpan = options.enrichSpan;
689
873
  }
874
+ withDurableSampling(state, startSpan) {
875
+ const run = state.durableContext ?? state.liveDurableContext;
876
+ return run != null && this.durable != null ? this.durable.withIds({
877
+ samplingDecision: run.samplingDecision,
878
+ traceState: run.traceState
879
+ }, startSpan) : startSpan();
880
+ }
690
881
  getCallState(callId) {
691
882
  return this.callStates.get(callId);
692
883
  }
693
884
  cleanupCallState(callId) {
694
885
  this.callStates.delete(callId);
695
886
  }
696
- recordInferenceDuration(state, { responseTimeMs, provider, responseModelId, errorType } = {}) {
887
+ recordInferenceDuration(state, { responseTimeMs, provider, responseModelId, errorType, endTimestamp } = {}) {
697
888
  const inference = state.inferenceMetrics;
698
889
  if (inference == null) return;
699
890
  state.inferenceMetrics = void 0;
891
+ const durationMs = responseTimeMs ?? (inference.startTimestamp != null && endTimestamp != null ? Math.max(0, endTimestamp - inference.startTimestamp) : performance.now() - inference.startTime);
700
892
  metrics.getMeter("gen_ai").createHistogram("gen_ai.client.inference.duration", {
701
893
  description: "GenAI client inference operation duration.",
702
894
  unit: "s",
@@ -716,7 +908,7 @@ var OpenTelemetry = class {
716
908
  40.96,
717
909
  81.92
718
910
  ] }
719
- }).record((responseTimeMs ?? performance.now() - inference.startTime) / 1e3, selectAttributes$1(state.telemetry, {
911
+ }).record(durationMs / 1e3, selectAttributes$1(state.telemetry, {
720
912
  "gen_ai.operation.name": "chat",
721
913
  "gen_ai.provider.name": mapProviderName(provider ?? inference.provider),
722
914
  "gen_ai.request.model": inference.modelId,
@@ -857,7 +1049,7 @@ var OpenTelemetry = class {
857
1049
  baseSupplementalAttributes
858
1050
  });
859
1051
  }
860
- onGenerateStart(event) {
1052
+ prepareGenerateStart(event) {
861
1053
  const telemetry = {
862
1054
  recordInputs: event.recordInputs,
863
1055
  recordOutputs: event.recordOutputs,
@@ -901,22 +1093,51 @@ var OpenTelemetry = class {
901
1093
  })) },
902
1094
  ...baseSupplementalAttributes
903
1095
  });
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
1096
+ return {
1097
+ spanName: event.durableContext?.run.rootSpanName ?? this.getAgentSpanName({
1098
+ operationName,
1099
+ modelId: event.modelId,
1100
+ functionId: telemetry.functionId
916
1101
  }),
917
- kind: SpanKind.INTERNAL
918
- });
919
- const rootContext = trace.setSpan(context.active(), rootSpan);
1102
+ rootSpanOptions: {
1103
+ attributes: event.durableContext?.run.rootAttributes ?? this.getSpanAttributes({
1104
+ attributes,
1105
+ spanType: "operation",
1106
+ operationId: event.operationId,
1107
+ callId: event.callId,
1108
+ runtimeContext
1109
+ }),
1110
+ kind: SpanKind.INTERNAL,
1111
+ startTime: getEventTime(event)
1112
+ },
1113
+ telemetry,
1114
+ settings,
1115
+ runtimeContext,
1116
+ baseSupplementalAttributes
1117
+ };
1118
+ }
1119
+ onGenerateStart(event) {
1120
+ const { spanName, rootSpanOptions, telemetry, settings, runtimeContext, baseSupplementalAttributes } = this.prepareGenerateStart(event);
1121
+ const run = event.durableContext?.run;
1122
+ let parentContext = context.active();
1123
+ let rootSpan;
1124
+ if (run != null && this.durable != null) {
1125
+ parentContext = trace.deleteSpan(parentContext);
1126
+ if (run.parentSpanContext != null) parentContext = trace.setSpanContext(parentContext, {
1127
+ ...run.parentSpanContext,
1128
+ traceState: run.parentSpanContext.traceState == null ? void 0 : createTraceState(run.parentSpanContext.traceState),
1129
+ isRemote: true
1130
+ });
1131
+ rootSpan = this.durable.withIds({
1132
+ traceId: run.traceId,
1133
+ spanId: run.rootSpanId,
1134
+ samplingDecision: run.samplingDecision,
1135
+ traceState: run.traceState
1136
+ }, () => this.tracer.startSpan(spanName, rootSpanOptions, parentContext));
1137
+ } else rootSpan = this.tracer.startSpan(spanName, rootSpanOptions);
1138
+ const actual = rootSpan.spanContext();
1139
+ const durableContext = run != null && actual.traceId === run.traceId && actual.spanId === run.rootSpanId ? run : void 0;
1140
+ const rootContext = trace.setSpan(parentContext, rootSpan);
920
1141
  this.callStates.set(event.callId, {
921
1142
  operationId: event.operationId,
922
1143
  telemetry,
@@ -934,7 +1155,8 @@ var OpenTelemetry = class {
934
1155
  provider: event.provider,
935
1156
  modelId: event.modelId,
936
1157
  runtimeContext,
937
- baseSupplementalAttributes
1158
+ baseSupplementalAttributes,
1159
+ durableContext
938
1160
  });
939
1161
  }
940
1162
  onObjectOperationStart(event) {
@@ -1062,6 +1284,7 @@ var OpenTelemetry = class {
1062
1284
  if (event.finishReason === "error") state.inferenceSpan.setStatus({ code: SpanStatusCode.ERROR });
1063
1285
  const { telemetry } = state;
1064
1286
  state.inferenceSpan.setAttributes(selectAttributes$1(telemetry, {
1287
+ ...getServerAttributes(event.request.url),
1065
1288
  "gen_ai.response.finish_reasons": [event.finishReason],
1066
1289
  "gen_ai.response.id": event.response.id,
1067
1290
  "gen_ai.response.model": event.response.modelId,
@@ -1151,7 +1374,8 @@ var OpenTelemetry = class {
1151
1374
  ...state.baseSupplementalAttributes,
1152
1375
  ...selectSupplementalAttributes(telemetry, this.supplementalAttributes, { toolChoice: { "ai.prompt.toolChoice": { input: () => event.stepToolChoice != null ? JSON.stringify(event.stepToolChoice) : void 0 } } })
1153
1376
  });
1154
- state.stepSpan = this.tracer.startSpan(`step ${event.steps.length + 1}`, {
1377
+ const rootContext = state.rootContext;
1378
+ const options = {
1155
1379
  attributes: this.getSpanAttributes({
1156
1380
  attributes: stepAttributes,
1157
1381
  spanType: "step",
@@ -1159,24 +1383,45 @@ var OpenTelemetry = class {
1159
1383
  callId: event.callId,
1160
1384
  runtimeContext: state.runtimeContext
1161
1385
  }),
1162
- kind: SpanKind.INTERNAL
1163
- }, state.rootContext);
1164
- state.stepContext = trace.setSpan(state.rootContext, state.stepSpan);
1386
+ kind: SpanKind.INTERNAL,
1387
+ startTime: getEventTime(event)
1388
+ };
1389
+ const startStepSpan = () => this.tracer.startSpan(`step ${event.steps.length + 1}`, options, rootContext);
1390
+ state.stepSpan = state.durableContext != null && this.durable != null ? this.durable.withIds({
1391
+ spanId: deriveSpanId(event.callId, "step", event.stepNumber),
1392
+ samplingDecision: state.durableContext.samplingDecision,
1393
+ traceState: state.durableContext.traceState
1394
+ }, startStepSpan) : startStepSpan();
1395
+ state.stepContext = trace.setSpan(rootContext, state.stepSpan);
1165
1396
  }
1166
1397
  onLanguageModelCallStart(event) {
1167
- const state = this.getCallState(event.callId);
1398
+ const existingState = this.getCallState(event.callId);
1399
+ if (existingState?.durableContext) return;
1400
+ const state = existingState ?? this.startDurableModelCall(event);
1168
1401
  if (!state?.stepContext) return;
1169
- this.recordInferenceDuration(state, { errorType: "_OTHER" });
1402
+ if (state.liveDurableContext && state.inferenceSpan != null) {
1403
+ state.inferenceSpan.setStatus({ code: SpanStatusCode.ERROR });
1404
+ state.inferenceSpan.end(getEventTime(event));
1405
+ state.inferenceSpan = void 0;
1406
+ state.inferenceContext = void 0;
1407
+ }
1408
+ this.recordInferenceDuration(state, {
1409
+ errorType: "_OTHER",
1410
+ endTimestamp: getEventTimestamp(event)
1411
+ });
1170
1412
  const { telemetry } = state;
1171
1413
  const providerName = mapProviderName(event.provider);
1172
- state.inferenceToolDefinitions = event.tools;
1414
+ const toolDefinitions = event.tools?.map(redactToolDefinition);
1415
+ state.inferenceToolDefinitions = toolDefinitions;
1173
1416
  state.inferenceMetrics = {
1174
1417
  startTime: performance.now(),
1418
+ startTimestamp: getEventTimestamp(event),
1175
1419
  provider: event.provider,
1176
1420
  modelId: event.modelId
1177
1421
  };
1178
1422
  const inferenceAttributes = selectAttributes$1(telemetry, {
1179
1423
  "gen_ai.operation.name": "chat",
1424
+ ...state.liveDurableContext ? state.baseSupplementalAttributes : {},
1180
1425
  "gen_ai.provider.name": providerName,
1181
1426
  "gen_ai.request.model": event.modelId,
1182
1427
  "gen_ai.request.frequency_penalty": state.settings.frequencyPenalty,
@@ -1194,28 +1439,32 @@ var OpenTelemetry = class {
1194
1439
  });
1195
1440
  return formattedMessages.length > 0 ? JSON.stringify(formattedMessages) : void 0;
1196
1441
  } },
1197
- "gen_ai.tool.definitions": { input: () => event.tools ? JSON.stringify(event.tools) : void 0 }
1198
- });
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
1442
+ "gen_ai.tool.definitions": { input: () => toolDefinitions ? JSON.stringify(toolDefinitions) : void 0 }
1443
+ });
1444
+ const inferenceSpanAttributes = this.getSpanAttributes({
1445
+ attributes: inferenceAttributes,
1446
+ spanType: "languageModel",
1447
+ operationId: state.operationId,
1448
+ callId: event.callId,
1449
+ runtimeContext: state.runtimeContext
1450
+ });
1451
+ const startInferenceSpan = () => this.tracer.startSpan(`chat ${event.modelId}`, {
1452
+ attributes: inferenceSpanAttributes,
1453
+ kind: SpanKind.CLIENT,
1454
+ startTime: getEventTime(event)
1208
1455
  }, state.stepContext);
1456
+ state.inferenceSpan = this.withDurableSampling(state, startInferenceSpan);
1209
1457
  state.inferenceContext = trace.setSpan(state.stepContext, state.inferenceSpan);
1210
1458
  }
1211
1459
  onLanguageModelCallEnd(event) {
1212
1460
  const state = this.getCallState(event.callId);
1213
- if (!state?.inferenceSpan) return;
1461
+ if (state?.durableContext || !state?.inferenceSpan) return;
1214
1462
  this.recordInferenceDuration(state, {
1215
1463
  responseTimeMs: event.performance.responseTimeMs,
1216
1464
  provider: event.provider,
1217
1465
  responseModelId: event.modelId,
1218
- errorType: event.finishReason === "error" ? "_OTHER" : void 0
1466
+ errorType: event.finishReason === "error" ? "_OTHER" : void 0,
1467
+ endTimestamp: getEventTimestamp(event)
1219
1468
  });
1220
1469
  if (event.finishReason === "error") state.inferenceSpan.setStatus({ code: SpanStatusCode.ERROR });
1221
1470
  const { telemetry } = state;
@@ -1234,6 +1483,7 @@ var OpenTelemetry = class {
1234
1483
  }
1235
1484
  state.inferenceSpan.setAttributes(selectAttributes$1(telemetry, {
1236
1485
  ...getGenAIClientPerformanceAttributes(event.performance),
1486
+ ...getServerAttributes(event.request?.url),
1237
1487
  "gen_ai.provider.name": providerName,
1238
1488
  "gen_ai.response.finish_reasons": [event.finishReason],
1239
1489
  "gen_ai.response.id": event.responseId,
@@ -1258,11 +1508,12 @@ var OpenTelemetry = class {
1258
1508
  }));
1259
1509
  const finalToolOutputs = /* @__PURE__ */ new Map();
1260
1510
  for (const part of event.content) if (part.type === "tool-error" || part.type === "tool-result" && part.preliminary !== true) finalToolOutputs.set(part.toolCallId, part);
1511
+ const endTime = getEventTime(event);
1261
1512
  const recordedToolCallIds = /* @__PURE__ */ new Set();
1262
1513
  for (const part of event.content) {
1263
1514
  if (part.type !== "tool-call" || !part.providerExecuted || recordedToolCallIds.has(part.toolCallId)) continue;
1264
1515
  recordedToolCallIds.add(part.toolCallId);
1265
- const toolSpan = this.tracer.startSpan(`execute_tool ${part.toolName}`, {
1516
+ const toolSpanOptions = {
1266
1517
  attributes: this.getSpanAttributes({
1267
1518
  attributes: selectAttributes$1(telemetry, {
1268
1519
  "gen_ai.operation.name": "execute_tool",
@@ -1276,19 +1527,98 @@ var OpenTelemetry = class {
1276
1527
  callId: event.callId,
1277
1528
  runtimeContext: state.runtimeContext
1278
1529
  }),
1279
- kind: SpanKind.INTERNAL
1280
- }, state.inferenceContext);
1530
+ kind: SpanKind.INTERNAL,
1531
+ startTime: endTime
1532
+ };
1533
+ const toolSpan = this.withDurableSampling(state, () => this.tracer.startSpan(`execute_tool ${part.toolName}`, toolSpanOptions, state.inferenceContext));
1281
1534
  const toolOutput = finalToolOutputs.get(part.toolCallId);
1282
1535
  if (toolOutput?.type === "tool-result") try {
1283
1536
  toolSpan.setAttributes(selectAttributes$1(telemetry, { "gen_ai.tool.call.result": { output: () => JSON.stringify(toolOutput.output) } }));
1284
1537
  } catch {}
1285
1538
  else if (toolOutput?.type === "tool-error") recordErrorOnSpan(toolSpan, toolOutput.error);
1286
- toolSpan.end();
1539
+ toolSpan.end(endTime);
1287
1540
  }
1288
- state.inferenceSpan.end();
1541
+ state.inferenceSpan.end(endTime);
1289
1542
  state.inferenceSpan = void 0;
1290
1543
  state.inferenceContext = void 0;
1291
1544
  state.inferenceToolDefinitions = void 0;
1545
+ if (state.liveDurableContext) this.cleanupCallState(event.callId);
1546
+ }
1547
+ /**
1548
+ * Starts a model call reported live from a durable step. The run's root and
1549
+ * step spans are reported when the run ends, so the model call is parented
1550
+ * to the step span's derived ID.
1551
+ */
1552
+ startDurableModelCall(event) {
1553
+ const durable = event.durableContext;
1554
+ if (durable?.phase !== "live" || durable.stepNumber == null || this.durable == null) return void 0;
1555
+ const run = durable.run;
1556
+ const stepContext = trace.setSpanContext(context.active(), {
1557
+ traceId: run.traceId,
1558
+ spanId: deriveSpanId(event.callId, "step", durable.stepNumber),
1559
+ traceFlags: run.traceFlags,
1560
+ traceState: run.traceState == null ? void 0 : createTraceState(run.traceState),
1561
+ isRemote: true
1562
+ });
1563
+ const telemetryEvent = event;
1564
+ const state = {
1565
+ operationId: "ai.workflowAgent.stream",
1566
+ telemetry: {
1567
+ recordInputs: telemetryEvent.recordInputs,
1568
+ recordOutputs: telemetryEvent.recordOutputs,
1569
+ functionId: telemetryEvent.functionId
1570
+ },
1571
+ rootSpan: void 0,
1572
+ rootContext: void 0,
1573
+ stepSpan: void 0,
1574
+ stepContext,
1575
+ inferenceSpan: void 0,
1576
+ inferenceContext: void 0,
1577
+ embedSpans: /* @__PURE__ */ new Map(),
1578
+ rerankSpan: void 0,
1579
+ decisionSpan: void 0,
1580
+ toolSpans: /* @__PURE__ */ new Map(),
1581
+ settings: {
1582
+ maxOutputTokens: event.maxOutputTokens,
1583
+ temperature: event.temperature,
1584
+ topP: event.topP,
1585
+ topK: event.topK,
1586
+ presencePenalty: event.presencePenalty,
1587
+ frequencyPenalty: event.frequencyPenalty,
1588
+ stopSequences: event.stopSequences,
1589
+ seed: event.seed
1590
+ },
1591
+ provider: event.provider,
1592
+ modelId: event.modelId,
1593
+ runtimeContext: durable.runtimeContext,
1594
+ baseSupplementalAttributes: selectSupplementalAttributes({
1595
+ recordInputs: telemetryEvent.recordInputs,
1596
+ recordOutputs: telemetryEvent.recordOutputs
1597
+ }, this.supplementalAttributes, {
1598
+ runtimeContext: getRuntimeContextAttributes(durable.runtimeContext),
1599
+ headers: getHeaderAttributes(durable.headers)
1600
+ }),
1601
+ liveDurableContext: run
1602
+ };
1603
+ this.callStates.set(event.callId, state);
1604
+ return state;
1605
+ }
1606
+ /**
1607
+ * Ends a model call reported live from a durable step that failed or was
1608
+ * aborted before its end event.
1609
+ */
1610
+ endDurableModelCall(callId, { error, errorType, endTimestamp }) {
1611
+ const state = this.getCallState(callId);
1612
+ if (!state?.liveDurableContext) return;
1613
+ this.recordInferenceDuration(state, {
1614
+ errorType,
1615
+ endTimestamp
1616
+ });
1617
+ if (state.inferenceSpan) {
1618
+ if (error !== void 0) recordErrorOnSpan(state.inferenceSpan, error);
1619
+ state.inferenceSpan.end(endTimestamp == null ? void 0 : new Date(endTimestamp));
1620
+ }
1621
+ this.cleanupCallState(callId);
1292
1622
  }
1293
1623
  onToolExecutionStart(event) {
1294
1624
  const state = this.getCallState(event.callId);
@@ -1304,7 +1634,7 @@ var OpenTelemetry = class {
1304
1634
  "gen_ai.tool.call.arguments": { input: () => JSON.stringify(toolCall.input) }
1305
1635
  });
1306
1636
  const spanName = `execute_tool ${toolCall.toolName}`;
1307
- const toolSpan = this.tracer.startSpan(spanName, {
1637
+ const toolSpanOptions = {
1308
1638
  attributes: this.getSpanAttributes({
1309
1639
  attributes,
1310
1640
  spanType: "tool",
@@ -1312,8 +1642,10 @@ var OpenTelemetry = class {
1312
1642
  callId: event.callId,
1313
1643
  runtimeContext: state.runtimeContext
1314
1644
  }),
1315
- kind: SpanKind.INTERNAL
1316
- }, parentContext);
1645
+ kind: SpanKind.INTERNAL,
1646
+ startTime: getEventTime(event)
1647
+ };
1648
+ const toolSpan = this.withDurableSampling(state, () => this.tracer.startSpan(spanName, toolSpanOptions, parentContext));
1317
1649
  const toolContext = trace.setSpan(parentContext, toolSpan);
1318
1650
  state.toolSpans.set(toolCall.toolCallId, {
1319
1651
  span: toolSpan,
@@ -1333,20 +1665,23 @@ var OpenTelemetry = class {
1333
1665
  span.setAttributes(selectAttributes$1(telemetry, { "gen_ai.tool.call.result": { output: () => JSON.stringify(toolOutput.output) } }));
1334
1666
  } catch {}
1335
1667
  else recordErrorOnSpan(span, toolOutput.error);
1336
- span.end();
1668
+ span.end(getEventTime(event));
1337
1669
  state.toolSpans.delete(event.toolCall.toolCallId);
1338
1670
  }
1339
1671
  onStepEnd(event) {
1340
1672
  const state = this.getCallState(event.callId);
1341
1673
  if (!state?.stepSpan) return;
1342
- this.recordInferenceDuration(state, { errorType: event.finishReason === "error" ? "_OTHER" : void 0 });
1674
+ this.recordInferenceDuration(state, {
1675
+ errorType: event.finishReason === "error" ? "_OTHER" : void 0,
1676
+ endTimestamp: getEventTimestamp(event)
1677
+ });
1343
1678
  if (event.finishReason === "error") state.stepSpan.setStatus({ code: SpanStatusCode.ERROR });
1344
1679
  const { telemetry } = state;
1345
1680
  state.stepSpan.setAttributes(selectSupplementalAttributes(telemetry, this.supplementalAttributes, {
1346
1681
  providerMetadata: { "ai.response.providerMetadata": event.providerMetadata ? JSON.stringify(event.providerMetadata) : void 0 },
1347
1682
  usage: getDetailedUsageAttributes(event.usage)
1348
1683
  }));
1349
- state.stepSpan.end();
1684
+ state.stepSpan.end(getEventTime(event));
1350
1685
  state.stepSpan = void 0;
1351
1686
  state.stepContext = void 0;
1352
1687
  }
@@ -1357,15 +1692,18 @@ var OpenTelemetry = class {
1357
1692
  onStepError(event) {
1358
1693
  const state = this.getCallState(event.callId);
1359
1694
  if (!state?.stepSpan) return;
1360
- this.recordInferenceDuration(state, { errorType: event.error instanceof Error ? event.error.name : "_OTHER" });
1695
+ this.recordInferenceDuration(state, {
1696
+ errorType: event.error instanceof Error ? event.error.name : "_OTHER",
1697
+ endTimestamp: getEventTimestamp(event)
1698
+ });
1361
1699
  if (state.inferenceSpan) {
1362
1700
  recordErrorOnSpan(state.inferenceSpan, event.error);
1363
- state.inferenceSpan.end();
1701
+ state.inferenceSpan.end(getEventTime(event));
1364
1702
  state.inferenceSpan = void 0;
1365
1703
  state.inferenceContext = void 0;
1366
1704
  }
1367
1705
  recordErrorOnSpan(state.stepSpan, event.error);
1368
- state.stepSpan.end();
1706
+ state.stepSpan.end(getEventTime(event));
1369
1707
  state.stepSpan = void 0;
1370
1708
  state.stepContext = void 0;
1371
1709
  }
@@ -1449,7 +1787,7 @@ var OpenTelemetry = class {
1449
1787
  usage: getDetailedUsageAttributes(event.usage)
1450
1788
  })
1451
1789
  }));
1452
- state.rootSpan.end();
1790
+ state.rootSpan.end(getEventTime(event));
1453
1791
  this.cleanupCallState(event.callId);
1454
1792
  }
1455
1793
  onObjectOperationEnd(event) {
@@ -1748,74 +2086,97 @@ var OpenTelemetry = class {
1748
2086
  }
1749
2087
  onAbort(event) {
1750
2088
  const state = this.getCallState(event.callId);
2089
+ if (state?.liveDurableContext) {
2090
+ this.endDurableModelCall(event.callId, {
2091
+ errorType: "AbortError",
2092
+ endTimestamp: getEventTimestamp(event)
2093
+ });
2094
+ return;
2095
+ }
1751
2096
  if (!state?.rootSpan) return;
1752
- this.recordInferenceDuration(state, { errorType: "AbortError" });
1753
- for (const { span: toolSpan } of state.toolSpans.values()) toolSpan.end();
2097
+ const endTime = getEventTime(event);
2098
+ this.recordInferenceDuration(state, {
2099
+ errorType: "AbortError",
2100
+ endTimestamp: getEventTimestamp(event)
2101
+ });
2102
+ for (const { span: toolSpan } of state.toolSpans.values()) toolSpan.end(endTime);
1754
2103
  state.toolSpans.clear();
1755
2104
  if (state.inferenceSpan) {
1756
- state.inferenceSpan.end();
2105
+ state.inferenceSpan.end(endTime);
1757
2106
  state.inferenceSpan = void 0;
1758
2107
  state.inferenceContext = void 0;
1759
2108
  }
1760
2109
  if (state.stepSpan) {
1761
- state.stepSpan.end();
2110
+ state.stepSpan.end(endTime);
1762
2111
  state.stepSpan = void 0;
1763
2112
  state.stepContext = void 0;
1764
2113
  }
1765
- for (const { span: embedSpan } of state.embedSpans.values()) embedSpan.end();
2114
+ for (const { span: embedSpan } of state.embedSpans.values()) embedSpan.end(endTime);
1766
2115
  state.embedSpans.clear();
1767
2116
  if (state.rerankSpan) {
1768
- state.rerankSpan.span.end();
2117
+ state.rerankSpan.span.end(endTime);
1769
2118
  state.rerankSpan = void 0;
1770
2119
  }
1771
2120
  if (state.decisionSpan) {
1772
- state.decisionSpan.span.end();
2121
+ state.decisionSpan.span.end(endTime);
1773
2122
  state.decisionSpan = void 0;
1774
2123
  }
1775
- state.rootSpan.end();
2124
+ state.rootSpan.end(endTime);
1776
2125
  this.cleanupCallState(event.callId);
1777
2126
  }
1778
2127
  onError(error) {
1779
2128
  const event = error;
1780
2129
  if (!event?.callId) return;
1781
2130
  const state = this.getCallState(event.callId);
1782
- if (!state?.rootSpan) return;
1783
2131
  const actualError = event.error ?? error;
1784
- this.recordInferenceDuration(state, { errorType: actualError instanceof Error ? actualError.name : "_OTHER" });
2132
+ if (state?.liveDurableContext) {
2133
+ this.endDurableModelCall(event.callId, {
2134
+ error: actualError,
2135
+ errorType: actualError instanceof Error ? actualError.name : "_OTHER",
2136
+ endTimestamp: getEventTimestamp(event)
2137
+ });
2138
+ return;
2139
+ }
2140
+ if (!state?.rootSpan) return;
2141
+ const endTime = getEventTime(event);
2142
+ this.recordInferenceDuration(state, {
2143
+ errorType: actualError instanceof Error ? actualError.name : "_OTHER",
2144
+ endTimestamp: getEventTimestamp(event)
2145
+ });
1785
2146
  for (const { span: toolSpan } of state.toolSpans.values()) {
1786
2147
  recordErrorOnSpan(toolSpan, actualError);
1787
- toolSpan.end();
2148
+ toolSpan.end(endTime);
1788
2149
  }
1789
2150
  state.toolSpans.clear();
1790
2151
  if (state.inferenceSpan) {
1791
2152
  recordErrorOnSpan(state.inferenceSpan, actualError);
1792
- state.inferenceSpan.end();
2153
+ state.inferenceSpan.end(endTime);
1793
2154
  state.inferenceSpan = void 0;
1794
2155
  state.inferenceContext = void 0;
1795
2156
  }
1796
2157
  if (state.stepSpan) {
1797
2158
  recordErrorOnSpan(state.stepSpan, actualError);
1798
- state.stepSpan.end();
2159
+ state.stepSpan.end(endTime);
1799
2160
  state.stepSpan = void 0;
1800
2161
  state.stepContext = void 0;
1801
2162
  }
1802
2163
  for (const { span: embedSpan } of state.embedSpans.values()) {
1803
2164
  recordErrorOnSpan(embedSpan, actualError);
1804
- embedSpan.end();
2165
+ embedSpan.end(endTime);
1805
2166
  }
1806
2167
  state.embedSpans.clear();
1807
2168
  if (state.rerankSpan) {
1808
2169
  recordErrorOnSpan(state.rerankSpan.span, actualError);
1809
- state.rerankSpan.span.end();
2170
+ state.rerankSpan.span.end(endTime);
1810
2171
  state.rerankSpan = void 0;
1811
2172
  }
1812
2173
  if (state.decisionSpan) {
1813
2174
  recordErrorOnSpan(state.decisionSpan.span, actualError);
1814
- state.decisionSpan.span.end();
2175
+ state.decisionSpan.span.end(endTime);
1815
2176
  state.decisionSpan = void 0;
1816
2177
  }
1817
2178
  recordErrorOnSpan(state.rootSpan, actualError);
1818
- state.rootSpan.end();
2179
+ state.rootSpan.end(endTime);
1819
2180
  this.cleanupCallState(event.callId);
1820
2181
  }
1821
2182
  };
@@ -2217,7 +2578,7 @@ var LegacyOpenTelemetry = class {
2217
2578
  "ai.model.provider": event.provider,
2218
2579
  "ai.model.id": event.modelId,
2219
2580
  "ai.prompt.messages": { input: () => event.promptMessages ? stringifyForTelemetry(event.promptMessages) : void 0 },
2220
- "ai.prompt.tools": { input: () => event.stepTools?.map((tool) => JSON.stringify(tool)) },
2581
+ "ai.prompt.tools": { input: () => event.stepTools?.map((tool) => JSON.stringify(redactToolDefinition(tool))) },
2221
2582
  "ai.prompt.toolChoice": { input: () => event.stepToolChoice != null ? JSON.stringify(event.stepToolChoice) : void 0 },
2222
2583
  "gen_ai.system": event.provider,
2223
2584
  "gen_ai.request.model": event.modelId,
@@ -2708,6 +3069,6 @@ var LegacyOpenTelemetry = class {
2708
3069
  }
2709
3070
  };
2710
3071
  //#endregion
2711
- export { LegacyOpenTelemetry, OpenTelemetry };
3072
+ export { LegacyOpenTelemetry, OpenTelemetry, OpenTelemetryIdGenerator };
2712
3073
 
2713
3074
  //# sourceMappingURL=index.js.map