@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.
@@ -1,4 +1,66 @@
1
- // ../core/dist/chunk-YUIXRQWN.js
1
+ // ../core/dist/chunk-BYBMRLZM.js
2
+ var EVAL_CORRELATION_ID_ATTRIBUTE = "raindrop.eval_correlation_id";
3
+ var PROBE_SCOPE = { correlationId: "" };
4
+ var EvalScopeStorage = class {
5
+ constructor() {
6
+ this._als = null;
7
+ this._probed = false;
8
+ }
9
+ maybeAdoptAsyncLocalStorage() {
10
+ if (this._probed) return;
11
+ this._probed = true;
12
+ try {
13
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
14
+ if (!Ctor) return;
15
+ const als = new Ctor();
16
+ als.run(PROBE_SCOPE, () => {
17
+ });
18
+ this._als = als;
19
+ } catch (e) {
20
+ this._als = null;
21
+ }
22
+ }
23
+ run(scope, callback) {
24
+ this.maybeAdoptAsyncLocalStorage();
25
+ if (this._als) return this._als.run(scope, callback);
26
+ const previous = this._syncScope;
27
+ this._syncScope = scope;
28
+ try {
29
+ return callback();
30
+ } finally {
31
+ this._syncScope = previous;
32
+ }
33
+ }
34
+ current() {
35
+ this.maybeAdoptAsyncLocalStorage();
36
+ if (this._als) return this._als.getStore();
37
+ return this._syncScope;
38
+ }
39
+ };
40
+ var EVAL_SCOPE_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.evalScopeStorage");
41
+ function evalScopeStorage() {
42
+ const holder = globalThis;
43
+ let storage = holder[EVAL_SCOPE_STORAGE_KEY];
44
+ if (!storage) {
45
+ storage = new EvalScopeStorage();
46
+ holder[EVAL_SCOPE_STORAGE_KEY] = storage;
47
+ }
48
+ return storage;
49
+ }
50
+ function currentEvalScope() {
51
+ try {
52
+ return evalScopeStorage().current();
53
+ } catch (e) {
54
+ return void 0;
55
+ }
56
+ }
57
+ function evalScopeAttributes() {
58
+ const scope = currentEvalScope();
59
+ if (!scope) return {};
60
+ return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
61
+ }
62
+
63
+ // ../core/dist/chunk-T53LQAH7.js
2
64
  function normalizeFeatureFlags(input) {
3
65
  if (Array.isArray(input)) {
4
66
  return Object.fromEntries(input.map((name) => [name, "true"]));
@@ -493,6 +555,7 @@ async function postJson(url, body, headers, opts) {
493
555
  const resp = await runWithTracingSuppressed(
494
556
  () => fetch(url, {
495
557
  method: "POST",
558
+ redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
496
559
  headers: {
497
560
  "Content-Type": "application/json",
498
561
  ...headers
@@ -616,6 +679,55 @@ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", se
616
679
  ]
617
680
  };
618
681
  }
682
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
683
+ function state() {
684
+ const holder = globalThis;
685
+ let current = holder[STATE_KEY];
686
+ if (!current) {
687
+ let storage = null;
688
+ try {
689
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
690
+ if (Ctor) storage = new Ctor();
691
+ } catch (e) {
692
+ storage = null;
693
+ }
694
+ current = {
695
+ storage,
696
+ syncDestination: void 0,
697
+ spanDestinations: /* @__PURE__ */ new WeakMap()
698
+ };
699
+ holder[STATE_KEY] = current;
700
+ }
701
+ return current;
702
+ }
703
+ function currentReplayTraceDestination() {
704
+ var _a, _b;
705
+ const routing = state();
706
+ return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
707
+ }
708
+ function rememberReplayTraceDestination(span) {
709
+ const destination = currentReplayTraceDestination();
710
+ if (destination) state().spanDestinations.set(span, destination);
711
+ }
712
+ function copyReplayTraceDestination(source, target) {
713
+ const destination = state().spanDestinations.get(source);
714
+ if (destination) state().spanDestinations.set(target, destination);
715
+ }
716
+ function replayTraceDestinationFor(value) {
717
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
718
+ return void 0;
719
+ }
720
+ return state().spanDestinations.get(value);
721
+ }
722
+ function recordReplayExportedSpan(destination, spanId, traceId) {
723
+ var _a, _b;
724
+ if (!destination || !spanId || !traceId) return;
725
+ (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
726
+ (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
727
+ }
728
+ function replayTraceUrl(baseUrl) {
729
+ return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
730
+ }
619
731
  var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
620
732
  var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
621
733
  var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
@@ -681,31 +793,36 @@ function resolveLocalDebuggerBaseUrl(baseUrl) {
681
793
  function localDebuggerEnabled(baseUrl) {
682
794
  return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
683
795
  }
796
+ var LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS = 2e3;
684
797
  function mirrorTraceExportToLocalDebugger(body, options = {}) {
685
798
  var _a;
686
799
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
687
- if (!baseUrl) return;
688
- void postJson(`${baseUrl}traces`, body, {}, {
800
+ if (!baseUrl) return Promise.resolve();
801
+ return postJson(`${baseUrl}traces`, body, {}, {
689
802
  maxAttempts: 1,
690
803
  debug: (_a = options.debug) != null ? _a : false,
691
- sdkName: options.sdkName
804
+ sdkName: options.sdkName,
805
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
692
806
  }).catch(() => {
693
807
  });
694
808
  }
695
809
  function mirrorPartialEventToLocalDebugger(event, options = {}) {
696
810
  var _a;
697
811
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
698
- if (!baseUrl) return;
812
+ if (!baseUrl) return Promise.resolve();
699
813
  const headers = options.writeKey ? { Authorization: `Bearer ${options.writeKey}` } : {};
700
- void postJson(`${baseUrl}events/track_partial`, event, headers, {
814
+ return postJson(`${baseUrl}events/track_partial`, event, headers, {
701
815
  maxAttempts: 1,
702
816
  debug: (_a = options.debug) != null ? _a : false,
703
- sdkName: options.sdkName
817
+ sdkName: options.sdkName,
818
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
704
819
  }).catch(() => {
705
820
  });
706
821
  }
707
822
  function sendLocalDebuggerLiveEvent(event, options = {}) {
708
823
  var _a, _b;
824
+ const destination = currentReplayTraceDestination();
825
+ if (destination && destination.kind !== "workshop") return;
709
826
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
710
827
  if (!baseUrl) return;
711
828
  void postJson(
@@ -877,6 +994,15 @@ var EventShipper = class {
877
994
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
878
995
  if (!this.enabled) return;
879
996
  if (!eventId || !eventId.trim()) return;
997
+ const capturedSticky = this.sticky.get(eventId);
998
+ const eventAlreadyKnown = capturedSticky !== void 0 || this.buffers.has(eventId);
999
+ const destination = currentReplayTraceDestination();
1000
+ const cloudReplay = destination !== void 0 && destination.kind !== "workshop";
1001
+ if ((capturedSticky == null ? void 0 : capturedSticky.replayOnly) === true || !eventAlreadyKnown && cloudReplay) {
1002
+ if (patch.isPending === false) this.sticky.delete(eventId);
1003
+ else this.sticky.set(eventId, { ...capturedSticky, replayOnly: true });
1004
+ return;
1005
+ }
880
1006
  const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
881
1007
  if (typeof patch.input === "string" && patch.input.length > maxChars) {
882
1008
  patch = { ...patch, input: capText(patch.input, maxChars) };
@@ -935,6 +1061,9 @@ var EventShipper = class {
935
1061
  try {
936
1062
  for (const t of this.timers.values()) clearTimeout(t);
937
1063
  this.timers.clear();
1064
+ for (const [eventId, sticky] of this.sticky) {
1065
+ if (sticky.replayOnly) this.sticky.delete(eventId);
1066
+ }
938
1067
  const settled = await raceWithTimeout(this.flush(), SHUTDOWN_DEADLINE_MS);
939
1068
  if (!settled) this.warnShutdownDrop("in-flight request(s) at shutdown");
940
1069
  } finally {
@@ -944,6 +1073,8 @@ var EventShipper = class {
944
1073
  async trackSignal(signal) {
945
1074
  var _a, _b;
946
1075
  if (!this.enabled) return;
1076
+ const destination = currentReplayTraceDestination();
1077
+ if (destination && destination.kind !== "workshop") return;
947
1078
  const body = [
948
1079
  {
949
1080
  event_id: signal.eventId,
@@ -978,6 +1109,8 @@ var EventShipper = class {
978
1109
  }
979
1110
  async identify(users) {
980
1111
  if (!this.enabled) return;
1112
+ const destination = currentReplayTraceDestination();
1113
+ if (destination && destination.kind !== "workshop") return;
981
1114
  const list = Array.isArray(users) ? users : [users];
982
1115
  const body = list.filter((user) => {
983
1116
  if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
@@ -1030,8 +1163,9 @@ var EventShipper = class {
1030
1163
  this.buffers.delete(eventId);
1031
1164
  if (!accumulated) return;
1032
1165
  const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
1033
- const eventName = (_c = (_b = accumulated.eventName) != null ? _b : sticky.eventName) != null ? _c : this.defaultEventName;
1034
- const userId = (_d = accumulated.userId) != null ? _d : sticky.userId;
1166
+ const isPending = (_c = (_b = accumulated.isPending) != null ? _b : sticky.isPending) != null ? _c : true;
1167
+ const eventName = (_e = (_d = accumulated.eventName) != null ? _d : sticky.eventName) != null ? _e : this.defaultEventName;
1168
+ const userId = (_f = accumulated.userId) != null ? _f : sticky.userId;
1035
1169
  if (!userId) {
1036
1170
  if (this.debug) {
1037
1171
  console.warn(`${this.prefix} skipping track_partial for ${eventId}: missing userId`);
@@ -1039,14 +1173,13 @@ var EventShipper = class {
1039
1173
  this.sticky.delete(eventId);
1040
1174
  return;
1041
1175
  }
1042
- const { wizardSession, ...restProperties } = (_e = accumulated.properties) != null ? _e : {};
1176
+ const { wizardSession, ...restProperties } = (_g = accumulated.properties) != null ? _g : {};
1043
1177
  let telemetryProperties = {};
1044
1178
  try {
1045
1179
  telemetryProperties = eventTelemetryProperties(accumulated);
1046
1180
  } catch (e) {
1047
1181
  }
1048
- const convoId = (_f = accumulated.convoId) != null ? _f : sticky.convoId;
1049
- const isPending = (_h = (_g = accumulated.isPending) != null ? _g : sticky.isPending) != null ? _h : true;
1182
+ const convoId = (_h = accumulated.convoId) != null ? _h : sticky.convoId;
1050
1183
  const payload = {
1051
1184
  event_id: eventId,
1052
1185
  user_id: userId,
@@ -1088,29 +1221,30 @@ var EventShipper = class {
1088
1221
  endpoint: url
1089
1222
  });
1090
1223
  }
1091
- if (this.localDebuggerUrl) {
1092
- mirrorPartialEventToLocalDebugger(payload, {
1093
- baseUrl: this.localDebuggerUrl,
1094
- writeKey: this.writeKey,
1095
- debug: this.debug,
1096
- sdkName: this.sdkName
1097
- });
1098
- }
1224
+ const mirror = this.localDebuggerUrl ? mirrorPartialEventToLocalDebugger(payload, {
1225
+ baseUrl: this.localDebuggerUrl,
1226
+ writeKey: this.writeKey,
1227
+ debug: this.debug,
1228
+ sdkName: this.sdkName
1229
+ }) : void 0;
1099
1230
  if (!this.writeKey) {
1100
1231
  if (!isPending) this.sticky.delete(eventId);
1232
+ if (mirror) await mirror;
1101
1233
  return;
1102
1234
  }
1103
1235
  const opts = this.requestOpts();
1104
1236
  if (!opts) {
1105
1237
  this.warnShutdownDrop(`track_partial ${eventId}`);
1106
1238
  if (!isPending) this.sticky.delete(eventId);
1239
+ if (mirror) await mirror;
1107
1240
  return;
1108
1241
  }
1109
1242
  const p = postJson(url, payload, this.requestHeaders(), opts);
1110
- this.inFlight.add(p);
1243
+ const combined = mirror ? Promise.all([mirror, p]).then(() => void 0) : p;
1244
+ this.inFlight.add(combined);
1111
1245
  try {
1112
1246
  try {
1113
- await p;
1247
+ await combined;
1114
1248
  if (this.debug) {
1115
1249
  console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
1116
1250
  }
@@ -1122,7 +1256,7 @@ var EventShipper = class {
1122
1256
  );
1123
1257
  }
1124
1258
  } finally {
1125
- this.inFlight.delete(p);
1259
+ this.inFlight.delete(combined);
1126
1260
  }
1127
1261
  if (!isPending) {
1128
1262
  this.sticky.delete(eventId);
@@ -1130,6 +1264,7 @@ var EventShipper = class {
1130
1264
  }
1131
1265
  };
1132
1266
  var MODEL_USAGE_ATTRIBUTES = {
1267
+ usageSource: "raindrop.usage.source",
1133
1268
  providerName: "gen_ai.provider.name",
1134
1269
  requestModel: "gen_ai.request.model",
1135
1270
  responseModel: "gen_ai.response.model",
@@ -1138,20 +1273,22 @@ var MODEL_USAGE_ATTRIBUTES = {
1138
1273
  reasoningTokens: "gen_ai.usage.reasoning_tokens",
1139
1274
  cacheReadInputTokens: "gen_ai.usage.cache_read_input_tokens",
1140
1275
  cacheWriteInputTokens: "gen_ai.usage.cache_write_input_tokens",
1141
- nonCachedInputTokens: "raindrop.usage.input_tokens.non_cached",
1142
- nonReasoningOutputTokens: "raindrop.usage.output_tokens.non_reasoning",
1143
- reasoningOutputTokens: "raindrop.usage.output_tokens.reasoning",
1144
- cacheReadTokens: "raindrop.usage.input_tokens.cache_read",
1145
- cacheWriteTokens: "raindrop.usage.input_tokens.cache_write"
1146
- };
1276
+ providerReportedCost: "gen_ai.usage.provider_reported_cost"};
1147
1277
  var MODEL_PROVIDER_NAMES = [
1278
+ ["google.vertex.anthropic", "google-vertex"],
1279
+ ["google.vertex_ai", "google-vertex"],
1148
1280
  ["google.vertex", "google-vertex"],
1281
+ ["gcp.vertex_ai", "google-vertex"],
1282
+ ["gcp.gemini", "google"],
1283
+ ["google_vertexai", "google-vertex"],
1149
1284
  ["vertex.anthropic", "google-vertex"],
1150
1285
  ["amazon-bedrock", "amazon-bedrock"],
1286
+ ["aws.bedrock", "amazon-bedrock"],
1151
1287
  ["bedrock", "amazon-bedrock"],
1152
1288
  ["anthropic", "anthropic"],
1153
1289
  ["openai", "openai"],
1154
1290
  ["google", "google"],
1291
+ ["az.ai.openai", "azure"],
1155
1292
  ["azure", "azure"],
1156
1293
  ["openrouter", "openrouter"]
1157
1294
  ];
@@ -1162,60 +1299,20 @@ function canonicalModelProvider(provider) {
1162
1299
  const match = MODEL_PROVIDER_NAMES.find(
1163
1300
  ([family]) => normalizedProvider === family || normalizedProvider.startsWith(`${family}.`)
1164
1301
  );
1165
- return (_a = match == null ? void 0 : match[1]) != null ? _a : provider;
1302
+ return (_a = match == null ? void 0 : match[1]) != null ? _a : normalizedProvider;
1166
1303
  }
1167
1304
  function tokenCount(value) {
1168
1305
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1169
1306
  }
1170
- function exclusiveTokens({
1171
- explicit,
1172
- total,
1173
- parts,
1174
- semantics
1175
- }) {
1176
- if (explicit !== void 0) return explicit;
1177
- if (total === void 0) return void 0;
1178
- if (semantics === "exclusive") return total;
1179
- const observedParts = parts.filter((part) => part !== void 0 && part > 0);
1180
- if (semantics === void 0 && observedParts.length > 0) return void 0;
1181
- const exclusive = total - observedParts.reduce((sum, part) => sum + part, 0);
1182
- return exclusive >= 0 ? exclusive : void 0;
1183
- }
1184
- function buildModelUsageAttributes(usage) {
1185
- const inputTokens = tokenCount(usage.inputTokens);
1186
- const outputTokens = tokenCount(usage.outputTokens);
1187
- const explicitNonCachedInputTokens = tokenCount(usage.nonCachedInputTokens);
1188
- const explicitNonReasoningOutputTokens = tokenCount(usage.nonReasoningOutputTokens);
1189
- const reasoningTokens = tokenCount(usage.reasoningTokens);
1190
- const cacheReadInputTokens = tokenCount(usage.cacheReadInputTokens);
1191
- const cacheWriteInputTokens = tokenCount(usage.cacheWriteInputTokens);
1192
- const nonCachedInputTokens = exclusiveTokens({
1193
- explicit: explicitNonCachedInputTokens,
1194
- total: inputTokens,
1195
- parts: [cacheReadInputTokens, cacheWriteInputTokens],
1196
- semantics: usage.inputTokenSemantics
1197
- });
1198
- const nonReasoningOutputTokens = exclusiveTokens({
1199
- explicit: explicitNonReasoningOutputTokens,
1200
- total: outputTokens,
1201
- parts: [reasoningTokens],
1202
- semantics: usage.outputTokenSemantics
1203
- });
1204
- const exclusivePoolAttributes = nonCachedInputTokens !== void 0 && nonReasoningOutputTokens !== void 0 ? [
1205
- // backend consumes this complete raindrop.* set as one atomic billing-pool contract.
1206
- attrInt(MODEL_USAGE_ATTRIBUTES.nonCachedInputTokens, nonCachedInputTokens),
1207
- attrInt(MODEL_USAGE_ATTRIBUTES.nonReasoningOutputTokens, nonReasoningOutputTokens),
1208
- attrInt(MODEL_USAGE_ATTRIBUTES.reasoningOutputTokens, reasoningTokens),
1209
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadTokens, cacheReadInputTokens),
1210
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteTokens, cacheWriteInputTokens)
1211
- ] : [];
1307
+ function buildRawModelUsageAttributes(usage) {
1308
+ const providerReportedCost = typeof usage.providerReportedCost === "number" && Number.isFinite(usage.providerReportedCost) && usage.providerReportedCost >= 0 ? usage.providerReportedCost : void 0;
1212
1309
  return [
1213
- attrInt(MODEL_USAGE_ATTRIBUTES.inputTokens, inputTokens),
1214
- attrInt(MODEL_USAGE_ATTRIBUTES.outputTokens, outputTokens),
1215
- attrInt(MODEL_USAGE_ATTRIBUTES.reasoningTokens, reasoningTokens),
1216
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadInputTokens, cacheReadInputTokens),
1217
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteInputTokens, cacheWriteInputTokens),
1218
- ...exclusivePoolAttributes
1310
+ attrInt(MODEL_USAGE_ATTRIBUTES.inputTokens, tokenCount(usage.inputTokens)),
1311
+ attrInt(MODEL_USAGE_ATTRIBUTES.outputTokens, tokenCount(usage.outputTokens)),
1312
+ attrInt(MODEL_USAGE_ATTRIBUTES.reasoningTokens, tokenCount(usage.reasoningTokens)),
1313
+ attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadInputTokens, tokenCount(usage.cacheReadInputTokens)),
1314
+ attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteInputTokens, tokenCount(usage.cacheWriteInputTokens)),
1315
+ attrDouble(MODEL_USAGE_ATTRIBUTES.providerReportedCost, providerReportedCost)
1219
1316
  ].filter((attribute) => attribute !== void 0);
1220
1317
  }
1221
1318
  var STRING_ALIASES = {
@@ -1507,7 +1604,10 @@ var TraceShipper = class {
1507
1604
  try {
1508
1605
  const result = this.transformSpanHook(current);
1509
1606
  if (result === null) return null;
1510
- if (result !== void 0) current = result;
1607
+ if (result !== void 0) {
1608
+ copyReplayTraceDestination(current, result);
1609
+ current = result;
1610
+ }
1511
1611
  } catch (err) {
1512
1612
  if (this.debug) {
1513
1613
  const msg = err instanceof Error ? err.message : String(err);
@@ -1517,13 +1617,19 @@ var TraceShipper = class {
1517
1617
  }
1518
1618
  }
1519
1619
  try {
1520
- current = normalizeModelUsageSpan(current);
1620
+ const normalized = normalizeModelUsageSpan(current);
1621
+ copyReplayTraceDestination(current, normalized);
1622
+ current = normalized;
1521
1623
  } catch (e) {
1522
1624
  }
1523
1625
  if (!this.disableDefaultRedaction) {
1524
- current = defaultTransformSpan(current);
1626
+ const redacted = defaultTransformSpan(current);
1627
+ copyReplayTraceDestination(current, redacted);
1628
+ current = redacted;
1525
1629
  }
1526
- return this.capSpanAttributes(current);
1630
+ const capped = this.capSpanAttributes(current);
1631
+ copyReplayTraceDestination(current, capped);
1632
+ return capped;
1527
1633
  }
1528
1634
  isDebugEnabled() {
1529
1635
  return this.debug;
@@ -1541,33 +1647,54 @@ var TraceShipper = class {
1541
1647
  const attrs = [
1542
1648
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1543
1649
  ...identityAttrs(args),
1544
- attrString("ai.operationId", args.operationId)
1650
+ attrString("ai.operationId", args.operationId),
1651
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1545
1652
  ];
1546
1653
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
1547
- const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
1548
- this.mirrorToLocalDebugger(
1549
- buildOtlpSpan({
1550
- ids: span.ids,
1551
- name: span.name,
1552
- startTimeUnixNano: span.startTimeUnixNano,
1553
- endTimeUnixNano: span.startTimeUnixNano,
1554
- // placeholder — will be updated on endSpan
1555
- attributes: span.attributes,
1556
- status: { code: SpanStatusCode.UNSET }
1557
- })
1558
- );
1654
+ const span = {
1655
+ ids,
1656
+ name: args.name,
1657
+ startTimeUnixNano: started,
1658
+ attributes: attrs
1659
+ };
1660
+ rememberReplayTraceDestination(span);
1661
+ const openSpan = buildOtlpSpan({
1662
+ ids: span.ids,
1663
+ name: span.name,
1664
+ startTimeUnixNano: span.startTimeUnixNano,
1665
+ endTimeUnixNano: span.startTimeUnixNano,
1666
+ // placeholder — will be updated on endSpan
1667
+ attributes: span.attributes,
1668
+ status: { code: SpanStatusCode.UNSET }
1669
+ });
1670
+ copyReplayTraceDestination(span, openSpan);
1671
+ this.mirrorToLocalDebugger(openSpan);
1559
1672
  return span;
1560
1673
  }
1561
- mirrorToLocalDebugger(span) {
1562
- if (!this.localDebuggerUrl) return;
1674
+ mirrorToLocalDebugger(span, completed = false) {
1675
+ const destination = replayTraceDestinationFor(span);
1676
+ if (destination && destination.kind !== "workshop") return;
1677
+ const localDebuggerUrl = (destination == null ? void 0 : destination.kind) === "workshop" ? destination.url : this.localDebuggerUrl;
1678
+ if (!localDebuggerUrl) return;
1563
1679
  const redacted = this.redactSpan(span);
1564
1680
  if (redacted === null) return;
1681
+ if (completed && (destination == null ? void 0 : destination.kind) === "workshop") {
1682
+ recordReplayExportedSpan(
1683
+ destination,
1684
+ base64ToHex(redacted.spanId),
1685
+ base64ToHex(redacted.traceId)
1686
+ );
1687
+ }
1565
1688
  const body = buildExportTraceServiceRequest([redacted], this.serviceName, this.serviceVersion);
1566
- mirrorTraceExportToLocalDebugger(body, {
1567
- baseUrl: this.localDebuggerUrl,
1689
+ const p = mirrorTraceExportToLocalDebugger(body, {
1690
+ baseUrl: localDebuggerUrl,
1568
1691
  debug: false,
1569
1692
  sdkName: this.sdkName
1570
1693
  });
1694
+ this.inFlight.add(p);
1695
+ void p.finally(() => {
1696
+ this.inFlight.delete(p);
1697
+ });
1571
1698
  }
1572
1699
  endSpan(span, extra) {
1573
1700
  var _a, _b;
@@ -1589,15 +1716,17 @@ var TraceShipper = class {
1589
1716
  attributes: span.attributes,
1590
1717
  status
1591
1718
  });
1719
+ copyReplayTraceDestination(span, otlp);
1592
1720
  this.enqueue(otlp);
1593
- this.mirrorToLocalDebugger(otlp);
1721
+ this.mirrorToLocalDebugger(otlp, true);
1594
1722
  }
1595
1723
  createSpan(args) {
1596
1724
  var _a;
1597
1725
  const ids = createSpanIds(args.parent);
1598
1726
  const attrs = [
1599
1727
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1600
- ...identityAttrs(args)
1728
+ ...identityAttrs(args),
1729
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1601
1730
  ];
1602
1731
  if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
1603
1732
  const otlp = buildOtlpSpan({
@@ -1608,8 +1737,9 @@ var TraceShipper = class {
1608
1737
  attributes: attrs,
1609
1738
  status: args.status
1610
1739
  });
1740
+ rememberReplayTraceDestination(otlp);
1611
1741
  this.enqueue(otlp);
1612
- this.mirrorToLocalDebugger(otlp);
1742
+ this.mirrorToLocalDebugger(otlp, true);
1613
1743
  }
1614
1744
  enqueue(span) {
1615
1745
  if (!this.enabled) return;
@@ -1623,6 +1753,13 @@ var TraceShipper = class {
1623
1753
  }
1624
1754
  const redacted = this.redactSpan(span);
1625
1755
  if (redacted === null) return;
1756
+ const destination = replayTraceDestinationFor(redacted);
1757
+ recordReplayExportedSpan(
1758
+ destination,
1759
+ base64ToHex(redacted.spanId),
1760
+ base64ToHex(redacted.traceId)
1761
+ );
1762
+ if ((destination == null ? void 0 : destination.kind) === "workshop") return;
1626
1763
  if (this.queue.length >= this.maxQueueSize) {
1627
1764
  this.queue.shift();
1628
1765
  }
@@ -1641,47 +1778,67 @@ var TraceShipper = class {
1641
1778
  }
1642
1779
  }
1643
1780
  async flush() {
1644
- if (!this.enabled) return;
1781
+ var _a;
1782
+ if (!this.enabled) {
1783
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
1784
+ })));
1785
+ return;
1786
+ }
1645
1787
  if (this.timer) {
1646
1788
  clearTimeout(this.timer);
1647
1789
  this.timer = void 0;
1648
1790
  }
1649
1791
  while (this.queue.length > 0) {
1650
1792
  const batch = this.queue.splice(0, this.maxBatchSize);
1651
- if (!this.writeKey) continue;
1652
- const opts = this.requestOpts();
1653
- if (!opts) {
1654
- rateLimitedLog(
1655
- `${this.prefix}.shutdown_deadline`,
1656
- () => console.warn(
1657
- `${this.prefix} shutdown flush deadline exceeded; dropping ${batch.length} spans`
1658
- )
1659
- );
1660
- continue;
1661
- }
1662
- const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
1663
- const url = `${this.baseUrl}traces`;
1664
- if (this.debug) {
1665
- console.log(`${this.prefix} sending traces batch`, {
1666
- spans: batch.length,
1667
- endpoint: url
1668
- });
1793
+ const groups = /* @__PURE__ */ new Map();
1794
+ for (const span of batch) {
1795
+ const destination = replayTraceDestinationFor(span);
1796
+ const spans = groups.get(destination);
1797
+ if (spans) spans.push(span);
1798
+ else groups.set(destination, [span]);
1669
1799
  }
1670
- const p = postJson(url, body, this.requestHeaders(), opts);
1671
- this.inFlight.add(p);
1672
- try {
1673
- try {
1674
- await p;
1675
- if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
1676
- } catch (err) {
1677
- const msg = err instanceof Error ? err.message : String(err);
1800
+ for (const [destination, spans] of groups) {
1801
+ if (!destination && !this.writeKey) continue;
1802
+ if ((destination == null ? void 0 : destination.kind) === "workshop") continue;
1803
+ const opts = this.requestOpts();
1804
+ if (!opts) {
1678
1805
  rateLimitedLog(
1679
- `${this.prefix}.send_spans_failed`,
1680
- () => console.warn(`${this.prefix} failed to send ${batch.length} spans: ${msg}`)
1806
+ `${this.prefix}.shutdown_deadline`,
1807
+ () => console.warn(
1808
+ `${this.prefix} shutdown flush deadline exceeded; dropping ${spans.length} spans`
1809
+ )
1681
1810
  );
1811
+ continue;
1812
+ }
1813
+ const body = buildExportTraceServiceRequest(spans, this.serviceName, this.serviceVersion);
1814
+ const url = destination ? replayTraceUrl(destination.url) : `${this.baseUrl}traces`;
1815
+ const headers = destination ? {
1816
+ Authorization: `Bearer ${destination.apiKey}`,
1817
+ "X-Raindrop-Replay-Id": destination.replayId,
1818
+ "X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
1819
+ } : this.requestHeaders();
1820
+ if (this.debug) {
1821
+ console.log(`${this.prefix} sending traces batch`, {
1822
+ spans: spans.length,
1823
+ endpoint: url
1824
+ });
1825
+ }
1826
+ const p = postJson(url, body, headers, opts);
1827
+ this.inFlight.add(p);
1828
+ try {
1829
+ try {
1830
+ await p;
1831
+ if (this.debug) console.log(`${this.prefix} sent ${spans.length} spans`);
1832
+ } catch (err) {
1833
+ const msg = err instanceof Error ? err.message : String(err);
1834
+ rateLimitedLog(
1835
+ `${this.prefix}.send_spans_failed`,
1836
+ () => console.warn(`${this.prefix} failed to send ${spans.length} spans: ${msg}`)
1837
+ );
1838
+ }
1839
+ } finally {
1840
+ this.inFlight.delete(p);
1682
1841
  }
1683
- } finally {
1684
- this.inFlight.delete(p);
1685
1842
  }
1686
1843
  }
1687
1844
  }
@@ -1724,7 +1881,9 @@ var TraceShipper = class {
1724
1881
  if (!settled) {
1725
1882
  rateLimitedLog(
1726
1883
  `${this.prefix}.shutdown_deadline`,
1727
- () => console.warn(`${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`)
1884
+ () => console.warn(
1885
+ `${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`
1886
+ )
1728
1887
  );
1729
1888
  }
1730
1889
  } finally {
@@ -1819,7 +1978,8 @@ function withCurrent(span, callback) {
1819
1978
  return getContextManager().runInContext(span, callback);
1820
1979
  }
1821
1980
  async function getCurrentParentSpanContext() {
1822
- return getContextManager().getParentSpanIds();
1981
+ var _a, _b;
1982
+ return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
1823
1983
  }
1824
1984
  async function runWithParentSpanContext(ctx, fn) {
1825
1985
  const cm = getContextManager();
@@ -1853,7 +2013,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
1853
2013
  // package.json
1854
2014
  var package_default = {
1855
2015
  name: "@raindrop-ai/ai-sdk",
1856
- version: "0.3.0"};
2016
+ version: "0.3.2"};
1857
2017
 
1858
2018
  // src/internal/version.ts
1859
2019
  var libraryName = package_default.name;
@@ -3097,29 +3257,6 @@ function firstTokenCount(...values) {
3097
3257
  }
3098
3258
  return void 0;
3099
3259
  }
3100
- function flatUsageSemantics(provider) {
3101
- const normalizedProvider = typeof provider === "string" ? provider.trim().toLowerCase() : void 0;
3102
- if (normalizedProvider === "anthropic" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("anthropic.")) || normalizedProvider === "vertex.anthropic" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("vertex.anthropic."))) {
3103
- return {
3104
- inputTokenSemantics: "exclusive",
3105
- outputTokenSemantics: "total"
3106
- };
3107
- }
3108
- if (normalizedProvider === "openai" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("openai.")) || normalizedProvider === "azure" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("azure."))) {
3109
- return {
3110
- inputTokenSemantics: "total",
3111
- outputTokenSemantics: "total"
3112
- };
3113
- }
3114
- if (normalizedProvider === "google" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("google."))) {
3115
- return {
3116
- inputTokenSemantics: "total",
3117
- // Google v5 reports candidate output and thoughts separately.
3118
- outputTokenSemantics: "exclusive"
3119
- };
3120
- }
3121
- return {};
3122
- }
3123
3260
  var CACHE_WRITE_METADATA_KEYS = [
3124
3261
  ["anthropic", "cacheCreationInputTokens"],
3125
3262
  ["openai", "cacheWriteTokens"],
@@ -3136,7 +3273,7 @@ function cacheWriteTokensFromProviderMetadata(providerMetadata) {
3136
3273
  })
3137
3274
  );
3138
3275
  }
3139
- function extractUsageMetricsFromUsage(usage, provider, providerMetadata) {
3276
+ function extractUsageMetricsFromUsage(usage, _provider, providerMetadata) {
3140
3277
  if (!isRecord(usage)) return {};
3141
3278
  const inputTokenValue = usage["inputTokens"];
3142
3279
  const outputTokenValue = usage["outputTokens"];
@@ -3204,7 +3341,7 @@ function extractUsageMetricsFromUsage(usage, provider, providerMetadata) {
3204
3341
  cacheReadInputTokens,
3205
3342
  cachedInputTokens: cacheReadInputTokens,
3206
3343
  cacheWriteInputTokens,
3207
- ...hasStructuredUsage ? {} : flatUsageSemantics(provider)
3344
+ ...hasStructuredUsage ? { usageSource: "ai-sdk-structured" } : {}
3208
3345
  };
3209
3346
  }
3210
3347
 
@@ -3402,13 +3539,13 @@ var RaindropTelemetryIntegration = class {
3402
3539
  };
3403
3540
  // ── onStepStart ─────────────────────────────────────────────────────────
3404
3541
  this.onStepStart = (event) => {
3405
- const state = this.getState(event.callId);
3406
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3407
- const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
3408
- const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
3409
- const { operationName, resourceName } = opName(stepOperationId, state.functionId);
3542
+ const state2 = this.getState(event.callId);
3543
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3544
+ const isStream = state2.operationId === "ai.streamText" || state2.operationId === "ai.streamObject";
3545
+ const stepOperationId = isStream ? `${state2.operationId}.doStream` : `${state2.operationId}.doGenerate`;
3546
+ const { operationName, resourceName } = opName(stepOperationId, state2.functionId);
3410
3547
  const inputAttrs = [];
3411
- if (state.recordInputs) {
3548
+ if (state2.recordInputs) {
3412
3549
  if (event.promptMessages) {
3413
3550
  inputAttrs.push(attrString("ai.prompt.messages", safeJsonWithUint8(event.promptMessages)));
3414
3551
  }
@@ -3431,25 +3568,25 @@ var RaindropTelemetryIntegration = class {
3431
3568
  }
3432
3569
  const stepSpan = this.traceShipper.startSpan({
3433
3570
  name: stepOperationId,
3434
- parent: state.rootParent,
3435
- eventId: state.eventId,
3436
- ...state.identity,
3571
+ parent: state2.rootParent,
3572
+ eventId: state2.eventId,
3573
+ ...state2.identity,
3437
3574
  operationId: stepOperationId,
3438
3575
  attributes: [
3439
3576
  attrString("operation.name", operationName),
3440
3577
  attrString("resource.name", resourceName),
3441
- attrString("ai.telemetry.functionId", state.functionId),
3578
+ attrString("ai.telemetry.functionId", state2.functionId),
3442
3579
  ...attrsFromModelProvider(event.provider),
3443
3580
  attrString("ai.model.id", event.modelId),
3444
3581
  attrString(MODEL_USAGE_ATTRIBUTES.requestModel, event.modelId),
3445
3582
  ...inputAttrs,
3446
- ...handoffSpanAttrs(state.handoff)
3583
+ ...handoffSpanAttrs(state2.handoff)
3447
3584
  ]
3448
3585
  });
3449
- state.stepSpan = stepSpan;
3450
- state.stepParent = this.spanParentRef(stepSpan);
3451
- state.stepProvider = event.provider;
3452
- state.stepModelId = event.modelId;
3586
+ state2.stepSpan = stepSpan;
3587
+ state2.stepParent = this.spanParentRef(stepSpan);
3588
+ state2.stepProvider = event.provider;
3589
+ state2.stepModelId = event.modelId;
3453
3590
  };
3454
3591
  this.onToolExecutionStart = (event) => this.toolExecutionStart(event);
3455
3592
  this.onToolExecutionEnd = (event) => this.toolExecutionEnd(event);
@@ -3476,33 +3613,33 @@ var RaindropTelemetryIntegration = class {
3476
3613
  var _a, _b, _c, _d, _e;
3477
3614
  const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
3478
3615
  if (!callId) return;
3479
- const state = this.getState(callId);
3480
- if (!state) return;
3616
+ const state2 = this.getState(callId);
3617
+ if (!state2) return;
3481
3618
  const chunk = event.chunk;
3482
3619
  if (!chunk || typeof chunk !== "object") return;
3483
3620
  if (chunk.type === "text-delta") {
3484
3621
  const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
3485
3622
  if (typeof delta === "string") {
3486
- if (state.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3487
- state.accumulatedText += delta;
3623
+ if (state2.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3624
+ state2.accumulatedText += delta;
3488
3625
  }
3489
- this.emitLive(state, "text_delta", delta);
3626
+ this.emitLive(state2, "text_delta", delta);
3490
3627
  }
3491
3628
  } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
3492
3629
  const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
3493
3630
  if (typeof text === "string") {
3494
- this.emitLive(state, "reasoning_delta", text);
3631
+ this.emitLive(state2, "reasoning_delta", text);
3495
3632
  }
3496
3633
  }
3497
3634
  };
3498
3635
  // ── onStepFinish ────────────────────────────────────────────────────────
3499
3636
  this.onStepFinish = (event) => {
3500
3637
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3501
- const state = this.getState(event.callId);
3502
- if (!(state == null ? void 0 : state.stepSpan)) return;
3503
- const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state.stepModelId;
3638
+ const state2 = this.getState(event.callId);
3639
+ if (!(state2 == null ? void 0 : state2.stepSpan)) return;
3640
+ const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state2.stepModelId;
3504
3641
  const outputAttrs = [];
3505
- if (state.recordOutputs) {
3642
+ if (state2.recordOutputs) {
3506
3643
  outputAttrs.push(
3507
3644
  attrString("ai.response.finishReason", event.finishReason),
3508
3645
  attrString("ai.response.text", capText2((_c = event.text) != null ? _c : void 0)),
@@ -3547,7 +3684,7 @@ var RaindropTelemetryIntegration = class {
3547
3684
  if (usage) {
3548
3685
  const usageMetrics = extractUsageMetricsFromUsage(
3549
3686
  usage,
3550
- state.stepProvider,
3687
+ state2.stepProvider,
3551
3688
  event.providerMetadata
3552
3689
  );
3553
3690
  outputAttrs.push(
@@ -3556,54 +3693,55 @@ var RaindropTelemetryIntegration = class {
3556
3693
  attrInt("ai.usage.totalTokens", usageMetrics.totalTokens),
3557
3694
  attrInt("ai.usage.reasoningTokens", usageMetrics.reasoningTokens),
3558
3695
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens),
3559
- ...buildModelUsageAttributes(usageMetrics)
3696
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
3697
+ ...buildRawModelUsageAttributes(usageMetrics)
3560
3698
  );
3561
3699
  }
3562
- this.emitProviderExecutedToolSpans(event, state);
3563
- this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
3564
- state.stepSpan = void 0;
3565
- state.stepParent = void 0;
3566
- state.stepProvider = void 0;
3567
- state.stepModelId = void 0;
3700
+ this.emitProviderExecutedToolSpans(event, state2);
3701
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: outputAttrs });
3702
+ state2.stepSpan = void 0;
3703
+ state2.stepParent = void 0;
3704
+ state2.stepProvider = void 0;
3705
+ state2.stepModelId = void 0;
3568
3706
  };
3569
3707
  // ── onEmbedStart ────────────────────────────────────────────────────────
3570
3708
  this.onEmbedStart = (event) => {
3571
- const state = this.getState(event.callId);
3572
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3573
- const { operationName, resourceName } = opName(event.operationId, state.functionId);
3574
- const inputAttrs = state.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3709
+ const state2 = this.getState(event.callId);
3710
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3711
+ const { operationName, resourceName } = opName(event.operationId, state2.functionId);
3712
+ const inputAttrs = state2.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3575
3713
  const embedSpan = this.traceShipper.startSpan({
3576
3714
  name: event.operationId,
3577
- parent: state.rootParent,
3578
- eventId: state.eventId,
3579
- ...state.identity,
3715
+ parent: state2.rootParent,
3716
+ eventId: state2.eventId,
3717
+ ...state2.identity,
3580
3718
  operationId: event.operationId,
3581
3719
  attributes: [
3582
3720
  attrString("operation.name", operationName),
3583
3721
  attrString("resource.name", resourceName),
3584
- attrString("ai.telemetry.functionId", state.functionId),
3722
+ attrString("ai.telemetry.functionId", state2.functionId),
3585
3723
  ...inputAttrs,
3586
- ...handoffSpanAttrs(state.handoff)
3724
+ ...handoffSpanAttrs(state2.handoff)
3587
3725
  ]
3588
3726
  });
3589
- state.embedSpans.set(event.embedCallId, embedSpan);
3727
+ state2.embedSpans.set(event.embedCallId, embedSpan);
3590
3728
  };
3591
3729
  // ── onEmbedFinish ───────────────────────────────────────────────────────
3592
3730
  this.onEmbedFinish = (event) => {
3593
3731
  var _a;
3594
- const state = this.getState(event.callId);
3595
- if (!state) return;
3596
- const embedSpan = state.embedSpans.get(event.embedCallId);
3732
+ const state2 = this.getState(event.callId);
3733
+ if (!state2) return;
3734
+ const embedSpan = state2.embedSpans.get(event.embedCallId);
3597
3735
  if (!embedSpan) return;
3598
3736
  const outputAttrs = [];
3599
- if (state.recordOutputs) {
3737
+ if (state2.recordOutputs) {
3600
3738
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embeddings)));
3601
3739
  }
3602
3740
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
3603
3741
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
3604
3742
  }
3605
3743
  this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
3606
- state.embedSpans.delete(event.embedCallId);
3744
+ state2.embedSpans.delete(event.embedCallId);
3607
3745
  };
3608
3746
  // v7 canary.159 renamed `onEmbedFinish` -> `onEmbedEnd`. Both names forward
3609
3747
  // to the same implementation; the installed SDK only wires up whichever it
@@ -3611,16 +3749,16 @@ var RaindropTelemetryIntegration = class {
3611
3749
  this.onEmbedEnd = (event) => this.onEmbedFinish(event);
3612
3750
  // ── onFinish ────────────────────────────────────────────────────────────
3613
3751
  this.onFinish = (event) => {
3614
- const state = this.getState(event.callId);
3615
- if (!state) return;
3616
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3752
+ const state2 = this.getState(event.callId);
3753
+ if (!state2) return;
3754
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3617
3755
  if (isEmbed) {
3618
- this.finishEmbed(event, state);
3756
+ this.finishEmbed(event, state2);
3619
3757
  } else {
3620
- this.finishGenerate(event, state);
3758
+ this.finishGenerate(event, state2);
3621
3759
  }
3622
- if (state.subagentToolCallSpan) {
3623
- this.traceShipper.endSpan(state.subagentToolCallSpan);
3760
+ if (state2.subagentToolCallSpan) {
3761
+ this.traceShipper.endSpan(state2.subagentToolCallSpan);
3624
3762
  }
3625
3763
  this.cleanup(event.callId);
3626
3764
  };
@@ -3635,42 +3773,42 @@ var RaindropTelemetryIntegration = class {
3635
3773
  var _a;
3636
3774
  const event = error;
3637
3775
  if (!(event == null ? void 0 : event.callId)) return;
3638
- const state = this.getState(event.callId);
3639
- if (!state) return;
3776
+ const state2 = this.getState(event.callId);
3777
+ if (!state2) return;
3640
3778
  const actualError = (_a = event.error) != null ? _a : error;
3641
- if (state.stepSpan) {
3642
- this.traceShipper.endSpan(state.stepSpan, { error: actualError });
3643
- state.stepProvider = void 0;
3644
- state.stepModelId = void 0;
3779
+ if (state2.stepSpan) {
3780
+ this.traceShipper.endSpan(state2.stepSpan, { error: actualError });
3781
+ state2.stepProvider = void 0;
3782
+ state2.stepModelId = void 0;
3645
3783
  }
3646
- for (const embedSpan of state.embedSpans.values()) {
3784
+ for (const embedSpan of state2.embedSpans.values()) {
3647
3785
  this.traceShipper.endSpan(embedSpan, { error: actualError });
3648
3786
  }
3649
- state.embedSpans.clear();
3650
- for (const toolCallId of state.parentContextToolCallIds) {
3787
+ state2.embedSpans.clear();
3788
+ for (const toolCallId of state2.parentContextToolCallIds) {
3651
3789
  this.priorParentContexts.delete(toolCallId);
3652
3790
  }
3653
- state.parentContextToolCallIds.clear();
3654
- for (const toolSpan of state.toolSpans.values()) {
3791
+ state2.parentContextToolCallIds.clear();
3792
+ for (const toolSpan of state2.toolSpans.values()) {
3655
3793
  this.traceShipper.endSpan(toolSpan, { error: actualError });
3656
3794
  }
3657
- state.toolSpans.clear();
3795
+ state2.toolSpans.clear();
3658
3796
  const abortReason = describeAbortReason(actualError);
3659
- if (state.rootSpan) {
3660
- this.traceShipper.endSpan(state.rootSpan, {
3797
+ if (state2.rootSpan) {
3798
+ this.traceShipper.endSpan(state2.rootSpan, {
3661
3799
  error: actualError,
3662
- attributes: this.abortOutcomeAttrs(state, abortReason, "error")
3800
+ attributes: this.abortOutcomeAttrs(state2, abortReason, "error")
3663
3801
  });
3664
3802
  }
3665
- if (state.subagentToolCallSpan) {
3666
- this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
3803
+ if (state2.subagentToolCallSpan) {
3804
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, { error: actualError });
3667
3805
  }
3668
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3806
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3669
3807
  if (!isEmbed) {
3670
- const errorIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3808
+ const errorIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3671
3809
  this.finalizeGenerateEvent(
3672
- state,
3673
- state.accumulatedText || void 0,
3810
+ state2,
3811
+ state2.accumulatedText || void 0,
3674
3812
  void 0,
3675
3813
  false,
3676
3814
  errorIsTheRunsOutcome ? { fallbackOutput: abortReason } : void 0
@@ -3689,51 +3827,51 @@ var RaindropTelemetryIntegration = class {
3689
3827
  this.onAbort = (event) => {
3690
3828
  const callId = event == null ? void 0 : event.callId;
3691
3829
  if (!callId) return;
3692
- const state = this.getState(callId);
3693
- if (!state) return;
3830
+ const state2 = this.getState(callId);
3831
+ if (!state2) return;
3694
3832
  const abortedAttr = attrString("ai.response.aborted", "true");
3695
- if (state.stepSpan) {
3696
- this.traceShipper.endSpan(state.stepSpan, { attributes: [abortedAttr] });
3697
- state.stepSpan = void 0;
3698
- state.stepParent = void 0;
3699
- state.stepProvider = void 0;
3700
- state.stepModelId = void 0;
3833
+ if (state2.stepSpan) {
3834
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: [abortedAttr] });
3835
+ state2.stepSpan = void 0;
3836
+ state2.stepParent = void 0;
3837
+ state2.stepProvider = void 0;
3838
+ state2.stepModelId = void 0;
3701
3839
  }
3702
- for (const embedSpan of state.embedSpans.values()) {
3840
+ for (const embedSpan of state2.embedSpans.values()) {
3703
3841
  this.traceShipper.endSpan(embedSpan, { attributes: [abortedAttr] });
3704
3842
  }
3705
- state.embedSpans.clear();
3706
- for (const toolCallId of state.parentContextToolCallIds) {
3843
+ state2.embedSpans.clear();
3844
+ for (const toolCallId of state2.parentContextToolCallIds) {
3707
3845
  this.priorParentContexts.delete(toolCallId);
3708
3846
  }
3709
- state.parentContextToolCallIds.clear();
3710
- for (const toolSpan of state.toolSpans.values()) {
3847
+ state2.parentContextToolCallIds.clear();
3848
+ for (const toolSpan of state2.toolSpans.values()) {
3711
3849
  this.traceShipper.endSpan(toolSpan, { attributes: [abortedAttr] });
3712
3850
  }
3713
- state.toolSpans.clear();
3714
- const abortIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3715
- if (state.rootSpan) {
3716
- this.traceShipper.endSpan(state.rootSpan, {
3851
+ state2.toolSpans.clear();
3852
+ const abortIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3853
+ if (state2.rootSpan) {
3854
+ this.traceShipper.endSpan(state2.rootSpan, {
3717
3855
  attributes: [
3718
3856
  abortedAttr,
3719
- attrInt("ai.toolCall.count", state.toolCallCount),
3857
+ attrInt("ai.toolCall.count", state2.toolCallCount),
3720
3858
  // An aborted detached child IS a cancelled sub-agent, and a cancelled
3721
3859
  // run is span-for-span identical to a finished one — spans close,
3722
3860
  // nothing errors, there is just no answer. So it is the one outcome
3723
3861
  // that has to be stated, and the child states it on itself.
3724
3862
  ...abortIsTheRunsOutcome ? cancelledSpanAttrs() : [],
3725
- ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3863
+ ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state2, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3726
3864
  ]
3727
3865
  });
3728
3866
  }
3729
- if (state.subagentToolCallSpan) {
3730
- this.traceShipper.endSpan(state.subagentToolCallSpan, {
3867
+ if (state2.subagentToolCallSpan) {
3868
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, {
3731
3869
  attributes: [abortedAttr]
3732
3870
  });
3733
3871
  }
3734
3872
  this.finalizeGenerateEvent(
3735
- state,
3736
- state.accumulatedText || void 0,
3873
+ state2,
3874
+ state2.accumulatedText || void 0,
3737
3875
  void 0,
3738
3876
  false,
3739
3877
  abortIsTheRunsOutcome ? {
@@ -3741,7 +3879,7 @@ var RaindropTelemetryIntegration = class {
3741
3879
  properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
3742
3880
  } : void 0
3743
3881
  );
3744
- if (abortIsTheRunsOutcome) this.subagents.noteSettled(state.eventId);
3882
+ if (abortIsTheRunsOutcome) this.subagents.noteSettled(state2.eventId);
3745
3883
  this.cleanup(callId);
3746
3884
  };
3747
3885
  // ── executeTool ─────────────────────────────────────────────────────────
@@ -3750,14 +3888,14 @@ var RaindropTelemetryIntegration = class {
3750
3888
  toolCallId,
3751
3889
  execute
3752
3890
  }) => {
3753
- const state = this.getState(callId);
3754
- const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
3891
+ const state2 = this.getState(callId);
3892
+ const toolSpan = state2 == null ? void 0 : state2.toolSpans.get(toolCallId);
3755
3893
  if (!toolSpan) return execute();
3756
3894
  return runWithParentSpanContext(
3757
3895
  {
3758
3896
  traceIdB64: toolSpan.ids.traceIdB64,
3759
3897
  spanIdB64: toolSpan.ids.spanIdB64,
3760
- eventId: state.eventId
3898
+ eventId: state2.eventId
3761
3899
  },
3762
3900
  () => execute()
3763
3901
  );
@@ -3806,35 +3944,35 @@ var RaindropTelemetryIntegration = class {
3806
3944
  activeDispatch() {
3807
3945
  var _a;
3808
3946
  const parentTool = getCurrentParentToolContext();
3809
- let state = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3947
+ let state2 = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3810
3948
  const inheritedEventId = (_a = getContextManager().getParentSpanIds()) == null ? void 0 : _a.eventId;
3811
- if (!state && inheritedEventId) {
3949
+ if (!state2 && inheritedEventId) {
3812
3950
  for (const candidate of this.callStates.values()) {
3813
3951
  if (candidate.eventId === inheritedEventId) {
3814
- state = candidate;
3952
+ state2 = candidate;
3815
3953
  break;
3816
3954
  }
3817
3955
  }
3818
3956
  }
3819
- if (!state) return void 0;
3957
+ if (!state2) return void 0;
3820
3958
  return {
3821
- eventId: state.eventId,
3822
- userId: state.identity.userId,
3823
- convoId: state.identity.convoId,
3824
- dispatchSpan: parentTool ? state.toolSpans.get(parentTool.toolCallId) : void 0,
3825
- turnSpans: [state.rootSpan, state.stepSpan].filter(
3959
+ eventId: state2.eventId,
3960
+ userId: state2.identity.userId,
3961
+ convoId: state2.identity.convoId,
3962
+ dispatchSpan: parentTool ? state2.toolSpans.get(parentTool.toolCallId) : void 0,
3963
+ turnSpans: [state2.rootSpan, state2.stepSpan].filter(
3826
3964
  (span) => span !== void 0
3827
3965
  ),
3828
- recordInputs: state.recordInputs
3966
+ recordInputs: state2.recordInputs
3829
3967
  };
3830
3968
  }
3831
3969
  /** Spans still open for an event, so a late outcome can still be stated. */
3832
3970
  openSpansForEvent(eventId) {
3833
3971
  const spans = [];
3834
- for (const state of this.callStates.values()) {
3835
- if (state.eventId !== eventId) continue;
3836
- if (state.rootSpan) spans.push(state.rootSpan);
3837
- if (state.stepSpan) spans.push(state.stepSpan);
3972
+ for (const state2 of this.callStates.values()) {
3973
+ if (state2.eventId !== eventId) continue;
3974
+ if (state2.rootSpan) spans.push(state2.rootSpan);
3975
+ if (state2.stepSpan) spans.push(state2.stepSpan);
3838
3976
  }
3839
3977
  return spans;
3840
3978
  }
@@ -3854,10 +3992,10 @@ var RaindropTelemetryIntegration = class {
3854
3992
  * created from an LLM span with output, `ai.response.text` here would state
3855
3993
  * the run's outcome through the span while the turn is still working.
3856
3994
  */
3857
- abortOutcomeAttrs(state, reason, finishReason) {
3858
- if (!state.handoff || state.nestedInEvent) return [];
3995
+ abortOutcomeAttrs(state2, reason, finishReason) {
3996
+ if (!state2.handoff || state2.nestedInEvent) return [];
3859
3997
  return [
3860
- attrString("ai.response.text", capText2(state.accumulatedText || reason)),
3998
+ attrString("ai.response.text", capText2(state2.accumulatedText || reason)),
3861
3999
  attrString("ai.response.finishReason", finishReason)
3862
4000
  ];
3863
4001
  }
@@ -3871,19 +4009,19 @@ var RaindropTelemetryIntegration = class {
3871
4009
  spanParentRef(span) {
3872
4010
  return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
3873
4011
  }
3874
- emitLive(state, type, content, extra) {
4012
+ emitLive(state2, type, content, extra) {
3875
4013
  var _a, _b, _c, _d, _e, _f;
3876
- if (!localDebuggerEnabled() || !state.rootSpan) return;
3877
- const callMeta = this.extractRaindropMetadata(state.metadata);
4014
+ if (!localDebuggerEnabled() || !state2.rootSpan) return;
4015
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
3878
4016
  sendLocalDebuggerLiveEvent({
3879
- traceId: state.rootSpan.ids.traceIdB64,
4017
+ traceId: state2.rootSpan.ids.traceIdB64,
3880
4018
  type,
3881
4019
  content,
3882
4020
  metadata: {
3883
4021
  userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
3884
4022
  convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
3885
4023
  eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
3886
- eventId: state.eventId,
4024
+ eventId: state2.eventId,
3887
4025
  ...extra
3888
4026
  }
3889
4027
  });
@@ -3961,29 +4099,29 @@ var RaindropTelemetryIntegration = class {
3961
4099
  toolCallId: toolCall.toolCallId,
3962
4100
  toolName: toolCall.toolName
3963
4101
  });
3964
- const state = this.getState(event.callId);
3965
- state == null ? void 0 : state.parentContextToolCallIds.add(toolCall.toolCallId);
3966
- if (!(state == null ? void 0 : state.stepParent)) return;
3967
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
3968
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
4102
+ const state2 = this.getState(event.callId);
4103
+ state2 == null ? void 0 : state2.parentContextToolCallIds.add(toolCall.toolCallId);
4104
+ if (!(state2 == null ? void 0 : state2.stepParent)) return;
4105
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4106
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
3969
4107
  const toolSpan = this.traceShipper.startSpan({
3970
4108
  name: "ai.toolCall",
3971
- parent: state.stepParent,
3972
- eventId: state.eventId,
3973
- ...state.identity,
4109
+ parent: state2.stepParent,
4110
+ eventId: state2.eventId,
4111
+ ...state2.identity,
3974
4112
  operationId: "ai.toolCall",
3975
4113
  attributes: [
3976
4114
  attrString("operation.name", operationName),
3977
4115
  attrString("resource.name", resourceName),
3978
- attrString("ai.telemetry.functionId", state.functionId),
4116
+ attrString("ai.telemetry.functionId", state2.functionId),
3979
4117
  attrString("ai.toolCall.name", toolCall.toolName),
3980
4118
  attrString("ai.toolCall.id", toolCall.toolCallId),
3981
4119
  ...inputAttrs,
3982
- ...handoffSpanAttrs(state.handoff)
4120
+ ...handoffSpanAttrs(state2.handoff)
3983
4121
  ]
3984
4122
  });
3985
- state.toolSpans.set(toolCall.toolCallId, toolSpan);
3986
- this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
4123
+ state2.toolSpans.set(toolCall.toolCallId, toolSpan);
4124
+ this.emitLive(state2, "tool_start", toolCall.toolName, { args: toolCall.input });
3987
4125
  }
3988
4126
  toolExecutionEnd(event) {
3989
4127
  var _a;
@@ -3997,20 +4135,20 @@ var RaindropTelemetryIntegration = class {
3997
4135
  clearParentToolContext();
3998
4136
  }
3999
4137
  }
4000
- const state = this.getState(event.callId);
4001
- if (!state) return;
4002
- const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
4138
+ const state2 = this.getState(event.callId);
4139
+ if (!state2) return;
4140
+ const toolSpan = state2.toolSpans.get(event.toolCall.toolCallId);
4003
4141
  if (!toolSpan) return;
4004
- state.toolCallCount += 1;
4142
+ state2.toolCallCount += 1;
4005
4143
  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 };
4006
4144
  if (outcome.success) {
4007
- const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4145
+ const outputAttrs = state2.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4008
4146
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4009
4147
  } else {
4010
4148
  this.traceShipper.endSpan(toolSpan, { error: outcome.error });
4011
4149
  }
4012
- this.emitLive(state, "tool_result", event.toolCall.toolName);
4013
- state.toolSpans.delete(event.toolCall.toolCallId);
4150
+ this.emitLive(state2, "tool_result", event.toolCall.toolName);
4151
+ state2.toolSpans.delete(event.toolCall.toolCallId);
4014
4152
  }
4015
4153
  // ── provider-executed tool calls ─────────────────────────────────────────
4016
4154
  //
@@ -4029,8 +4167,8 @@ var RaindropTelemetryIntegration = class {
4029
4167
  //
4030
4168
  // Client-executed tools are excluded (`providerExecuted` falsy) — they were
4031
4169
  // already spanned during execution, so this never double-emits.
4032
- emitProviderExecutedToolSpans(event, state) {
4033
- if (!state.stepParent) return;
4170
+ emitProviderExecutedToolSpans(event, state2) {
4171
+ if (!state2.stepParent) return;
4034
4172
  const content = Array.isArray(event.content) ? event.content : [];
4035
4173
  const providerToolCalls = content.filter(
4036
4174
  (part) => (part == null ? void 0 : part.type) === "tool-call" && part.providerExecuted === true
@@ -4043,42 +4181,42 @@ var RaindropTelemetryIntegration = class {
4043
4181
  }
4044
4182
  }
4045
4183
  for (const call of providerToolCalls) {
4046
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
4047
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4184
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4185
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4048
4186
  const toolSpan = this.traceShipper.startSpan({
4049
4187
  name: "ai.toolCall",
4050
- parent: state.stepParent,
4051
- eventId: state.eventId,
4052
- ...state.identity,
4188
+ parent: state2.stepParent,
4189
+ eventId: state2.eventId,
4190
+ ...state2.identity,
4053
4191
  operationId: "ai.toolCall",
4054
4192
  attributes: [
4055
4193
  attrString("operation.name", operationName),
4056
4194
  attrString("resource.name", resourceName),
4057
- attrString("ai.telemetry.functionId", state.functionId),
4195
+ attrString("ai.telemetry.functionId", state2.functionId),
4058
4196
  attrString("ai.toolCall.name", call.toolName),
4059
4197
  attrString("ai.toolCall.id", call.toolCallId),
4060
4198
  attrString("ai.toolCall.providerExecuted", "true"),
4061
4199
  ...inputAttrs,
4062
- ...handoffSpanAttrs(state.handoff)
4200
+ ...handoffSpanAttrs(state2.handoff)
4063
4201
  ]
4064
4202
  });
4065
- state.toolCallCount += 1;
4066
- this.emitLive(state, "tool_start", call.toolName, { args: call.input });
4203
+ state2.toolCallCount += 1;
4204
+ this.emitLive(state2, "tool_start", call.toolName, { args: call.input });
4067
4205
  const resultPart = resultsByCallId.get(call.toolCallId);
4068
4206
  if ((resultPart == null ? void 0 : resultPart.type) === "tool-error") {
4069
4207
  this.traceShipper.endSpan(toolSpan, { error: resultPart.error });
4070
4208
  } else {
4071
- const outputAttrs = state.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4209
+ const outputAttrs = state2.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4072
4210
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4073
4211
  }
4074
- this.emitLive(state, "tool_result", call.toolName);
4212
+ this.emitLive(state2, "tool_result", call.toolName);
4075
4213
  }
4076
4214
  }
4077
- finishGenerate(event, state) {
4215
+ finishGenerate(event, state2) {
4078
4216
  var _a, _b, _c, _d, _e, _f;
4079
- if (state.rootSpan) {
4217
+ if (state2.rootSpan) {
4080
4218
  const outputAttrs = [];
4081
- if (state.recordOutputs) {
4219
+ if (state2.recordOutputs) {
4082
4220
  outputAttrs.push(
4083
4221
  attrString("ai.response.finishReason", event.finishReason),
4084
4222
  attrString("ai.response.text", capText2((_a = event.text) != null ? _a : void 0)),
@@ -4119,12 +4257,12 @@ var RaindropTelemetryIntegration = class {
4119
4257
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens)
4120
4258
  );
4121
4259
  }
4122
- outputAttrs.push(attrInt("ai.toolCall.count", state.toolCallCount));
4123
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4260
+ outputAttrs.push(attrInt("ai.toolCall.count", state2.toolCallCount));
4261
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4124
4262
  }
4125
4263
  this.finalizeGenerateEvent(
4126
- state,
4127
- (_e = event.text) != null ? _e : state.accumulatedText || void 0,
4264
+ state2,
4265
+ (_e = event.text) != null ? _e : state2.accumulatedText || void 0,
4128
4266
  (_f = event.response) == null ? void 0 : _f.modelId,
4129
4267
  hasUnresolvedToolApproval(event)
4130
4268
  );
@@ -4140,29 +4278,29 @@ var RaindropTelemetryIntegration = class {
4140
4278
  * is finalized by that resume — otherwise each execution would finalize the
4141
4279
  * same event ID into a separate canonical row.
4142
4280
  */
4143
- finalizeGenerateEvent(state, output, model, keepPending = false, detachedOutcome) {
4281
+ finalizeGenerateEvent(state2, output, model, keepPending = false, detachedOutcome) {
4144
4282
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
4145
- const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
4283
+ const suppressSubagentEvent = state2.subagentName !== void 0 && state2.subagentToolCallSpan !== void 0;
4146
4284
  if (!this.sendEvents || suppressSubagentEvent) return;
4147
- if (this.subagents.wasSettledExplicitly(state.eventId)) return;
4148
- const callMeta = this.extractRaindropMetadata(state.metadata);
4285
+ if (this.subagents.wasSettledExplicitly(state2.eventId)) return;
4286
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
4149
4287
  const userId = (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId;
4150
4288
  if (!userId) return;
4151
- const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state.operationId;
4289
+ const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state2.operationId;
4152
4290
  const cappedOutput = capText2(output);
4153
- const reportedOutput = state.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4154
- const input = capText2(state.inputText);
4291
+ const reportedOutput = state2.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4292
+ const input = capText2(state2.inputText);
4155
4293
  const properties = {
4156
4294
  ...(_f = this.defaultContext) == null ? void 0 : _f.properties,
4157
4295
  ...callMeta.properties,
4158
- ...state.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4296
+ ...state2.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4159
4297
  };
4160
4298
  const featureFlags = {
4161
4299
  ...((_g = this.defaultContext) == null ? void 0 : _g.featureFlags) ? normalizeFeatureFlags(this.defaultContext.featureFlags) : {},
4162
4300
  ...callMeta.featureFlags
4163
4301
  };
4164
4302
  const convoId = (_i = callMeta.convoId) != null ? _i : (_h = this.defaultContext) == null ? void 0 : _h.convoId;
4165
- void this.eventShipper.patch(state.eventId, {
4303
+ void this.eventShipper.patch(state2.eventId, {
4166
4304
  eventName,
4167
4305
  userId,
4168
4306
  convoId,
@@ -4180,12 +4318,12 @@ var RaindropTelemetryIntegration = class {
4180
4318
  }
4181
4319
  });
4182
4320
  }
4183
- finishEmbed(event, state) {
4321
+ finishEmbed(event, state2) {
4184
4322
  var _a;
4185
- if (!state.rootSpan) return;
4323
+ if (!state2.rootSpan) return;
4186
4324
  const outputAttrs = [];
4187
- const isMany = state.operationId === "ai.embedMany";
4188
- if (state.recordOutputs) {
4325
+ const isMany = state2.operationId === "ai.embedMany";
4326
+ if (state2.recordOutputs) {
4189
4327
  if (isMany) {
4190
4328
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embedding)));
4191
4329
  } else {
@@ -4195,7 +4333,7 @@ var RaindropTelemetryIntegration = class {
4195
4333
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
4196
4334
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
4197
4335
  }
4198
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4336
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4199
4337
  }
4200
4338
  };
4201
4339
 
@@ -4504,9 +4642,7 @@ function extractRaindropMetadata(metadata) {
4504
4642
  } catch (e) {
4505
4643
  }
4506
4644
  } else if (featureFlags && typeof featureFlags === "object") {
4507
- result.featureFlags = normalizeFeatureFlags(
4508
- featureFlags
4509
- );
4645
+ result.featureFlags = normalizeFeatureFlags(featureFlags);
4510
4646
  }
4511
4647
  return result;
4512
4648
  }
@@ -4717,12 +4853,7 @@ function setupOperation(params) {
4717
4853
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
4718
4854
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
4719
4855
  ...attrsFromSettings(arg),
4720
- ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
4721
- attrString(
4722
- "ai.prompt",
4723
- safeJsonWithUint8(normalizePromptAttr(arg))
4724
- )
4725
- ]
4856
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [attrString("ai.prompt", safeJsonWithUint8(normalizePromptAttr(arg)))]
4726
4857
  ]
4727
4858
  }) : void 0;
4728
4859
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
@@ -5072,7 +5203,10 @@ function wrapAISDK(aiSDK, deps) {
5072
5203
  }
5073
5204
  const useNative = deps.options.nativeTelemetry === true;
5074
5205
  if (useNative) {
5075
- const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
5206
+ const wrapTimeCtx = resolveContext(deps.options.context, {
5207
+ operation: "wrap",
5208
+ args: void 0
5209
+ });
5076
5210
  const integration = new RaindropTelemetryIntegration({
5077
5211
  traceShipper: deps.traceShipper,
5078
5212
  eventShipper: deps.eventShipper,
@@ -5317,7 +5451,13 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
5317
5451
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
5318
5452
  attrString(
5319
5453
  "ai.prompt",
5320
- safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
5454
+ safeJsonWithUint8(
5455
+ normalizePromptAttr({
5456
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
5457
+ prompt: mergedArgs["prompt"],
5458
+ messages: mergedArgs["messages"]
5459
+ })
5460
+ )
5321
5461
  )
5322
5462
  ]
5323
5463
  ]
@@ -5531,7 +5671,13 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
5531
5671
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
5532
5672
  attrString(
5533
5673
  "ai.prompt",
5534
- safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
5674
+ safeJsonWithUint8(
5675
+ normalizePromptAttr({
5676
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
5677
+ prompt: mergedArgs["prompt"],
5678
+ messages: mergedArgs["messages"]
5679
+ })
5680
+ )
5535
5681
  )
5536
5682
  ]
5537
5683
  ]
@@ -5908,9 +6054,19 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
5908
6054
  for (const part of content) {
5909
6055
  if (isRecord(part)) {
5910
6056
  if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
5911
- sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
6057
+ sendLocalDebuggerLiveEvent({
6058
+ traceId,
6059
+ type: "reasoning_delta",
6060
+ content: (_b = part["text"]) != null ? _b : part["thinking"],
6061
+ metadata: liveMeta
6062
+ });
5912
6063
  } else if (part["type"] === "text" && typeof part["text"] === "string") {
5913
- sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
6064
+ sendLocalDebuggerLiveEvent({
6065
+ traceId,
6066
+ type: "text_delta",
6067
+ content: part["text"],
6068
+ metadata: liveMeta
6069
+ });
5914
6070
  }
5915
6071
  }
5916
6072
  }
@@ -5991,7 +6147,10 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
5991
6147
  attributes: [
5992
6148
  ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
5993
6149
  attrString("ai.response.finishReason", finishReason),
5994
- attrString("ai.response.text", activeText.length ? capText2(activeText) : void 0),
6150
+ attrString(
6151
+ "ai.response.text",
6152
+ activeText.length ? capText2(activeText) : void 0
6153
+ ),
5995
6154
  attrString(
5996
6155
  "ai.response.toolCalls",
5997
6156
  safeJsonWithUint8(toolCallsLocal.length ? toolCallsLocal : void 0)
@@ -6009,7 +6168,8 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6009
6168
  ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
6010
6169
  attrString("gen_ai.response.id", responseId),
6011
6170
  attrString(MODEL_USAGE_ATTRIBUTES.responseModel, finalResponseModelId),
6012
- ...buildModelUsageAttributes(usageMetrics),
6171
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
6172
+ ...buildRawModelUsageAttributes(usageMetrics),
6013
6173
  ...msToFirstChunk !== void 0 ? [attrInt("ai.stream.msToFirstChunk", msToFirstChunk)] : [],
6014
6174
  ...msToFinish !== void 0 ? [attrInt("ai.stream.msToFinish", msToFinish)] : [],
6015
6175
  ...avgOutTokensPerSecond !== void 0 ? [attrDouble("ai.stream.avgOutputTokensPerSecond", avgOutTokensPerSecond)] : [],
@@ -6063,19 +6223,44 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6063
6223
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
6064
6224
  if (localDebuggerEnabled() && ctx.rootParentForChildren) {
6065
6225
  const traceId = ctx.rootParentForChildren.traceIdB64;
6066
- const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
6226
+ const liveMeta = getLocalDebuggerMetadata({
6227
+ ...ctx.context,
6228
+ eventId: ctx.eventId
6229
+ });
6067
6230
  if (type === "text-delta") {
6068
6231
  const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
6069
- if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
6232
+ if (typeof text === "string" && text)
6233
+ sendLocalDebuggerLiveEvent({
6234
+ traceId,
6235
+ type: "text_delta",
6236
+ content: text,
6237
+ metadata: liveMeta
6238
+ });
6070
6239
  } else if (type === "reasoning" || type === "reasoning-delta") {
6071
6240
  const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
6072
- if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
6241
+ if (typeof text === "string" && text)
6242
+ sendLocalDebuggerLiveEvent({
6243
+ traceId,
6244
+ type: "reasoning_delta",
6245
+ content: text,
6246
+ metadata: liveMeta
6247
+ });
6073
6248
  } else if (type === "tool-call") {
6074
6249
  const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
6075
- sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
6250
+ sendLocalDebuggerLiveEvent({
6251
+ traceId,
6252
+ type: "tool_start",
6253
+ content: toolName,
6254
+ metadata: { ...liveMeta, args: value["args"] }
6255
+ });
6076
6256
  } else if (type === "tool-result") {
6077
6257
  const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
6078
- sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
6258
+ sendLocalDebuggerLiveEvent({
6259
+ traceId,
6260
+ type: "tool_result",
6261
+ content: toolName,
6262
+ metadata: { ...liveMeta, result: value["result"] }
6263
+ });
6079
6264
  }
6080
6265
  }
6081
6266
  }
@@ -6155,11 +6340,7 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
6155
6340
  } else {
6156
6341
  responseTimestampIso = (/* @__PURE__ */ new Date()).toISOString();
6157
6342
  }
6158
- const usageMetrics = extractUsageMetricsFromUsage(
6159
- usage,
6160
- modelInfo.provider,
6161
- providerMetadata
6162
- );
6343
+ const usageMetrics = extractUsageMetricsFromUsage(usage, modelInfo.provider, providerMetadata);
6163
6344
  const { inputTokens, outputTokens } = usageMetrics;
6164
6345
  ctx.traceShipper.endSpan(span, {
6165
6346
  attributes: [
@@ -6180,7 +6361,8 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
6180
6361
  ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
6181
6362
  attrString("gen_ai.response.id", responseId),
6182
6363
  attrString(MODEL_USAGE_ATTRIBUTES.responseModel, responseModelId),
6183
- ...buildModelUsageAttributes(usageMetrics)
6364
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
6365
+ ...buildRawModelUsageAttributes(usageMetrics)
6184
6366
  ]
6185
6367
  });
6186
6368
  }