@raindrop-ai/ai-sdk 0.3.1 → 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-3V4MIA75.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);
@@ -1472,7 +1606,10 @@ var TraceShipper = class {
1472
1606
  try {
1473
1607
  const result = this.transformSpanHook(current);
1474
1608
  if (result === null) return null;
1475
- if (result !== void 0) current = result;
1609
+ if (result !== void 0) {
1610
+ copyReplayTraceDestination(current, result);
1611
+ current = result;
1612
+ }
1476
1613
  } catch (err) {
1477
1614
  if (this.debug) {
1478
1615
  const msg = err instanceof Error ? err.message : String(err);
@@ -1482,13 +1619,19 @@ var TraceShipper = class {
1482
1619
  }
1483
1620
  }
1484
1621
  try {
1485
- current = normalizeModelUsageSpan(current);
1622
+ const normalized = normalizeModelUsageSpan(current);
1623
+ copyReplayTraceDestination(current, normalized);
1624
+ current = normalized;
1486
1625
  } catch (e) {
1487
1626
  }
1488
1627
  if (!this.disableDefaultRedaction) {
1489
- current = defaultTransformSpan(current);
1628
+ const redacted = defaultTransformSpan(current);
1629
+ copyReplayTraceDestination(current, redacted);
1630
+ current = redacted;
1490
1631
  }
1491
- return this.capSpanAttributes(current);
1632
+ const capped = this.capSpanAttributes(current);
1633
+ copyReplayTraceDestination(current, capped);
1634
+ return capped;
1492
1635
  }
1493
1636
  isDebugEnabled() {
1494
1637
  return this.debug;
@@ -1506,33 +1649,54 @@ var TraceShipper = class {
1506
1649
  const attrs = [
1507
1650
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1508
1651
  ...identityAttrs(args),
1509
- attrString("ai.operationId", args.operationId)
1652
+ attrString("ai.operationId", args.operationId),
1653
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1510
1654
  ];
1511
1655
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
1512
- const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
1513
- this.mirrorToLocalDebugger(
1514
- buildOtlpSpan({
1515
- ids: span.ids,
1516
- name: span.name,
1517
- startTimeUnixNano: span.startTimeUnixNano,
1518
- endTimeUnixNano: span.startTimeUnixNano,
1519
- // placeholder — will be updated on endSpan
1520
- attributes: span.attributes,
1521
- status: { code: SpanStatusCode.UNSET }
1522
- })
1523
- );
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);
1524
1674
  return span;
1525
1675
  }
1526
- mirrorToLocalDebugger(span) {
1527
- 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;
1528
1681
  const redacted = this.redactSpan(span);
1529
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
+ }
1530
1690
  const body = buildExportTraceServiceRequest([redacted], this.serviceName, this.serviceVersion);
1531
- mirrorTraceExportToLocalDebugger(body, {
1532
- baseUrl: this.localDebuggerUrl,
1691
+ const p = mirrorTraceExportToLocalDebugger(body, {
1692
+ baseUrl: localDebuggerUrl,
1533
1693
  debug: false,
1534
1694
  sdkName: this.sdkName
1535
1695
  });
1696
+ this.inFlight.add(p);
1697
+ void p.finally(() => {
1698
+ this.inFlight.delete(p);
1699
+ });
1536
1700
  }
1537
1701
  endSpan(span, extra) {
1538
1702
  var _a, _b;
@@ -1554,15 +1718,17 @@ var TraceShipper = class {
1554
1718
  attributes: span.attributes,
1555
1719
  status
1556
1720
  });
1721
+ copyReplayTraceDestination(span, otlp);
1557
1722
  this.enqueue(otlp);
1558
- this.mirrorToLocalDebugger(otlp);
1723
+ this.mirrorToLocalDebugger(otlp, true);
1559
1724
  }
1560
1725
  createSpan(args) {
1561
1726
  var _a;
1562
1727
  const ids = createSpanIds(args.parent);
1563
1728
  const attrs = [
1564
1729
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1565
- ...identityAttrs(args)
1730
+ ...identityAttrs(args),
1731
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1566
1732
  ];
1567
1733
  if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
1568
1734
  const otlp = buildOtlpSpan({
@@ -1573,8 +1739,9 @@ var TraceShipper = class {
1573
1739
  attributes: attrs,
1574
1740
  status: args.status
1575
1741
  });
1742
+ rememberReplayTraceDestination(otlp);
1576
1743
  this.enqueue(otlp);
1577
- this.mirrorToLocalDebugger(otlp);
1744
+ this.mirrorToLocalDebugger(otlp, true);
1578
1745
  }
1579
1746
  enqueue(span) {
1580
1747
  if (!this.enabled) return;
@@ -1588,6 +1755,13 @@ var TraceShipper = class {
1588
1755
  }
1589
1756
  const redacted = this.redactSpan(span);
1590
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;
1591
1765
  if (this.queue.length >= this.maxQueueSize) {
1592
1766
  this.queue.shift();
1593
1767
  }
@@ -1606,47 +1780,67 @@ var TraceShipper = class {
1606
1780
  }
1607
1781
  }
1608
1782
  async flush() {
1609
- 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
+ }
1610
1789
  if (this.timer) {
1611
1790
  clearTimeout(this.timer);
1612
1791
  this.timer = void 0;
1613
1792
  }
1614
1793
  while (this.queue.length > 0) {
1615
1794
  const batch = this.queue.splice(0, this.maxBatchSize);
1616
- if (!this.writeKey) continue;
1617
- const opts = this.requestOpts();
1618
- if (!opts) {
1619
- rateLimitedLog(
1620
- `${this.prefix}.shutdown_deadline`,
1621
- () => console.warn(
1622
- `${this.prefix} shutdown flush deadline exceeded; dropping ${batch.length} spans`
1623
- )
1624
- );
1625
- continue;
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]);
1626
1801
  }
1627
- const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
1628
- const url = `${this.baseUrl}traces`;
1629
- if (this.debug) {
1630
- console.log(`${this.prefix} sending traces batch`, {
1631
- spans: batch.length,
1632
- endpoint: url
1633
- });
1634
- }
1635
- const p = postJson(url, body, this.requestHeaders(), opts);
1636
- this.inFlight.add(p);
1637
- try {
1638
- try {
1639
- await p;
1640
- if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
1641
- } catch (err) {
1642
- 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) {
1643
1807
  rateLimitedLog(
1644
- `${this.prefix}.send_spans_failed`,
1645
- () => 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
+ )
1646
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);
1647
1843
  }
1648
- } finally {
1649
- this.inFlight.delete(p);
1650
1844
  }
