@raindrop-ai/ai-sdk 0.3.0 → 0.3.2

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,7 +4,69 @@ var async_hooks = require('async_hooks');
4
4
 
5
5
  // src/index.node.ts
6
6
 
7
- // ../core/dist/chunk-YUIXRQWN.js
7
+ // ../core/dist/chunk-BYBMRLZM.js
8
+ var EVAL_CORRELATION_ID_ATTRIBUTE = "raindrop.eval_correlation_id";
9
+ var PROBE_SCOPE = { correlationId: "" };
10
+ var EvalScopeStorage = class {
11
+ constructor() {
12
+ this._als = null;
13
+ this._probed = false;
14
+ }
15
+ maybeAdoptAsyncLocalStorage() {
16
+ if (this._probed) return;
17
+ this._probed = true;
18
+ try {
19
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
20
+ if (!Ctor) return;
21
+ const als = new Ctor();
22
+ als.run(PROBE_SCOPE, () => {
23
+ });
24
+ this._als = als;
25
+ } catch (e) {
26
+ this._als = null;
27
+ }
28
+ }
29
+ run(scope, callback) {
30
+ this.maybeAdoptAsyncLocalStorage();
31
+ if (this._als) return this._als.run(scope, callback);
32
+ const previous = this._syncScope;
33
+ this._syncScope = scope;
34
+ try {
35
+ return callback();
36
+ } finally {
37
+ this._syncScope = previous;
38
+ }
39
+ }
40
+ current() {
41
+ this.maybeAdoptAsyncLocalStorage();
42
+ if (this._als) return this._als.getStore();
43
+ return this._syncScope;
44
+ }
45
+ };
46
+ var EVAL_SCOPE_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.evalScopeStorage");
47
+ function evalScopeStorage() {
48
+ const holder = globalThis;
49
+ let storage = holder[EVAL_SCOPE_STORAGE_KEY];
50
+ if (!storage) {
51
+ storage = new EvalScopeStorage();
52
+ holder[EVAL_SCOPE_STORAGE_KEY] = storage;
53
+ }
54
+ return storage;
55
+ }
56
+ function currentEvalScope() {
57
+ try {
58
+ return evalScopeStorage().current();
59
+ } catch (e) {
60
+ return void 0;
61
+ }
62
+ }
63
+ function evalScopeAttributes() {
64
+ const scope = currentEvalScope();
65
+ if (!scope) return {};
66
+ return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
67
+ }
68
+
69
+ // ../core/dist/chunk-T53LQAH7.js
8
70
  function normalizeFeatureFlags(input) {
9
71
  if (Array.isArray(input)) {
10
72
  return Object.fromEntries(input.map((name) => [name, "true"]));
@@ -499,6 +561,7 @@ async function postJson(url, body, headers, opts) {
499
561
  const resp = await runWithTracingSuppressed(
500
562
  () => fetch(url, {
501
563
  method: "POST",
564
+ redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
502
565
  headers: {
503
566
  "Content-Type": "application/json",
504
567
  ...headers
@@ -622,6 +685,55 @@ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", se
622
685
  ]
623
686
  };
624
687
  }
688
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
689
+ function state() {
690
+ const holder = globalThis;
691
+ let current = holder[STATE_KEY];
692
+ if (!current) {
693
+ let storage = null;
694
+ try {
695
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
696
+ if (Ctor) storage = new Ctor();
697
+ } catch (e) {
698
+ storage = null;
699
+ }
700
+ current = {
701
+ storage,
702
+ syncDestination: void 0,
703
+ spanDestinations: /* @__PURE__ */ new WeakMap()
704
+ };
705
+ holder[STATE_KEY] = current;
706
+ }
707
+ return current;
708
+ }
709
+ function currentReplayTraceDestination() {
710
+ var _a, _b;
711
+ const routing = state();
712
+ return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
713
+ }
714
+ function rememberReplayTraceDestination(span) {
715
+ const destination = currentReplayTraceDestination();
716
+ if (destination) state().spanDestinations.set(span, destination);
717
+ }
718
+ function copyReplayTraceDestination(source, target) {
719
+ const destination = state().spanDestinations.get(source);
720
+ if (destination) state().spanDestinations.set(target, destination);
721
+ }
722
+ function replayTraceDestinationFor(value) {
723
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
724
+ return void 0;
725
+ }
726
+ return state().spanDestinations.get(value);
727
+ }
728
+ function recordReplayExportedSpan(destination, spanId, traceId) {
729
+ var _a, _b;
730
+ if (!destination || !spanId || !traceId) return;
731
+ (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
732
+ (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
733
+ }
734
+ function replayTraceUrl(baseUrl) {
735
+ return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
736
+ }
625
737
  var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
626
738
  var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
627
739
  var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
@@ -687,31 +799,36 @@ function resolveLocalDebuggerBaseUrl(baseUrl) {
687
799
  function localDebuggerEnabled(baseUrl) {
688
800
  return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
689
801
  }
802
+ var LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS = 2e3;
690
803
  function mirrorTraceExportToLocalDebugger(body, options = {}) {
691
804
  var _a;
692
805
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
693
- if (!baseUrl) return;
694
- void postJson(`${baseUrl}traces`, body, {}, {
806
+ if (!baseUrl) return Promise.resolve();
807
+ return postJson(`${baseUrl}traces`, body, {}, {
695
808
  maxAttempts: 1,
696
809
  debug: (_a = options.debug) != null ? _a : false,
697
- sdkName: options.sdkName
810
+ sdkName: options.sdkName,
811
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
698
812
  }).catch(() => {
699
813
  });
700
814
  }
701
815
  function mirrorPartialEventToLocalDebugger(event, options = {}) {
702
816
  var _a;
703
817
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
704
- if (!baseUrl) return;
818
+ if (!baseUrl) return Promise.resolve();
705
819
  const headers = options.writeKey ? { Authorization: `Bearer ${options.writeKey}` } : {};
706
- void postJson(`${baseUrl}events/track_partial`, event, headers, {
820
+ return postJson(`${baseUrl}events/track_partial`, event, headers, {
707
821
  maxAttempts: 1,
708
822
  debug: (_a = options.debug) != null ? _a : false,
709
- sdkName: options.sdkName
823
+ sdkName: options.sdkName,
824
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
710
825
  }).catch(() => {
711
826
  });
712
827
  }
713
828
  function sendLocalDebuggerLiveEvent(event, options = {}) {
714
829
  var _a, _b;
830
+ const destination = currentReplayTraceDestination();
831
+ if (destination && destination.kind !== "workshop") return;
715
832
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
716
833
  if (!baseUrl) return;
717
834
  void postJson(
@@ -883,6 +1000,15 @@ var EventShipper = class {
883
1000
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
884
1001
  if (!this.enabled) return;
885
1002
  if (!eventId || !eventId.trim()) return;
1003
+ const capturedSticky = this.sticky.get(eventId);
1004
+ const eventAlreadyKnown = capturedSticky !== void 0 || this.buffers.has(eventId);
1005
+ const destination = currentReplayTraceDestination();
1006
+ const cloudReplay = destination !== void 0 && destination.kind !== "workshop";
1007
+ if ((capturedSticky == null ? void 0 : capturedSticky.replayOnly) === true || !eventAlreadyKnown && cloudReplay) {
1008
+ if (patch.isPending === false) this.sticky.delete(eventId);
1009
+ else this.sticky.set(eventId, { ...capturedSticky, replayOnly: true });
1010
+ return;
1011
+ }
886
1012
  const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
887
1013
  if (typeof patch.input === "string" && patch.input.length > maxChars) {
888
1014
  patch = { ...patch, input: capText(patch.input, maxChars) };
@@ -941,6 +1067,9 @@ var EventShipper = class {
941
1067
  try {
942
1068
  for (const t of this.timers.values()) clearTimeout(t);
943
1069
  this.timers.clear();
1070
+ for (const [eventId, sticky] of this.sticky) {
1071
+ if (sticky.replayOnly) this.sticky.delete(eventId);
1072
+ }
944
1073
  const settled = await raceWithTimeout(this.flush(), SHUTDOWN_DEADLINE_MS);
945
1074
  if (!settled) this.warnShutdownDrop("in-flight request(s) at shutdown");
946
1075
  } finally {
@@ -950,6 +1079,8 @@ var EventShipper = class {
950
1079
  async trackSignal(signal) {
951
1080
  var _a, _b;
952
1081
  if (!this.enabled) return;
1082
+ const destination = currentReplayTraceDestination();
1083
+ if (destination && destination.kind !== "workshop") return;
953
1084
  const body = [
954
1085
  {
955
1086
  event_id: signal.eventId,
@@ -984,6 +1115,8 @@ var EventShipper = class {
984
1115
  }
985
1116
  async identify(users) {
986
1117
  if (!this.enabled) return;
1118
+ const destination = currentReplayTraceDestination();
1119
+ if (destination && destination.kind !== "workshop") return;
987
1120
  const list = Array.isArray(users) ? users : [users];
988
1121
  const body = list.filter((user) => {
989
1122
  if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
@@ -1036,8 +1169,9 @@ var EventShipper = class {
1036
1169
  this.buffers.delete(eventId);
1037
1170
  if (!accumulated) return;
1038
1171
  const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
1039
- const eventName = (_c = (_b = accumulated.eventName) != null ? _b : sticky.eventName) != null ? _c : this.defaultEventName;
1040
- const userId = (_d = accumulated.userId) != null ? _d : sticky.userId;
1172
+ const isPending = (_c = (_b = accumulated.isPending) != null ? _b : sticky.isPending) != null ? _c : true;
1173
+ const eventName = (_e = (_d = accumulated.eventName) != null ? _d : sticky.eventName) != null ? _e : this.defaultEventName;
1174
+ const userId = (_f = accumulated.userId) != null ? _f : sticky.userId;
1041
1175
  if (!userId) {
1042
1176
  if (this.debug) {
1043
1177
  console.warn(`${this.prefix} skipping track_partial for ${eventId}: missing userId`);
@@ -1045,14 +1179,13 @@ var EventShipper = class {
1045
1179
  this.sticky.delete(eventId);
1046
1180
  return;
1047
1181
  }
1048
- const { wizardSession, ...restProperties } = (_e = accumulated.properties) != null ? _e : {};
1182
+ const { wizardSession, ...restProperties } = (_g = accumulated.properties) != null ? _g : {};
1049
1183
  let telemetryProperties = {};
1050
1184
  try {
1051
1185
  telemetryProperties = eventTelemetryProperties(accumulated);
1052
1186
  } catch (e) {
1053
1187
  }
1054
- const convoId = (_f = accumulated.convoId) != null ? _f : sticky.convoId;
1055
- const isPending = (_h = (_g = accumulated.isPending) != null ? _g : sticky.isPending) != null ? _h : true;
1188
+ const convoId = (_h = accumulated.convoId) != null ? _h : sticky.convoId;
1056
1189
  const payload = {
1057
1190
  event_id: eventId,
1058
1191
  user_id: userId,
@@ -1094,29 +1227,30 @@ var EventShipper = class {
1094
1227
  endpoint: url
1095
1228
  });
1096
1229
  }
1097
- if (this.localDebuggerUrl) {
1098
- mirrorPartialEventToLocalDebugger(payload, {
1099
- baseUrl: this.localDebuggerUrl,
1100
- writeKey: this.writeKey,
1101
- debug: this.debug,
1102
- sdkName: this.sdkName
1103
- });
1104
- }
1230
+ const mirror = this.localDebuggerUrl ? mirrorPartialEventToLocalDebugger(payload, {
1231
+ baseUrl: this.localDebuggerUrl,
1232
+ writeKey: this.writeKey,
1233
+ debug: this.debug,
1234
+ sdkName: this.sdkName
1235
+ }) : void 0;
1105
1236
  if (!this.writeKey) {
1106
1237
  if (!isPending) this.sticky.delete(eventId);
1238
+ if (mirror) await mirror;
1107
1239
  return;
1108
1240
  }
1109
1241
  const opts = this.requestOpts();
1110
1242
  if (!opts) {
1111
1243
  this.warnShutdownDrop(`track_partial ${eventId}`);
1112
1244
  if (!isPending) this.sticky.delete(eventId);
1245
+ if (mirror) await mirror;
1113
1246
  return;
1114
1247
  }
1115
1248
  const p = postJson(url, payload, this.requestHeaders(), opts);
1116
- this.inFlight.add(p);
1249
+ const combined = mirror ? Promise.all([mirror, p]).then(() => void 0) : p;
1250
+ this.inFlight.add(combined);
1117
1251
  try {
1118
1252
  try {
1119
- await p;
1253
+ await combined;
1120
1254
  if (this.debug) {
1121
1255
  console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
1122
1256
  }
@@ -1128,7 +1262,7 @@ var EventShipper = class {
1128
1262
  );
1129
1263
  }
1130
1264
  } finally {
1131
- this.inFlight.delete(p);
1265
+ this.inFlight.delete(combined);
1132
1266
  }
1133
1267
  if (!isPending) {
1134
1268
  this.sticky.delete(eventId);
@@ -1136,6 +1270,7 @@ var EventShipper = class {
1136
1270
  }
1137
1271
  };
1138
1272
  var MODEL_USAGE_ATTRIBUTES = {
1273
+ usageSource: "raindrop.usage.source",
1139
1274
  providerName: "gen_ai.provider.name",
1140
1275
  requestModel: "gen_ai.request.model",
1141
1276
  responseModel: "gen_ai.response.model",
@@ -1144,20 +1279,22 @@ var MODEL_USAGE_ATTRIBUTES = {
1144
1279
  reasoningTokens: "gen_ai.usage.reasoning_tokens",
1145
1280
  cacheReadInputTokens: "gen_ai.usage.cache_read_input_tokens",
1146
1281
  cacheWriteInputTokens: "gen_ai.usage.cache_write_input_tokens",
1147
- nonCachedInputTokens: "raindrop.usage.input_tokens.non_cached",
1148
- nonReasoningOutputTokens: "raindrop.usage.output_tokens.non_reasoning",
1149
- reasoningOutputTokens: "raindrop.usage.output_tokens.reasoning",
1150
- cacheReadTokens: "raindrop.usage.input_tokens.cache_read",
1151
- cacheWriteTokens: "raindrop.usage.input_tokens.cache_write"
1152
- };
1282
+ providerReportedCost: "gen_ai.usage.provider_reported_cost"};
1153
1283
  var MODEL_PROVIDER_NAMES = [
1284
+ ["google.vertex.anthropic", "google-vertex"],
1285
+ ["google.vertex_ai", "google-vertex"],
1154
1286
  ["google.vertex", "google-vertex"],
1287
+ ["gcp.vertex_ai", "google-vertex"],
1288
+ ["gcp.gemini", "google"],
1289
+ ["google_vertexai", "google-vertex"],
1155
1290
  ["vertex.anthropic", "google-vertex"],
1156
1291
  ["amazon-bedrock", "amazon-bedrock"],
1292
+ ["aws.bedrock", "amazon-bedrock"],
1157
1293
  ["bedrock", "amazon-bedrock"],
1158
1294
  ["anthropic", "anthropic"],
1159
1295
  ["openai", "openai"],
1160
1296
  ["google", "google"],
1297
+ ["az.ai.openai", "azure"],
1161
1298
  ["azure", "azure"],
1162
1299
  ["openrouter", "openrouter"]
1163
1300
  ];
@@ -1168,60 +1305,20 @@ function canonicalModelProvider(provider) {
1168
1305
  const match = MODEL_PROVIDER_NAMES.find(
1169
1306
  ([family]) => normalizedProvider === family || normalizedProvider.startsWith(`${family}.`)
1170
1307
  );
1171
- return (_a = match == null ? void 0 : match[1]) != null ? _a : provider;
1308
+ return (_a = match == null ? void 0 : match[1]) != null ? _a : normalizedProvider;
1172
1309
  }
1173
1310
  function tokenCount(value) {
1174
1311
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1175
1312
  }
1176
- function exclusiveTokens({
1177
- explicit,
1178
- total,
1179
- parts,
1180
- semantics
1181
- }) {
1182
- if (explicit !== void 0) return explicit;
1183
- if (total === void 0) return void 0;
1184
- if (semantics === "exclusive") return total;
1185
- const observedParts = parts.filter((part) => part !== void 0 && part > 0);
1186
- if (semantics === void 0 && observedParts.length > 0) return void 0;
1187
- const exclusive = total - observedParts.reduce((sum, part) => sum + part, 0);
1188
- return exclusive >= 0 ? exclusive : void 0;
1189
- }
1190
- function buildModelUsageAttributes(usage) {
1191
- const inputTokens = tokenCount(usage.inputTokens);
1192
- const outputTokens = tokenCount(usage.outputTokens);
1193
- const explicitNonCachedInputTokens = tokenCount(usage.nonCachedInputTokens);
1194
- const explicitNonReasoningOutputTokens = tokenCount(usage.nonReasoningOutputTokens);
1195
- const reasoningTokens = tokenCount(usage.reasoningTokens);
1196
- const cacheReadInputTokens = tokenCount(usage.cacheReadInputTokens);
1197
- const cacheWriteInputTokens = tokenCount(usage.cacheWriteInputTokens);
1198
- const nonCachedInputTokens = exclusiveTokens({
1199
- explicit: explicitNonCachedInputTokens,
1200
- total: inputTokens,
1201
- parts: [cacheReadInputTokens, cacheWriteInputTokens],
1202
- semantics: usage.inputTokenSemantics
1203
- });
1204
- const nonReasoningOutputTokens = exclusiveTokens({
1205
- explicit: explicitNonReasoningOutputTokens,
1206
- total: outputTokens,
1207
- parts: [reasoningTokens],
1208
- semantics: usage.outputTokenSemantics
1209
- });
1210
- const exclusivePoolAttributes = nonCachedInputTokens !== void 0 && nonReasoningOutputTokens !== void 0 ? [
1211
- // backend consumes this complete raindrop.* set as one atomic billing-pool contract.
1212
- attrInt(MODEL_USAGE_ATTRIBUTES.nonCachedInputTokens, nonCachedInputTokens),
1213
- attrInt(MODEL_USAGE_ATTRIBUTES.nonReasoningOutputTokens, nonReasoningOutputTokens),
1214
- attrInt(MODEL_USAGE_ATTRIBUTES.reasoningOutputTokens, reasoningTokens),
1215
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadTokens, cacheReadInputTokens),
1216
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteTokens, cacheWriteInputTokens)
1217
- ] : [];
1313
+ function buildRawModelUsageAttributes(usage) {
1314
+ const providerReportedCost = typeof usage.providerReportedCost === "number" && Number.isFinite(usage.providerReportedCost) && usage.providerReportedCost >= 0 ? usage.providerReportedCost : void 0;
1218
1315
  return [
1219
- attrInt(MODEL_USAGE_ATTRIBUTES.inputTokens, inputTokens),
1220
- attrInt(MODEL_USAGE_ATTRIBUTES.outputTokens, outputTokens),
1221
- attrInt(MODEL_USAGE_ATTRIBUTES.reasoningTokens, reasoningTokens),
1222
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadInputTokens, cacheReadInputTokens),
1223
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteInputTokens, cacheWriteInputTokens),
1224
- ...exclusivePoolAttributes
1316
+ attrInt(MODEL_USAGE_ATTRIBUTES.inputTokens, tokenCount(usage.inputTokens)),
1317
+ attrInt(MODEL_USAGE_ATTRIBUTES.outputTokens, tokenCount(usage.outputTokens)),
1318
+ attrInt(MODEL_USAGE_ATTRIBUTES.reasoningTokens, tokenCount(usage.reasoningTokens)),
1319
+ attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadInputTokens, tokenCount(usage.cacheReadInputTokens)),
1320
+ attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteInputTokens, tokenCount(usage.cacheWriteInputTokens)),
1321
+ attrDouble(MODEL_USAGE_ATTRIBUTES.providerReportedCost, providerReportedCost)
1225
1322
  ].filter((attribute) => attribute !== void 0);
1226
1323
  }
1227
1324
  var STRING_ALIASES = {
@@ -1513,7 +1610,10 @@ var TraceShipper = class {
1513
1610
  try {
1514
1611
  const result = this.transformSpanHook(current);
1515
1612
  if (result === null) return null;
1516
- if (result !== void 0) current = result;
1613
+ if (result !== void 0) {
1614
+ copyReplayTraceDestination(current, result);
1615
+ current = result;
1616
+ }
1517
1617
  } catch (err) {
1518
1618
  if (this.debug) {
1519
1619
  const msg = err instanceof Error ? err.message : String(err);
@@ -1523,13 +1623,19 @@ var TraceShipper = class {
1523
1623
  }
1524
1624
  }
1525
1625
  try {
1526
- current = normalizeModelUsageSpan(current);
1626
+ const normalized = normalizeModelUsageSpan(current);
1627
+ copyReplayTraceDestination(current, normalized);
1628
+ current = normalized;
1527
1629
  } catch (e) {
1528
1630
  }
1529
1631
  if (!this.disableDefaultRedaction) {
1530
- current = defaultTransformSpan(current);
1632
+ const redacted = defaultTransformSpan(current);
1633
+ copyReplayTraceDestination(current, redacted);
1634
+ current = redacted;
1531
1635
  }
1532
- return this.capSpanAttributes(current);
1636
+ const capped = this.capSpanAttributes(current);
1637
+ copyReplayTraceDestination(current, capped);
1638
+ return capped;
1533
1639
  }
1534
1640
  isDebugEnabled() {
1535
1641
  return this.debug;
@@ -1547,33 +1653,54 @@ var TraceShipper = class {
1547
1653
  const attrs = [
1548
1654
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1549
1655
  ...identityAttrs(args),
1550
- attrString("ai.operationId", args.operationId)
1656
+ attrString("ai.operationId", args.operationId),
1657
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1551
1658
  ];
1552
1659
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
1553
- const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
1554
- this.mirrorToLocalDebugger(
1555
- buildOtlpSpan({
1556
- ids: span.ids,
1557
- name: span.name,
1558
- startTimeUnixNano: span.startTimeUnixNano,
1559
- endTimeUnixNano: span.startTimeUnixNano,
1560
- // placeholder — will be updated on endSpan
1561
- attributes: span.attributes,
1562
- status: { code: SpanStatusCode.UNSET }
1563
- })
1564
- );
1660
+ const span = {
1661
+ ids,
1662
+ name: args.name,
1663
+ startTimeUnixNano: started,
1664
+ attributes: attrs
1665
+ };
1666
+ rememberReplayTraceDestination(span);
1667
+ const openSpan = buildOtlpSpan({
1668
+ ids: span.ids,
1669
+ name: span.name,
1670
+ startTimeUnixNano: span.startTimeUnixNano,
1671
+ endTimeUnixNano: span.startTimeUnixNano,
1672
+ // placeholder — will be updated on endSpan
1673
+ attributes: span.attributes,
1674
+ status: { code: SpanStatusCode.UNSET }
1675
+ });
1676
+ copyReplayTraceDestination(span, openSpan);
1677
+ this.mirrorToLocalDebugger(openSpan);
1565
1678
  return span;
1566
1679
  }
1567
- mirrorToLocalDebugger(span) {
1568
- if (!this.localDebuggerUrl) return;
1680
+ mirrorToLocalDebugger(span, completed = false) {
1681
+ const destination = replayTraceDestinationFor(span);
1682
+ if (destination && destination.kind !== "workshop") return;
1683
+ const localDebuggerUrl = (destination == null ? void 0 : destination.kind) === "workshop" ? destination.url : this.localDebuggerUrl;
1684
+ if (!localDebuggerUrl) return;
1569
1685
  const redacted = this.redactSpan(span);
1570
1686
  if (redacted === null) return;
1687
+ if (completed && (destination == null ? void 0 : destination.kind) === "workshop") {
1688
+ recordReplayExportedSpan(
1689
+ destination,
1690
+ base64ToHex(redacted.spanId),
1691
+ base64ToHex(redacted.traceId)
1692
+ );
1693
+ }
1571
1694
  const body = buildExportTraceServiceRequest([redacted], this.serviceName, this.serviceVersion);
1572
- mirrorTraceExportToLocalDebugger(body, {
1573
- baseUrl: this.localDebuggerUrl,
1695
+ const p = mirrorTraceExportToLocalDebugger(body, {
1696
+ baseUrl: localDebuggerUrl,
1574
1697
  debug: false,
1575
1698
  sdkName: this.sdkName
1576
1699
  });
1700
+ this.inFlight.add(p);
1701
+ void p.finally(() => {
1702
+ this.inFlight.delete(p);
1703
+ });
1577
1704
  }
1578
1705
  endSpan(span, extra) {
1579
1706
  var _a, _b;
@@ -1595,15 +1722,17 @@ var TraceShipper = class {
1595
1722
  attributes: span.attributes,
1596
1723
  status
1597
1724
  });
1725
+ copyReplayTraceDestination(span, otlp);
1598
1726
  this.enqueue(otlp);
1599
- this.mirrorToLocalDebugger(otlp);
1727
+ this.mirrorToLocalDebugger(otlp, true);
1600
1728
  }
1601
1729
  createSpan(args) {
1602
1730
  var _a;
1603
1731
  const ids = createSpanIds(args.parent);
1604
1732
  const attrs = [
1605
1733
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1606
- ...identityAttrs(args)
1734
+ ...identityAttrs(args),
1735
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1607
1736
  ];
1608
1737
  if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
1609
1738
  const otlp = buildOtlpSpan({
@@ -1614,8 +1743,9 @@ var TraceShipper = class {
1614
1743
  attributes: attrs,
1615
1744
  status: args.status
1616
1745
  });
1746
+ rememberReplayTraceDestination(otlp);
1617
1747
  this.enqueue(otlp);
1618
- this.mirrorToLocalDebugger(otlp);
1748
+ this.mirrorToLocalDebugger(otlp, true);
1619
1749
  }
1620
1750
  enqueue(span) {
1621
1751
  if (!this.enabled) return;
@@ -1629,6 +1759,13 @@ var TraceShipper = class {
1629
1759
  }
1630
1760
  const redacted = this.redactSpan(span);
1631
1761
  if (redacted === null) return;
1762
+ const destination = replayTraceDestinationFor(redacted);
1763
+ recordReplayExportedSpan(
1764
+ destination,
1765
+ base64ToHex(redacted.spanId),
1766
+ base64ToHex(redacted.traceId)
1767
+ );
1768
+ if ((destination == null ? void 0 : destination.kind) === "workshop") return;
1632
1769
  if (this.queue.length >= this.maxQueueSize) {
1633
1770
  this.queue.shift();
1634
1771
  }
@@ -1647,47 +1784,67 @@ var TraceShipper = class {
1647
1784
  }
1648
1785
  }
1649
1786
  async flush() {
1650
- if (!this.enabled) return;
1787
+ var _a;
1788
+ if (!this.enabled) {
1789
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
1790
+ })));
1791
+ return;
1792
+ }
1651
1793
  if (this.timer) {
1652
1794
  clearTimeout(this.timer);
1653
1795
  this.timer = void 0;
1654
1796
  }
1655
1797
  while (this.queue.length > 0) {
1656
1798
  const batch = this.queue.splice(0, this.maxBatchSize);
1657
- if (!this.writeKey) continue;
1658
- const opts = this.requestOpts();
1659
- if (!opts) {
1660
- rateLimitedLog(
1661
- `${this.prefix}.shutdown_deadline`,
1662
- () => console.warn(
1663
- `${this.prefix} shutdown flush deadline exceeded; dropping ${batch.length} spans`
1664
- )
1665
- );
1666
- continue;
1667
- }
1668
- const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
1669
- const url = `${this.baseUrl}traces`;
1670
- if (this.debug) {
1671
- console.log(`${this.prefix} sending traces batch`, {
1672
- spans: batch.length,
1673
- endpoint: url
1674
- });
1799
+ const groups = /* @__PURE__ */ new Map();
1800
+ for (const span of batch) {
1801
+ const destination = replayTraceDestinationFor(span);
1802
+ const spans = groups.get(destination);
1803
+ if (spans) spans.push(span);
1804
+ else groups.set(destination, [span]);
1675
1805
  }
1676
- const p = postJson(url, body, this.requestHeaders(), opts);
1677
- this.inFlight.add(p);
1678
- try {
1679
- try {
1680
- await p;
1681
- if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
1682
- } catch (err) {
1683
- const msg = err instanceof Error ? err.message : String(err);
1806
+ for (const [destination, spans] of groups) {
1807
+ if (!destination && !this.writeKey) continue;
1808
+ if ((destination == null ? void 0 : destination.kind) === "workshop") continue;
1809
+ const opts = this.requestOpts();
1810
+ if (!opts) {
1684
1811
  rateLimitedLog(
1685
- `${this.prefix}.send_spans_failed`,
1686
- () => console.warn(`${this.prefix} failed to send ${batch.length} spans: ${msg}`)
1812
+ `${this.prefix}.shutdown_deadline`,
1813
+ () => console.warn(
1814
+ `${this.prefix} shutdown flush deadline exceeded; dropping ${spans.length} spans`
1815
+ )
1687
1816
  );
1817
+ continue;
1818
+ }
1819
+ const body = buildExportTraceServiceRequest(spans, this.serviceName, this.serviceVersion);
1820
+ const url = destination ? replayTraceUrl(destination.url) : `${this.baseUrl}traces`;
1821
+ const headers = destination ? {
1822
+ Authorization: `Bearer ${destination.apiKey}`,
1823
+ "X-Raindrop-Replay-Id": destination.replayId,
1824
+ "X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
1825
+ } : this.requestHeaders();
1826
+ if (this.debug) {
1827
+ console.log(`${this.prefix} sending traces batch`, {
1828
+ spans: spans.length,
1829
+ endpoint: url
1830
+ });
1831
+ }
1832
+ const p = postJson(url, body, headers, opts);
1833
+ this.inFlight.add(p);
1834
+ try {
1835
+ try {
1836
+ await p;
1837
+ if (this.debug) console.log(`${this.prefix} sent ${spans.length} spans`);
1838
+ } catch (err) {
1839
+ const msg = err instanceof Error ? err.message : String(err);
1840
+ rateLimitedLog(
1841
+ `${this.prefix}.send_spans_failed`,
1842
+ () => console.warn(`${this.prefix} failed to send ${spans.length} spans: ${msg}`)
1843
+ );
1844
+ }
1845
+ } finally {
1846
+ this.inFlight.delete(p);
1688
1847
  }
1689
- } finally {
1690
- this.inFlight.delete(p);
1691
1848
  }
1692
1849
  }
1693
1850
  }
@@ -1730,7 +1887,9 @@ var TraceShipper = class {
1730
1887
  if (!settled) {
1731
1888
  rateLimitedLog(
1732
1889
  `${this.prefix}.shutdown_deadline`,
1733
- () => console.warn(`${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`)
1890
+ () => console.warn(
1891
+ `${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`
1892
+ )
1734
1893
  );
1735
1894
  }
1736
1895
  } finally {
@@ -1825,7 +1984,8 @@ function withCurrent(span, callback) {
1825
1984
  return getContextManager().runInContext(span, callback);
1826
1985
  }
1827
1986
  async function getCurrentParentSpanContext() {
1828
- return getContextManager().getParentSpanIds();
1987
+ var _a, _b;
1988
+ return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
1829
1989
  }
1830
1990
  async function runWithParentSpanContext(ctx, fn) {
1831
1991
  const cm = getContextManager();
@@ -1885,7 +2045,7 @@ installTracingSuppressionHook();
1885
2045
  // package.json
1886
2046
  var package_default = {
1887
2047
  name: "@raindrop-ai/ai-sdk",
1888
- version: "0.3.0"};
2048
+ version: "0.3.2"};
1889
2049
 
1890
2050
  // src/internal/version.ts
1891
2051
  var libraryName = package_default.name;
@@ -3129,29 +3289,6 @@ function firstTokenCount(...values) {
3129
3289
  }
3130
3290
  return void 0;
3131
3291
  }
3132
- function flatUsageSemantics(provider) {
3133
- const normalizedProvider = typeof provider === "string" ? provider.trim().toLowerCase() : void 0;
3134
- if (normalizedProvider === "anthropic" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("anthropic.")) || normalizedProvider === "vertex.anthropic" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("vertex.anthropic."))) {
3135
- return {
3136
- inputTokenSemantics: "exclusive",
3137
- outputTokenSemantics: "total"
3138
- };
3139
- }
3140
- if (normalizedProvider === "openai" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("openai.")) || normalizedProvider === "azure" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("azure."))) {
3141
- return {
3142
- inputTokenSemantics: "total",
3143
- outputTokenSemantics: "total"
3144
- };
3145
- }
3146
- if (normalizedProvider === "google" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("google."))) {
3147
- return {
3148
- inputTokenSemantics: "total",
3149
- // Google v5 reports candidate output and thoughts separately.
3150
- outputTokenSemantics: "exclusive"
3151
- };
3152
- }
3153
- return {};
3154
- }
3155
3292
  var CACHE_WRITE_METADATA_KEYS = [
3156
3293
  ["anthropic", "cacheCreationInputTokens"],
3157
3294
  ["openai", "cacheWriteTokens"],
@@ -3168,7 +3305,7 @@ function cacheWriteTokensFromProviderMetadata(providerMetadata) {
3168
3305
  })
3169
3306
  );
3170
3307
  }
3171
- function extractUsageMetricsFromUsage(usage, provider, providerMetadata) {
3308
+ function extractUsageMetricsFromUsage(usage, _provider, providerMetadata) {
3172
3309
  if (!isRecord(usage)) return {};
3173
3310
  const inputTokenValue = usage["inputTokens"];
3174
3311
  const outputTokenValue = usage["outputTokens"];
@@ -3236,7 +3373,7 @@ function extractUsageMetricsFromUsage(usage, provider, providerMetadata) {
3236
3373
  cacheReadInputTokens,
3237
3374
  cachedInputTokens: cacheReadInputTokens,
3238
3375
  cacheWriteInputTokens,
3239
- ...hasStructuredUsage ? {} : flatUsageSemantics(provider)
3376
+ ...hasStructuredUsage ? { usageSource: "ai-sdk-structured" } : {}
3240
3377
  };
3241
3378
  }
3242
3379
 
@@ -3434,13 +3571,13 @@ var RaindropTelemetryIntegration = class {
3434
3571
  };
3435
3572
  // ── onStepStart ─────────────────────────────────────────────────────────
3436
3573
  this.onStepStart = (event) => {
3437
- const state = this.getState(event.callId);
3438
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3439
- const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
3440
- const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
3441
- const { operationName, resourceName } = opName(stepOperationId, state.functionId);
3574
+ const state2 = this.getState(event.callId);
3575
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3576
+ const isStream = state2.operationId === "ai.streamText" || state2.operationId === "ai.streamObject";
3577
+ const stepOperationId = isStream ? `${state2.operationId}.doStream` : `${state2.operationId}.doGenerate`;
3578
+ const { operationName, resourceName } = opName(stepOperationId, state2.functionId);
3442
3579
  const inputAttrs = [];
3443
- if (state.recordInputs) {
3580
+ if (state2.recordInputs) {
3444
3581
  if (event.promptMessages) {
3445
3582
  inputAttrs.push(attrString("ai.prompt.messages", safeJsonWithUint8(event.promptMessages)));
3446
3583
  }
@@ -3463,25 +3600,25 @@ var RaindropTelemetryIntegration = class {
3463
3600
  }
3464
3601
  const stepSpan = this.traceShipper.startSpan({
3465
3602
  name: stepOperationId,
3466
- parent: state.rootParent,
3467
- eventId: state.eventId,
3468
- ...state.identity,
3603
+ parent: state2.rootParent,
3604
+ eventId: state2.eventId,
3605
+ ...state2.identity,
3469
3606
  operationId: stepOperationId,
3470
3607
  attributes: [
3471
3608
  attrString("operation.name", operationName),
3472
3609
  attrString("resource.name", resourceName),
3473
- attrString("ai.telemetry.functionId", state.functionId),
3610
+ attrString("ai.telemetry.functionId", state2.functionId),
3474
3611
  ...attrsFromModelProvider(event.provider),
3475
3612
  attrString("ai.model.id", event.modelId),
3476
3613
  attrString(MODEL_USAGE_ATTRIBUTES.requestModel, event.modelId),
3477
3614
  ...inputAttrs,
3478
- ...handoffSpanAttrs(state.handoff)
3615
+ ...handoffSpanAttrs(state2.handoff)
3479
3616
  ]
3480
3617
  });
3481
- state.stepSpan = stepSpan;
3482
- state.stepParent = this.spanParentRef(stepSpan);
3483
- state.stepProvider = event.provider;
3484
- state.stepModelId = event.modelId;
3618
+ state2.stepSpan = stepSpan;
3619
+ state2.stepParent = this.spanParentRef(stepSpan);
3620
+ state2.stepProvider = event.provider;
3621
+ state2.stepModelId = event.modelId;
3485
3622
  };
3486
3623
  this.onToolExecutionStart = (event) => this.toolExecutionStart(event);
3487
3624
  this.onToolExecutionEnd = (event) => this.toolExecutionEnd(event);
@@ -3508,33 +3645,33 @@ var RaindropTelemetryIntegration = class {
3508
3645
  var _a, _b, _c, _d, _e;
3509
3646
  const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
3510
3647
  if (!callId) return;
3511
- const state = this.getState(callId);
3512
- if (!state) return;
3648
+ const state2 = this.getState(callId);
3649
+ if (!state2) return;
3513
3650
  const chunk = event.chunk;
3514
3651
  if (!chunk || typeof chunk !== "object") return;
3515
3652
  if (chunk.type === "text-delta") {
3516
3653
  const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
3517
3654
  if (typeof delta === "string") {
3518
- if (state.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3519
- state.accumulatedText += delta;
3655
+ if (state2.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3656
+ state2.accumulatedText += delta;
3520
3657
  }
3521
- this.emitLive(state, "text_delta", delta);
3658
+ this.emitLive(state2, "text_delta", delta);
3522
3659
  }
3523
3660
  } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
3524
3661
  const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
3525
3662
  if (typeof text === "string") {
3526
- this.emitLive(state, "reasoning_delta", text);
3663
+ this.emitLive(state2, "reasoning_delta", text);
3527
3664
  }
3528
3665
  }
3529
3666
  };
3530
3667
  // ── onStepFinish ────────────────────────────────────────────────────────
3531
3668
  this.onStepFinish = (event) => {
3532
3669
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3533
- const state = this.getState(event.callId);
3534
- if (!(state == null ? void 0 : state.stepSpan)) return;
3535
- const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state.stepModelId;
3670
+ const state2 = this.getState(event.callId);
3671
+ if (!(state2 == null ? void 0 : state2.stepSpan)) return;
3672
+ const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state2.stepModelId;
3536
3673
  const outputAttrs = [];
3537
- if (state.recordOutputs) {
3674
+ if (state2.recordOutputs) {
3538
3675
  outputAttrs.push(
3539
3676
  attrString("ai.response.finishReason", event.finishReason),
3540
3677
  attrString("ai.response.text", capText2((_c = event.text) != null ? _c : void 0)),
@@ -3579,7 +3716,7 @@ var RaindropTelemetryIntegration = class {
3579
3716
  if (usage) {
3580
3717
  const usageMetrics = extractUsageMetricsFromUsage(
3581
3718
  usage,
3582
- state.stepProvider,
3719
+ state2.stepProvider,
3583
3720
  event.providerMetadata
3584
3721
  );
3585
3722
  outputAttrs.push(
@@ -3588,54 +3725,55 @@ var RaindropTelemetryIntegration = class {
3588
3725
  attrInt("ai.usage.totalTokens", usageMetrics.totalTokens),
3589
3726
  attrInt("ai.usage.reasoningTokens", usageMetrics.reasoningTokens),
3590
3727
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens),
3591
- ...buildModelUsageAttributes(usageMetrics)
3728
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
3729
+ ...buildRawModelUsageAttributes(usageMetrics)
3592
3730
  );
3593
3731
  }
3594
- this.emitProviderExecutedToolSpans(event, state);
3595
- this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
3596
- state.stepSpan = void 0;
3597
- state.stepParent = void 0;
3598
- state.stepProvider = void 0;
3599
- state.stepModelId = void 0;
3732
+ this.emitProviderExecutedToolSpans(event, state2);
3733
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: outputAttrs });
3734
+ state2.stepSpan = void 0;
3735
+ state2.stepParent = void 0;
3736
+ state2.stepProvider = void 0;
3737
+ state2.stepModelId = void 0;
3600
3738
  };
3601
3739
  // ── onEmbedStart ────────────────────────────────────────────────────────
3602
3740
  this.onEmbedStart = (event) => {
3603
- const state = this.getState(event.callId);
3604
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3605
- const { operationName, resourceName } = opName(event.operationId, state.functionId);
3606
- const inputAttrs = state.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3741
+ const state2 = this.getState(event.callId);
3742
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3743
+ const { operationName, resourceName } = opName(event.operationId, state2.functionId);
3744
+ const inputAttrs = state2.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3607
3745
  const embedSpan = this.traceShipper.startSpan({
3608
3746
  name: event.operationId,
3609
- parent: state.rootParent,
3610
- eventId: state.eventId,
3611
- ...state.identity,
3747
+ parent: state2.rootParent,
3748
+ eventId: state2.eventId,
3749
+ ...state2.identity,
3612
3750
  operationId: event.operationId,
3613
3751
  attributes: [
3614
3752
  attrString("operation.name", operationName),
3615
3753
  attrString("resource.name", resourceName),
3616
- attrString("ai.telemetry.functionId", state.functionId),
3754
+ attrString("ai.telemetry.functionId", state2.functionId),
3617
3755
  ...inputAttrs,
3618
- ...handoffSpanAttrs(state.handoff)
3756
+ ...handoffSpanAttrs(state2.handoff)
3619
3757
  ]
3620
3758
  });
3621
- state.embedSpans.set(event.embedCallId, embedSpan);
3759
+ state2.embedSpans.set(event.embedCallId, embedSpan);
3622
3760
  };
3623
3761
  // ── onEmbedFinish ───────────────────────────────────────────────────────
3624
3762
  this.onEmbedFinish = (event) => {
3625
3763
  var _a;
3626
- const state = this.getState(event.callId);
3627
- if (!state) return;
3628
- const embedSpan = state.embedSpans.get(event.embedCallId);
3764
+ const state2 = this.getState(event.callId);
3765
+ if (!state2) return;
3766
+ const embedSpan = state2.embedSpans.get(event.embedCallId);
3629
3767
  if (!embedSpan) return;
3630
3768
  const outputAttrs = [];
3631
- if (state.recordOutputs) {
3769
+ if (state2.recordOutputs) {
3632
3770
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embeddings)));
3633
3771
  }
3634
3772
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
3635
3773
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
3636
3774
  }
3637
3775
  this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
3638
- state.embedSpans.delete(event.embedCallId);
3776
+ state2.embedSpans.delete(event.embedCallId);
3639
3777
  };
3640
3778
  // v7 canary.159 renamed `onEmbedFinish` -> `onEmbedEnd`. Both names forward
3641
3779
  // to the same implementation; the installed SDK only wires up whichever it
@@ -3643,16 +3781,16 @@ var RaindropTelemetryIntegration = class {
3643
3781
  this.onEmbedEnd = (event) => this.onEmbedFinish(event);
3644
3782
  // ── onFinish ────────────────────────────────────────────────────────────
3645
3783
  this.onFinish = (event) => {
3646
- const state = this.getState(event.callId);
3647
- if (!state) return;
3648
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3784
+ const state2 = this.getState(event.callId);
3785
+ if (!state2) return;
3786
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3649
3787
  if (isEmbed) {
3650
- this.finishEmbed(event, state);
3788
+ this.finishEmbed(event, state2);
3651
3789
  } else {
3652
- this.finishGenerate(event, state);
3790
+ this.finishGenerate(event, state2);
3653
3791
  }
3654
- if (state.subagentToolCallSpan) {
3655
- this.traceShipper.endSpan(state.subagentToolCallSpan);
3792
+ if (state2.subagentToolCallSpan) {
3793
+ this.traceShipper.endSpan(state2.subagentToolCallSpan);
3656
3794
  }
3657
3795
  this.cleanup(event.callId);
3658
3796
  };
@@ -3667,42 +3805,42 @@ var RaindropTelemetryIntegration = class {
3667
3805
  var _a;
3668
3806
  const event = error;
3669
3807
  if (!(event == null ? void 0 : event.callId)) return;
3670
- const state = this.getState(event.callId);
3671
- if (!state) return;
3808
+ const state2 = this.getState(event.callId);
3809
+ if (!state2) return;
3672
3810
  const actualError = (_a = event.error) != null ? _a : error;
3673
- if (state.stepSpan) {
3674
- this.traceShipper.endSpan(state.stepSpan, { error: actualError });
3675
- state.stepProvider = void 0;
3676
- state.stepModelId = void 0;
3811
+ if (state2.stepSpan) {
3812
+ this.traceShipper.endSpan(state2.stepSpan, { error: actualError });
3813
+ state2.stepProvider = void 0;
3814
+ state2.stepModelId = void 0;
3677
3815
  }
3678
- for (const embedSpan of state.embedSpans.values()) {
3816
+ for (const embedSpan of state2.embedSpans.values()) {
3679
3817
  this.traceShipper.endSpan(embedSpan, { error: actualError });
3680
3818
  }
3681
- state.embedSpans.clear();
3682
- for (const toolCallId of state.parentContextToolCallIds) {
3819
+ state2.embedSpans.clear();
3820
+ for (const toolCallId of state2.parentContextToolCallIds) {
3683
3821
  this.priorParentContexts.delete(toolCallId);
3684
3822
  }
3685
- state.parentContextToolCallIds.clear();
3686
- for (const toolSpan of state.toolSpans.values()) {
3823
+ state2.parentContextToolCallIds.clear();
3824
+ for (const toolSpan of state2.toolSpans.values()) {
3687
3825
  this.traceShipper.endSpan(toolSpan, { error: actualError });
3688
3826
  }
3689
- state.toolSpans.clear();
3827
+ state2.toolSpans.clear();
3690
3828
  const abortReason = describeAbortReason(actualError);
3691
- if (state.rootSpan) {
3692
- this.traceShipper.endSpan(state.rootSpan, {
3829
+ if (state2.rootSpan) {
3830
+ this.traceShipper.endSpan(state2.rootSpan, {
3693
3831
  error: actualError,
3694
- attributes: this.abortOutcomeAttrs(state, abortReason, "error")
3832
+ attributes: this.abortOutcomeAttrs(state2, abortReason, "error")
3695
3833
  });
3696
3834
  }
3697
- if (state.subagentToolCallSpan) {
3698
- this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
3835
+ if (state2.subagentToolCallSpan) {
3836
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, { error: actualError });
3699
3837
  }
3700
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3838
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3701
3839
  if (!isEmbed) {
3702
- const errorIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3840
+ const errorIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3703
3841
  this.finalizeGenerateEvent(
3704
- state,
3705
- state.accumulatedText || void 0,
3842
+ state2,
3843
+ state2.accumulatedText || void 0,
3706
3844
  void 0,
3707
3845
  false,
3708
3846
  errorIsTheRunsOutcome ? { fallbackOutput: abortReason } : void 0
@@ -3721,51 +3859,51 @@ var RaindropTelemetryIntegration = class {
3721
3859
  this.onAbort = (event) => {
3722
3860
  const callId = event == null ? void 0 : event.callId;
3723
3861
  if (!callId) return;
3724
- const state = this.getState(callId);
3725
- if (!state) return;
3862
+ const state2 = this.getState(callId);
3863
+ if (!state2) return;
3726
3864
  const abortedAttr = attrString("ai.response.aborted", "true");
3727
- if (state.stepSpan) {
3728
- this.traceShipper.endSpan(state.stepSpan, { attributes: [abortedAttr] });
3729
- state.stepSpan = void 0;
3730
- state.stepParent = void 0;
3731
- state.stepProvider = void 0;
3732
- state.stepModelId = void 0;
3865
+ if (state2.stepSpan) {
3866
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: [abortedAttr] });
3867
+ state2.stepSpan = void 0;
3868
+ state2.stepParent = void 0;
3869
+ state2.stepProvider = void 0;
3870
+ state2.stepModelId = void 0;
3733
3871
  }
3734
- for (const embedSpan of state.embedSpans.values()) {
3872
+ for (const embedSpan of state2.embedSpans.values()) {
3735
3873
  this.traceShipper.endSpan(embedSpan, { attributes: [abortedAttr] });
3736
3874
  }
3737
- state.embedSpans.clear();
3738
- for (const toolCallId of state.parentContextToolCallIds) {
3875
+ state2.embedSpans.clear();
3876
+ for (const toolCallId of state2.parentContextToolCallIds) {
3739
3877
  this.priorParentContexts.delete(toolCallId);
3740
3878
  }
3741
- state.parentContextToolCallIds.clear();
3742
- for (const toolSpan of state.toolSpans.values()) {
3879
+ state2.parentContextToolCallIds.clear();
3880
+ for (const toolSpan of state2.toolSpans.values()) {
3743
3881
  this.traceShipper.endSpan(toolSpan, { attributes: [abortedAttr] });
3744
3882
  }
3745
- state.toolSpans.clear();
3746
- const abortIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3747
- if (state.rootSpan) {
3748
- this.traceShipper.endSpan(state.rootSpan, {
3883
+ state2.toolSpans.clear();
3884
+ const abortIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3885
+ if (state2.rootSpan) {
3886
+ this.traceShipper.endSpan(state2.rootSpan, {
3749
3887
  attributes: [
3750
3888
  abortedAttr,
3751
- attrInt("ai.toolCall.count", state.toolCallCount),
3889
+ attrInt("ai.toolCall.count", state2.toolCallCount),
3752
3890
  // An aborted detached child IS a cancelled sub-agent, and a cancelled
3753
3891
  // run is span-for-span identical to a finished one — spans close,
3754
3892
  // nothing errors, there is just no answer. So it is the one outcome
3755
3893
  // that has to be stated, and the child states it on itself.
3756
3894
  ...abortIsTheRunsOutcome ? cancelledSpanAttrs() : [],
3757
- ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3895
+ ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state2, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3758
3896
  ]
3759
3897
  });
3760
3898
  }
3761
- if (state.subagentToolCallSpan) {
3762
- this.traceShipper.endSpan(state.subagentToolCallSpan, {
3899
+ if (state2.subagentToolCallSpan) {
3900
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, {
3763
3901
  attributes: [abortedAttr]
3764
3902
  });
3765
3903
  }
3766
3904
  this.finalizeGenerateEvent(
3767
- state,
3768
- state.accumulatedText || void 0,
3905
+ state2,
3906
+ state2.accumulatedText || void 0,
3769
3907
  void 0,
3770
3908
  false,
3771
3909
  abortIsTheRunsOutcome ? {
@@ -3773,7 +3911,7 @@ var RaindropTelemetryIntegration = class {
3773
3911
  properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
3774
3912
  } : void 0
3775
3913
  );
3776
- if (abortIsTheRunsOutcome) this.subagents.noteSettled(state.eventId);
3914
+ if (abortIsTheRunsOutcome) this.subagents.noteSettled(state2.eventId);
3777
3915
  this.cleanup(callId);
3778
3916
  };
3779
3917
  // ── executeTool ─────────────────────────────────────────────────────────
@@ -3782,14 +3920,14 @@ var RaindropTelemetryIntegration = class {
3782
3920
  toolCallId,
3783
3921
  execute
3784
3922
  }) => {
3785
- const state = this.getState(callId);
3786
- const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
3923
+ const state2 = this.getState(callId);
3924
+ const toolSpan = state2 == null ? void 0 : state2.toolSpans.get(toolCallId);
3787
3925
  if (!toolSpan) return execute();
3788
3926
  return runWithParentSpanContext(
3789
3927
  {
3790
3928
  traceIdB64: toolSpan.ids.traceIdB64,
3791
3929
  spanIdB64: toolSpan.ids.spanIdB64,
3792
- eventId: state.eventId
3930
+ eventId: state2.eventId
3793
3931
  },
3794
3932
  () => execute()
3795
3933
  );
@@ -3838,35 +3976,35 @@ var RaindropTelemetryIntegration = class {
3838
3976
  activeDispatch() {
3839
3977
  var _a;
3840
3978
  const parentTool = getCurrentParentToolContext();
3841
- let state = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3979
+ let state2 = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3842
3980
  const inheritedEventId = (_a = getContextManager().getParentSpanIds()) == null ? void 0 : _a.eventId;
3843
- if (!state && inheritedEventId) {
3981
+ if (!state2 && inheritedEventId) {
3844
3982
  for (const candidate of this.callStates.values()) {
3845
3983
  if (candidate.eventId === inheritedEventId) {
3846
- state = candidate;
3984
+ state2 = candidate;
3847
3985
  break;
3848
3986
  }
3849
3987
  }
3850
3988
  }
3851
- if (!state) return void 0;
3989
+ if (!state2) return void 0;
3852
3990
  return {
3853
- eventId: state.eventId,
3854
- userId: state.identity.userId,
3855
- convoId: state.identity.convoId,
3856
- dispatchSpan: parentTool ? state.toolSpans.get(parentTool.toolCallId) : void 0,
3857
- turnSpans: [state.rootSpan, state.stepSpan].filter(
3991
+ eventId: state2.eventId,
3992
+ userId: state2.identity.userId,
3993
+ convoId: state2.identity.convoId,
3994
+ dispatchSpan: parentTool ? state2.toolSpans.get(parentTool.toolCallId) : void 0,
3995
+ turnSpans: [state2.rootSpan, state2.stepSpan].filter(
3858
3996
  (span) => span !== void 0
3859
3997
  ),
3860
- recordInputs: state.recordInputs
3998
+ recordInputs: state2.recordInputs
3861
3999
  };
3862
4000
  }
3863
4001
  /** Spans still open for an event, so a late outcome can still be stated. */
3864
4002
  openSpansForEvent(eventId) {
3865
4003
  const spans = [];
3866
- for (const state of this.callStates.values()) {
3867
- if (state.eventId !== eventId) continue;
3868
- if (state.rootSpan) spans.push(state.rootSpan);
3869
- if (state.stepSpan) spans.push(state.stepSpan);
4004
+ for (const state2 of this.callStates.values()) {
4005
+ if (state2.eventId !== eventId) continue;
4006
+ if (state2.rootSpan) spans.push(state2.rootSpan);
4007
+ if (state2.stepSpan) spans.push(state2.stepSpan);
3870
4008
  }
3871
4009
  return spans;
3872
4010
  }
@@ -3886,10 +4024,10 @@ var RaindropTelemetryIntegration = class {
3886
4024
  * created from an LLM span with output, `ai.response.text` here would state
3887
4025
  * the run's outcome through the span while the turn is still working.
3888
4026
  */
3889
- abortOutcomeAttrs(state, reason, finishReason) {
3890
- if (!state.handoff || state.nestedInEvent) return [];
4027
+ abortOutcomeAttrs(state2, reason, finishReason) {
4028
+ if (!state2.handoff || state2.nestedInEvent) return [];
3891
4029
  return [
3892
- attrString("ai.response.text", capText2(state.accumulatedText || reason)),
4030
+ attrString("ai.response.text", capText2(state2.accumulatedText || reason)),
3893
4031
  attrString("ai.response.finishReason", finishReason)
3894
4032
  ];
3895
4033
  }
@@ -3903,19 +4041,19 @@ var RaindropTelemetryIntegration = class {
3903
4041
  spanParentRef(span) {
3904
4042
  return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
3905
4043
  }
3906
- emitLive(state, type, content, extra) {
4044
+ emitLive(state2, type, content, extra) {
3907
4045
  var _a, _b, _c, _d, _e, _f;
3908
- if (!localDebuggerEnabled() || !state.rootSpan) return;
3909
- const callMeta = this.extractRaindropMetadata(state.metadata);
4046
+ if (!localDebuggerEnabled() || !state2.rootSpan) return;
4047
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
3910
4048
  sendLocalDebuggerLiveEvent({
3911
- traceId: state.rootSpan.ids.traceIdB64,
4049
+ traceId: state2.rootSpan.ids.traceIdB64,
3912
4050
  type,
3913
4051
  content,
3914
4052
  metadata: {
3915
4053
  userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
3916
4054
  convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
3917
4055
  eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
3918
- eventId: state.eventId,
4056
+ eventId: state2.eventId,
3919
4057
  ...extra
3920
4058
  }
3921
4059
  });
@@ -3993,29 +4131,29 @@ var RaindropTelemetryIntegration = class {
3993
4131
  toolCallId: toolCall.toolCallId,
3994
4132
  toolName: toolCall.toolName
3995
4133
  });
3996
- const state = this.getState(event.callId);
3997
- state == null ? void 0 : state.parentContextToolCallIds.add(toolCall.toolCallId);
3998
- if (!(state == null ? void 0 : state.stepParent)) return;
3999
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
4000
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
4134
+ const state2 = this.getState(event.callId);
4135
+ state2 == null ? void 0 : state2.parentContextToolCallIds.add(toolCall.toolCallId);
4136
+ if (!(state2 == null ? void 0 : state2.stepParent)) return;
4137
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4138
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
4001
4139
  const toolSpan = this.traceShipper.startSpan({
4002
4140
  name: "ai.toolCall",
4003
- parent: state.stepParent,
4004
- eventId: state.eventId,
4005
- ...state.identity,
4141
+ parent: state2.stepParent,
4142
+ eventId: state2.eventId,
4143
+ ...state2.identity,
4006
4144
  operationId: "ai.toolCall",
4007
4145
  attributes: [
4008
4146
  attrString("operation.name", operationName),
4009
4147
  attrString("resource.name", resourceName),
4010
- attrString("ai.telemetry.functionId", state.functionId),
4148
+ attrString("ai.telemetry.functionId", state2.functionId),
4011
4149
  attrString("ai.toolCall.name", toolCall.toolName),
4012
4150
  attrString("ai.toolCall.id", toolCall.toolCallId),
4013
4151
  ...inputAttrs,
4014
- ...handoffSpanAttrs(state.handoff)
4152
+ ...handoffSpanAttrs(state2.handoff)
4015
4153
  ]
4016
4154
  });
4017
- state.toolSpans.set(toolCall.toolCallId, toolSpan);
4018
- this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
4155
+ state2.toolSpans.set(toolCall.toolCallId, toolSpan);
4156
+ this.emitLive(state2, "tool_start", toolCall.toolName, { args: toolCall.input });
4019
4157
  }
4020
4158
  toolExecutionEnd(event) {
4021
4159
  var _a;
@@ -4029,20 +4167,20 @@ var RaindropTelemetryIntegration = class {
4029
4167
  clearParentToolContext();
4030
4168
  }
4031
4169
  }
4032
- const state = this.getState(event.callId);
4033
- if (!state) return;
4034
- const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
4170
+ const state2 = this.getState(event.callId);
4171
+ if (!state2) return;
4172
+ const toolSpan = state2.toolSpans.get(event.toolCall.toolCallId);
4035
4173
  if (!toolSpan) return;
4036
- state.toolCallCount += 1;
4174
+ state2.toolCallCount += 1;
4037
4175
  const outcome = "toolOutput" in event ? event.toolOutput.type === "tool-result" ? { success: true, output: event.toolOutput.output } : { success: false, error: event.toolOutput.error } : event.success ? { success: true, output: event.output } : { success: false, error: event.error };
4038
4176
  if (outcome.success) {
4039
- const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4177
+ const outputAttrs = state2.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4040
4178
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4041
4179
  } else {
4042
4180
  this.traceShipper.endSpan(toolSpan, { error: outcome.error });
4043
4181
  }
4044
- this.emitLive(state, "tool_result", event.toolCall.toolName);
4045
- state.toolSpans.delete(event.toolCall.toolCallId);
4182
+ this.emitLive(state2, "tool_result", event.toolCall.toolName);
4183
+ state2.toolSpans.delete(event.toolCall.toolCallId);
4046
4184
  }
4047
4185
  // ── provider-executed tool calls ─────────────────────────────────────────
4048
4186
  //
@@ -4061,8 +4199,8 @@ var RaindropTelemetryIntegration = class {
4061
4199
  //
4062
4200
  // Client-executed tools are excluded (`providerExecuted` falsy) — they were
4063
4201
  // already spanned during execution, so this never double-emits.
4064
- emitProviderExecutedToolSpans(event, state) {
4065
- if (!state.stepParent) return;
4202
+ emitProviderExecutedToolSpans(event, state2) {
4203
+ if (!state2.stepParent) return;
4066
4204
  const content = Array.isArray(event.content) ? event.content : [];
4067
4205
  const providerToolCalls = content.filter(
4068
4206
  (part) => (part == null ? void 0 : part.type) === "tool-call" && part.providerExecuted === true
@@ -4075,42 +4213,42 @@ var RaindropTelemetryIntegration = class {
4075
4213
  }
4076
4214
  }
4077
4215
  for (const call of providerToolCalls) {
4078
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
4079
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4216
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4217
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4080
4218
  const toolSpan = this.traceShipper.startSpan({
4081
4219
  name: "ai.toolCall",
4082
- parent: state.stepParent,
4083
- eventId: state.eventId,
4084
- ...state.identity,
4220
+ parent: state2.stepParent,
4221
+ eventId: state2.eventId,
4222
+ ...state2.identity,
4085
4223
  operationId: "ai.toolCall",
4086
4224
  attributes: [
4087
4225
  attrString("operation.name", operationName),
4088
4226
  attrString("resource.name", resourceName),
4089
- attrString("ai.telemetry.functionId", state.functionId),
4227
+ attrString("ai.telemetry.functionId", state2.functionId),
4090
4228
  attrString("ai.toolCall.name", call.toolName),
4091
4229
  attrString("ai.toolCall.id", call.toolCallId),
4092
4230
  attrString("ai.toolCall.providerExecuted", "true"),
4093
4231
  ...inputAttrs,
4094
- ...handoffSpanAttrs(state.handoff)
4232
+ ...handoffSpanAttrs(state2.handoff)
4095
4233
  ]
4096
4234
  });
4097
- state.toolCallCount += 1;
4098
- this.emitLive(state, "tool_start", call.toolName, { args: call.input });
4235
+ state2.toolCallCount += 1;
4236
+ this.emitLive(state2, "tool_start", call.toolName, { args: call.input });
4099
4237
  const resultPart = resultsByCallId.get(call.toolCallId);
4100
4238
  if ((resultPart == null ? void 0 : resultPart.type) === "tool-error") {
4101
4239
  this.traceShipper.endSpan(toolSpan, { error: resultPart.error });
4102
4240
  } else {
4103
- const outputAttrs = state.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4241
+ const outputAttrs = state2.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4104
4242
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4105
4243
  }
4106
- this.emitLive(state, "tool_result", call.toolName);
4244
+ this.emitLive(state2, "tool_result", call.toolName);
4107
4245
  }
4108
4246
  }
4109
- finishGenerate(event, state) {
4247
+ finishGenerate(event, state2) {
4110
4248
  var _a, _b, _c, _d, _e, _f;
4111
- if (state.rootSpan) {
4249
+ if (state2.rootSpan) {
4112
4250
  const outputAttrs = [];
4113
- if (state.recordOutputs) {
4251
+ if (state2.recordOutputs) {
4114
4252
  outputAttrs.push(
4115
4253
  attrString("ai.response.finishReason", event.finishReason),
4116
4254
  attrString("ai.response.text", capText2((_a = event.text) != null ? _a : void 0)),
@@ -4151,12 +4289,12 @@ var RaindropTelemetryIntegration = class {
4151
4289
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens)
4152
4290
  );
4153
4291
  }
4154
- outputAttrs.push(attrInt("ai.toolCall.count", state.toolCallCount));
4155
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4292
+ outputAttrs.push(attrInt("ai.toolCall.count", state2.toolCallCount));
4293
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4156
4294
  }
4157
4295
  this.finalizeGenerateEvent(
4158
- state,
4159
- (_e = event.text) != null ? _e : state.accumulatedText || void 0,
4296
+ state2,
4297
+ (_e = event.text) != null ? _e : state2.accumulatedText || void 0,
4160
4298
  (_f = event.response) == null ? void 0 : _f.modelId,
4161
4299
  hasUnresolvedToolApproval(event)
4162
4300
  );
@@ -4172,29 +4310,29 @@ var RaindropTelemetryIntegration = class {
4172
4310
  * is finalized by that resume — otherwise each execution would finalize the
4173
4311
  * same event ID into a separate canonical row.
4174
4312
  */
4175
- finalizeGenerateEvent(state, output, model, keepPending = false, detachedOutcome) {
4313
+ finalizeGenerateEvent(state2, output, model, keepPending = false, detachedOutcome) {
4176
4314
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
4177
- const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
4315
+ const suppressSubagentEvent = state2.subagentName !== void 0 && state2.subagentToolCallSpan !== void 0;
4178
4316
  if (!this.sendEvents || suppressSubagentEvent) return;
4179
- if (this.subagents.wasSettledExplicitly(state.eventId)) return;
4180
- const callMeta = this.extractRaindropMetadata(state.metadata);
4317
+ if (this.subagents.wasSettledExplicitly(state2.eventId)) return;
4318
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
4181
4319
  const userId = (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId;
4182
4320
  if (!userId) return;
4183
- const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state.operationId;
4321
+ const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state2.operationId;
4184
4322
  const cappedOutput = capText2(output);
4185
- const reportedOutput = state.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4186
- const input = capText2(state.inputText);
4323
+ const reportedOutput = state2.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4324
+ const input = capText2(state2.inputText);
4187
4325
  const properties = {
4188
4326
  ...(_f = this.defaultContext) == null ? void 0 : _f.properties,
4189
4327
  ...callMeta.properties,
4190
- ...state.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4328
+ ...state2.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4191
4329
  };
4192
4330
  const featureFlags = {
4193
4331
  ...((_g = this.defaultContext) == null ? void 0 : _g.featureFlags) ? normalizeFeatureFlags(this.defaultContext.featureFlags) : {},
4194
4332
  ...callMeta.featureFlags
4195
4333
  };
4196
4334
  const convoId = (_i = callMeta.convoId) != null ? _i : (_h = this.defaultContext) == null ? void 0 : _h.convoId;
4197
- void this.eventShipper.patch(state.eventId, {
4335
+ void this.eventShipper.patch(state2.eventId, {
4198
4336
  eventName,
4199
4337
  userId,
4200
4338
  convoId,
@@ -4212,12 +4350,12 @@ var RaindropTelemetryIntegration = class {
4212
4350
  }
4213
4351
  });
4214
4352
  }
4215
- finishEmbed(event, state) {
4353
+ finishEmbed(event, state2) {
4216
4354
  var _a;
4217
- if (!state.rootSpan) return;
4355
+ if (!state2.rootSpan) return;
4218
4356
  const outputAttrs = [];
4219
- const isMany = state.operationId === "ai.embedMany";
4220
- if (state.recordOutputs) {
4357
+ const isMany = state2.operationId === "ai.embedMany";
4358
+ if (state2.recordOutputs) {
4221
4359
  if (isMany) {
4222
4360
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embedding)));
4223
4361
  } else {
@@ -4227,7 +4365,7 @@ var RaindropTelemetryIntegration = class {
4227
4365
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
4228
4366
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
4229
4367
  }
4230
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4368
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4231
4369
  }
4232
4370
  };
4233
4371
 
@@ -4536,9 +4674,7 @@ function extractRaindropMetadata(metadata) {
4536
4674
  } catch (e) {
4537
4675
  }
4538
4676
  } else if (featureFlags && typeof featureFlags === "object") {
4539
- result.featureFlags = normalizeFeatureFlags(
4540
- featureFlags
4541
- );
4677
+ result.featureFlags = normalizeFeatureFlags(featureFlags);
4542
4678
  }
4543
4679
  return result;
4544
4680
  }
@@ -4749,12 +4885,7 @@ function setupOperation(params) {
4749
4885
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
4750
4886
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
4751
4887
  ...attrsFromSettings(arg),
4752
- ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
4753
- attrString(
4754
- "ai.prompt",
4755
- safeJsonWithUint8(normalizePromptAttr(arg))
4756
- )
4757
- ]
4888
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [attrString("ai.prompt", safeJsonWithUint8(normalizePromptAttr(arg)))]
4758
4889
  ]
4759
4890
  }) : void 0;
4760
4891
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
@@ -5104,7 +5235,10 @@ function wrapAISDK(aiSDK, deps) {
5104
5235
  }
5105
5236
  const useNative = deps.options.nativeTelemetry === true;
5106
5237
  if (useNative) {
5107
- const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
5238
+ const wrapTimeCtx = resolveContext(deps.options.context, {
5239
+ operation: "wrap",
5240
+ args: void 0
5241
+ });
5108
5242
  const integration = new RaindropTelemetryIntegration({
5109
5243
  traceShipper: deps.traceShipper,
5110
5244
  eventShipper: deps.eventShipper,
@@ -5349,7 +5483,13 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
5349
5483
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
5350
5484
  attrString(
5351
5485
  "ai.prompt",
5352
- safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
5486
+ safeJsonWithUint8(
5487
+ normalizePromptAttr({
5488
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
5489
+ prompt: mergedArgs["prompt"],
5490
+ messages: mergedArgs["messages"]
5491
+ })
5492
+ )
5353
5493
  )
5354
5494
  ]
5355
5495
  ]
@@ -5563,7 +5703,13 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
5563
5703
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
5564
5704
  attrString(
5565
5705
  "ai.prompt",
5566
- safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
5706
+ safeJsonWithUint8(
5707
+ normalizePromptAttr({
5708
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
5709
+ prompt: mergedArgs["prompt"],
5710
+ messages: mergedArgs["messages"]
5711
+ })
5712
+ )
5567
5713
  )
5568
5714
  ]
5569
5715
  ]
@@ -5940,9 +6086,19 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
5940
6086
  for (const part of content) {
5941
6087
  if (isRecord(part)) {
5942
6088
  if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
5943
- sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
6089
+ sendLocalDebuggerLiveEvent({
6090
+ traceId,
6091
+ type: "reasoning_delta",
6092
+ content: (_b = part["text"]) != null ? _b : part["thinking"],
6093
+ metadata: liveMeta
6094
+ });
5944
6095
  } else if (part["type"] === "text" && typeof part["text"] === "string") {
5945
- sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
6096
+ sendLocalDebuggerLiveEvent({
6097
+ traceId,
6098
+ type: "text_delta",
6099
+ content: part["text"],
6100
+ metadata: liveMeta
6101
+ });
5946
6102
  }
5947
6103
  }
5948
6104
  }
@@ -6023,7 +6179,10 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6023
6179
  attributes: [
6024
6180
  ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
6025
6181
  attrString("ai.response.finishReason", finishReason),
6026
- attrString("ai.response.text", activeText.length ? capText2(activeText) : void 0),
6182
+ attrString(
6183
+ "ai.response.text",
6184
+ activeText.length ? capText2(activeText) : void 0
6185
+ ),
6027
6186
  attrString(
6028
6187
  "ai.response.toolCalls",
6029
6188
  safeJsonWithUint8(toolCallsLocal.length ? toolCallsLocal : void 0)
@@ -6041,7 +6200,8 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6041
6200
  ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
6042
6201
  attrString("gen_ai.response.id", responseId),
6043
6202
  attrString(MODEL_USAGE_ATTRIBUTES.responseModel, finalResponseModelId),
6044
- ...buildModelUsageAttributes(usageMetrics),
6203
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
6204
+ ...buildRawModelUsageAttributes(usageMetrics),
6045
6205
  ...msToFirstChunk !== void 0 ? [attrInt("ai.stream.msToFirstChunk", msToFirstChunk)] : [],
6046
6206
  ...msToFinish !== void 0 ? [attrInt("ai.stream.msToFinish", msToFinish)] : [],
6047
6207
  ...avgOutTokensPerSecond !== void 0 ? [attrDouble("ai.stream.avgOutputTokensPerSecond", avgOutTokensPerSecond)] : [],
@@ -6095,19 +6255,44 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6095
6255
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
6096
6256
  if (localDebuggerEnabled() && ctx.rootParentForChildren) {
6097
6257
  const traceId = ctx.rootParentForChildren.traceIdB64;
6098
- const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
6258
+ const liveMeta = getLocalDebuggerMetadata({
6259
+ ...ctx.context,
6260
+ eventId: ctx.eventId
6261
+ });
6099
6262
  if (type === "text-delta") {
6100
6263
  const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
6101
- if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
6264
+ if (typeof text === "string" && text)
6265
+ sendLocalDebuggerLiveEvent({
6266
+ traceId,
6267
+ type: "text_delta",
6268
+ content: text,
6269
+ metadata: liveMeta
6270
+ });
6102
6271
  } else if (type === "reasoning" || type === "reasoning-delta") {
6103
6272
  const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
6104
- if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
6273
+ if (typeof text === "string" && text)
6274
+ sendLocalDebuggerLiveEvent({
6275
+ traceId,
6276
+ type: "reasoning_delta",
6277
+ content: text,
6278
+ metadata: liveMeta
6279
+ });
6105
6280
  } else if (type === "tool-call") {
6106
6281
  const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
6107
- sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
6282
+ sendLocalDebuggerLiveEvent({
6283
+ traceId,
6284
+ type: "tool_start",
6285
+ content: toolName,
6286
+ metadata: { ...liveMeta, args: value["args"] }
6287
+ });
6108
6288
  } else if (type === "tool-result") {
6109
6289
  const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
6110
- sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
6290
+ sendLocalDebuggerLiveEvent({
6291
+ traceId,
6292
+ type: "tool_result",
6293
+ content: toolName,
6294
+ metadata: { ...liveMeta, result: value["result"] }
6295
+ });
6111
6296
  }
6112
6297
  }
6113
6298
  }
@@ -6187,11 +6372,7 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
6187
6372
  } else {
6188
6373
  responseTimestampIso = (/* @__PURE__ */ new Date()).toISOString();
6189
6374
  }
6190
- const usageMetrics = extractUsageMetricsFromUsage(
6191
- usage,
6192
- modelInfo.provider,
6193
- providerMetadata
6194
- );
6375
+ const usageMetrics = extractUsageMetricsFromUsage(usage, modelInfo.provider, providerMetadata);
6195
6376
  const { inputTokens, outputTokens } = usageMetrics;
6196
6377
  ctx.traceShipper.endSpan(span, {
6197
6378
  attributes: [
@@ -6212,7 +6393,8 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
6212
6393
  ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
6213
6394
  attrString("gen_ai.response.id", responseId),
6214
6395
  attrString(MODEL_USAGE_ATTRIBUTES.responseModel, responseModelId),
6215
- ...buildModelUsageAttributes(usageMetrics)
6396
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
6397
+ ...buildRawModelUsageAttributes(usageMetrics)
6216
6398
  ]
6217
6399
  });
6218
6400
  }