@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,6 +1,68 @@
1
1
  import { AsyncLocalStorage } from 'async_hooks';
2
2
 
3
- // ../core/dist/chunk-YUIXRQWN.js
3
+ // ../core/dist/chunk-BYBMRLZM.js
4
+ var EVAL_CORRELATION_ID_ATTRIBUTE = "raindrop.eval_correlation_id";
5
+ var PROBE_SCOPE = { correlationId: "" };
6
+ var EvalScopeStorage = class {
7
+ constructor() {
8
+ this._als = null;
9
+ this._probed = false;
10
+ }
11
+ maybeAdoptAsyncLocalStorage() {
12
+ if (this._probed) return;
13
+ this._probed = true;
14
+ try {
15
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
16
+ if (!Ctor) return;
17
+ const als = new Ctor();
18
+ als.run(PROBE_SCOPE, () => {
19
+ });
20
+ this._als = als;
21
+ } catch (e) {
22
+ this._als = null;
23
+ }
24
+ }
25
+ run(scope, callback) {
26
+ this.maybeAdoptAsyncLocalStorage();
27
+ if (this._als) return this._als.run(scope, callback);
28
+ const previous = this._syncScope;
29
+ this._syncScope = scope;
30
+ try {
31
+ return callback();
32
+ } finally {
33
+ this._syncScope = previous;
34
+ }
35
+ }
36
+ current() {
37
+ this.maybeAdoptAsyncLocalStorage();
38
+ if (this._als) return this._als.getStore();
39
+ return this._syncScope;
40
+ }
41
+ };
42
+ var EVAL_SCOPE_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.evalScopeStorage");
43
+ function evalScopeStorage() {
44
+ const holder = globalThis;
45
+ let storage = holder[EVAL_SCOPE_STORAGE_KEY];
46
+ if (!storage) {
47
+ storage = new EvalScopeStorage();
48
+ holder[EVAL_SCOPE_STORAGE_KEY] = storage;
49
+ }
50
+ return storage;
51
+ }
52
+ function currentEvalScope() {
53
+ try {
54
+ return evalScopeStorage().current();
55
+ } catch (e) {
56
+ return void 0;
57
+ }
58
+ }
59
+ function evalScopeAttributes() {
60
+ const scope = currentEvalScope();
61
+ if (!scope) return {};
62
+ return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
63
+ }
64
+
65
+ // ../core/dist/chunk-T53LQAH7.js
4
66
  function normalizeFeatureFlags(input) {
5
67
  if (Array.isArray(input)) {
6
68
  return Object.fromEntries(input.map((name) => [name, "true"]));
@@ -495,6 +557,7 @@ async function postJson(url, body, headers, opts) {
495
557
  const resp = await runWithTracingSuppressed(
496
558
  () => fetch(url, {
497
559
  method: "POST",
560
+ redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
498
561
  headers: {
499
562
  "Content-Type": "application/json",
500
563
  ...headers
@@ -618,6 +681,55 @@ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", se
618
681
  ]
619
682
  };
620
683
  }
684
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
685
+ function state() {
686
+ const holder = globalThis;
687
+ let current = holder[STATE_KEY];
688
+ if (!current) {
689
+ let storage = null;
690
+ try {
691
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
692
+ if (Ctor) storage = new Ctor();
693
+ } catch (e) {
694
+ storage = null;
695
+ }
696
+ current = {
697
+ storage,
698
+ syncDestination: void 0,
699
+ spanDestinations: /* @__PURE__ */ new WeakMap()
700
+ };
701
+ holder[STATE_KEY] = current;
702
+ }
703
+ return current;
704
+ }
705
+ function currentReplayTraceDestination() {
706
+ var _a, _b;
707
+ const routing = state();
708
+ return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
709
+ }
710
+ function rememberReplayTraceDestination(span) {
711
+ const destination = currentReplayTraceDestination();
712
+ if (destination) state().spanDestinations.set(span, destination);
713
+ }
714
+ function copyReplayTraceDestination(source, target) {
715
+ const destination = state().spanDestinations.get(source);
716
+ if (destination) state().spanDestinations.set(target, destination);
717
+ }
718
+ function replayTraceDestinationFor(value) {
719
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
720
+ return void 0;
721
+ }
722
+ return state().spanDestinations.get(value);
723
+ }
724
+ function recordReplayExportedSpan(destination, spanId, traceId) {
725
+ var _a, _b;
726
+ if (!destination || !spanId || !traceId) return;
727
+ (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
728
+ (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
729
+ }
730
+ function replayTraceUrl(baseUrl) {
731
+ return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
732
+ }
621
733
  var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
622
734
  var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
623
735
  var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
@@ -683,31 +795,36 @@ function resolveLocalDebuggerBaseUrl(baseUrl) {
683
795
  function localDebuggerEnabled(baseUrl) {
684
796
  return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
685
797
  }
798
+ var LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS = 2e3;
686
799
  function mirrorTraceExportToLocalDebugger(body, options = {}) {
687
800
  var _a;
688
801
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
689
- if (!baseUrl) return;
690
- void postJson(`${baseUrl}traces`, body, {}, {
802
+ if (!baseUrl) return Promise.resolve();
803
+ return postJson(`${baseUrl}traces`, body, {}, {
691
804
  maxAttempts: 1,
692
805
  debug: (_a = options.debug) != null ? _a : false,
693
- sdkName: options.sdkName
806
+ sdkName: options.sdkName,
807
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
694
808
  }).catch(() => {
695
809
  });
696
810
  }
697
811
  function mirrorPartialEventToLocalDebugger(event, options = {}) {
698
812
  var _a;
699
813
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
700
- if (!baseUrl) return;
814
+ if (!baseUrl) return Promise.resolve();
701
815
  const headers = options.writeKey ? { Authorization: `Bearer ${options.writeKey}` } : {};
702
- void postJson(`${baseUrl}events/track_partial`, event, headers, {
816
+ return postJson(`${baseUrl}events/track_partial`, event, headers, {
703
817
  maxAttempts: 1,
704
818
  debug: (_a = options.debug) != null ? _a : false,
705
- sdkName: options.sdkName
819
+ sdkName: options.sdkName,
820
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
706
821
  }).catch(() => {
707
822
  });
708
823
  }
709
824
  function sendLocalDebuggerLiveEvent(event, options = {}) {
710
825
  var _a, _b;
826
+ const destination = currentReplayTraceDestination();
827
+ if (destination && destination.kind !== "workshop") return;
711
828
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
712
829
  if (!baseUrl) return;
713
830
  void postJson(
@@ -879,6 +996,15 @@ var EventShipper = class {
879
996
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
880
997
  if (!this.enabled) return;
881
998
  if (!eventId || !eventId.trim()) return;
999
+ const capturedSticky = this.sticky.get(eventId);
1000
+ const eventAlreadyKnown = capturedSticky !== void 0 || this.buffers.has(eventId);
1001
+ const destination = currentReplayTraceDestination();
1002
+ const cloudReplay = destination !== void 0 && destination.kind !== "workshop";
1003
+ if ((capturedSticky == null ? void 0 : capturedSticky.replayOnly) === true || !eventAlreadyKnown && cloudReplay) {
1004
+ if (patch.isPending === false) this.sticky.delete(eventId);
1005
+ else this.sticky.set(eventId, { ...capturedSticky, replayOnly: true });
1006
+ return;
1007
+ }
882
1008
  const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
883
1009
  if (typeof patch.input === "string" && patch.input.length > maxChars) {
884
1010
  patch = { ...patch, input: capText(patch.input, maxChars) };
@@ -937,6 +1063,9 @@ var EventShipper = class {
937
1063
  try {
938
1064
  for (const t of this.timers.values()) clearTimeout(t);
939
1065
  this.timers.clear();
1066
+ for (const [eventId, sticky] of this.sticky) {
1067
+ if (sticky.replayOnly) this.sticky.delete(eventId);
1068
+ }
940
1069
  const settled = await raceWithTimeout(this.flush(), SHUTDOWN_DEADLINE_MS);
941
1070
  if (!settled) this.warnShutdownDrop("in-flight request(s) at shutdown");
942
1071
  } finally {
@@ -946,6 +1075,8 @@ var EventShipper = class {
946
1075
  async trackSignal(signal) {
947
1076
  var _a, _b;
948
1077
  if (!this.enabled) return;
1078
+ const destination = currentReplayTraceDestination();
1079
+ if (destination && destination.kind !== "workshop") return;
949
1080
  const body = [
950
1081
  {
951
1082
  event_id: signal.eventId,
@@ -980,6 +1111,8 @@ var EventShipper = class {
980
1111
  }
981
1112
  async identify(users) {
982
1113
  if (!this.enabled) return;
1114
+ const destination = currentReplayTraceDestination();
1115
+ if (destination && destination.kind !== "workshop") return;
983
1116
  const list = Array.isArray(users) ? users : [users];
984
1117
  const body = list.filter((user) => {
985
1118
  if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
@@ -1032,8 +1165,9 @@ var EventShipper = class {
1032
1165
  this.buffers.delete(eventId);
1033
1166
  if (!accumulated) return;
1034
1167
  const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
1035
- const eventName = (_c = (_b = accumulated.eventName) != null ? _b : sticky.eventName) != null ? _c : this.defaultEventName;
1036
- const userId = (_d = accumulated.userId) != null ? _d : sticky.userId;
1168
+ const isPending = (_c = (_b = accumulated.isPending) != null ? _b : sticky.isPending) != null ? _c : true;
1169
+ const eventName = (_e = (_d = accumulated.eventName) != null ? _d : sticky.eventName) != null ? _e : this.defaultEventName;
1170
+ const userId = (_f = accumulated.userId) != null ? _f : sticky.userId;
1037
1171
  if (!userId) {
1038
1172
  if (this.debug) {
1039
1173
  console.warn(`${this.prefix} skipping track_partial for ${eventId}: missing userId`);
@@ -1041,14 +1175,13 @@ var EventShipper = class {
1041
1175
  this.sticky.delete(eventId);
1042
1176
  return;
1043
1177
  }
1044
- const { wizardSession, ...restProperties } = (_e = accumulated.properties) != null ? _e : {};
1178
+ const { wizardSession, ...restProperties } = (_g = accumulated.properties) != null ? _g : {};
1045
1179
  let telemetryProperties = {};
1046
1180
  try {
1047
1181
  telemetryProperties = eventTelemetryProperties(accumulated);
1048
1182
  } catch (e) {
1049
1183
  }
1050
- const convoId = (_f = accumulated.convoId) != null ? _f : sticky.convoId;
1051
- const isPending = (_h = (_g = accumulated.isPending) != null ? _g : sticky.isPending) != null ? _h : true;
1184
+ const convoId = (_h = accumulated.convoId) != null ? _h : sticky.convoId;
1052
1185
  const payload = {
1053
1186
  event_id: eventId,
1054
1187
  user_id: userId,
@@ -1090,29 +1223,30 @@ var EventShipper = class {
1090
1223
  endpoint: url
1091
1224
  });
1092
1225
  }
1093
- if (this.localDebuggerUrl) {
1094
- mirrorPartialEventToLocalDebugger(payload, {
1095
- baseUrl: this.localDebuggerUrl,
1096
- writeKey: this.writeKey,
1097
- debug: this.debug,
1098
- sdkName: this.sdkName
1099
- });
1100
- }
1226
+ const mirror = this.localDebuggerUrl ? mirrorPartialEventToLocalDebugger(payload, {
1227
+ baseUrl: this.localDebuggerUrl,
1228
+ writeKey: this.writeKey,
1229
+ debug: this.debug,
1230
+ sdkName: this.sdkName
1231
+ }) : void 0;
1101
1232
  if (!this.writeKey) {
1102
1233
  if (!isPending) this.sticky.delete(eventId);
1234
+ if (mirror) await mirror;
1103
1235
  return;
1104
1236
  }
1105
1237
  const opts = this.requestOpts();
1106
1238
  if (!opts) {
1107
1239
  this.warnShutdownDrop(`track_partial ${eventId}`);
1108
1240
  if (!isPending) this.sticky.delete(eventId);
1241
+ if (mirror) await mirror;
1109
1242
  return;
1110
1243
  }
1111
1244
  const p = postJson(url, payload, this.requestHeaders(), opts);
1112
- this.inFlight.add(p);
1245
+ const combined = mirror ? Promise.all([mirror, p]).then(() => void 0) : p;
1246
+ this.inFlight.add(combined);
1113
1247
  try {
1114
1248
  try {
1115
- await p;
1249
+ await combined;
1116
1250
  if (this.debug) {
1117
1251
  console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
1118
1252
  }
@@ -1124,7 +1258,7 @@ var EventShipper = class {
1124
1258
  );
1125
1259
  }
1126
1260
  } finally {
1127
- this.inFlight.delete(p);
1261
+ this.inFlight.delete(combined);
1128
1262
  }
1129
1263
  if (!isPending) {
1130
1264
  this.sticky.delete(eventId);
@@ -1132,6 +1266,7 @@ var EventShipper = class {
1132
1266
  }
1133
1267
  };
1134
1268
  var MODEL_USAGE_ATTRIBUTES = {
1269
+ usageSource: "raindrop.usage.source",
1135
1270
  providerName: "gen_ai.provider.name",
1136
1271
  requestModel: "gen_ai.request.model",
1137
1272
  responseModel: "gen_ai.response.model",
@@ -1140,20 +1275,22 @@ var MODEL_USAGE_ATTRIBUTES = {
1140
1275
  reasoningTokens: "gen_ai.usage.reasoning_tokens",
1141
1276
  cacheReadInputTokens: "gen_ai.usage.cache_read_input_tokens",
1142
1277
  cacheWriteInputTokens: "gen_ai.usage.cache_write_input_tokens",
1143
- nonCachedInputTokens: "raindrop.usage.input_tokens.non_cached",
1144
- nonReasoningOutputTokens: "raindrop.usage.output_tokens.non_reasoning",
1145
- reasoningOutputTokens: "raindrop.usage.output_tokens.reasoning",
1146
- cacheReadTokens: "raindrop.usage.input_tokens.cache_read",
1147
- cacheWriteTokens: "raindrop.usage.input_tokens.cache_write"
1148
- };
1278
+ providerReportedCost: "gen_ai.usage.provider_reported_cost"};
1149
1279
  var MODEL_PROVIDER_NAMES = [
1280
+ ["google.vertex.anthropic", "google-vertex"],
1281
+ ["google.vertex_ai", "google-vertex"],
1150
1282
  ["google.vertex", "google-vertex"],
1283
+ ["gcp.vertex_ai", "google-vertex"],
1284
+ ["gcp.gemini", "google"],
1285
+ ["google_vertexai", "google-vertex"],
1151
1286
  ["vertex.anthropic", "google-vertex"],
1152
1287
  ["amazon-bedrock", "amazon-bedrock"],
1288
+ ["aws.bedrock", "amazon-bedrock"],
1153
1289
  ["bedrock", "amazon-bedrock"],
1154
1290
  ["anthropic", "anthropic"],
1155
1291
  ["openai", "openai"],
1156
1292
  ["google", "google"],
1293
+ ["az.ai.openai", "azure"],
1157
1294
  ["azure", "azure"],
1158
1295
  ["openrouter", "openrouter"]
1159
1296
  ];
@@ -1164,60 +1301,20 @@ function canonicalModelProvider(provider) {
1164
1301
  const match = MODEL_PROVIDER_NAMES.find(
1165
1302
  ([family]) => normalizedProvider === family || normalizedProvider.startsWith(`${family}.`)
1166
1303
  );
1167
- return (_a = match == null ? void 0 : match[1]) != null ? _a : provider;
1304
+ return (_a = match == null ? void 0 : match[1]) != null ? _a : normalizedProvider;
1168
1305
  }
1169
1306
  function tokenCount(value) {
1170
1307
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1171
1308
  }
1172
- function exclusiveTokens({
1173
- explicit,
1174
- total,
1175
- parts,
1176
- semantics
1177
- }) {
1178
- if (explicit !== void 0) return explicit;
1179
- if (total === void 0) return void 0;
1180
- if (semantics === "exclusive") return total;
1181
- const observedParts = parts.filter((part) => part !== void 0 && part > 0);
1182
- if (semantics === void 0 && observedParts.length > 0) return void 0;
1183
- const exclusive = total - observedParts.reduce((sum, part) => sum + part, 0);
1184
- return exclusive >= 0 ? exclusive : void 0;
1185
- }
1186
- function buildModelUsageAttributes(usage) {
1187
- const inputTokens = tokenCount(usage.inputTokens);
1188
- const outputTokens = tokenCount(usage.outputTokens);
1189
- const explicitNonCachedInputTokens = tokenCount(usage.nonCachedInputTokens);
1190
- const explicitNonReasoningOutputTokens = tokenCount(usage.nonReasoningOutputTokens);
1191
- const reasoningTokens = tokenCount(usage.reasoningTokens);
1192
- const cacheReadInputTokens = tokenCount(usage.cacheReadInputTokens);
1193
- const cacheWriteInputTokens = tokenCount(usage.cacheWriteInputTokens);
1194
- const nonCachedInputTokens = exclusiveTokens({
1195
- explicit: explicitNonCachedInputTokens,
1196
- total: inputTokens,
1197
- parts: [cacheReadInputTokens, cacheWriteInputTokens],
1198
- semantics: usage.inputTokenSemantics
1199
- });
1200
- const nonReasoningOutputTokens = exclusiveTokens({
1201
- explicit: explicitNonReasoningOutputTokens,
1202
- total: outputTokens,
1203
- parts: [reasoningTokens],
1204
- semantics: usage.outputTokenSemantics
1205
- });
1206
- const exclusivePoolAttributes = nonCachedInputTokens !== void 0 && nonReasoningOutputTokens !== void 0 ? [
1207
- // backend consumes this complete raindrop.* set as one atomic billing-pool contract.
1208
- attrInt(MODEL_USAGE_ATTRIBUTES.nonCachedInputTokens, nonCachedInputTokens),
1209
- attrInt(MODEL_USAGE_ATTRIBUTES.nonReasoningOutputTokens, nonReasoningOutputTokens),
1210
- attrInt(MODEL_USAGE_ATTRIBUTES.reasoningOutputTokens, reasoningTokens),
1211
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadTokens, cacheReadInputTokens),
1212
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteTokens, cacheWriteInputTokens)
1213
- ] : [];
1309
+ function buildRawModelUsageAttributes(usage) {
1310
+ const providerReportedCost = typeof usage.providerReportedCost === "number" && Number.isFinite(usage.providerReportedCost) && usage.providerReportedCost >= 0 ? usage.providerReportedCost : void 0;
1214
1311
  return [
1215
- attrInt(MODEL_USAGE_ATTRIBUTES.inputTokens, inputTokens),
1216
- attrInt(MODEL_USAGE_ATTRIBUTES.outputTokens, outputTokens),
1217
- attrInt(MODEL_USAGE_ATTRIBUTES.reasoningTokens, reasoningTokens),
1218
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadInputTokens, cacheReadInputTokens),
1219
- attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteInputTokens, cacheWriteInputTokens),
1220
- ...exclusivePoolAttributes
1312
+ attrInt(MODEL_USAGE_ATTRIBUTES.inputTokens, tokenCount(usage.inputTokens)),
1313
+ attrInt(MODEL_USAGE_ATTRIBUTES.outputTokens, tokenCount(usage.outputTokens)),
1314
+ attrInt(MODEL_USAGE_ATTRIBUTES.reasoningTokens, tokenCount(usage.reasoningTokens)),
1315
+ attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadInputTokens, tokenCount(usage.cacheReadInputTokens)),
1316
+ attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteInputTokens, tokenCount(usage.cacheWriteInputTokens)),
1317
+ attrDouble(MODEL_USAGE_ATTRIBUTES.providerReportedCost, providerReportedCost)
1221
1318
  ].filter((attribute) => attribute !== void 0);
1222
1319
  }
1223
1320
  var STRING_ALIASES = {
@@ -1509,7 +1606,10 @@ var TraceShipper = class {
1509
1606
  try {
1510
1607
  const result = this.transformSpanHook(current);
1511
1608
  if (result === null) return null;
1512
- if (result !== void 0) current = result;
1609
+ if (result !== void 0) {
1610
+ copyReplayTraceDestination(current, result);
1611
+ current = result;
1612
+ }
1513
1613
  } catch (err) {
1514
1614
  if (this.debug) {
1515
1615
  const msg = err instanceof Error ? err.message : String(err);
@@ -1519,13 +1619,19 @@ var TraceShipper = class {
1519
1619
  }
1520
1620
  }
1521
1621
  try {
1522
- current = normalizeModelUsageSpan(current);
1622
+ const normalized = normalizeModelUsageSpan(current);
1623
+ copyReplayTraceDestination(current, normalized);
1624
+ current = normalized;
1523
1625
  } catch (e) {
1524
1626
  }
1525
1627
  if (!this.disableDefaultRedaction) {
1526
- current = defaultTransformSpan(current);
1628
+ const redacted = defaultTransformSpan(current);
1629
+ copyReplayTraceDestination(current, redacted);
1630
+ current = redacted;
1527
1631
  }
1528
- return this.capSpanAttributes(current);
1632
+ const capped = this.capSpanAttributes(current);
1633
+ copyReplayTraceDestination(current, capped);
1634
+ return capped;
1529
1635
  }
1530
1636
  isDebugEnabled() {
1531
1637
  return this.debug;
@@ -1543,33 +1649,54 @@ var TraceShipper = class {
1543
1649
  const attrs = [
1544
1650
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1545
1651
  ...identityAttrs(args),
1546
- attrString("ai.operationId", args.operationId)
1652
+ attrString("ai.operationId", args.operationId),
1653
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1547
1654
  ];
1548
1655
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
1549
- const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
1550
- this.mirrorToLocalDebugger(
1551
- buildOtlpSpan({
1552
- ids: span.ids,
1553
- name: span.name,
1554
- startTimeUnixNano: span.startTimeUnixNano,
1555
- endTimeUnixNano: span.startTimeUnixNano,
1556
- // placeholder — will be updated on endSpan
1557
- attributes: span.attributes,
1558
- status: { code: SpanStatusCode.UNSET }
1559
- })
1560
- );
1656
+ const span = {
1657
+ ids,
1658
+ name: args.name,
1659
+ startTimeUnixNano: started,
1660
+ attributes: attrs
1661
+ };
1662
+ rememberReplayTraceDestination(span);
1663
+ const openSpan = buildOtlpSpan({
1664
+ ids: span.ids,
1665
+ name: span.name,
1666
+ startTimeUnixNano: span.startTimeUnixNano,
1667
+ endTimeUnixNano: span.startTimeUnixNano,
1668
+ // placeholder — will be updated on endSpan
1669
+ attributes: span.attributes,
1670
+ status: { code: SpanStatusCode.UNSET }
1671
+ });
1672
+ copyReplayTraceDestination(span, openSpan);
1673
+ this.mirrorToLocalDebugger(openSpan);
1561
1674
  return span;
1562
1675
  }
1563
- mirrorToLocalDebugger(span) {
1564
- if (!this.localDebuggerUrl) return;
1676
+ mirrorToLocalDebugger(span, completed = false) {
1677
+ const destination = replayTraceDestinationFor(span);
1678
+ if (destination && destination.kind !== "workshop") return;
1679
+ const localDebuggerUrl = (destination == null ? void 0 : destination.kind) === "workshop" ? destination.url : this.localDebuggerUrl;
1680
+ if (!localDebuggerUrl) return;
1565
1681
  const redacted = this.redactSpan(span);
1566
1682
  if (redacted === null) return;
1683
+ if (completed && (destination == null ? void 0 : destination.kind) === "workshop") {
1684
+ recordReplayExportedSpan(
1685
+ destination,
1686
+ base64ToHex(redacted.spanId),
1687
+ base64ToHex(redacted.traceId)
1688
+ );
1689
+ }
1567
1690
  const body = buildExportTraceServiceRequest([redacted], this.serviceName, this.serviceVersion);
1568
- mirrorTraceExportToLocalDebugger(body, {
1569
- baseUrl: this.localDebuggerUrl,
1691
+ const p = mirrorTraceExportToLocalDebugger(body, {
1692
+ baseUrl: localDebuggerUrl,
1570
1693
  debug: false,
1571
1694
  sdkName: this.sdkName
1572
1695
  });
1696
+ this.inFlight.add(p);
1697
+ void p.finally(() => {
1698
+ this.inFlight.delete(p);
1699
+ });
1573
1700
  }
1574
1701
  endSpan(span, extra) {
1575
1702
  var _a, _b;
@@ -1591,15 +1718,17 @@ var TraceShipper = class {
1591
1718
  attributes: span.attributes,
1592
1719
  status
1593
1720
  });
1721
+ copyReplayTraceDestination(span, otlp);
1594
1722
  this.enqueue(otlp);
1595
- this.mirrorToLocalDebugger(otlp);
1723
+ this.mirrorToLocalDebugger(otlp, true);
1596
1724
  }
1597
1725
  createSpan(args) {
1598
1726
  var _a;
1599
1727
  const ids = createSpanIds(args.parent);
1600
1728
  const attrs = [
1601
1729
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1602
- ...identityAttrs(args)
1730
+ ...identityAttrs(args),
1731
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1603
1732
  ];
1604
1733
  if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
1605
1734
  const otlp = buildOtlpSpan({
@@ -1610,8 +1739,9 @@ var TraceShipper = class {
1610
1739
  attributes: attrs,
1611
1740
  status: args.status
1612
1741
  });
1742
+ rememberReplayTraceDestination(otlp);
1613
1743
  this.enqueue(otlp);
1614
- this.mirrorToLocalDebugger(otlp);
1744
+ this.mirrorToLocalDebugger(otlp, true);
1615
1745
  }
1616
1746
  enqueue(span) {
1617
1747
  if (!this.enabled) return;
@@ -1625,6 +1755,13 @@ var TraceShipper = class {
1625
1755
  }
1626
1756
  const redacted = this.redactSpan(span);
1627
1757
  if (redacted === null) return;
1758
+ const destination = replayTraceDestinationFor(redacted);
1759
+ recordReplayExportedSpan(
1760
+ destination,
1761
+ base64ToHex(redacted.spanId),
1762
+ base64ToHex(redacted.traceId)
1763
+ );
1764
+ if ((destination == null ? void 0 : destination.kind) === "workshop") return;
1628
1765
  if (this.queue.length >= this.maxQueueSize) {
1629
1766
  this.queue.shift();
1630
1767
  }
@@ -1643,47 +1780,67 @@ var TraceShipper = class {
1643
1780
  }
1644
1781
  }
1645
1782
  async flush() {
1646
- if (!this.enabled) return;
1783
+ var _a;
1784
+ if (!this.enabled) {
1785
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
1786
+ })));
1787
+ return;
1788
+ }
1647
1789
  if (this.timer) {
1648
1790
  clearTimeout(this.timer);
1649
1791
  this.timer = void 0;
1650
1792
  }
1651
1793
  while (this.queue.length > 0) {
1652
1794
  const batch = this.queue.splice(0, this.maxBatchSize);
1653
- if (!this.writeKey) continue;
1654
- const opts = this.requestOpts();
1655
- if (!opts) {
1656
- rateLimitedLog(
1657
- `${this.prefix}.shutdown_deadline`,
1658
- () => console.warn(
1659
- `${this.prefix} shutdown flush deadline exceeded; dropping ${batch.length} spans`
1660
- )
1661
- );
1662
- continue;
1663
- }
1664
- const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
1665
- const url = `${this.baseUrl}traces`;
1666
- if (this.debug) {
1667
- console.log(`${this.prefix} sending traces batch`, {
1668
- spans: batch.length,
1669
- endpoint: url
1670
- });
1795
+ const groups = /* @__PURE__ */ new Map();
1796
+ for (const span of batch) {
1797
+ const destination = replayTraceDestinationFor(span);
1798
+ const spans = groups.get(destination);
1799
+ if (spans) spans.push(span);
1800
+ else groups.set(destination, [span]);
1671
1801
  }
1672
- const p = postJson(url, body, this.requestHeaders(), opts);
1673
- this.inFlight.add(p);
1674
- try {
1675
- try {
1676
- await p;
1677
- if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
1678
- } catch (err) {
1679
- const msg = err instanceof Error ? err.message : String(err);
1802
+ for (const [destination, spans] of groups) {
1803
+ if (!destination && !this.writeKey) continue;
1804
+ if ((destination == null ? void 0 : destination.kind) === "workshop") continue;
1805
+ const opts = this.requestOpts();
1806
+ if (!opts) {
1680
1807
  rateLimitedLog(
1681
- `${this.prefix}.send_spans_failed`,
1682
- () => console.warn(`${this.prefix} failed to send ${batch.length} spans: ${msg}`)
1808
+ `${this.prefix}.shutdown_deadline`,
1809
+ () => console.warn(
1810
+ `${this.prefix} shutdown flush deadline exceeded; dropping ${spans.length} spans`
1811
+ )
1683
1812
  );
1813
+ continue;
1814
+ }
1815
+ const body = buildExportTraceServiceRequest(spans, this.serviceName, this.serviceVersion);
1816
+ const url = destination ? replayTraceUrl(destination.url) : `${this.baseUrl}traces`;
1817
+ const headers = destination ? {
1818
+ Authorization: `Bearer ${destination.apiKey}`,
1819
+ "X-Raindrop-Replay-Id": destination.replayId,
1820
+ "X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
1821
+ } : this.requestHeaders();
1822
+ if (this.debug) {
1823
+ console.log(`${this.prefix} sending traces batch`, {
1824
+ spans: spans.length,
1825
+ endpoint: url
1826
+ });
1827
+ }
1828
+ const p = postJson(url, body, headers, opts);
1829
+ this.inFlight.add(p);
1830
+ try {
1831
+ try {
1832
+ await p;
1833
+ if (this.debug) console.log(`${this.prefix} sent ${spans.length} spans`);
1834
+ } catch (err) {
1835
+ const msg = err instanceof Error ? err.message : String(err);
1836
+ rateLimitedLog(
1837
+ `${this.prefix}.send_spans_failed`,
1838
+ () => console.warn(`${this.prefix} failed to send ${spans.length} spans: ${msg}`)
1839
+ );
1840
+ }
1841
+ } finally {
1842
+ this.inFlight.delete(p);
1684
1843
  }
1685
- } finally {
1686
- this.inFlight.delete(p);
1687
1844
  }
1688
1845
  }
1689
1846
  }
@@ -1726,7 +1883,9 @@ var TraceShipper = class {
1726
1883
  if (!settled) {
1727
1884
  rateLimitedLog(
1728
1885
  `${this.prefix}.shutdown_deadline`,
1729
- () => console.warn(`${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`)
1886
+ () => console.warn(
1887
+ `${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`
1888
+ )
1730
1889
  );
1731
1890
  }
1732
1891
  } finally {
@@ -1821,7 +1980,8 @@ function withCurrent(span, callback) {
1821
1980
  return getContextManager().runInContext(span, callback);
1822
1981
  }
1823
1982
  async function getCurrentParentSpanContext() {
1824
- return getContextManager().getParentSpanIds();
1983
+ var _a, _b;
1984
+ return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
1825
1985
  }
1826
1986
  async function runWithParentSpanContext(ctx, fn) {
1827
1987
  const cm = getContextManager();
@@ -3103,29 +3263,6 @@ function firstTokenCount(...values) {
3103
3263
  }
3104
3264
  return void 0;
3105
3265
  }
3106
- function flatUsageSemantics(provider) {
3107
- const normalizedProvider = typeof provider === "string" ? provider.trim().toLowerCase() : void 0;
3108
- if (normalizedProvider === "anthropic" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("anthropic.")) || normalizedProvider === "vertex.anthropic" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("vertex.anthropic."))) {
3109
- return {
3110
- inputTokenSemantics: "exclusive",
3111
- outputTokenSemantics: "total"
3112
- };
3113
- }
3114
- if (normalizedProvider === "openai" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("openai.")) || normalizedProvider === "azure" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("azure."))) {
3115
- return {
3116
- inputTokenSemantics: "total",
3117
- outputTokenSemantics: "total"
3118
- };
3119
- }
3120
- if (normalizedProvider === "google" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("google."))) {
3121
- return {
3122
- inputTokenSemantics: "total",
3123
- // Google v5 reports candidate output and thoughts separately.
3124
- outputTokenSemantics: "exclusive"
3125
- };
3126
- }
3127
- return {};
3128
- }
3129
3266
  var CACHE_WRITE_METADATA_KEYS = [
3130
3267
  ["anthropic", "cacheCreationInputTokens"],
3131
3268
  ["openai", "cacheWriteTokens"],
@@ -3142,7 +3279,7 @@ function cacheWriteTokensFromProviderMetadata(providerMetadata) {
3142
3279
  })
3143
3280
  );
3144
3281
  }
3145
- function extractUsageMetricsFromUsage(usage, provider, providerMetadata) {
3282
+ function extractUsageMetricsFromUsage(usage, _provider, providerMetadata) {
3146
3283
  if (!isRecord(usage)) return {};
3147
3284
  const inputTokenValue = usage["inputTokens"];
3148
3285
  const outputTokenValue = usage["outputTokens"];
@@ -3210,7 +3347,7 @@ function extractUsageMetricsFromUsage(usage, provider, providerMetadata) {
3210
3347
  cacheReadInputTokens,
3211
3348
  cachedInputTokens: cacheReadInputTokens,
3212
3349
  cacheWriteInputTokens,
3213
- ...hasStructuredUsage ? {} : flatUsageSemantics(provider)
3350
+ ...hasStructuredUsage ? { usageSource: "ai-sdk-structured" } : {}
3214
3351
  };
3215
3352
  }
3216
3353
 
@@ -3408,13 +3545,13 @@ var RaindropTelemetryIntegration = class {
3408
3545
  };
3409
3546
  // ── onStepStart ─────────────────────────────────────────────────────────
3410
3547
  this.onStepStart = (event) => {
3411
- const state = this.getState(event.callId);
3412
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3413
- const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
3414
- const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
3415
- const { operationName, resourceName } = opName(stepOperationId, state.functionId);
3548
+ const state2 = this.getState(event.callId);
3549
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3550
+ const isStream = state2.operationId === "ai.streamText" || state2.operationId === "ai.streamObject";
3551
+ const stepOperationId = isStream ? `${state2.operationId}.doStream` : `${state2.operationId}.doGenerate`;
3552
+ const { operationName, resourceName } = opName(stepOperationId, state2.functionId);
3416
3553
  const inputAttrs = [];
3417
- if (state.recordInputs) {
3554
+ if (state2.recordInputs) {
3418
3555
  if (event.promptMessages) {
3419
3556
  inputAttrs.push(attrString("ai.prompt.messages", safeJsonWithUint8(event.promptMessages)));
3420
3557
  }
@@ -3437,25 +3574,25 @@ var RaindropTelemetryIntegration = class {
3437
3574
  }
3438
3575
  const stepSpan = this.traceShipper.startSpan({
3439
3576
  name: stepOperationId,
3440
- parent: state.rootParent,
3441
- eventId: state.eventId,
3442
- ...state.identity,
3577
+ parent: state2.rootParent,
3578
+ eventId: state2.eventId,
3579
+ ...state2.identity,
3443
3580
  operationId: stepOperationId,
3444
3581
  attributes: [
3445
3582
  attrString("operation.name", operationName),
3446
3583
  attrString("resource.name", resourceName),
3447
- attrString("ai.telemetry.functionId", state.functionId),
3584
+ attrString("ai.telemetry.functionId", state2.functionId),
3448
3585
  ...attrsFromModelProvider(event.provider),
3449
3586
  attrString("ai.model.id", event.modelId),
3450
3587
  attrString(MODEL_USAGE_ATTRIBUTES.requestModel, event.modelId),
3451
3588
  ...inputAttrs,
3452
- ...handoffSpanAttrs(state.handoff)
3589
+ ...handoffSpanAttrs(state2.handoff)
3453
3590
  ]
3454
3591
  });
3455
- state.stepSpan = stepSpan;
3456
- state.stepParent = this.spanParentRef(stepSpan);
3457
- state.stepProvider = event.provider;
3458
- state.stepModelId = event.modelId;
3592
+ state2.stepSpan = stepSpan;
3593
+ state2.stepParent = this.spanParentRef(stepSpan);
3594
+ state2.stepProvider = event.provider;
3595
+ state2.stepModelId = event.modelId;
3459
3596
  };
3460
3597
  this.onToolExecutionStart = (event) => this.toolExecutionStart(event);
3461
3598
  this.onToolExecutionEnd = (event) => this.toolExecutionEnd(event);
@@ -3482,33 +3619,33 @@ var RaindropTelemetryIntegration = class {
3482
3619
  var _a, _b, _c, _d, _e;
3483
3620
  const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
3484
3621
  if (!callId) return;
3485
- const state = this.getState(callId);
3486
- if (!state) return;
3622
+ const state2 = this.getState(callId);
3623
+ if (!state2) return;
3487
3624
  const chunk = event.chunk;
3488
3625
  if (!chunk || typeof chunk !== "object") return;
3489
3626
  if (chunk.type === "text-delta") {
3490
3627
  const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
3491
3628
  if (typeof delta === "string") {
3492
- if (state.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3493
- state.accumulatedText += delta;
3629
+ if (state2.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3630
+ state2.accumulatedText += delta;
3494
3631
  }
3495
- this.emitLive(state, "text_delta", delta);
3632
+ this.emitLive(state2, "text_delta", delta);
3496
3633
  }
3497
3634
  } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
3498
3635
  const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
3499
3636
  if (typeof text === "string") {
3500
- this.emitLive(state, "reasoning_delta", text);
3637
+ this.emitLive(state2, "reasoning_delta", text);
3501
3638
  }
3502
3639
  }
3503
3640
  };
3504
3641
  // ── onStepFinish ────────────────────────────────────────────────────────
3505
3642
  this.onStepFinish = (event) => {
3506
3643
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3507
- const state = this.getState(event.callId);
3508
- if (!(state == null ? void 0 : state.stepSpan)) return;
3509
- const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state.stepModelId;
3644
+ const state2 = this.getState(event.callId);
3645
+ if (!(state2 == null ? void 0 : state2.stepSpan)) return;
3646
+ const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state2.stepModelId;
3510
3647
  const outputAttrs = [];
3511
- if (state.recordOutputs) {
3648
+ if (state2.recordOutputs) {
3512
3649
  outputAttrs.push(
3513
3650
  attrString("ai.response.finishReason", event.finishReason),
3514
3651
  attrString("ai.response.text", capText2((_c = event.text) != null ? _c : void 0)),
@@ -3553,7 +3690,7 @@ var RaindropTelemetryIntegration = class {
3553
3690
  if (usage) {
3554
3691
  const usageMetrics = extractUsageMetricsFromUsage(
3555
3692
  usage,
3556
- state.stepProvider,
3693
+ state2.stepProvider,
3557
3694
  event.providerMetadata
3558
3695
  );
3559
3696
  outputAttrs.push(
@@ -3562,54 +3699,55 @@ var RaindropTelemetryIntegration = class {
3562
3699
  attrInt("ai.usage.totalTokens", usageMetrics.totalTokens),
3563
3700
  attrInt("ai.usage.reasoningTokens", usageMetrics.reasoningTokens),
3564
3701
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens),
3565
- ...buildModelUsageAttributes(usageMetrics)
3702
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
3703
+ ...buildRawModelUsageAttributes(usageMetrics)
3566
3704
  );
3567
3705
  }
3568
- this.emitProviderExecutedToolSpans(event, state);
3569
- this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
3570
- state.stepSpan = void 0;
3571
- state.stepParent = void 0;
3572
- state.stepProvider = void 0;
3573
- state.stepModelId = void 0;
3706
+ this.emitProviderExecutedToolSpans(event, state2);
3707
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: outputAttrs });
3708
+ state2.stepSpan = void 0;
3709
+ state2.stepParent = void 0;
3710
+ state2.stepProvider = void 0;
3711
+ state2.stepModelId = void 0;
3574
3712
  };
3575
3713
  // ── onEmbedStart ────────────────────────────────────────────────────────
3576
3714
  this.onEmbedStart = (event) => {
3577
- const state = this.getState(event.callId);
3578
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3579
- const { operationName, resourceName } = opName(event.operationId, state.functionId);
3580
- const inputAttrs = state.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3715
+ const state2 = this.getState(event.callId);
3716
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3717
+ const { operationName, resourceName } = opName(event.operationId, state2.functionId);
3718
+ const inputAttrs = state2.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3581
3719
  const embedSpan = this.traceShipper.startSpan({
3582
3720
  name: event.operationId,
3583
- parent: state.rootParent,
3584
- eventId: state.eventId,
3585
- ...state.identity,
3721
+ parent: state2.rootParent,
3722
+ eventId: state2.eventId,
3723
+ ...state2.identity,
3586
3724
  operationId: event.operationId,
3587
3725
  attributes: [
3588
3726
  attrString("operation.name", operationName),
3589
3727
  attrString("resource.name", resourceName),
3590
- attrString("ai.telemetry.functionId", state.functionId),
3728
+ attrString("ai.telemetry.functionId", state2.functionId),
3591
3729
  ...inputAttrs,
3592
- ...handoffSpanAttrs(state.handoff)
3730
+ ...handoffSpanAttrs(state2.handoff)
3593
3731
  ]
3594
3732
  });
3595
- state.embedSpans.set(event.embedCallId, embedSpan);
3733
+ state2.embedSpans.set(event.embedCallId, embedSpan);
3596
3734
  };
3597
3735
  // ── onEmbedFinish ───────────────────────────────────────────────────────
3598
3736
  this.onEmbedFinish = (event) => {
3599
3737
  var _a;
3600
- const state = this.getState(event.callId);
3601
- if (!state) return;
3602
- const embedSpan = state.embedSpans.get(event.embedCallId);
3738
+ const state2 = this.getState(event.callId);
3739
+ if (!state2) return;
3740
+ const embedSpan = state2.embedSpans.get(event.embedCallId);
3603
3741
  if (!embedSpan) return;
3604
3742
  const outputAttrs = [];
3605
- if (state.recordOutputs) {
3743
+ if (state2.recordOutputs) {
3606
3744
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embeddings)));
3607
3745
  }
3608
3746
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
3609
3747
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
3610
3748
  }
3611
3749
  this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
3612
- state.embedSpans.delete(event.embedCallId);
3750
+ state2.embedSpans.delete(event.embedCallId);
3613
3751
  };
3614
3752
  // v7 canary.159 renamed `onEmbedFinish` -> `onEmbedEnd`. Both names forward
3615
3753
  // to the same implementation; the installed SDK only wires up whichever it
@@ -3617,16 +3755,16 @@ var RaindropTelemetryIntegration = class {
3617
3755
  this.onEmbedEnd = (event) => this.onEmbedFinish(event);
3618
3756
  // ── onFinish ────────────────────────────────────────────────────────────
3619
3757
  this.onFinish = (event) => {
3620
- const state = this.getState(event.callId);
3621
- if (!state) return;
3622
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3758
+ const state2 = this.getState(event.callId);
3759
+ if (!state2) return;
3760
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3623
3761
  if (isEmbed) {
3624
- this.finishEmbed(event, state);
3762
+ this.finishEmbed(event, state2);
3625
3763
  } else {
3626
- this.finishGenerate(event, state);
3764
+ this.finishGenerate(event, state2);
3627
3765
  }
3628
- if (state.subagentToolCallSpan) {
3629
- this.traceShipper.endSpan(state.subagentToolCallSpan);
3766
+ if (state2.subagentToolCallSpan) {
3767
+ this.traceShipper.endSpan(state2.subagentToolCallSpan);
3630
3768
  }
3631
3769
  this.cleanup(event.callId);
3632
3770
  };
@@ -3641,42 +3779,42 @@ var RaindropTelemetryIntegration = class {
3641
3779
  var _a;
3642
3780
  const event = error;
3643
3781
  if (!(event == null ? void 0 : event.callId)) return;
3644
- const state = this.getState(event.callId);
3645
- if (!state) return;
3782
+ const state2 = this.getState(event.callId);
3783
+ if (!state2) return;
3646
3784
  const actualError = (_a = event.error) != null ? _a : error;
3647
- if (state.stepSpan) {
3648
- this.traceShipper.endSpan(state.stepSpan, { error: actualError });
3649
- state.stepProvider = void 0;
3650
- state.stepModelId = void 0;
3785
+ if (state2.stepSpan) {
3786
+ this.traceShipper.endSpan(state2.stepSpan, { error: actualError });
3787
+ state2.stepProvider = void 0;
3788
+ state2.stepModelId = void 0;
3651
3789
  }
3652
- for (const embedSpan of state.embedSpans.values()) {
3790
+ for (const embedSpan of state2.embedSpans.values()) {
3653
3791
  this.traceShipper.endSpan(embedSpan, { error: actualError });
3654
3792
  }
3655
- state.embedSpans.clear();
3656
- for (const toolCallId of state.parentContextToolCallIds) {
3793
+ state2.embedSpans.clear();
3794
+ for (const toolCallId of state2.parentContextToolCallIds) {
3657
3795
  this.priorParentContexts.delete(toolCallId);
3658
3796
  }
3659
- state.parentContextToolCallIds.clear();
3660
- for (const toolSpan of state.toolSpans.values()) {
3797
+ state2.parentContextToolCallIds.clear();
3798
+ for (const toolSpan of state2.toolSpans.values()) {
3661
3799
  this.traceShipper.endSpan(toolSpan, { error: actualError });
3662
3800
  }
3663
- state.toolSpans.clear();
3801
+ state2.toolSpans.clear();
3664
3802
  const abortReason = describeAbortReason(actualError);
3665
- if (state.rootSpan) {
3666
- this.traceShipper.endSpan(state.rootSpan, {
3803
+ if (state2.rootSpan) {
3804
+ this.traceShipper.endSpan(state2.rootSpan, {
3667
3805
  error: actualError,
3668
- attributes: this.abortOutcomeAttrs(state, abortReason, "error")
3806
+ attributes: this.abortOutcomeAttrs(state2, abortReason, "error")
3669
3807
  });
3670
3808
  }
3671
- if (state.subagentToolCallSpan) {
3672
- this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
3809
+ if (state2.subagentToolCallSpan) {
3810
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, { error: actualError });
3673
3811
  }
3674
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3812
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3675
3813
  if (!isEmbed) {
3676
- const errorIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3814
+ const errorIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3677
3815
  this.finalizeGenerateEvent(
3678
- state,
3679
- state.accumulatedText || void 0,
3816
+ state2,
3817
+ state2.accumulatedText || void 0,
3680
3818
  void 0,
3681
3819
  false,
3682
3820
  errorIsTheRunsOutcome ? { fallbackOutput: abortReason } : void 0
@@ -3695,51 +3833,51 @@ var RaindropTelemetryIntegration = class {
3695
3833
  this.onAbort = (event) => {
3696
3834
  const callId = event == null ? void 0 : event.callId;
3697
3835
  if (!callId) return;
3698
- const state = this.getState(callId);
3699
- if (!state) return;
3836
+ const state2 = this.getState(callId);
3837
+ if (!state2) return;
3700
3838
  const abortedAttr = attrString("ai.response.aborted", "true");
3701
- if (state.stepSpan) {
3702
- this.traceShipper.endSpan(state.stepSpan, { attributes: [abortedAttr] });
3703
- state.stepSpan = void 0;
3704
- state.stepParent = void 0;
3705
- state.stepProvider = void 0;
3706
- state.stepModelId = void 0;
3839
+ if (state2.stepSpan) {
3840
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: [abortedAttr] });
3841
+ state2.stepSpan = void 0;
3842
+ state2.stepParent = void 0;
3843
+ state2.stepProvider = void 0;
3844
+ state2.stepModelId = void 0;
3707
3845
  }
3708
- for (const embedSpan of state.embedSpans.values()) {
3846
+ for (const embedSpan of state2.embedSpans.values()) {
3709
3847
  this.traceShipper.endSpan(embedSpan, { attributes: [abortedAttr] });
3710
3848
  }
3711
- state.embedSpans.clear();
3712
- for (const toolCallId of state.parentContextToolCallIds) {
3849
+ state2.embedSpans.clear();
3850
+ for (const toolCallId of state2.parentContextToolCallIds) {
3713
3851
  this.priorParentContexts.delete(toolCallId);
3714
3852
  }
3715
- state.parentContextToolCallIds.clear();
3716
- for (const toolSpan of state.toolSpans.values()) {
3853
+ state2.parentContextToolCallIds.clear();
3854
+ for (const toolSpan of state2.toolSpans.values()) {
3717
3855
  this.traceShipper.endSpan(toolSpan, { attributes: [abortedAttr] });
3718
3856
  }
3719
- state.toolSpans.clear();
3720
- const abortIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3721
- if (state.rootSpan) {
3722
- this.traceShipper.endSpan(state.rootSpan, {
3857
+ state2.toolSpans.clear();
3858
+ const abortIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3859
+ if (state2.rootSpan) {
3860
+ this.traceShipper.endSpan(state2.rootSpan, {
3723
3861
  attributes: [
3724
3862
  abortedAttr,
3725
- attrInt("ai.toolCall.count", state.toolCallCount),
3863
+ attrInt("ai.toolCall.count", state2.toolCallCount),
3726
3864
  // An aborted detached child IS a cancelled sub-agent, and a cancelled
3727
3865
  // run is span-for-span identical to a finished one — spans close,
3728
3866
  // nothing errors, there is just no answer. So it is the one outcome
3729
3867
  // that has to be stated, and the child states it on itself.
3730
3868
  ...abortIsTheRunsOutcome ? cancelledSpanAttrs() : [],
3731
- ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3869
+ ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state2, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3732
3870
  ]
3733
3871
  });
3734
3872
  }
3735
- if (state.subagentToolCallSpan) {
3736
- this.traceShipper.endSpan(state.subagentToolCallSpan, {
3873
+ if (state2.subagentToolCallSpan) {
3874
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, {
3737
3875
  attributes: [abortedAttr]
3738
3876
  });
3739
3877
  }
3740
3878
  this.finalizeGenerateEvent(
3741
- state,
3742
- state.accumulatedText || void 0,
3879
+ state2,
3880
+ state2.accumulatedText || void 0,
3743
3881
  void 0,
3744
3882
  false,
3745
3883
  abortIsTheRunsOutcome ? {
@@ -3747,7 +3885,7 @@ var RaindropTelemetryIntegration = class {
3747
3885
  properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
3748
3886
  } : void 0
3749
3887
  );
3750
- if (abortIsTheRunsOutcome) this.subagents.noteSettled(state.eventId);
3888
+ if (abortIsTheRunsOutcome) this.subagents.noteSettled(state2.eventId);
3751
3889
  this.cleanup(callId);
3752
3890
  };
3753
3891
  // ── executeTool ─────────────────────────────────────────────────────────
@@ -3756,14 +3894,14 @@ var RaindropTelemetryIntegration = class {
3756
3894
  toolCallId,
3757
3895
  execute
3758
3896
  }) => {
3759
- const state = this.getState(callId);
3760
- const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
3897
+ const state2 = this.getState(callId);
3898
+ const toolSpan = state2 == null ? void 0 : state2.toolSpans.get(toolCallId);
3761
3899
  if (!toolSpan) return execute();
3762
3900
  return runWithParentSpanContext(
3763
3901
  {
3764
3902
  traceIdB64: toolSpan.ids.traceIdB64,
3765
3903
  spanIdB64: toolSpan.ids.spanIdB64,
3766
- eventId: state.eventId
3904
+ eventId: state2.eventId
3767
3905
  },
3768
3906
  () => execute()
3769
3907
  );
@@ -3812,35 +3950,35 @@ var RaindropTelemetryIntegration = class {
3812
3950
  activeDispatch() {
3813
3951
  var _a;
3814
3952
  const parentTool = getCurrentParentToolContext();
3815
- let state = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3953
+ let state2 = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3816
3954
  const inheritedEventId = (_a = getContextManager().getParentSpanIds()) == null ? void 0 : _a.eventId;
3817
- if (!state && inheritedEventId) {
3955
+ if (!state2 && inheritedEventId) {
3818
3956
  for (const candidate of this.callStates.values()) {
3819
3957
  if (candidate.eventId === inheritedEventId) {
3820
- state = candidate;
3958
+ state2 = candidate;
3821
3959
  break;
3822
3960
  }
3823
3961
  }
3824
3962
  }
3825
- if (!state) return void 0;
3963
+ if (!state2) return void 0;
3826
3964
  return {
3827
- eventId: state.eventId,
3828
- userId: state.identity.userId,
3829
- convoId: state.identity.convoId,
3830
- dispatchSpan: parentTool ? state.toolSpans.get(parentTool.toolCallId) : void 0,
3831
- turnSpans: [state.rootSpan, state.stepSpan].filter(
3965
+ eventId: state2.eventId,
3966
+ userId: state2.identity.userId,
3967
+ convoId: state2.identity.convoId,
3968
+ dispatchSpan: parentTool ? state2.toolSpans.get(parentTool.toolCallId) : void 0,
3969
+ turnSpans: [state2.rootSpan, state2.stepSpan].filter(
3832
3970
  (span) => span !== void 0
3833
3971
  ),
3834
- recordInputs: state.recordInputs
3972
+ recordInputs: state2.recordInputs
3835
3973
  };
3836
3974
  }
3837
3975
  /** Spans still open for an event, so a late outcome can still be stated. */
3838
3976
  openSpansForEvent(eventId) {
3839
3977
  const spans = [];
3840
- for (const state of this.callStates.values()) {
3841
- if (state.eventId !== eventId) continue;
3842
- if (state.rootSpan) spans.push(state.rootSpan);
3843
- if (state.stepSpan) spans.push(state.stepSpan);
3978
+ for (const state2 of this.callStates.values()) {
3979
+ if (state2.eventId !== eventId) continue;
3980
+ if (state2.rootSpan) spans.push(state2.rootSpan);
3981
+ if (state2.stepSpan) spans.push(state2.stepSpan);
3844
3982
  }
3845
3983
  return spans;
3846
3984
  }
@@ -3860,10 +3998,10 @@ var RaindropTelemetryIntegration = class {
3860
3998
  * created from an LLM span with output, `ai.response.text` here would state
3861
3999
  * the run's outcome through the span while the turn is still working.
3862
4000
  */
3863
- abortOutcomeAttrs(state, reason, finishReason) {
3864
- if (!state.handoff || state.nestedInEvent) return [];
4001
+ abortOutcomeAttrs(state2, reason, finishReason) {
4002
+ if (!state2.handoff || state2.nestedInEvent) return [];
3865
4003
  return [
3866
- attrString("ai.response.text", capText2(state.accumulatedText || reason)),
4004
+ attrString("ai.response.text", capText2(state2.accumulatedText || reason)),
3867
4005
  attrString("ai.response.finishReason", finishReason)
3868
4006
  ];
3869
4007
  }
@@ -3877,19 +4015,19 @@ var RaindropTelemetryIntegration = class {
3877
4015
  spanParentRef(span) {
3878
4016
  return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
3879
4017
  }
3880
- emitLive(state, type, content, extra) {
4018
+ emitLive(state2, type, content, extra) {
3881
4019
  var _a, _b, _c, _d, _e, _f;
3882
- if (!localDebuggerEnabled() || !state.rootSpan) return;
3883
- const callMeta = this.extractRaindropMetadata(state.metadata);
4020
+ if (!localDebuggerEnabled() || !state2.rootSpan) return;
4021
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
3884
4022
  sendLocalDebuggerLiveEvent({
3885
- traceId: state.rootSpan.ids.traceIdB64,
4023
+ traceId: state2.rootSpan.ids.traceIdB64,
3886
4024
  type,
3887
4025
  content,
3888
4026
  metadata: {
3889
4027
  userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
3890
4028
  convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
3891
4029
  eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
3892
- eventId: state.eventId,
4030
+ eventId: state2.eventId,
3893
4031
  ...extra
3894
4032
  }
3895
4033
  });
@@ -3967,29 +4105,29 @@ var RaindropTelemetryIntegration = class {
3967
4105
  toolCallId: toolCall.toolCallId,
3968
4106
  toolName: toolCall.toolName
3969
4107
  });
3970
- const state = this.getState(event.callId);
3971
- state == null ? void 0 : state.parentContextToolCallIds.add(toolCall.toolCallId);
3972
- if (!(state == null ? void 0 : state.stepParent)) return;
3973
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
3974
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
4108
+ const state2 = this.getState(event.callId);
4109
+ state2 == null ? void 0 : state2.parentContextToolCallIds.add(toolCall.toolCallId);
4110
+ if (!(state2 == null ? void 0 : state2.stepParent)) return;
4111
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4112
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
3975
4113
  const toolSpan = this.traceShipper.startSpan({
3976
4114
  name: "ai.toolCall",
3977
- parent: state.stepParent,
3978
- eventId: state.eventId,
3979
- ...state.identity,
4115
+ parent: state2.stepParent,
4116
+ eventId: state2.eventId,
4117
+ ...state2.identity,
3980
4118
  operationId: "ai.toolCall",
3981
4119
  attributes: [
3982
4120
  attrString("operation.name", operationName),
3983
4121
  attrString("resource.name", resourceName),
3984
- attrString("ai.telemetry.functionId", state.functionId),
4122
+ attrString("ai.telemetry.functionId", state2.functionId),
3985
4123
  attrString("ai.toolCall.name", toolCall.toolName),
3986
4124
  attrString("ai.toolCall.id", toolCall.toolCallId),
3987
4125
  ...inputAttrs,
3988
- ...handoffSpanAttrs(state.handoff)
4126
+ ...handoffSpanAttrs(state2.handoff)
3989
4127
  ]
3990
4128
  });
3991
- state.toolSpans.set(toolCall.toolCallId, toolSpan);
3992
- this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
4129
+ state2.toolSpans.set(toolCall.toolCallId, toolSpan);
4130
+ this.emitLive(state2, "tool_start", toolCall.toolName, { args: toolCall.input });
3993
4131
  }
3994
4132
  toolExecutionEnd(event) {
3995
4133
  var _a;
@@ -4003,20 +4141,20 @@ var RaindropTelemetryIntegration = class {
4003
4141
  clearParentToolContext();
4004
4142
  }
4005
4143
  }
4006
- const state = this.getState(event.callId);
4007
- if (!state) return;
4008
- const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
4144
+ const state2 = this.getState(event.callId);
4145
+ if (!state2) return;
4146
+ const toolSpan = state2.toolSpans.get(event.toolCall.toolCallId);
4009
4147
  if (!toolSpan) return;
4010
- state.toolCallCount += 1;
4148
+ state2.toolCallCount += 1;
4011
4149
  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 };
4012
4150
  if (outcome.success) {
4013
- const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4151
+ const outputAttrs = state2.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4014
4152
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4015
4153
  } else {
4016
4154
  this.traceShipper.endSpan(toolSpan, { error: outcome.error });
4017
4155
  }
4018
- this.emitLive(state, "tool_result", event.toolCall.toolName);
4019
- state.toolSpans.delete(event.toolCall.toolCallId);
4156
+ this.emitLive(state2, "tool_result", event.toolCall.toolName);
4157
+ state2.toolSpans.delete(event.toolCall.toolCallId);
4020
4158
  }
4021
4159
  // ── provider-executed tool calls ─────────────────────────────────────────
4022
4160
  //
@@ -4035,8 +4173,8 @@ var RaindropTelemetryIntegration = class {
4035
4173
  //
4036
4174
  // Client-executed tools are excluded (`providerExecuted` falsy) — they were
4037
4175
  // already spanned during execution, so this never double-emits.
4038
- emitProviderExecutedToolSpans(event, state) {
4039
- if (!state.stepParent) return;
4176
+ emitProviderExecutedToolSpans(event, state2) {
4177
+ if (!state2.stepParent) return;
4040
4178
  const content = Array.isArray(event.content) ? event.content : [];
4041
4179
  const providerToolCalls = content.filter(
4042
4180
  (part) => (part == null ? void 0 : part.type) === "tool-call" && part.providerExecuted === true
@@ -4049,42 +4187,42 @@ var RaindropTelemetryIntegration = class {
4049
4187
  }
4050
4188
  }
4051
4189
  for (const call of providerToolCalls) {
4052
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
4053
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4190
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4191
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4054
4192
  const toolSpan = this.traceShipper.startSpan({
4055
4193
  name: "ai.toolCall",
4056
- parent: state.stepParent,
4057
- eventId: state.eventId,
4058
- ...state.identity,
4194
+ parent: state2.stepParent,
4195
+ eventId: state2.eventId,
4196
+ ...state2.identity,
4059
4197
  operationId: "ai.toolCall",
4060
4198
  attributes: [
4061
4199
  attrString("operation.name", operationName),
4062
4200
  attrString("resource.name", resourceName),
4063
- attrString("ai.telemetry.functionId", state.functionId),
4201
+ attrString("ai.telemetry.functionId", state2.functionId),
4064
4202
  attrString("ai.toolCall.name", call.toolName),
4065
4203
  attrString("ai.toolCall.id", call.toolCallId),
4066
4204
  attrString("ai.toolCall.providerExecuted", "true"),
4067
4205
  ...inputAttrs,
4068
- ...handoffSpanAttrs(state.handoff)
4206
+ ...handoffSpanAttrs(state2.handoff)
4069
4207
  ]
4070
4208
  });
4071
- state.toolCallCount += 1;
4072
- this.emitLive(state, "tool_start", call.toolName, { args: call.input });
4209
+ state2.toolCallCount += 1;
4210
+ this.emitLive(state2, "tool_start", call.toolName, { args: call.input });
4073
4211
  const resultPart = resultsByCallId.get(call.toolCallId);
4074
4212
  if ((resultPart == null ? void 0 : resultPart.type) === "tool-error") {
4075
4213
  this.traceShipper.endSpan(toolSpan, { error: resultPart.error });
4076
4214
  } else {
4077
- const outputAttrs = state.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4215
+ const outputAttrs = state2.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4078
4216
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4079
4217
  }
4080
- this.emitLive(state, "tool_result", call.toolName);
4218
+ this.emitLive(state2, "tool_result", call.toolName);
4081
4219
  }
4082
4220
  }
4083
- finishGenerate(event, state) {
4221
+ finishGenerate(event, state2) {
4084
4222
  var _a, _b, _c, _d, _e, _f;
4085
- if (state.rootSpan) {
4223
+ if (state2.rootSpan) {
4086
4224
  const outputAttrs = [];
4087
- if (state.recordOutputs) {
4225
+ if (state2.recordOutputs) {
4088
4226
  outputAttrs.push(
4089
4227
  attrString("ai.response.finishReason", event.finishReason),
4090
4228
  attrString("ai.response.text", capText2((_a = event.text) != null ? _a : void 0)),
@@ -4125,12 +4263,12 @@ var RaindropTelemetryIntegration = class {
4125
4263
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens)
4126
4264
  );
4127
4265
  }
4128
- outputAttrs.push(attrInt("ai.toolCall.count", state.toolCallCount));
4129
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4266
+ outputAttrs.push(attrInt("ai.toolCall.count", state2.toolCallCount));
4267
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4130
4268
  }
4131
4269
  this.finalizeGenerateEvent(
4132
- state,
4133
- (_e = event.text) != null ? _e : state.accumulatedText || void 0,
4270
+ state2,
4271
+ (_e = event.text) != null ? _e : state2.accumulatedText || void 0,
4134
4272
  (_f = event.response) == null ? void 0 : _f.modelId,
4135
4273
  hasUnresolvedToolApproval(event)
4136
4274
  );
@@ -4146,29 +4284,29 @@ var RaindropTelemetryIntegration = class {
4146
4284
  * is finalized by that resume — otherwise each execution would finalize the
4147
4285
  * same event ID into a separate canonical row.
4148
4286
  */
4149
- finalizeGenerateEvent(state, output, model, keepPending = false, detachedOutcome) {
4287
+ finalizeGenerateEvent(state2, output, model, keepPending = false, detachedOutcome) {
4150
4288
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
4151
- const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
4289
+ const suppressSubagentEvent = state2.subagentName !== void 0 && state2.subagentToolCallSpan !== void 0;
4152
4290
  if (!this.sendEvents || suppressSubagentEvent) return;
4153
- if (this.subagents.wasSettledExplicitly(state.eventId)) return;
4154
- const callMeta = this.extractRaindropMetadata(state.metadata);
4291
+ if (this.subagents.wasSettledExplicitly(state2.eventId)) return;
4292
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
4155
4293
  const userId = (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId;
4156
4294
  if (!userId) return;
4157
- const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state.operationId;
4295
+ const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state2.operationId;
4158
4296
  const cappedOutput = capText2(output);
4159
- const reportedOutput = state.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4160
- const input = capText2(state.inputText);
4297
+ const reportedOutput = state2.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4298
+ const input = capText2(state2.inputText);
4161
4299
  const properties = {
4162
4300
  ...(_f = this.defaultContext) == null ? void 0 : _f.properties,
4163
4301
  ...callMeta.properties,
4164
- ...state.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4302
+ ...state2.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4165
4303
  };
4166
4304
  const featureFlags = {
4167
4305
  ...((_g = this.defaultContext) == null ? void 0 : _g.featureFlags) ? normalizeFeatureFlags(this.defaultContext.featureFlags) : {},
4168
4306
  ...callMeta.featureFlags
4169
4307
  };
4170
4308
  const convoId = (_i = callMeta.convoId) != null ? _i : (_h = this.defaultContext) == null ? void 0 : _h.convoId;
4171
- void this.eventShipper.patch(state.eventId, {
4309
+ void this.eventShipper.patch(state2.eventId, {
4172
4310
  eventName,
4173
4311
  userId,
4174
4312
  convoId,
@@ -4186,12 +4324,12 @@ var RaindropTelemetryIntegration = class {
4186
4324
  }
4187
4325
  });
4188
4326
  }
4189
- finishEmbed(event, state) {
4327
+ finishEmbed(event, state2) {
4190
4328
  var _a;
4191
- if (!state.rootSpan) return;
4329
+ if (!state2.rootSpan) return;
4192
4330
  const outputAttrs = [];
4193
- const isMany = state.operationId === "ai.embedMany";
4194
- if (state.recordOutputs) {
4331
+ const isMany = state2.operationId === "ai.embedMany";
4332
+ if (state2.recordOutputs) {
4195
4333
  if (isMany) {
4196
4334
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embedding)));
4197
4335
  } else {
@@ -4201,7 +4339,7 @@ var RaindropTelemetryIntegration = class {
4201
4339
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
4202
4340
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
4203
4341
  }
4204
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4342
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4205
4343
  }
4206
4344
  };
4207
4345
 
@@ -4497,9 +4635,7 @@ function extractRaindropMetadata(metadata) {
4497
4635
  } catch (e) {
4498
4636
  }
4499
4637
  } else if (featureFlags && typeof featureFlags === "object") {
4500
- result.featureFlags = normalizeFeatureFlags(
4501
- featureFlags
4502
- );
4638
+ result.featureFlags = normalizeFeatureFlags(featureFlags);
4503
4639
  }
4504
4640
  return result;
4505
4641
  }
@@ -4710,12 +4846,7 @@ function setupOperation(params) {
4710
4846
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
4711
4847
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
4712
4848
  ...attrsFromSettings(arg),
4713
- ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
4714
- attrString(
4715
- "ai.prompt",
4716
- safeJsonWithUint8(normalizePromptAttr(arg))
4717
- )
4718
- ]
4849
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [attrString("ai.prompt", safeJsonWithUint8(normalizePromptAttr(arg)))]
4719
4850
  ]
4720
4851
  }) : void 0;
4721
4852
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
@@ -5065,7 +5196,10 @@ function wrapAISDK(aiSDK, deps) {
5065
5196
  }
5066
5197
  const useNative = deps.options.nativeTelemetry === true;
5067
5198
  if (useNative) {
5068
- const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
5199
+ const wrapTimeCtx = resolveContext(deps.options.context, {
5200
+ operation: "wrap",
5201
+ args: void 0
5202
+ });
5069
5203
  const integration = new RaindropTelemetryIntegration({
5070
5204
  traceShipper: deps.traceShipper,
5071
5205
  eventShipper: deps.eventShipper,
@@ -5310,7 +5444,13 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
5310
5444
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
5311
5445
  attrString(
5312
5446
  "ai.prompt",
5313
- safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
5447
+ safeJsonWithUint8(
5448
+ normalizePromptAttr({
5449
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
5450
+ prompt: mergedArgs["prompt"],
5451
+ messages: mergedArgs["messages"]
5452
+ })
5453
+ )
5314
5454
  )
5315
5455
  ]
5316
5456
  ]
@@ -5524,7 +5664,13 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
5524
5664
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
5525
5665
  attrString(
5526
5666
  "ai.prompt",
5527
- safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
5667
+ safeJsonWithUint8(
5668
+ normalizePromptAttr({
5669
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
5670
+ prompt: mergedArgs["prompt"],
5671
+ messages: mergedArgs["messages"]
5672
+ })
5673
+ )
5528
5674
  )
5529
5675
  ]
5530
5676
  ]
@@ -5901,9 +6047,19 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
5901
6047
  for (const part of content) {
5902
6048
  if (isRecord(part)) {
5903
6049
  if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
5904
- sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
6050
+ sendLocalDebuggerLiveEvent({
6051
+ traceId,
6052
+ type: "reasoning_delta",
6053
+ content: (_b = part["text"]) != null ? _b : part["thinking"],
6054
+ metadata: liveMeta
6055
+ });
5905
6056
  } else if (part["type"] === "text" && typeof part["text"] === "string") {
5906
- sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
6057
+ sendLocalDebuggerLiveEvent({
6058
+ traceId,
6059
+ type: "text_delta",
6060
+ content: part["text"],
6061
+ metadata: liveMeta
6062
+ });
5907
6063
  }
5908
6064
  }
5909
6065
  }
@@ -5984,7 +6140,10 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
5984
6140
  attributes: [
5985
6141
  ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
5986
6142
  attrString("ai.response.finishReason", finishReason),
5987
- attrString("ai.response.text", activeText.length ? capText2(activeText) : void 0),
6143
+ attrString(
6144
+ "ai.response.text",
6145
+ activeText.length ? capText2(activeText) : void 0
6146
+ ),
5988
6147
  attrString(
5989
6148
  "ai.response.toolCalls",
5990
6149
  safeJsonWithUint8(toolCallsLocal.length ? toolCallsLocal : void 0)
@@ -6002,7 +6161,8 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6002
6161
  ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
6003
6162
  attrString("gen_ai.response.id", responseId),
6004
6163
  attrString(MODEL_USAGE_ATTRIBUTES.responseModel, finalResponseModelId),
6005
- ...buildModelUsageAttributes(usageMetrics),
6164
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
6165
+ ...buildRawModelUsageAttributes(usageMetrics),
6006
6166
  ...msToFirstChunk !== void 0 ? [attrInt("ai.stream.msToFirstChunk", msToFirstChunk)] : [],
6007
6167
  ...msToFinish !== void 0 ? [attrInt("ai.stream.msToFinish", msToFinish)] : [],
6008
6168
  ...avgOutTokensPerSecond !== void 0 ? [attrDouble("ai.stream.avgOutputTokensPerSecond", avgOutTokensPerSecond)] : [],
@@ -6056,19 +6216,44 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6056
6216
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
6057
6217
  if (localDebuggerEnabled() && ctx.rootParentForChildren) {
6058
6218
  const traceId = ctx.rootParentForChildren.traceIdB64;
6059
- const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
6219
+ const liveMeta = getLocalDebuggerMetadata({
6220
+ ...ctx.context,
6221
+ eventId: ctx.eventId
6222
+ });
6060
6223
  if (type === "text-delta") {
6061
6224
  const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
6062
- if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
6225
+ if (typeof text === "string" && text)
6226
+ sendLocalDebuggerLiveEvent({
6227
+ traceId,
6228
+ type: "text_delta",
6229
+ content: text,
6230
+ metadata: liveMeta
6231
+ });
6063
6232
  } else if (type === "reasoning" || type === "reasoning-delta") {
6064
6233
  const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
6065
- if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
6234
+ if (typeof text === "string" && text)
6235
+ sendLocalDebuggerLiveEvent({
6236
+ traceId,
6237
+ type: "reasoning_delta",
6238
+ content: text,
6239
+ metadata: liveMeta
6240
+ });
6066
6241
  } else if (type === "tool-call") {
6067
6242
  const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
6068
- sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
6243
+ sendLocalDebuggerLiveEvent({
6244
+ traceId,
6245
+ type: "tool_start",
6246
+ content: toolName,
6247
+ metadata: { ...liveMeta, args: value["args"] }
6248
+ });
6069
6249
  } else if (type === "tool-result") {
6070
6250
  const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
6071
- sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
6251
+ sendLocalDebuggerLiveEvent({
6252
+ traceId,
6253
+ type: "tool_result",
6254
+ content: toolName,
6255
+ metadata: { ...liveMeta, result: value["result"] }
6256
+ });
6072
6257
  }
6073
6258
  }
6074
6259
  }
@@ -6148,11 +6333,7 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
6148
6333
  } else {
6149
6334
  responseTimestampIso = (/* @__PURE__ */ new Date()).toISOString();
6150
6335
  }
6151
- const usageMetrics = extractUsageMetricsFromUsage(
6152
- usage,
6153
- modelInfo.provider,
6154
- providerMetadata
6155
- );
6336
+ const usageMetrics = extractUsageMetricsFromUsage(usage, modelInfo.provider, providerMetadata);
6156
6337
  const { inputTokens, outputTokens } = usageMetrics;
6157
6338
  ctx.traceShipper.endSpan(span, {
6158
6339
  attributes: [
@@ -6173,7 +6354,8 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
6173
6354
  ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
6174
6355
  attrString("gen_ai.response.id", responseId),
6175
6356
  attrString(MODEL_USAGE_ATTRIBUTES.responseModel, responseModelId),
6176
- ...buildModelUsageAttributes(usageMetrics)
6357
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
6358
+ ...buildRawModelUsageAttributes(usageMetrics)
6177
6359
  ]
6178
6360
  });
6179
6361
  }
@@ -6270,7 +6452,7 @@ function mergeAttachments(...groups) {
6270
6452
  // package.json
6271
6453
  var package_default = {
6272
6454
  name: "@raindrop-ai/ai-sdk",
6273
- version: "0.3.0"};
6455
+ version: "0.3.2"};
6274
6456
 
6275
6457
  // src/internal/version.ts
6276
6458
  var libraryName = package_default.name;