1651
1845
  }
1652
1846
  }
@@ -1689,7 +1883,9 @@ var TraceShipper = class {
1689
1883
  if (!settled) {
1690
1884
  rateLimitedLog(
1691
1885
  `${this.prefix}.shutdown_deadline`,
1692
- () => 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
+ )
1693
1889
  );
1694
1890
  }
1695
1891
  } finally {
@@ -1784,7 +1980,8 @@ function withCurrent(span, callback) {
1784
1980
  return getContextManager().runInContext(span, callback);
1785
1981
  }
1786
1982
  async function getCurrentParentSpanContext() {
1787
- return getContextManager().getParentSpanIds();
1983
+ var _a, _b;
1984
+ return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
1788
1985
  }
1789
1986
  async function runWithParentSpanContext(ctx, fn) {
1790
1987
  const cm = getContextManager();
@@ -1818,7 +2015,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
1818
2015
  // package.json
1819
2016
  var package_default = {
1820
2017
  name: "@raindrop-ai/ai-sdk",
1821
- version: "0.3.1"};
2018
+ version: "0.3.2"};
1822
2019
 
1823
2020
  // src/internal/version.ts
1824
2021
  var libraryName = package_default.name;
@@ -3344,13 +3541,13 @@ var RaindropTelemetryIntegration = class {
3344
3541
  };
3345
3542
  // ── onStepStart ─────────────────────────────────────────────────────────
3346
3543
  this.onStepStart = (event) => {
3347
- const state = this.getState(event.callId);
3348
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3349
- const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
3350
- const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
3351
- 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);
3352
3549
  const inputAttrs = [];
3353
- if (state.recordInputs) {
3550
+ if (state2.recordInputs) {
3354
3551
  if (event.promptMessages) {
3355
3552
  inputAttrs.push(attrString("ai.prompt.messages", safeJsonWithUint8(event.promptMessages)));
3356
3553
  }
@@ -3373,25 +3570,25 @@ var RaindropTelemetryIntegration = class {
3373
3570
  }
3374
3571
  const stepSpan = this.traceShipper.startSpan({
3375
3572
  name: stepOperationId,
3376
- parent: state.rootParent,
3377
- eventId: state.eventId,
3378
- ...state.identity,
3573
+ parent: state2.rootParent,
3574
+ eventId: state2.eventId,
3575
+ ...state2.identity,
3379
3576
  operationId: stepOperationId,
3380
3577
  attributes: [
3381
3578
  attrString("operation.name", operationName),
3382
3579
  attrString("resource.name", resourceName),
3383
- attrString("ai.telemetry.functionId", state.functionId),
3580
+ attrString("ai.telemetry.functionId", state2.functionId),
3384
3581
  ...attrsFromModelProvider(event.provider),
3385
3582
  attrString("ai.model.id", event.modelId),
3386
3583
  attrString(MODEL_USAGE_ATTRIBUTES.requestModel, event.modelId),
3387
3584
  ...inputAttrs,
3388
- ...handoffSpanAttrs(state.handoff)
3585
+ ...handoffSpanAttrs(state2.handoff)
3389
3586
  ]
3390
3587
  });
3391
- state.stepSpan = stepSpan;
3392
- state.stepParent = this.spanParentRef(stepSpan);
3393
- state.stepProvider = event.provider;
3394
- state.stepModelId = event.modelId;
3588
+ state2.stepSpan = stepSpan;
3589
+ state2.stepParent = this.spanParentRef(stepSpan);
3590
+ state2.stepProvider = event.provider;
3591
+ state2.stepModelId = event.modelId;
3395
3592
  };
3396
3593
  this.onToolExecutionStart = (event) => this.toolExecutionStart(event);
3397
3594
  this.onToolExecutionEnd = (event) => this.toolExecutionEnd(event);
@@ -3418,33 +3615,33 @@ var RaindropTelemetryIntegration = class {
3418
3615
  var _a, _b, _c, _d, _e;
3419
3616
  const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
3420
3617
  if (!callId) return;
3421
- const state = this.getState(callId);
3422
- if (!state) return;
3618
+ const state2 = this.getState(callId);
3619
+ if (!state2) return;
3423
3620
  const chunk = event.chunk;
3424
3621
  if (!chunk || typeof chunk !== "object") return;
3425
3622
  if (chunk.type === "text-delta") {
3426
3623
  const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
3427
3624
  if (typeof delta === "string") {
3428
- if (state.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3429
- state.accumulatedText += delta;
3625
+ if (state2.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3626
+ state2.accumulatedText += delta;
3430
3627
  }
3431
- this.emitLive(state, "text_delta", delta);
3628
+ this.emitLive(state2, "text_delta", delta);
3432
3629
  }
3433
3630
  } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
3434
3631
  const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
3435
3632
  if (typeof text === "string") {
3436
- this.emitLive(state, "reasoning_delta", text);
3633
+ this.emitLive(state2, "reasoning_delta", text);
3437
3634
  }
3438
3635
  }
3439
3636
  };
3440
3637
  // ── onStepFinish ────────────────────────────────────────────────────────
3441
3638
  this.onStepFinish = (event) => {
3442
3639
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3443
- const state = this.getState(event.callId);
3444
- if (!(state == null ? void 0 : state.stepSpan)) return;
3445
- 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;
3446
3643
  const outputAttrs = [];
3447
- if (state.recordOutputs) {
3644
+ if (state2.recordOutputs) {
3448
3645
  outputAttrs.push(
3449
3646
  attrString("ai.response.finishReason", event.finishReason),
3450
3647
  attrString("ai.response.text", capText2((_c = event.text) != null ? _c : void 0)),
@@ -3489,7 +3686,7 @@ var RaindropTelemetryIntegration = class {
3489
3686
  if (usage) {
3490
3687
  const usageMetrics = extractUsageMetricsFromUsage(
3491
3688
  usage,
3492
- state.stepProvider,
3689
+ state2.stepProvider,
3493
3690
  event.providerMetadata
3494
3691
  );
3495
3692
  outputAttrs.push(
@@ -3502,51 +3699,51 @@ var RaindropTelemetryIntegration = class {
3502
3699
  ...buildRawModelUsageAttributes(usageMetrics)
3503
3700
  );
3504
3701
  }
3505
- this.emitProviderExecutedToolSpans(event, state);
3506
- this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
3507
- state.stepSpan = void 0;
3508
- state.stepParent = void 0;
3509
- state.stepProvider = void 0;
3510
- 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;
3511
3708
  };
3512
3709
  // ── onEmbedStart ────────────────────────────────────────────────────────
3513
3710
  this.onEmbedStart = (event) => {
3514
- const state = this.getState(event.callId);
3515
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3516
- const { operationName, resourceName } = opName(event.operationId, state.functionId);
3517
- 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))] : [];
3518
3715
  const embedSpan = this.traceShipper.startSpan({
3519
3716
  name: event.operationId,
3520
- parent: state.rootParent,
3521
- eventId: state.eventId,
3522
- ...state.identity,
3717
+ parent: state2.rootParent,
3718
+ eventId: state2.eventId,
3719
+ ...state2.identity,
3523
3720
  operationId: event.operationId,
3524
3721
  attributes: [
3525
3722
  attrString("operation.name", operationName),
3526
3723
  attrString("resource.name", resourceName),
3527
- attrString("ai.telemetry.functionId", state.functionId),
3724
+ attrString("ai.telemetry.functionId", state2.functionId),
3528
3725
  ...inputAttrs,
3529
- ...handoffSpanAttrs(state.handoff)
3726
+ ...handoffSpanAttrs(state2.handoff)
3530
3727
  ]
3531
3728
  });
3532
- state.embedSpans.set(event.embedCallId, embedSpan);
3729
+ state2.embedSpans.set(event.embedCallId, embedSpan);
3533
3730
  };
3534
3731
  // ── onEmbedFinish ───────────────────────────────────────────────────────
3535
3732
  this.onEmbedFinish = (event) => {
3536
3733
  var _a;
3537
- const state = this.getState(event.callId);
3538
- if (!state) return;
3539
- 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);
3540
3737
  if (!embedSpan) return;
3541
3738
  const outputAttrs = [];
3542
- if (state.recordOutputs) {
3739
+ if (state2.recordOutputs) {
3543
3740
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embeddings)));
3544
3741
  }
3545
3742
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
3546
3743
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
3547
3744
  }
3548
3745
  this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
3549
- state.embedSpans.delete(event.embedCallId);
3746
+ state2.embedSpans.delete(event.embedCallId);
3550
3747
  };
