@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
  'use strict';
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();
@@ -1855,7 +2015,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
1855
2015
  // package.json
1856
2016
  var package_default = {
1857
2017
  name: "@raindrop-ai/ai-sdk",
1858
- version: "0.3.0"};
2018
+ version: "0.3.2"};
1859
2019
 
1860
2020
  // src/internal/version.ts
1861
2021
  var libraryName = package_default.name;
@@ -3099,29 +3259,6 @@ function firstTokenCount(...values) {
3099
3259
  }
3100
3260
  return void 0;
3101
3261
  }
3102
- function flatUsageSemantics(provider) {
3103
- const normalizedProvider = typeof provider === "string" ? provider.trim().toLowerCase() : void 0;
3104
- if (normalizedProvider === "anthropic" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("anthropic.")) || normalizedProvider === "vertex.anthropic" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("vertex.anthropic."))) {
3105
- return {
3106
- inputTokenSemantics: "exclusive",
3107
- outputTokenSemantics: "total"
3108
- };
3109
- }
3110
- if (normalizedProvider === "openai" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("openai.")) || normalizedProvider === "azure" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("azure."))) {
3111
- return {
3112
- inputTokenSemantics: "total",
3113
- outputTokenSemantics: "total"
3114
- };
3115
- }
3116
- if (normalizedProvider === "google" || (normalizedProvider == null ? void 0 : normalizedProvider.startsWith("google."))) {
3117
- return {
3118
- inputTokenSemantics: "total",
3119
- // Google v5 reports candidate output and thoughts separately.
3120
- outputTokenSemantics: "exclusive"
3121
- };
3122
- }
3123
- return {};
3124
- }
3125
3262
  var CACHE_WRITE_METADATA_KEYS = [
3126
3263
  ["anthropic", "cacheCreationInputTokens"],
3127
3264
  ["openai", "cacheWriteTokens"],
@@ -3138,7 +3275,7 @@ function cacheWriteTokensFromProviderMetadata(providerMetadata) {
3138
3275
  })
3139
3276
  );
3140
3277
  }
3141
- function extractUsageMetricsFromUsage(usage, provider, providerMetadata) {
3278
+ function extractUsageMetricsFromUsage(usage, _provider, providerMetadata) {
3142
3279
  if (!isRecord(usage)) return {};
3143
3280
  const inputTokenValue = usage["inputTokens"];
3144
3281
  const outputTokenValue = usage["outputTokens"];
@@ -3206,7 +3343,7 @@ function extractUsageMetricsFromUsage(usage, provider, providerMetadata) {
3206
3343
  cacheReadInputTokens,
3207
3344
  cachedInputTokens: cacheReadInputTokens,
3208
3345
  cacheWriteInputTokens,
3209
- ...hasStructuredUsage ? {} : flatUsageSemantics(provider)
3346
+ ...hasStructuredUsage ? { usageSource: "ai-sdk-structured" } : {}
3210
3347
  };
3211
3348
  }
3212
3349
 
@@ -3404,13 +3541,13 @@ var RaindropTelemetryIntegration = class {
3404
3541
  };
3405
3542
  // ── onStepStart ─────────────────────────────────────────────────────────
3406
3543
  this.onStepStart = (event) => {
3407
- const state = this.getState(event.callId);
3408
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3409
- const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
3410
- const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
3411
- const { operationName, resourceName } = opName(stepOperationId, state.functionId);
3544
+ const state2 = this.getState(event.callId);
3545
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3546
+ const isStream = state2.operationId === "ai.streamText" || state2.operationId === "ai.streamObject";
3547
+ const stepOperationId = isStream ? `${state2.operationId}.doStream` : `${state2.operationId}.doGenerate`;
3548
+ const { operationName, resourceName } = opName(stepOperationId, state2.functionId);
3412
3549
  const inputAttrs = [];
3413
- if (state.recordInputs) {
3550
+ if (state2.recordInputs) {
3414
3551
  if (event.promptMessages) {
3415
3552
  inputAttrs.push(attrString("ai.prompt.messages", safeJsonWithUint8(event.promptMessages)));
3416
3553
  }
@@ -3433,25 +3570,25 @@ var RaindropTelemetryIntegration = class {
3433
3570
  }
3434
3571
  const stepSpan = this.traceShipper.startSpan({
3435
3572
  name: stepOperationId,
3436
- parent: state.rootParent,
3437
- eventId: state.eventId,
3438
- ...state.identity,
3573
+ parent: state2.rootParent,
3574
+ eventId: state2.eventId,
3575
+ ...state2.identity,
3439
3576
  operationId: stepOperationId,
3440
3577
  attributes: [
3441
3578
  attrString("operation.name", operationName),
3442
3579
  attrString("resource.name", resourceName),
3443
- attrString("ai.telemetry.functionId", state.functionId),
3580
+ attrString("ai.telemetry.functionId", state2.functionId),
3444
3581
  ...attrsFromModelProvider(event.provider),
3445
3582
  attrString("ai.model.id", event.modelId),
3446
3583
  attrString(MODEL_USAGE_ATTRIBUTES.requestModel, event.modelId),
3447
3584
  ...inputAttrs,
3448
- ...handoffSpanAttrs(state.handoff)
3585
+ ...handoffSpanAttrs(state2.handoff)
3449
3586
  ]
3450
3587
  });
3451
- state.stepSpan = stepSpan;
3452
- state.stepParent = this.spanParentRef(stepSpan);
3453
- state.stepProvider = event.provider;
3454
- state.stepModelId = event.modelId;
3588
+ state2.stepSpan = stepSpan;
3589
+ state2.stepParent = this.spanParentRef(stepSpan);
3590
+ state2.stepProvider = event.provider;
3591
+ state2.stepModelId = event.modelId;
3455
3592
  };
3456
3593
  this.onToolExecutionStart = (event) => this.toolExecutionStart(event);
3457
3594
  this.onToolExecutionEnd = (event) => this.toolExecutionEnd(event);
@@ -3478,33 +3615,33 @@ var RaindropTelemetryIntegration = class {
3478
3615
  var _a, _b, _c, _d, _e;
3479
3616
  const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
3480
3617
  if (!callId) return;
3481
- const state = this.getState(callId);
3482
- if (!state) return;
3618
+ const state2 = this.getState(callId);
3619
+ if (!state2) return;
3483
3620
  const chunk = event.chunk;
3484
3621
  if (!chunk || typeof chunk !== "object") return;
3485
3622
  if (chunk.type === "text-delta") {
3486
3623
  const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
3487
3624
  if (typeof delta === "string") {
3488
- if (state.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3489
- state.accumulatedText += delta;
3625
+ if (state2.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3626
+ state2.accumulatedText += delta;
3490
3627
  }
3491
- this.emitLive(state, "text_delta", delta);
3628
+ this.emitLive(state2, "text_delta", delta);
3492
3629
  }
3493
3630
  } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
3494
3631
  const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
3495
3632
  if (typeof text === "string") {
3496
- this.emitLive(state, "reasoning_delta", text);
3633
+ this.emitLive(state2, "reasoning_delta", text);
3497
3634
  }
3498
3635
  }
3499
3636
  };
3500
3637
  // ── onStepFinish ────────────────────────────────────────────────────────
3501
3638
  this.onStepFinish = (event) => {
3502
3639
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3503
- const state = this.getState(event.callId);
3504
- if (!(state == null ? void 0 : state.stepSpan)) return;
3505
- const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state.stepModelId;
3640
+ const state2 = this.getState(event.callId);
3641
+ if (!(state2 == null ? void 0 : state2.stepSpan)) return;
3642
+ const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state2.stepModelId;
3506
3643
  const outputAttrs = [];
3507
- if (state.recordOutputs) {
3644
+ if (state2.recordOutputs) {
3508
3645
  outputAttrs.push(
3509
3646
  attrString("ai.response.finishReason", event.finishReason),
3510
3647
  attrString("ai.response.text", capText2((_c = event.text) != null ? _c : void 0)),
@@ -3549,7 +3686,7 @@ var RaindropTelemetryIntegration = class {
3549
3686
  if (usage) {
3550
3687
  const usageMetrics = extractUsageMetricsFromUsage(
3551
3688
  usage,
3552
- state.stepProvider,
3689
+ state2.stepProvider,
3553
3690
  event.providerMetadata
3554
3691
  );
3555
3692
  outputAttrs.push(
@@ -3558,54 +3695,55 @@ var RaindropTelemetryIntegration = class {
3558
3695
  attrInt("ai.usage.totalTokens", usageMetrics.totalTokens),
3559
3696
  attrInt("ai.usage.reasoningTokens", usageMetrics.reasoningTokens),
3560
3697
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens),
3561
- ...buildModelUsageAttributes(usageMetrics)
3698
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
3699
+ ...buildRawModelUsageAttributes(usageMetrics)
3562
3700
  );
3563
3701
  }
3564
- this.emitProviderExecutedToolSpans(event, state);
3565
- this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
3566
- state.stepSpan = void 0;
3567
- state.stepParent = void 0;
3568
- state.stepProvider = void 0;
3569
- state.stepModelId = void 0;
3702
+ this.emitProviderExecutedToolSpans(event, state2);
3703
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: outputAttrs });
3704
+ state2.stepSpan = void 0;
3705
+ state2.stepParent = void 0;
3706
+ state2.stepProvider = void 0;
3707
+ state2.stepModelId = void 0;
3570
3708
  };
3571
3709
  // ── onEmbedStart ────────────────────────────────────────────────────────
3572
3710
  this.onEmbedStart = (event) => {
3573
- const state = this.getState(event.callId);
3574
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3575
- const { operationName, resourceName } = opName(event.operationId, state.functionId);
3576
- const inputAttrs = state.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3711
+ const state2 = this.getState(event.callId);
3712
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3713
+ const { operationName, resourceName } = opName(event.operationId, state2.functionId);
3714
+ const inputAttrs = state2.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3577
3715
  const embedSpan = this.traceShipper.startSpan({
3578
3716
  name: event.operationId,
3579
- parent: state.rootParent,
3580
- eventId: state.eventId,
3581
- ...state.identity,
3717
+ parent: state2.rootParent,
3718
+ eventId: state2.eventId,
3719
+ ...state2.identity,
3582
3720
  operationId: event.operationId,
3583
3721
  attributes: [
3584
3722
  attrString("operation.name", operationName),
3585
3723
  attrString("resource.name", resourceName),
3586
- attrString("ai.telemetry.functionId", state.functionId),
3724
+ attrString("ai.telemetry.functionId", state2.functionId),
3587
3725
  ...inputAttrs,
3588
- ...handoffSpanAttrs(state.handoff)
3726
+ ...handoffSpanAttrs(state2.handoff)
3589
3727
  ]
3590
3728
  });
3591
- state.embedSpans.set(event.embedCallId, embedSpan);
3729
+ state2.embedSpans.set(event.embedCallId, embedSpan);
3592
3730
  };
3593
3731
  // ── onEmbedFinish ───────────────────────────────────────────────────────
3594
3732
  this.onEmbedFinish = (event) => {
3595
3733
  var _a;
3596
- const state = this.getState(event.callId);
3597
- if (!state) return;
3598
- const embedSpan = state.embedSpans.get(event.embedCallId);
3734
+ const state2 = this.getState(event.callId);
3735
+ if (!state2) return;
3736
+ const embedSpan = state2.embedSpans.get(event.embedCallId);
3599
3737
  if (!embedSpan) return;
3600
3738
  const outputAttrs = [];
3601
- if (state.recordOutputs) {
3739
+ if (state2.recordOutputs) {
3602
3740
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embeddings)));
3603
3741
  }
3604
3742
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
3605
3743
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
3606
3744
  }
3607
3745
  this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
3608
- state.embedSpans.delete(event.embedCallId);
3746
+ state2.embedSpans.delete(event.embedCallId);
3609
3747
  };
3610
3748
  // v7 canary.159 renamed `onEmbedFinish` -> `onEmbedEnd`. Both names forward
3611
3749
  // to the same implementation; the installed SDK only wires up whichever it
@@ -3613,16 +3751,16 @@ var RaindropTelemetryIntegration = class {
3613
3751
  this.onEmbedEnd = (event) => this.onEmbedFinish(event);
3614
3752
  // ── onFinish ────────────────────────────────────────────────────────────
3615
3753
  this.onFinish = (event) => {
3616
- const state = this.getState(event.callId);
3617
- if (!state) return;
3618
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3754
+ const state2 = this.getState(event.callId);
3755
+ if (!state2) return;
3756
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3619
3757
  if (isEmbed) {
3620
- this.finishEmbed(event, state);
3758
+ this.finishEmbed(event, state2);
3621
3759
  } else {
3622
- this.finishGenerate(event, state);
3760
+ this.finishGenerate(event, state2);
3623
3761
  }
3624
- if (state.subagentToolCallSpan) {
3625
- this.traceShipper.endSpan(state.subagentToolCallSpan);
3762
+ if (state2.subagentToolCallSpan) {
3763
+ this.traceShipper.endSpan(state2.subagentToolCallSpan);
3626
3764
  }
3627
3765
  this.cleanup(event.callId);
3628
3766
  };
@@ -3637,42 +3775,42 @@ var RaindropTelemetryIntegration = class {
3637
3775
  var _a;
3638
3776
  const event = error;
3639
3777
  if (!(event == null ? void 0 : event.callId)) return;
3640
- const state = this.getState(event.callId);
3641
- if (!state) return;
3778
+ const state2 = this.getState(event.callId);
3779
+ if (!state2) return;
3642
3780
  const actualError = (_a = event.error) != null ? _a : error;
3643
- if (state.stepSpan) {
3644
- this.traceShipper.endSpan(state.stepSpan, { error: actualError });
3645
- state.stepProvider = void 0;
3646
- state.stepModelId = void 0;
3781
+ if (state2.stepSpan) {
3782
+ this.traceShipper.endSpan(state2.stepSpan, { error: actualError });
3783
+ state2.stepProvider = void 0;
3784
+ state2.stepModelId = void 0;
3647
3785
  }
3648
- for (const embedSpan of state.embedSpans.values()) {
3786
+ for (const embedSpan of state2.embedSpans.values()) {
3649
3787
  this.traceShipper.endSpan(embedSpan, { error: actualError });
3650
3788
  }
3651
- state.embedSpans.clear();
3652
- for (const toolCallId of state.parentContextToolCallIds) {
3789
+ state2.embedSpans.clear();
3790
+ for (const toolCallId of state2.parentContextToolCallIds) {
3653
3791
  this.priorParentContexts.delete(toolCallId);
3654
3792
  }
3655
- state.parentContextToolCallIds.clear();
3656
- for (const toolSpan of state.toolSpans.values()) {
3793
+ state2.parentContextToolCallIds.clear();
3794
+ for (const toolSpan of state2.toolSpans.values()) {
3657
3795
  this.traceShipper.endSpan(toolSpan, { error: actualError });
3658
3796
  }
3659
- state.toolSpans.clear();
3797
+ state2.toolSpans.clear();
3660
3798
  const abortReason = describeAbortReason(actualError);
3661
- if (state.rootSpan) {
3662
- this.traceShipper.endSpan(state.rootSpan, {
3799
+ if (state2.rootSpan) {
3800
+ this.traceShipper.endSpan(state2.rootSpan, {
3663
3801
  error: actualError,
3664
- attributes: this.abortOutcomeAttrs(state, abortReason, "error")
3802
+ attributes: this.abortOutcomeAttrs(state2, abortReason, "error")
3665
3803
  });
3666
3804
  }
3667
- if (state.subagentToolCallSpan) {
3668
- this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
3805
+ if (state2.subagentToolCallSpan) {
3806
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, { error: actualError });
3669
3807
  }
3670
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3808
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3671
3809
  if (!isEmbed) {
3672
- const errorIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3810
+ const errorIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3673
3811
  this.finalizeGenerateEvent(
3674
- state,
3675
- state.accumulatedText || void 0,
3812
+ state2,
3813
+ state2.accumulatedText || void 0,
3676
3814
  void 0,
3677
3815
  false,
3678
3816
  errorIsTheRunsOutcome ? { fallbackOutput: abortReason } : void 0
@@ -3691,51 +3829,51 @@ var RaindropTelemetryIntegration = class {
3691
3829
  this.onAbort = (event) => {
3692
3830
  const callId = event == null ? void 0 : event.callId;
3693
3831
  if (!callId) return;
3694
- const state = this.getState(callId);
3695
- if (!state) return;
3832
+ const state2 = this.getState(callId);
3833
+ if (!state2) return;
3696
3834
  const abortedAttr = attrString("ai.response.aborted", "true");
3697
- if (state.stepSpan) {
3698
- this.traceShipper.endSpan(state.stepSpan, { attributes: [abortedAttr] });
3699
- state.stepSpan = void 0;
3700
- state.stepParent = void 0;
3701
- state.stepProvider = void 0;
3702
- state.stepModelId = void 0;
3835
+ if (state2.stepSpan) {
3836
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: [abortedAttr] });
3837
+ state2.stepSpan = void 0;
3838
+ state2.stepParent = void 0;
3839
+ state2.stepProvider = void 0;
3840
+ state2.stepModelId = void 0;
3703
3841
  }
3704
- for (const embedSpan of state.embedSpans.values()) {
3842
+ for (const embedSpan of state2.embedSpans.values()) {
3705
3843
  this.traceShipper.endSpan(embedSpan, { attributes: [abortedAttr] });
3706
3844
  }
3707
- state.embedSpans.clear();
3708
- for (const toolCallId of state.parentContextToolCallIds) {
3845
+ state2.embedSpans.clear();
3846
+ for (const toolCallId of state2.parentContextToolCallIds) {
3709
3847
  this.priorParentContexts.delete(toolCallId);
3710
3848
  }
3711
- state.parentContextToolCallIds.clear();
3712
- for (const toolSpan of state.toolSpans.values()) {
3849
+ state2.parentContextToolCallIds.clear();
3850
+ for (const toolSpan of state2.toolSpans.values()) {
3713
3851
  this.traceShipper.endSpan(toolSpan, { attributes: [abortedAttr] });
3714
3852
  }
3715
- state.toolSpans.clear();
3716
- const abortIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3717
- if (state.rootSpan) {
3718
- this.traceShipper.endSpan(state.rootSpan, {
3853
+ state2.toolSpans.clear();
3854
+ const abortIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3855
+ if (state2.rootSpan) {
3856
+ this.traceShipper.endSpan(state2.rootSpan, {
3719
3857
  attributes: [
3720
3858
  abortedAttr,
3721
- attrInt("ai.toolCall.count", state.toolCallCount),
3859
+ attrInt("ai.toolCall.count", state2.toolCallCount),
3722
3860
  // An aborted detached child IS a cancelled sub-agent, and a cancelled
3723
3861
  // run is span-for-span identical to a finished one — spans close,
3724
3862
  // nothing errors, there is just no answer. So it is the one outcome
3725
3863
  // that has to be stated, and the child states it on itself.
3726
3864
  ...abortIsTheRunsOutcome ? cancelledSpanAttrs() : [],
3727
- ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3865
+ ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state2, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3728
3866
  ]
3729
3867
  });
3730
3868
  }
3731
- if (state.subagentToolCallSpan) {
3732
- this.traceShipper.endSpan(state.subagentToolCallSpan, {
3869
+ if (state2.subagentToolCallSpan) {
3870
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, {
3733
3871
  attributes: [abortedAttr]
3734
3872
  });
3735
3873
  }
3736
3874
  this.finalizeGenerateEvent(
3737
- state,
3738
- state.accumulatedText || void 0,
3875
+ state2,
3876
+ state2.accumulatedText || void 0,
3739
3877
  void 0,
3740
3878
  false,
3741
3879
  abortIsTheRunsOutcome ? {
@@ -3743,7 +3881,7 @@ var RaindropTelemetryIntegration = class {
3743
3881
  properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
3744
3882
  } : void 0
3745
3883
  );
3746
- if (abortIsTheRunsOutcome) this.subagents.noteSettled(state.eventId);
3884
+ if (abortIsTheRunsOutcome) this.subagents.noteSettled(state2.eventId);
3747
3885
  this.cleanup(callId);
3748
3886
  };
3749
3887
  // ── executeTool ─────────────────────────────────────────────────────────
@@ -3752,14 +3890,14 @@ var RaindropTelemetryIntegration = class {
3752
3890
  toolCallId,
3753
3891
  execute
3754
3892
  }) => {
3755
- const state = this.getState(callId);
3756
- const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
3893
+ const state2 = this.getState(callId);
3894
+ const toolSpan = state2 == null ? void 0 : state2.toolSpans.get(toolCallId);
3757
3895
  if (!toolSpan) return execute();
3758
3896
  return runWithParentSpanContext(
3759
3897
  {
3760
3898
  traceIdB64: toolSpan.ids.traceIdB64,
3761
3899
  spanIdB64: toolSpan.ids.spanIdB64,
3762
- eventId: state.eventId
3900
+ eventId: state2.eventId
3763
3901
  },
3764
3902
  () => execute()
3765
3903
  );
@@ -3808,35 +3946,35 @@ var RaindropTelemetryIntegration = class {
3808
3946
  activeDispatch() {
3809
3947
  var _a;
3810
3948
  const parentTool = getCurrentParentToolContext();
3811
- let state = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3949
+ let state2 = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3812
3950
  const inheritedEventId = (_a = getContextManager().getParentSpanIds()) == null ? void 0 : _a.eventId;
3813
- if (!state && inheritedEventId) {
3951
+ if (!state2 && inheritedEventId) {
3814
3952
  for (const candidate of this.callStates.values()) {
3815
3953
  if (candidate.eventId === inheritedEventId) {
3816
- state = candidate;
3954
+ state2 = candidate;
3817
3955
  break;
3818
3956
  }
3819
3957
  }
3820
3958
  }
3821
- if (!state) return void 0;
3959
+ if (!state2) return void 0;
3822
3960
  return {
3823
- eventId: state.eventId,
3824
- userId: state.identity.userId,
3825
- convoId: state.identity.convoId,
3826
- dispatchSpan: parentTool ? state.toolSpans.get(parentTool.toolCallId) : void 0,
3827
- turnSpans: [state.rootSpan, state.stepSpan].filter(
3961
+ eventId: state2.eventId,
3962
+ userId: state2.identity.userId,
3963
+ convoId: state2.identity.convoId,
3964
+ dispatchSpan: parentTool ? state2.toolSpans.get(parentTool.toolCallId) : void 0,
3965
+ turnSpans: [state2.rootSpan, state2.stepSpan].filter(
3828
3966
  (span) => span !== void 0
3829
3967
  ),
3830
- recordInputs: state.recordInputs
3968
+ recordInputs: state2.recordInputs
3831
3969
  };
3832
3970
  }
3833
3971
  /** Spans still open for an event, so a late outcome can still be stated. */
3834
3972
  openSpansForEvent(eventId) {
3835
3973
  const spans = [];
3836
- for (const state of this.callStates.values()) {
3837
- if (state.eventId !== eventId) continue;
3838
- if (state.rootSpan) spans.push(state.rootSpan);
3839
- if (state.stepSpan) spans.push(state.stepSpan);
3974
+ for (const state2 of this.callStates.values()) {
3975
+ if (state2.eventId !== eventId) continue;
3976
+ if (state2.rootSpan) spans.push(state2.rootSpan);
3977
+ if (state2.stepSpan) spans.push(state2.stepSpan);
3840
3978
  }
3841
3979
  return spans;
3842
3980
  }
@@ -3856,10 +3994,10 @@ var RaindropTelemetryIntegration = class {
3856
3994
  * created from an LLM span with output, `ai.response.text` here would state
3857
3995
  * the run's outcome through the span while the turn is still working.
3858
3996
  */
3859
- abortOutcomeAttrs(state, reason, finishReason) {
3860
- if (!state.handoff || state.nestedInEvent) return [];
3997
+ abortOutcomeAttrs(state2, reason, finishReason) {
3998
+ if (!state2.handoff || state2.nestedInEvent) return [];
3861
3999
  return [
3862
- attrString("ai.response.text", capText2(state.accumulatedText || reason)),
4000
+ attrString("ai.response.text", capText2(state2.accumulatedText || reason)),
3863
4001
  attrString("ai.response.finishReason", finishReason)
3864
4002
  ];
3865
4003
  }
@@ -3873,19 +4011,19 @@ var RaindropTelemetryIntegration = class {
3873
4011
  spanParentRef(span) {
3874
4012
  return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
3875
4013
  }
3876
- emitLive(state, type, content, extra) {
4014
+ emitLive(state2, type, content, extra) {
3877
4015
  var _a, _b, _c, _d, _e, _f;
3878
- if (!localDebuggerEnabled() || !state.rootSpan) return;
3879
- const callMeta = this.extractRaindropMetadata(state.metadata);
4016
+ if (!localDebuggerEnabled() || !state2.rootSpan) return;
4017
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
3880
4018
  sendLocalDebuggerLiveEvent({
3881
- traceId: state.rootSpan.ids.traceIdB64,
4019
+ traceId: state2.rootSpan.ids.traceIdB64,
3882
4020
  type,
3883
4021
  content,
3884
4022
  metadata: {
3885
4023
  userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
3886
4024
  convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
3887
4025
  eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
3888
- eventId: state.eventId,
4026
+ eventId: state2.eventId,
3889
4027
  ...extra
3890
4028
  }
3891
4029
  });
@@ -3963,29 +4101,29 @@ var RaindropTelemetryIntegration = class {
3963
4101
  toolCallId: toolCall.toolCallId,
3964
4102
  toolName: toolCall.toolName
3965
4103
  });
3966
- const state = this.getState(event.callId);
3967
- state == null ? void 0 : state.parentContextToolCallIds.add(toolCall.toolCallId);
3968
- if (!(state == null ? void 0 : state.stepParent)) return;
3969
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
3970
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
4104
+ const state2 = this.getState(event.callId);
4105
+ state2 == null ? void 0 : state2.parentContextToolCallIds.add(toolCall.toolCallId);
4106
+ if (!(state2 == null ? void 0 : state2.stepParent)) return;
4107
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4108
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
3971
4109
  const toolSpan = this.traceShipper.startSpan({
3972
4110
  name: "ai.toolCall",
3973
- parent: state.stepParent,
3974
- eventId: state.eventId,
3975
- ...state.identity,
4111
+ parent: state2.stepParent,
4112
+ eventId: state2.eventId,
4113
+ ...state2.identity,
3976
4114
  operationId: "ai.toolCall",
3977
4115
  attributes: [
3978
4116
  attrString("operation.name", operationName),
3979
4117
  attrString("resource.name", resourceName),
3980
- attrString("ai.telemetry.functionId", state.functionId),
4118
+ attrString("ai.telemetry.functionId", state2.functionId),
3981
4119
  attrString("ai.toolCall.name", toolCall.toolName),
3982
4120
  attrString("ai.toolCall.id", toolCall.toolCallId),
3983
4121
  ...inputAttrs,
3984
- ...handoffSpanAttrs(state.handoff)
4122
+ ...handoffSpanAttrs(state2.handoff)
3985
4123
  ]
3986
4124
  });
3987
- state.toolSpans.set(toolCall.toolCallId, toolSpan);
3988
- this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
4125
+ state2.toolSpans.set(toolCall.toolCallId, toolSpan);
4126
+ this.emitLive(state2, "tool_start", toolCall.toolName, { args: toolCall.input });
3989
4127
  }
3990
4128
  toolExecutionEnd(event) {
3991
4129
  var _a;
@@ -3999,20 +4137,20 @@ var RaindropTelemetryIntegration = class {
3999
4137
  clearParentToolContext();
4000
4138
  }
4001
4139
  }
4002
- const state = this.getState(event.callId);
4003
- if (!state) return;
4004
- const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
4140
+ const state2 = this.getState(event.callId);
4141
+ if (!state2) return;
4142
+ const toolSpan = state2.toolSpans.get(event.toolCall.toolCallId);
4005
4143
  if (!toolSpan) return;
4006
- state.toolCallCount += 1;
4144
+ state2.toolCallCount += 1;
4007
4145
  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 };
4008
4146
  if (outcome.success) {
4009
- const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4147
+ const outputAttrs = state2.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4010
4148
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4011
4149
  } else {
4012
4150
  this.traceShipper.endSpan(toolSpan, { error: outcome.error });
4013
4151
  }
4014
- this.emitLive(state, "tool_result", event.toolCall.toolName);
4015
- state.toolSpans.delete(event.toolCall.toolCallId);
4152
+ this.emitLive(state2, "tool_result", event.toolCall.toolName);
4153
+ state2.toolSpans.delete(event.toolCall.toolCallId);
4016
4154
  }
4017
4155
  // ── provider-executed tool calls ─────────────────────────────────────────
4018
4156
  //
@@ -4031,8 +4169,8 @@ var RaindropTelemetryIntegration = class {
4031
4169
  //
4032
4170
  // Client-executed tools are excluded (`providerExecuted` falsy) — they were
4033
4171
  // already spanned during execution, so this never double-emits.
4034
- emitProviderExecutedToolSpans(event, state) {
4035
- if (!state.stepParent) return;
4172
+ emitProviderExecutedToolSpans(event, state2) {
4173
+ if (!state2.stepParent) return;
4036
4174
  const content = Array.isArray(event.content) ? event.content : [];
4037
4175
  const providerToolCalls = content.filter(
4038
4176
  (part) => (part == null ? void 0 : part.type) === "tool-call" && part.providerExecuted === true
@@ -4045,42 +4183,42 @@ var RaindropTelemetryIntegration = class {
4045
4183
  }
4046
4184
  }
4047
4185
  for (const call of providerToolCalls) {
4048
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
4049
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4186
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4187
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4050
4188
  const toolSpan = this.traceShipper.startSpan({
4051
4189
  name: "ai.toolCall",
4052
- parent: state.stepParent,
4053
- eventId: state.eventId,
4054
- ...state.identity,
4190
+ parent: state2.stepParent,
4191
+ eventId: state2.eventId,
4192
+ ...state2.identity,
4055
4193
  operationId: "ai.toolCall",
4056
4194
  attributes: [
4057
4195
  attrString("operation.name", operationName),
4058
4196
  attrString("resource.name", resourceName),
4059
- attrString("ai.telemetry.functionId", state.functionId),
4197
+ attrString("ai.telemetry.functionId", state2.functionId),
4060
4198
  attrString("ai.toolCall.name", call.toolName),
4061
4199
  attrString("ai.toolCall.id", call.toolCallId),
4062
4200
  attrString("ai.toolCall.providerExecuted", "true"),
4063
4201
  ...inputAttrs,
4064
- ...handoffSpanAttrs(state.handoff)
4202
+ ...handoffSpanAttrs(state2.handoff)
4065
4203
  ]
4066
4204
  });
4067
- state.toolCallCount += 1;
4068
- this.emitLive(state, "tool_start", call.toolName, { args: call.input });
4205
+ state2.toolCallCount += 1;
4206
+ this.emitLive(state2, "tool_start", call.toolName, { args: call.input });
4069
4207
  const resultPart = resultsByCallId.get(call.toolCallId);
4070
4208
  if ((resultPart == null ? void 0 : resultPart.type) === "tool-error") {
4071
4209
  this.traceShipper.endSpan(toolSpan, { error: resultPart.error });
4072
4210
  } else {
4073
- const outputAttrs = state.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4211
+ const outputAttrs = state2.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4074
4212
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4075
4213
  }
4076
- this.emitLive(state, "tool_result", call.toolName);
4214
+ this.emitLive(state2, "tool_result", call.toolName);
4077
4215
  }
4078
4216
  }
4079
- finishGenerate(event, state) {
4217
+ finishGenerate(event, state2) {
4080
4218
  var _a, _b, _c, _d, _e, _f;
4081
- if (state.rootSpan) {
4219
+ if (state2.rootSpan) {
4082
4220
  const outputAttrs = [];
4083
- if (state.recordOutputs) {
4221
+ if (state2.recordOutputs) {
4084
4222
  outputAttrs.push(
4085
4223
  attrString("ai.response.finishReason", event.finishReason),
4086
4224
  attrString("ai.response.text", capText2((_a = event.text) != null ? _a : void 0)),
@@ -4121,12 +4259,12 @@ var RaindropTelemetryIntegration = class {
4121
4259
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens)
4122
4260
  );
4123
4261
  }
4124
- outputAttrs.push(attrInt("ai.toolCall.count", state.toolCallCount));
4125
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4262
+ outputAttrs.push(attrInt("ai.toolCall.count", state2.toolCallCount));
4263
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4126
4264
  }
4127
4265
  this.finalizeGenerateEvent(
4128
- state,
4129
- (_e = event.text) != null ? _e : state.accumulatedText || void 0,
4266
+ state2,
4267
+ (_e = event.text) != null ? _e : state2.accumulatedText || void 0,
4130
4268
  (_f = event.response) == null ? void 0 : _f.modelId,
4131
4269
  hasUnresolvedToolApproval(event)
4132
4270
  );
@@ -4142,29 +4280,29 @@ var RaindropTelemetryIntegration = class {
4142
4280
  * is finalized by that resume — otherwise each execution would finalize the
4143
4281
  * same event ID into a separate canonical row.
4144
4282
  */
4145
- finalizeGenerateEvent(state, output, model, keepPending = false, detachedOutcome) {
4283
+ finalizeGenerateEvent(state2, output, model, keepPending = false, detachedOutcome) {
4146
4284
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
4147
- const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
4285
+ const suppressSubagentEvent = state2.subagentName !== void 0 && state2.subagentToolCallSpan !== void 0;
4148
4286
  if (!this.sendEvents || suppressSubagentEvent) return;
4149
- if (this.subagents.wasSettledExplicitly(state.eventId)) return;
4150
- const callMeta = this.extractRaindropMetadata(state.metadata);
4287
+ if (this.subagents.wasSettledExplicitly(state2.eventId)) return;
4288
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
4151
4289
  const userId = (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId;
4152
4290
  if (!userId) return;
4153
- const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state.operationId;
4291
+ const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state2.operationId;
4154
4292
  const cappedOutput = capText2(output);
4155
- const reportedOutput = state.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4156
- const input = capText2(state.inputText);
4293
+ const reportedOutput = state2.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4294
+ const input = capText2(state2.inputText);
4157
4295
  const properties = {
4158
4296
  ...(_f = this.defaultContext) == null ? void 0 : _f.properties,
4159
4297
  ...callMeta.properties,
4160
- ...state.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4298
+ ...state2.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4161
4299
  };
4162
4300
  const featureFlags = {
4163
4301
  ...((_g = this.defaultContext) == null ? void 0 : _g.featureFlags) ? normalizeFeatureFlags(this.defaultContext.featureFlags) : {},
4164
4302
  ...callMeta.featureFlags
4165
4303
  };
4166
4304
  const convoId = (_i = callMeta.convoId) != null ? _i : (_h = this.defaultContext) == null ? void 0 : _h.convoId;
4167
- void this.eventShipper.patch(state.eventId, {
4305
+ void this.eventShipper.patch(state2.eventId, {
4168
4306
  eventName,
4169
4307
  userId,
4170
4308
  convoId,
@@ -4182,12 +4320,12 @@ var RaindropTelemetryIntegration = class {
4182
4320
  }
4183
4321
  });
4184
4322
  }
4185
- finishEmbed(event, state) {
4323
+ finishEmbed(event, state2) {
4186
4324
  var _a;
4187
- if (!state.rootSpan) return;
4325
+ if (!state2.rootSpan) return;
4188
4326
  const outputAttrs = [];
4189
- const isMany = state.operationId === "ai.embedMany";
4190
- if (state.recordOutputs) {
4327
+ const isMany = state2.operationId === "ai.embedMany";
4328
+ if (state2.recordOutputs) {
4191
4329
  if (isMany) {
4192
4330
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embedding)));
4193
4331
  } else {
@@ -4197,7 +4335,7 @@ var RaindropTelemetryIntegration = class {
4197
4335
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
4198
4336
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
4199
4337
  }
4200
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4338
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4201
4339
  }
4202
4340
  };
4203
4341
 
@@ -4506,9 +4644,7 @@ function extractRaindropMetadata(metadata) {
4506
4644
  } catch (e) {
4507
4645
  }
4508
4646
  } else if (featureFlags && typeof featureFlags === "object") {
4509
- result.featureFlags = normalizeFeatureFlags(
4510
- featureFlags
4511
- );
4647
+ result.featureFlags = normalizeFeatureFlags(featureFlags);
4512
4648
  }
4513
4649
  return result;
4514
4650
  }
@@ -4719,12 +4855,7 @@ function setupOperation(params) {
4719
4855
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
4720
4856
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
4721
4857
  ...attrsFromSettings(arg),
4722
- ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
4723
- attrString(
4724
- "ai.prompt",
4725
- safeJsonWithUint8(normalizePromptAttr(arg))
4726
- )
4727
- ]
4858
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [attrString("ai.prompt", safeJsonWithUint8(normalizePromptAttr(arg)))]
4728
4859
  ]
4729
4860
  }) : void 0;
4730
4861
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
@@ -5074,7 +5205,10 @@ function wrapAISDK(aiSDK, deps) {
5074
5205
  }
5075
5206
  const useNative = deps.options.nativeTelemetry === true;
5076
5207
  if (useNative) {
5077
- const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
5208
+ const wrapTimeCtx = resolveContext(deps.options.context, {
5209
+ operation: "wrap",
5210
+ args: void 0
5211
+ });
5078
5212
  const integration = new RaindropTelemetryIntegration({
5079
5213
  traceShipper: deps.traceShipper,
5080
5214
  eventShipper: deps.eventShipper,
@@ -5319,7 +5453,13 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
5319
5453
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
5320
5454
  attrString(
5321
5455
  "ai.prompt",
5322
- safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
5456
+ safeJsonWithUint8(
5457
+ normalizePromptAttr({
5458
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
5459
+ prompt: mergedArgs["prompt"],
5460
+ messages: mergedArgs["messages"]
5461
+ })
5462
+ )
5323
5463
  )
5324
5464
  ]
5325
5465
  ]
@@ -5533,7 +5673,13 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
5533
5673
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
5534
5674
  attrString(
5535
5675
  "ai.prompt",
5536
- safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
5676
+ safeJsonWithUint8(
5677
+ normalizePromptAttr({
5678
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
5679
+ prompt: mergedArgs["prompt"],
5680
+ messages: mergedArgs["messages"]
5681
+ })
5682
+ )
5537
5683
  )
5538
5684
  ]
5539
5685
  ]
@@ -5910,9 +6056,19 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
5910
6056
  for (const part of content) {
5911
6057
  if (isRecord(part)) {
5912
6058
  if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
5913
- sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
6059
+ sendLocalDebuggerLiveEvent({
6060
+ traceId,
6061
+ type: "reasoning_delta",
6062
+ content: (_b = part["text"]) != null ? _b : part["thinking"],
6063
+ metadata: liveMeta
6064
+ });
5914
6065
  } else if (part["type"] === "text" && typeof part["text"] === "string") {
5915
- sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
6066
+ sendLocalDebuggerLiveEvent({
6067
+ traceId,
6068
+ type: "text_delta",
6069
+ content: part["text"],
6070
+ metadata: liveMeta
6071
+ });
5916
6072
  }
5917
6073
  }
5918
6074
  }
@@ -5993,7 +6149,10 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
5993
6149
  attributes: [
5994
6150
  ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
5995
6151
  attrString("ai.response.finishReason", finishReason),
5996
- attrString("ai.response.text", activeText.length ? capText2(activeText) : void 0),
6152
+ attrString(
6153
+ "ai.response.text",
6154
+ activeText.length ? capText2(activeText) : void 0
6155
+ ),
5997
6156
  attrString(
5998
6157
  "ai.response.toolCalls",
5999
6158
  safeJsonWithUint8(toolCallsLocal.length ? toolCallsLocal : void 0)
@@ -6011,7 +6170,8 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6011
6170
  ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
6012
6171
  attrString("gen_ai.response.id", responseId),
6013
6172
  attrString(MODEL_USAGE_ATTRIBUTES.responseModel, finalResponseModelId),
6014
- ...buildModelUsageAttributes(usageMetrics),
6173
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
6174
+ ...buildRawModelUsageAttributes(usageMetrics),
6015
6175
  ...msToFirstChunk !== void 0 ? [attrInt("ai.stream.msToFirstChunk", msToFirstChunk)] : [],
6016
6176
  ...msToFinish !== void 0 ? [attrInt("ai.stream.msToFinish", msToFinish)] : [],
6017
6177
  ...avgOutTokensPerSecond !== void 0 ? [attrDouble("ai.stream.avgOutputTokensPerSecond", avgOutTokensPerSecond)] : [],
@@ -6065,19 +6225,44 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
6065
6225
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
6066
6226
  if (localDebuggerEnabled() && ctx.rootParentForChildren) {
6067
6227
  const traceId = ctx.rootParentForChildren.traceIdB64;
6068
- const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
6228
+ const liveMeta = getLocalDebuggerMetadata({
6229
+ ...ctx.context,
6230
+ eventId: ctx.eventId
6231
+ });
6069
6232
  if (type === "text-delta") {
6070
6233
  const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
6071
- if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
6234
+ if (typeof text === "string" && text)
6235
+ sendLocalDebuggerLiveEvent({
6236
+ traceId,
6237
+ type: "text_delta",
6238
+ content: text,
6239
+ metadata: liveMeta
6240
+ });
6072
6241
  } else if (type === "reasoning" || type === "reasoning-delta") {
6073
6242
  const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
6074
- if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
6243
+ if (typeof text === "string" && text)
6244
+ sendLocalDebuggerLiveEvent({
6245
+ traceId,
6246
+ type: "reasoning_delta",
6247
+ content: text,
6248
+ metadata: liveMeta
6249
+ });
6075
6250
  } else if (type === "tool-call") {
6076
6251
  const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
6077
- sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
6252
+ sendLocalDebuggerLiveEvent({
6253
+ traceId,
6254
+ type: "tool_start",
6255
+ content: toolName,
6256
+ metadata: { ...liveMeta, args: value["args"] }
6257
+ });
6078
6258
  } else if (type === "tool-result") {
6079
6259
  const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
6080
- sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
6260
+ sendLocalDebuggerLiveEvent({
6261
+ traceId,
6262
+ type: "tool_result",
6263
+ content: toolName,
6264
+ metadata: { ...liveMeta, result: value["result"] }
6265
+ });
6081
6266
  }
6082
6267
  }
6083
6268
  }
@@ -6157,11 +6342,7 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
6157
6342
  } else {
6158
6343
  responseTimestampIso = (/* @__PURE__ */ new Date()).toISOString();
6159
6344
  }
6160
- const usageMetrics = extractUsageMetricsFromUsage(
6161
- usage,
6162
- modelInfo.provider,
6163
- providerMetadata
6164
- );
6345
+ const usageMetrics = extractUsageMetricsFromUsage(usage, modelInfo.provider, providerMetadata);
6165
6346
  const { inputTokens, outputTokens } = usageMetrics;
6166
6347
  ctx.traceShipper.endSpan(span, {
6167
6348
  attributes: [
@@ -6182,7 +6363,8 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
6182
6363
  ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
6183
6364
  attrString("gen_ai.response.id", responseId),
6184
6365
  attrString(MODEL_USAGE_ATTRIBUTES.responseModel, responseModelId),
6185
- ...buildModelUsageAttributes(usageMetrics)
6366
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, usageMetrics.usageSource),
6367
+ ...buildRawModelUsageAttributes(usageMetrics)
6186
6368
  ]
6187
6369
  });
6188
6370
  }