3551
3748
  // v7 canary.159 renamed `onEmbedFinish` -> `onEmbedEnd`. Both names forward
3552
3749
  // to the same implementation; the installed SDK only wires up whichever it
@@ -3554,16 +3751,16 @@ var RaindropTelemetryIntegration = class {
3554
3751
  this.onEmbedEnd = (event) => this.onEmbedFinish(event);
3555
3752
  // ── onFinish ────────────────────────────────────────────────────────────
3556
3753
  this.onFinish = (event) => {
3557
- const state = this.getState(event.callId);
3558
- if (!state) return;
3559
- 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";
3560
3757
  if (isEmbed) {
3561
- this.finishEmbed(event, state);
3758
+ this.finishEmbed(event, state2);
3562
3759
  } else {
3563
- this.finishGenerate(event, state);
3760
+ this.finishGenerate(event, state2);
3564
3761
  }
3565
- if (state.subagentToolCallSpan) {
3566
- this.traceShipper.endSpan(state.subagentToolCallSpan);
3762
+ if (state2.subagentToolCallSpan) {
3763
+ this.traceShipper.endSpan(state2.subagentToolCallSpan);
3567
3764
  }
3568
3765
  this.cleanup(event.callId);
3569
3766
  };
@@ -3578,42 +3775,42 @@ var RaindropTelemetryIntegration = class {
3578
3775
  var _a;
3579
3776
  const event = error;
3580
3777
  if (!(event == null ? void 0 : event.callId)) return;
3581
- const state = this.getState(event.callId);
3582
- if (!state) return;
3778
+ const state2 = this.getState(event.callId);
3779
+ if (!state2) return;
3583
3780
  const actualError = (_a = event.error) != null ? _a : error;
3584
- if (state.stepSpan) {
3585
- this.traceShipper.endSpan(state.stepSpan, { error: actualError });
3586
- state.stepProvider = void 0;
3587
- 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;
3588
3785
  }
3589
- for (const embedSpan of state.embedSpans.values()) {
3786
+ for (const embedSpan of state2.embedSpans.values()) {
3590
3787
  this.traceShipper.endSpan(embedSpan, { error: actualError });
3591
3788
  }
3592
- state.embedSpans.clear();
3593
- for (const toolCallId of state.parentContextToolCallIds) {
3789
+ state2.embedSpans.clear();
3790
+ for (const toolCallId of state2.parentContextToolCallIds) {
3594
3791
  this.priorParentContexts.delete(toolCallId);
3595
3792
  }
3596
- state.parentContextToolCallIds.clear();
3597
- for (const toolSpan of state.toolSpans.values()) {
3793
+ state2.parentContextToolCallIds.clear();
3794
+ for (const toolSpan of state2.toolSpans.values()) {
3598
3795
  this.traceShipper.endSpan(toolSpan, { error: actualError });
3599
3796
  }
3600
- state.toolSpans.clear();
3797
+ state2.toolSpans.clear();
3601
3798
  const abortReason = describeAbortReason(actualError);
3602
- if (state.rootSpan) {
3603
- this.traceShipper.endSpan(state.rootSpan, {
3799
+ if (state2.rootSpan) {
3800
+ this.traceShipper.endSpan(state2.rootSpan, {
3604
3801
  error: actualError,
3605
- attributes: this.abortOutcomeAttrs(state, abortReason, "error")
3802
+ attributes: this.abortOutcomeAttrs(state2, abortReason, "error")
3606
3803
  });
3607
3804
  }
3608
- if (state.subagentToolCallSpan) {
3609
- this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
3805
+ if (state2.subagentToolCallSpan) {
3806
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, { error: actualError });
3610
3807
  }
3611
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3808
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3612
3809
  if (!isEmbed) {
3613
- const errorIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3810
+ const errorIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3614
3811
  this.finalizeGenerateEvent(
3615
- state,
3616
- state.accumulatedText || void 0,
3812
+ state2,
3813
+ state2.accumulatedText || void 0,
3617
3814
  void 0,
3618
3815
  false,
3619
3816
  errorIsTheRunsOutcome ? { fallbackOutput: abortReason } : void 0
@@ -3632,51 +3829,51 @@ var RaindropTelemetryIntegration = class {
3632
3829
  this.onAbort = (event) => {
3633
3830
  const callId = event == null ? void 0 : event.callId;
3634
3831
  if (!callId) return;
3635
- const state = this.getState(callId);
3636
- if (!state) return;
3832
+ const state2 = this.getState(callId);
3833
+ if (!state2) return;
3637
3834
  const abortedAttr = attrString("ai.response.aborted", "true");
3638
- if (state.stepSpan) {
3639
- this.traceShipper.endSpan(state.stepSpan, { attributes: [abortedAttr] });
3640
- state.stepSpan = void 0;
3641
- state.stepParent = void 0;
3642
- state.stepProvider = void 0;
3643
- 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;
3644
3841
  }
3645
- for (const embedSpan of state.embedSpans.values()) {
3842
+ for (const embedSpan of state2.embedSpans.values()) {
3646
3843
  this.traceShipper.endSpan(embedSpan, { attributes: [abortedAttr] });
3647
3844
  }
3648
- state.embedSpans.clear();
3649
- for (const toolCallId of state.parentContextToolCallIds) {
3845
+ state2.embedSpans.clear();
3846
+ for (const toolCallId of state2.parentContextToolCallIds) {
3650
3847
  this.priorParentContexts.delete(toolCallId);
3651
3848
  }
3652
- state.parentContextToolCallIds.clear();
3653
- for (const toolSpan of state.toolSpans.values()) {
3849
+ state2.parentContextToolCallIds.clear();
3850
+ for (const toolSpan of state2.toolSpans.values()) {
3654
3851
  this.traceShipper.endSpan(toolSpan, { attributes: [abortedAttr] });
3655
3852
  }
3656
- state.toolSpans.clear();
3657
- const abortIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3658
- if (state.rootSpan) {
3659
- 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, {
3660
3857
  attributes: [
3661
3858
  abortedAttr,
3662
- attrInt("ai.toolCall.count", state.toolCallCount),
3859
+ attrInt("ai.toolCall.count", state2.toolCallCount),
3663
3860
  // An aborted detached child IS a cancelled sub-agent, and a cancelled
3664
3861
  // run is span-for-span identical to a finished one — spans close,
3665
3862
  // nothing errors, there is just no answer. So it is the one outcome
3666
3863
  // that has to be stated, and the child states it on itself.
3667
3864
  ...abortIsTheRunsOutcome ? cancelledSpanAttrs() : [],
3668
- ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3865
+ ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state2, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3669
3866
  ]
3670
3867
  });
3671
3868
  }
3672
- if (state.subagentToolCallSpan) {
3673
- this.traceShipper.endSpan(state.subagentToolCallSpan, {
3869
+ if (state2.subagentToolCallSpan) {
3870
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, {
3674
3871
  attributes: [abortedAttr]
3675
3872
  });
3676
3873
  }
3677
3874
  this.finalizeGenerateEvent(
3678
- state,
3679
- state.accumulatedText || void 0,
3875
+ state2,
3876
+ state2.accumulatedText || void 0,
3680
3877
  void 0,
3681
3878
  false,
3682
3879
  abortIsTheRunsOutcome ? {
@@ -3684,7 +3881,7 @@ var RaindropTelemetryIntegration = class {
3684
3881
  properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
3685
3882
  } : void 0
3686
3883
  );
3687
- if (abortIsTheRunsOutcome) this.subagents.noteSettled(state.eventId);
3884
+ if (abortIsTheRunsOutcome) this.subagents.noteSettled(state2.eventId);
3688
3885
  this.cleanup(callId);
3689
3886
  };
3690
3887
  // ── executeTool ─────────────────────────────────────────────────────────
@@ -3693,14 +3890,14 @@ var RaindropTelemetryIntegration = class {
3693
3890
  toolCallId,
3694
3891
  execute
3695
3892
  }) => {
3696
- const state = this.getState(callId);
3697
- 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);
3698
3895
  if (!toolSpan) return execute();
3699
3896
  return runWithParentSpanContext(
3700
3897
  {
3701
3898
  traceIdB64: toolSpan.ids.traceIdB64,
3702
3899
  spanIdB64: toolSpan.ids.spanIdB64,
3703
- eventId: state.eventId
3900
+ eventId: state2.eventId
3704
3901
  },
3705
3902
  () => execute()
3706
3903
  );
@@ -3749,35 +3946,35 @@ var RaindropTelemetryIntegration = class {
3749
3946
  activeDispatch() {
3750
3947
  var _a;
3751
3948
  const parentTool = getCurrentParentToolContext();
3752
- let state = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3949
+ let state2 = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3753
3950
  const inheritedEventId = (_a = getContextManager().getParentSpanIds()) == null ? void 0 : _a.eventId;
3754
- if (!state && inheritedEventId) {
3951
+ if (!state2 && inheritedEventId) {
3755
3952
  for (const candidate of this.callStates.values()) {
3756
3953
  if (candidate.eventId === inheritedEventId) {
3757
- state = candidate;
3954
+ state2 = candidate;
3758
3955
  break;
3759
3956
  }
3760
3957
  }
3761
3958
  }
3762
- if (!state) return void 0;
3959
+ if (!state2) return void 0;
3763
3960
  return {
3764
- eventId: state.eventId,
3765
- userId: state.identity.userId,
3766
- convoId: state.identity.convoId,
3767
- dispatchSpan: parentTool ? state.toolSpans.get(parentTool.toolCallId) : void 0,
3768
- 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(
3769
3966
  (span) => span !== void 0
3770
3967
  ),
3771
- recordInputs: state.recordInputs
3968
+ recordInputs: state2.recordInputs
3772
3969
  };
3773
3970
  }
3774
3971
  /** Spans still open for an event, so a late outcome can still be stated. */
3775
3972
  openSpansForEvent(eventId) {
3776
3973
  const spans = [];
3777
- for (const state of this.callStates.values()) {
3778
- if (state.eventId !== eventId) continue;
3779
- if (state.rootSpan) spans.push(state.rootSpan);
3780
- 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);
3781
3978
  }
3782
3979
  return spans;
3783
3980
  }
@@ -3797,10 +3994,10 @@ var RaindropTelemetryIntegration = class {
3797
3994
  * created from an LLM span with output, `ai.response.text` here would state
3798
3995
  * the run's outcome through the span while the turn is still working.
3799
3996
  */
3800
- abortOutcomeAttrs(state, reason, finishReason) {
3801
- if (!state.handoff || state.nestedInEvent) return [];
3997
+ abortOutcomeAttrs(state2, reason, finishReason) {
3998
+ if (!state2.handoff || state2.nestedInEvent) return [];
3802
3999
  return [
3803
- attrString("ai.response.text", capText2(state.accumulatedText || reason)),
4000
+ attrString("ai.response.text", capText2(state2.accumulatedText || reason)),
3804
4001
  attrString("ai.response.finishReason", finishReason)
3805
4002
  ];
3806
4003
  }
@@ -3814,19 +4011,19 @@ var RaindropTelemetryIntegration = class {
3814
4011
  spanParentRef(span) {
3815
4012
  return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
3816
4013
  }
3817
- emitLive(state, type, content, extra) {
4014
+ emitLive(state2, type, content, extra) {
3818
4015
  var _a, _b, _c, _d, _e, _f;
3819
- if (!localDebuggerEnabled() || !state.rootSpan) return;
3820
- const callMeta = this.extractRaindropMetadata(state.metadata);
4016
+ if (!localDebuggerEnabled() || !state2.rootSpan) return;
4017
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
3821
4018
  sendLocalDebuggerLiveEvent({
3822
- traceId: state.rootSpan.ids.traceIdB64,
4019
+ traceId: state2.rootSpan.ids.traceIdB64,
3823
4020
  type,
3824
4021
  content,
3825
4022
  metadata: {
3826
4023
  userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
3827
4024
  convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
3828
4025
  eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
3829
- eventId: state.eventId,
4026
+ eventId: state2.eventId,
3830
4027
  ...extra
3831
4028
  }
3832
4029
  });
@@ -3904,29 +4101,29 @@ var RaindropTelemetryIntegration = class {
3904
4101
  toolCallId: toolCall.toolCallId,
3905
4102
  toolName: toolCall.toolName
3906
4103
  });
3907
- const state = this.getState(event.callId);
3908
- state == null ? void 0 : state.parentContextToolCallIds.add(toolCall.toolCallId);
3909
- if (!(state == null ? void 0 : state.stepParent)) return;
3910
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
3911
- 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))] : [];
3912
4109
  const toolSpan = this.traceShipper.startSpan({
3913
4110
  name: "ai.toolCall",
3914
- parent: state.stepParent,
3915
- eventId: state.eventId,
3916
- ...state.identity,
4111
+ parent: state2.stepParent,
4112
+ eventId: state2.eventId,
4113
+ ...state2.identity,
3917
4114
  operationId: "ai.toolCall",
3918
4115
  attributes: [
3919
4116
  attrString("operation.name", operationName),
3920
4117
  attrString("resource.name", resourceName),
3921
- attrString("ai.telemetry.functionId", state.functionId),
4118
+ attrString("ai.telemetry.functionId", state2.functionId),
3922
4119
  attrString("ai.toolCall.name", toolCall.toolName),
3923
4120
  attrString("ai.toolCall.id", toolCall.toolCallId),
3924
4121
  ...inputAttrs,
3925
- ...handoffSpanAttrs(state.handoff)
4122
+ ...handoffSpanAttrs(state2.handoff)
3926
4123
  ]
3927
4124
  });
3928
- state.toolSpans.set(toolCall.toolCallId, toolSpan);
3929
- 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 });
3930
4127
  }
3931
4128
  toolExecutionEnd(event) {
3932
4129
  var _a;
@@ -3940,20 +4137,20 @@ var RaindropTelemetryIntegration = class {
3940
4137
  clearParentToolContext();
3941
4138
  }
3942
4139
  }
3943
- const state = this.getState(event.callId);
3944
- if (!state) return;
3945
- 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);
3946
4143
  if (!toolSpan) return;
3947
- state.toolCallCount += 1;
4144
+ state2.toolCallCount += 1;
3948
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 };
3949
4146
  if (outcome.success) {
3950
- const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4147
+ const outputAttrs = state2.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
3951
4148
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
3952
4149
  } else {
3953
4150
  this.traceShipper.endSpan(toolSpan, { error: outcome.error });
3954
4151
  }
3955
- this.emitLive(state, "tool_result", event.toolCall.toolName);
3956
- state.toolSpans.delete(event.toolCall.toolCallId);
4152
+ this.emitLive(state2, "tool_result", event.toolCall.toolName);
4153
+ state2.toolSpans.delete(event.toolCall.toolCallId);
3957
4154
  }
3958
4155
  // ── provider-executed tool calls ─────────────────────────────────────────
3959
4156
  //
@@ -3972,8 +4169,8 @@ var RaindropTelemetryIntegration = class {
3972
4169
  //
3973
4170
  // Client-executed tools are excluded (`providerExecuted` falsy) — they were
3974
4171
  // already spanned during execution, so this never double-emits.
3975
- emitProviderExecutedToolSpans(event, state) {
3976
- if (!state.stepParent) return;
4172
+ emitProviderExecutedToolSpans(event, state2) {
4173
+ if (!state2.stepParent) return;
3977
4174
  const content = Array.isArray(event.content) ? event.content : [];
3978
4175
  const providerToolCalls = content.filter(
3979
4176
  (part) => (part == null ? void 0 : part.type) === "tool-call" && part.providerExecuted === true
@@ -3986,42 +4183,42 @@ var RaindropTelemetryIntegration = class {
3986
4183
  }
3987
4184
  }
3988
4185
  for (const call of providerToolCalls) {
3989
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
3990
- 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))] : [];
3991
4188
  const toolSpan = this.traceShipper.startSpan({
3992
4189
  name: "ai.toolCall",
3993
- parent: state.stepParent,
3994
- eventId: state.eventId,
3995
- ...state.identity,
4190
+ parent: state2.stepParent,
4191
+ eventId: state2.eventId,
4192
+ ...state2.identity,
3996
4193
  operationId: "ai.toolCall",
3997
4194
  attributes: [
3998
4195
  attrString("operation.name", operationName),
3999
4196
  attrString("resource.name", resourceName),
4000
- attrString("ai.telemetry.functionId", state.functionId),
4197
+ attrString("ai.telemetry.functionId", state2.functionId),
4001
4198
  attrString("ai.toolCall.name", call.toolName),
4002
4199
  attrString("ai.toolCall.id", call.toolCallId),
4003
4200
  attrString("ai.toolCall.providerExecuted", "true"),
4004
4201
  ...inputAttrs,
4005
- ...handoffSpanAttrs(state.handoff)
4202
+ ...handoffSpanAttrs(state2.handoff)
4006
4203
  ]
4007
4204
  });
4008
- state.toolCallCount += 1;
4009
- 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 });
4010
4207
  const resultPart = resultsByCallId.get(call.toolCallId);
4011
4208
  if ((resultPart == null ? void 0 : resultPart.type) === "tool-error") {
4012
4209
  this.traceShipper.endSpan(toolSpan, { error: resultPart.error });
4013
4210
  } else {
4014
- 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))] : [];
4015
4212
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4016
4213
  }
4017
- this.emitLive(state, "tool_result", call.toolName);
4214
+ this.emitLive(state2, "tool_result", call.toolName);
4018
4215
  }
4019
4216
  }
4020
- finishGenerate(event, state) {
4217
+ finishGenerate(event, state2) {
4021
4218
  var _a, _b, _c, _d, _e, _f;
4022
- if (state.rootSpan) {
4219
+ if (state2.rootSpan) {
4023
4220
  const outputAttrs = [];
4024
- if (state.recordOutputs) {
4221
+ if (state2.recordOutputs) {
4025
4222
  outputAttrs.push(
4026
4223
  attrString("ai.response.finishReason", event.finishReason),
4027
4224
  attrString("ai.response.text", capText2((_a = event.text) != null ? _a : void 0)),
@@ -4062,12 +4259,12 @@ var RaindropTelemetryIntegration = class {
4062
4259
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens)
4063
4260
  );
4064
4261
  }
4065
- outputAttrs.push(attrInt("ai.toolCall.count", state.toolCallCount));
4066
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4262
+ outputAttrs.push(attrInt("ai.toolCall.count", state2.toolCallCount));
4263
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4067
4264
  }
4068
4265
  this.finalizeGenerateEvent(
4069
- state,
4070
- (_e = event.text) != null ? _e : state.accumulatedText || void 0,
4266
+ state2,
4267
+ (_e = event.text) != null ? _e : state2.accumulatedText || void 0,
4071
4268
  (_f = event.response) == null ? void 0 : _f.modelId,
4072
4269
  hasUnresolvedToolApproval(event)
4073
4270
  );
@@ -4083,29 +4280,29 @@ var RaindropTelemetryIntegration = class {
4083
4280
  * is finalized by that resume — otherwise each execution would finalize the
4084
4281
  * same event ID into a separate canonical row.
4085
4282
  */
4086
- finalizeGenerateEvent(state, output, model, keepPending = false, detachedOutcome) {
4283
+ finalizeGenerateEvent(state2, output, model, keepPending = false, detachedOutcome) {
4087
4284
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
4088
- const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
4285
+ const suppressSubagentEvent = state2.subagentName !== void 0 && state2.subagentToolCallSpan !== void 0;
4089
4286
  if (!this.sendEvents || suppressSubagentEvent) return;
4090
- if (this.subagents.wasSettledExplicitly(state.eventId)) return;
4091
- const callMeta = this.extractRaindropMetadata(state.metadata);
4287
+ if (this.subagents.wasSettledExplicitly(state2.eventId)) return;
4288
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
4092
4289
  const userId = (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId;
4093
4290
  if (!userId) return;
4094
- 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;
4095
4292
  const cappedOutput = capText2(output);
4096
- const reportedOutput = state.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4097
- 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);
4098
4295
  const properties = {
4099
4296
  ...(_f = this.defaultContext) == null ? void 0 : _f.properties,
4100
4297
  ...callMeta.properties,
4101
- ...state.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4298
+ ...state2.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4102
4299
  };
4103
4300
  const featureFlags = {
4104
4301
  ...((_g = this.defaultContext) == null ? void 0 : _g.featureFlags) ? normalizeFeatureFlags(this.defaultContext.featureFlags) : {},
4105
4302
  ...callMeta.featureFlags
4106
4303
  };
4107
4304
  const convoId = (_i = callMeta.convoId) != null ? _i : (_h = this.defaultContext) == null ? void 0 : _h.convoId;
4108
- void this.eventShipper.patch(state.eventId, {
4305
+ void this.eventShipper.patch(state2.eventId, {
4109
4306
  eventName,
4110
4307
  userId,
4111
4308
  convoId,
@@ -4123,12 +4320,12 @@ var RaindropTelemetryIntegration = class {
4123
4320
  }
4124
4321
  });
4125
4322
  }
4126
- finishEmbed(event, state) {
4323
+ finishEmbed(event, state2) {
4127
4324
  var _a;
4128
- if (!state.rootSpan) return;
4325
+ if (!state2.rootSpan) return;
4129
4326
  const outputAttrs = [];
4130
- const isMany = state.operationId === "ai.embedMany";
4131
- if (state.recordOutputs) {
4327
+ const isMany = state2.operationId === "ai.embedMany";
4328
+ if (state2.recordOutputs) {
4132
4329
  if (isMany) {
4133
4330
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embedding)));
4134
4331
  } else {
@@ -4138,7 +4335,7 @@ var RaindropTelemetryIntegration = class {
4138
4335
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
4139
4336
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
4140
4337
  }
4141
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4338
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4142
4339
  }
4143
4340
  };
4144
4341