@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,4 +1,66 @@
1
- // ../core/dist/chunk-3V4MIA75.js
1
+ // ../core/dist/chunk-BYBMRLZM.js
2
+ var EVAL_CORRELATION_ID_ATTRIBUTE = "raindrop.eval_correlation_id";
3
+ var PROBE_SCOPE = { correlationId: "" };
4
+ var EvalScopeStorage = class {
5
+ constructor() {
6
+ this._als = null;
7
+ this._probed = false;
8
+ }
9
+ maybeAdoptAsyncLocalStorage() {
10
+ if (this._probed) return;
11
+ this._probed = true;
12
+ try {
13
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
14
+ if (!Ctor) return;
15
+ const als = new Ctor();
16
+ als.run(PROBE_SCOPE, () => {
17
+ });
18
+ this._als = als;
19
+ } catch (e) {
20
+ this._als = null;
21
+ }
22
+ }
23
+ run(scope, callback) {
24
+ this.maybeAdoptAsyncLocalStorage();
25
+ if (this._als) return this._als.run(scope, callback);
26
+ const previous = this._syncScope;
27
+ this._syncScope = scope;
28
+ try {
29
+ return callback();
30
+ } finally {
31
+ this._syncScope = previous;
32
+ }
33
+ }
34
+ current() {
35
+ this.maybeAdoptAsyncLocalStorage();
36
+ if (this._als) return this._als.getStore();
37
+ return this._syncScope;
38
+ }
39
+ };
40
+ var EVAL_SCOPE_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.evalScopeStorage");
41
+ function evalScopeStorage() {
42
+ const holder = globalThis;
43
+ let storage = holder[EVAL_SCOPE_STORAGE_KEY];
44
+ if (!storage) {
45
+ storage = new EvalScopeStorage();
46
+ holder[EVAL_SCOPE_STORAGE_KEY] = storage;
47
+ }
48
+ return storage;
49
+ }
50
+ function currentEvalScope() {
51
+ try {
52
+ return evalScopeStorage().current();
53
+ } catch (e) {
54
+ return void 0;
55
+ }
56
+ }
57
+ function evalScopeAttributes() {
58
+ const scope = currentEvalScope();
59
+ if (!scope) return {};
60
+ return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
61
+ }
62
+
63
+ // ../core/dist/chunk-T53LQAH7.js
2
64
  function normalizeFeatureFlags(input) {
3
65
  if (Array.isArray(input)) {
4
66
  return Object.fromEntries(input.map((name) => [name, "true"]));
@@ -493,6 +555,7 @@ async function postJson(url, body, headers, opts) {
493
555
  const resp = await runWithTracingSuppressed(
494
556
  () => fetch(url, {
495
557
  method: "POST",
558
+ redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
496
559
  headers: {
497
560
  "Content-Type": "application/json",
498
561
  ...headers
@@ -616,6 +679,55 @@ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", se
616
679
  ]
617
680
  };
618
681
  }
682
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
683
+ function state() {
684
+ const holder = globalThis;
685
+ let current = holder[STATE_KEY];
686
+ if (!current) {
687
+ let storage = null;
688
+ try {
689
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
690
+ if (Ctor) storage = new Ctor();
691
+ } catch (e) {
692
+ storage = null;
693
+ }
694
+ current = {
695
+ storage,
696
+ syncDestination: void 0,
697
+ spanDestinations: /* @__PURE__ */ new WeakMap()
698
+ };
699
+ holder[STATE_KEY] = current;
700
+ }
701
+ return current;
702
+ }
703
+ function currentReplayTraceDestination() {
704
+ var _a, _b;
705
+ const routing = state();
706
+ return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
707
+ }
708
+ function rememberReplayTraceDestination(span) {
709
+ const destination = currentReplayTraceDestination();
710
+ if (destination) state().spanDestinations.set(span, destination);
711
+ }
712
+ function copyReplayTraceDestination(source, target) {
713
+ const destination = state().spanDestinations.get(source);
714
+ if (destination) state().spanDestinations.set(target, destination);
715
+ }
716
+ function replayTraceDestinationFor(value) {
717
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
718
+ return void 0;
719
+ }
720
+ return state().spanDestinations.get(value);
721
+ }
722
+ function recordReplayExportedSpan(destination, spanId, traceId) {
723
+ var _a, _b;
724
+ if (!destination || !spanId || !traceId) return;
725
+ (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
726
+ (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
727
+ }
728
+ function replayTraceUrl(baseUrl) {
729
+ return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
730
+ }
619
731
  var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
620
732
  var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
621
733
  var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
@@ -681,31 +793,36 @@ function resolveLocalDebuggerBaseUrl(baseUrl) {
681
793
  function localDebuggerEnabled(baseUrl) {
682
794
  return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
683
795
  }
796
+ var LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS = 2e3;
684
797
  function mirrorTraceExportToLocalDebugger(body, options = {}) {
685
798
  var _a;
686
799
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
687
- if (!baseUrl) return;
688
- void postJson(`${baseUrl}traces`, body, {}, {
800
+ if (!baseUrl) return Promise.resolve();
801
+ return postJson(`${baseUrl}traces`, body, {}, {
689
802
  maxAttempts: 1,
690
803
  debug: (_a = options.debug) != null ? _a : false,
691
- sdkName: options.sdkName
804
+ sdkName: options.sdkName,
805
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
692
806
  }).catch(() => {
693
807
  });
694
808
  }
695
809
  function mirrorPartialEventToLocalDebugger(event, options = {}) {
696
810
  var _a;
697
811
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
698
- if (!baseUrl) return;
812
+ if (!baseUrl) return Promise.resolve();
699
813
  const headers = options.writeKey ? { Authorization: `Bearer ${options.writeKey}` } : {};
700
- void postJson(`${baseUrl}events/track_partial`, event, headers, {
814
+ return postJson(`${baseUrl}events/track_partial`, event, headers, {
701
815
  maxAttempts: 1,
702
816
  debug: (_a = options.debug) != null ? _a : false,
703
- sdkName: options.sdkName
817
+ sdkName: options.sdkName,
818
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
704
819
  }).catch(() => {
705
820
  });
706
821
  }
707
822
  function sendLocalDebuggerLiveEvent(event, options = {}) {
708
823
  var _a, _b;
824
+ const destination = currentReplayTraceDestination();
825
+ if (destination && destination.kind !== "workshop") return;
709
826
  const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
710
827
  if (!baseUrl) return;
711
828
  void postJson(
@@ -877,6 +994,15 @@ var EventShipper = class {
877
994
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
878
995
  if (!this.enabled) return;
879
996
  if (!eventId || !eventId.trim()) return;
997
+ const capturedSticky = this.sticky.get(eventId);
998
+ const eventAlreadyKnown = capturedSticky !== void 0 || this.buffers.has(eventId);
999
+ const destination = currentReplayTraceDestination();
1000
+ const cloudReplay = destination !== void 0 && destination.kind !== "workshop";
1001
+ if ((capturedSticky == null ? void 0 : capturedSticky.replayOnly) === true || !eventAlreadyKnown && cloudReplay) {
1002
+ if (patch.isPending === false) this.sticky.delete(eventId);
1003
+ else this.sticky.set(eventId, { ...capturedSticky, replayOnly: true });
1004
+ return;
1005
+ }
880
1006
  const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
881
1007
  if (typeof patch.input === "string" && patch.input.length > maxChars) {
882
1008
  patch = { ...patch, input: capText(patch.input, maxChars) };
@@ -935,6 +1061,9 @@ var EventShipper = class {
935
1061
  try {
936
1062
  for (const t of this.timers.values()) clearTimeout(t);
937
1063
  this.timers.clear();
1064
+ for (const [eventId, sticky] of this.sticky) {
1065
+ if (sticky.replayOnly) this.sticky.delete(eventId);
1066
+ }
938
1067
  const settled = await raceWithTimeout(this.flush(), SHUTDOWN_DEADLINE_MS);
939
1068
  if (!settled) this.warnShutdownDrop("in-flight request(s) at shutdown");
940
1069
  } finally {
@@ -944,6 +1073,8 @@ var EventShipper = class {
944
1073
  async trackSignal(signal) {
945
1074
  var _a, _b;
946
1075
  if (!this.enabled) return;
1076
+ const destination = currentReplayTraceDestination();
1077
+ if (destination && destination.kind !== "workshop") return;
947
1078
  const body = [
948
1079
  {
949
1080
  event_id: signal.eventId,
@@ -978,6 +1109,8 @@ var EventShipper = class {
978
1109
  }
979
1110
  async identify(users) {
980
1111
  if (!this.enabled) return;
1112
+ const destination = currentReplayTraceDestination();
1113
+ if (destination && destination.kind !== "workshop") return;
981
1114
  const list = Array.isArray(users) ? users : [users];
982
1115
  const body = list.filter((user) => {
983
1116
  if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
@@ -1030,8 +1163,9 @@ var EventShipper = class {
1030
1163
  this.buffers.delete(eventId);
1031
1164
  if (!accumulated) return;
1032
1165
  const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
1033
- const eventName = (_c = (_b = accumulated.eventName) != null ? _b : sticky.eventName) != null ? _c : this.defaultEventName;
1034
- const userId = (_d = accumulated.userId) != null ? _d : sticky.userId;
1166
+ const isPending = (_c = (_b = accumulated.isPending) != null ? _b : sticky.isPending) != null ? _c : true;
1167
+ const eventName = (_e = (_d = accumulated.eventName) != null ? _d : sticky.eventName) != null ? _e : this.defaultEventName;
1168
+ const userId = (_f = accumulated.userId) != null ? _f : sticky.userId;
1035
1169
  if (!userId) {
1036
1170
  if (this.debug) {
1037
1171
  console.warn(`${this.prefix} skipping track_partial for ${eventId}: missing userId`);
@@ -1039,14 +1173,13 @@ var EventShipper = class {
1039
1173
  this.sticky.delete(eventId);
1040
1174
  return;
1041
1175
  }
1042
- const { wizardSession, ...restProperties } = (_e = accumulated.properties) != null ? _e : {};
1176
+ const { wizardSession, ...restProperties } = (_g = accumulated.properties) != null ? _g : {};
1043
1177
  let telemetryProperties = {};
1044
1178
  try {
1045
1179
  telemetryProperties = eventTelemetryProperties(accumulated);
1046
1180
  } catch (e) {
1047
1181
  }
1048
- const convoId = (_f = accumulated.convoId) != null ? _f : sticky.convoId;
1049
- const isPending = (_h = (_g = accumulated.isPending) != null ? _g : sticky.isPending) != null ? _h : true;
1182
+ const convoId = (_h = accumulated.convoId) != null ? _h : sticky.convoId;
1050
1183
  const payload = {
1051
1184
  event_id: eventId,
1052
1185
  user_id: userId,
@@ -1088,29 +1221,30 @@ var EventShipper = class {
1088
1221
  endpoint: url
1089
1222
  });
1090
1223
  }
1091
- if (this.localDebuggerUrl) {
1092
- mirrorPartialEventToLocalDebugger(payload, {
1093
- baseUrl: this.localDebuggerUrl,
1094
- writeKey: this.writeKey,
1095
- debug: this.debug,
1096
- sdkName: this.sdkName
1097
- });
1098
- }
1224
+ const mirror = this.localDebuggerUrl ? mirrorPartialEventToLocalDebugger(payload, {
1225
+ baseUrl: this.localDebuggerUrl,
1226
+ writeKey: this.writeKey,
1227
+ debug: this.debug,
1228
+ sdkName: this.sdkName
1229
+ }) : void 0;
1099
1230
  if (!this.writeKey) {
1100
1231
  if (!isPending) this.sticky.delete(eventId);
1232
+ if (mirror) await mirror;
1101
1233
  return;
1102
1234
  }
1103
1235
  const opts = this.requestOpts();
1104
1236
  if (!opts) {
1105
1237
  this.warnShutdownDrop(`track_partial ${eventId}`);
1106
1238
  if (!isPending) this.sticky.delete(eventId);
1239
+ if (mirror) await mirror;
1107
1240
  return;
1108
1241
  }
1109
1242
  const p = postJson(url, payload, this.requestHeaders(), opts);
1110
- this.inFlight.add(p);
1243
+ const combined = mirror ? Promise.all([mirror, p]).then(() => void 0) : p;
1244
+ this.inFlight.add(combined);
1111
1245
  try {
1112
1246
  try {
1113
- await p;
1247
+ await combined;
1114
1248
  if (this.debug) {
1115
1249
  console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
1116
1250
  }
@@ -1122,7 +1256,7 @@ var EventShipper = class {
1122
1256
  );
1123
1257
  }
1124
1258
  } finally {
1125
- this.inFlight.delete(p);
1259
+ this.inFlight.delete(combined);
1126
1260
  }
1127
1261
  if (!isPending) {
1128
1262
  this.sticky.delete(eventId);
@@ -1470,7 +1604,10 @@ var TraceShipper = class {
1470
1604
  try {
1471
1605
  const result = this.transformSpanHook(current);
1472
1606
  if (result === null) return null;
1473
- if (result !== void 0) current = result;
1607
+ if (result !== void 0) {
1608
+ copyReplayTraceDestination(current, result);
1609
+ current = result;
1610
+ }
1474
1611
  } catch (err) {
1475
1612
  if (this.debug) {
1476
1613
  const msg = err instanceof Error ? err.message : String(err);
@@ -1480,13 +1617,19 @@ var TraceShipper = class {
1480
1617
  }
1481
1618
  }
1482
1619
  try {
1483
- current = normalizeModelUsageSpan(current);
1620
+ const normalized = normalizeModelUsageSpan(current);
1621
+ copyReplayTraceDestination(current, normalized);
1622
+ current = normalized;
1484
1623
  } catch (e) {
1485
1624
  }
1486
1625
  if (!this.disableDefaultRedaction) {
1487
- current = defaultTransformSpan(current);
1626
+ const redacted = defaultTransformSpan(current);
1627
+ copyReplayTraceDestination(current, redacted);
1628
+ current = redacted;
1488
1629
  }
1489
- return this.capSpanAttributes(current);
1630
+ const capped = this.capSpanAttributes(current);
1631
+ copyReplayTraceDestination(current, capped);
1632
+ return capped;
1490
1633
  }
1491
1634
  isDebugEnabled() {
1492
1635
  return this.debug;
@@ -1504,33 +1647,54 @@ var TraceShipper = class {
1504
1647
  const attrs = [
1505
1648
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1506
1649
  ...identityAttrs(args),
1507
- attrString("ai.operationId", args.operationId)
1650
+ attrString("ai.operationId", args.operationId),
1651
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1508
1652
  ];
1509
1653
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
1510
- const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
1511
- this.mirrorToLocalDebugger(
1512
- buildOtlpSpan({
1513
- ids: span.ids,
1514
- name: span.name,
1515
- startTimeUnixNano: span.startTimeUnixNano,
1516
- endTimeUnixNano: span.startTimeUnixNano,
1517
- // placeholder — will be updated on endSpan
1518
- attributes: span.attributes,
1519
- status: { code: SpanStatusCode.UNSET }
1520
- })
1521
- );
1654
+ const span = {
1655
+ ids,
1656
+ name: args.name,
1657
+ startTimeUnixNano: started,
1658
+ attributes: attrs
1659
+ };
1660
+ rememberReplayTraceDestination(span);
1661
+ const openSpan = buildOtlpSpan({
1662
+ ids: span.ids,
1663
+ name: span.name,
1664
+ startTimeUnixNano: span.startTimeUnixNano,
1665
+ endTimeUnixNano: span.startTimeUnixNano,
1666
+ // placeholder — will be updated on endSpan
1667
+ attributes: span.attributes,
1668
+ status: { code: SpanStatusCode.UNSET }
1669
+ });
1670
+ copyReplayTraceDestination(span, openSpan);
1671
+ this.mirrorToLocalDebugger(openSpan);
1522
1672
  return span;
1523
1673
  }
1524
- mirrorToLocalDebugger(span) {
1525
- if (!this.localDebuggerUrl) return;
1674
+ mirrorToLocalDebugger(span, completed = false) {
1675
+ const destination = replayTraceDestinationFor(span);
1676
+ if (destination && destination.kind !== "workshop") return;
1677
+ const localDebuggerUrl = (destination == null ? void 0 : destination.kind) === "workshop" ? destination.url : this.localDebuggerUrl;
1678
+ if (!localDebuggerUrl) return;
1526
1679
  const redacted = this.redactSpan(span);
1527
1680
  if (redacted === null) return;
1681
+ if (completed && (destination == null ? void 0 : destination.kind) === "workshop") {
1682
+ recordReplayExportedSpan(
1683
+ destination,
1684
+ base64ToHex(redacted.spanId),
1685
+ base64ToHex(redacted.traceId)
1686
+ );
1687
+ }
1528
1688
  const body = buildExportTraceServiceRequest([redacted], this.serviceName, this.serviceVersion);
1529
- mirrorTraceExportToLocalDebugger(body, {
1530
- baseUrl: this.localDebuggerUrl,
1689
+ const p = mirrorTraceExportToLocalDebugger(body, {
1690
+ baseUrl: localDebuggerUrl,
1531
1691
  debug: false,
1532
1692
  sdkName: this.sdkName
1533
1693
  });
1694
+ this.inFlight.add(p);
1695
+ void p.finally(() => {
1696
+ this.inFlight.delete(p);
1697
+ });
1534
1698
  }
1535
1699
  endSpan(span, extra) {
1536
1700
  var _a, _b;
@@ -1552,15 +1716,17 @@ var TraceShipper = class {
1552
1716
  attributes: span.attributes,
1553
1717
  status
1554
1718
  });
1719
+ copyReplayTraceDestination(span, otlp);
1555
1720
  this.enqueue(otlp);
1556
- this.mirrorToLocalDebugger(otlp);
1721
+ this.mirrorToLocalDebugger(otlp, true);
1557
1722
  }
1558
1723
  createSpan(args) {
1559
1724
  var _a;
1560
1725
  const ids = createSpanIds(args.parent);
1561
1726
  const attrs = [
1562
1727
  attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1563
- ...identityAttrs(args)
1728
+ ...identityAttrs(args),
1729
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1564
1730
  ];
1565
1731
  if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
1566
1732
  const otlp = buildOtlpSpan({
@@ -1571,8 +1737,9 @@ var TraceShipper = class {
1571
1737
  attributes: attrs,
1572
1738
  status: args.status
1573
1739
  });
1740
+ rememberReplayTraceDestination(otlp);
1574
1741
  this.enqueue(otlp);
1575
- this.mirrorToLocalDebugger(otlp);
1742
+ this.mirrorToLocalDebugger(otlp, true);
1576
1743
  }
1577
1744
  enqueue(span) {
1578
1745
  if (!this.enabled) return;
@@ -1586,6 +1753,13 @@ var TraceShipper = class {
1586
1753
  }
1587
1754
  const redacted = this.redactSpan(span);
1588
1755
  if (redacted === null) return;
1756
+ const destination = replayTraceDestinationFor(redacted);
1757
+ recordReplayExportedSpan(
1758
+ destination,
1759
+ base64ToHex(redacted.spanId),
1760
+ base64ToHex(redacted.traceId)
1761
+ );
1762
+ if ((destination == null ? void 0 : destination.kind) === "workshop") return;
1589
1763
  if (this.queue.length >= this.maxQueueSize) {
1590
1764
  this.queue.shift();
1591
1765
  }
@@ -1604,47 +1778,67 @@ var TraceShipper = class {
1604
1778
  }
1605
1779
  }
1606
1780
  async flush() {
1607
- if (!this.enabled) return;
1781
+ var _a;
1782
+ if (!this.enabled) {
1783
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
1784
+ })));
1785
+ return;
1786
+ }
1608
1787
  if (this.timer) {
1609
1788
  clearTimeout(this.timer);
1610
1789
  this.timer = void 0;
1611
1790
  }
1612
1791
  while (this.queue.length > 0) {
1613
1792
  const batch = this.queue.splice(0, this.maxBatchSize);
1614
- if (!this.writeKey) continue;
1615
- const opts = this.requestOpts();
1616
- if (!opts) {
1617
- rateLimitedLog(
1618
- `${this.prefix}.shutdown_deadline`,
1619
- () => console.warn(
1620
- `${this.prefix} shutdown flush deadline exceeded; dropping ${batch.length} spans`
1621
- )
1622
- );
1623
- continue;
1793
+ const groups = /* @__PURE__ */ new Map();
1794
+ for (const span of batch) {
1795
+ const destination = replayTraceDestinationFor(span);
1796
+ const spans = groups.get(destination);
1797
+ if (spans) spans.push(span);
1798
+ else groups.set(destination, [span]);
1624
1799
  }
1625
- const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
1626
- const url = `${this.baseUrl}traces`;
1627
- if (this.debug) {
1628
- console.log(`${this.prefix} sending traces batch`, {
1629
- spans: batch.length,
1630
- endpoint: url
1631
- });
1632
- }
1633
- const p = postJson(url, body, this.requestHeaders(), opts);
1634
- this.inFlight.add(p);
1635
- try {
1636
- try {
1637
- await p;
1638
- if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
1639
- } catch (err) {
1640
- const msg = err instanceof Error ? err.message : String(err);
1800
+ for (const [destination, spans] of groups) {
1801
+ if (!destination && !this.writeKey) continue;
1802
+ if ((destination == null ? void 0 : destination.kind) === "workshop") continue;
1803
+ const opts = this.requestOpts();
1804
+ if (!opts) {
1641
1805
  rateLimitedLog(
1642
- `${this.prefix}.send_spans_failed`,
1643
- () => console.warn(`${this.prefix} failed to send ${batch.length} spans: ${msg}`)
1806
+ `${this.prefix}.shutdown_deadline`,
1807
+ () => console.warn(
1808
+ `${this.prefix} shutdown flush deadline exceeded; dropping ${spans.length} spans`
1809
+ )
1644
1810
  );
1811
+ continue;
1812
+ }
1813
+ const body = buildExportTraceServiceRequest(spans, this.serviceName, this.serviceVersion);
1814
+ const url = destination ? replayTraceUrl(destination.url) : `${this.baseUrl}traces`;
1815
+ const headers = destination ? {
1816
+ Authorization: `Bearer ${destination.apiKey}`,
1817
+ "X-Raindrop-Replay-Id": destination.replayId,
1818
+ "X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
1819
+ } : this.requestHeaders();
1820
+ if (this.debug) {
1821
+ console.log(`${this.prefix} sending traces batch`, {
1822
+ spans: spans.length,
1823
+ endpoint: url
1824
+ });
1825
+ }
1826
+ const p = postJson(url, body, headers, opts);
1827
+ this.inFlight.add(p);
1828
+ try {
1829
+ try {
1830
+ await p;
1831
+ if (this.debug) console.log(`${this.prefix} sent ${spans.length} spans`);
1832
+ } catch (err) {
1833
+ const msg = err instanceof Error ? err.message : String(err);
1834
+ rateLimitedLog(
1835
+ `${this.prefix}.send_spans_failed`,
1836
+ () => console.warn(`${this.prefix} failed to send ${spans.length} spans: ${msg}`)
1837
+ );
1838
+ }
1839
+ } finally {
1840
+ this.inFlight.delete(p);
1645
1841
  }
1646
- } finally {
1647
- this.inFlight.delete(p);
1648
1842
  }
1649
1843
  }
1650
1844
  }
@@ -1687,7 +1881,9 @@ var TraceShipper = class {
1687
1881
  if (!settled) {
1688
1882
  rateLimitedLog(
1689
1883
  `${this.prefix}.shutdown_deadline`,
1690
- () => console.warn(`${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`)
1884
+ () => console.warn(
1885
+ `${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`
1886
+ )
1691
1887
  );
1692
1888
  }
1693
1889
  } finally {
@@ -1782,7 +1978,8 @@ function withCurrent(span, callback) {
1782
1978
  return getContextManager().runInContext(span, callback);
1783
1979
  }
1784
1980
  async function getCurrentParentSpanContext() {
1785
- return getContextManager().getParentSpanIds();
1981
+ var _a, _b;
1982
+ return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
1786
1983
  }
1787
1984
  async function runWithParentSpanContext(ctx, fn) {
1788
1985
  const cm = getContextManager();
@@ -1816,7 +2013,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
1816
2013
  // package.json
1817
2014
  var package_default = {
1818
2015
  name: "@raindrop-ai/ai-sdk",
1819
- version: "0.3.1"};
2016
+ version: "0.3.2"};
1820
2017
 
1821
2018
  // src/internal/version.ts
1822
2019
  var libraryName = package_default.name;
@@ -3342,13 +3539,13 @@ var RaindropTelemetryIntegration = class {
3342
3539
  };
3343
3540
  // ── onStepStart ─────────────────────────────────────────────────────────
3344
3541
  this.onStepStart = (event) => {
3345
- const state = this.getState(event.callId);
3346
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3347
- const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
3348
- const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
3349
- const { operationName, resourceName } = opName(stepOperationId, state.functionId);
3542
+ const state2 = this.getState(event.callId);
3543
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3544
+ const isStream = state2.operationId === "ai.streamText" || state2.operationId === "ai.streamObject";
3545
+ const stepOperationId = isStream ? `${state2.operationId}.doStream` : `${state2.operationId}.doGenerate`;
3546
+ const { operationName, resourceName } = opName(stepOperationId, state2.functionId);
3350
3547
  const inputAttrs = [];
3351
- if (state.recordInputs) {
3548
+ if (state2.recordInputs) {
3352
3549
  if (event.promptMessages) {
3353
3550
  inputAttrs.push(attrString("ai.prompt.messages", safeJsonWithUint8(event.promptMessages)));
3354
3551
  }
@@ -3371,25 +3568,25 @@ var RaindropTelemetryIntegration = class {
3371
3568
  }
3372
3569
  const stepSpan = this.traceShipper.startSpan({
3373
3570
  name: stepOperationId,
3374
- parent: state.rootParent,
3375
- eventId: state.eventId,
3376
- ...state.identity,
3571
+ parent: state2.rootParent,
3572
+ eventId: state2.eventId,
3573
+ ...state2.identity,
3377
3574
  operationId: stepOperationId,
3378
3575
  attributes: [
3379
3576
  attrString("operation.name", operationName),
3380
3577
  attrString("resource.name", resourceName),
3381
- attrString("ai.telemetry.functionId", state.functionId),
3578
+ attrString("ai.telemetry.functionId", state2.functionId),
3382
3579
  ...attrsFromModelProvider(event.provider),
3383
3580
  attrString("ai.model.id", event.modelId),
3384
3581
  attrString(MODEL_USAGE_ATTRIBUTES.requestModel, event.modelId),
3385
3582
  ...inputAttrs,
3386
- ...handoffSpanAttrs(state.handoff)
3583
+ ...handoffSpanAttrs(state2.handoff)
3387
3584
  ]
3388
3585
  });
3389
- state.stepSpan = stepSpan;
3390
- state.stepParent = this.spanParentRef(stepSpan);
3391
- state.stepProvider = event.provider;
3392
- state.stepModelId = event.modelId;
3586
+ state2.stepSpan = stepSpan;
3587
+ state2.stepParent = this.spanParentRef(stepSpan);
3588
+ state2.stepProvider = event.provider;
3589
+ state2.stepModelId = event.modelId;
3393
3590
  };
3394
3591
  this.onToolExecutionStart = (event) => this.toolExecutionStart(event);
3395
3592
  this.onToolExecutionEnd = (event) => this.toolExecutionEnd(event);
@@ -3416,33 +3613,33 @@ var RaindropTelemetryIntegration = class {
3416
3613
  var _a, _b, _c, _d, _e;
3417
3614
  const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
3418
3615
  if (!callId) return;
3419
- const state = this.getState(callId);
3420
- if (!state) return;
3616
+ const state2 = this.getState(callId);
3617
+ if (!state2) return;
3421
3618
  const chunk = event.chunk;
3422
3619
  if (!chunk || typeof chunk !== "object") return;
3423
3620
  if (chunk.type === "text-delta") {
3424
3621
  const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
3425
3622
  if (typeof delta === "string") {
3426
- if (state.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3427
- state.accumulatedText += delta;
3623
+ if (state2.accumulatedText.length <= effectiveMaxTextFieldChars()) {
3624
+ state2.accumulatedText += delta;
3428
3625
  }
3429
- this.emitLive(state, "text_delta", delta);
3626
+ this.emitLive(state2, "text_delta", delta);
3430
3627
  }
3431
3628
  } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
3432
3629
  const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
3433
3630
  if (typeof text === "string") {
3434
- this.emitLive(state, "reasoning_delta", text);
3631
+ this.emitLive(state2, "reasoning_delta", text);
3435
3632
  }
3436
3633
  }
3437
3634
  };
3438
3635
  // ── onStepFinish ────────────────────────────────────────────────────────
3439
3636
  this.onStepFinish = (event) => {
3440
3637
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3441
- const state = this.getState(event.callId);
3442
- if (!(state == null ? void 0 : state.stepSpan)) return;
3443
- const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state.stepModelId;
3638
+ const state2 = this.getState(event.callId);
3639
+ if (!(state2 == null ? void 0 : state2.stepSpan)) return;
3640
+ const responseModelId = (_b = (_a = event.response) == null ? void 0 : _a.modelId) != null ? _b : state2.stepModelId;
3444
3641
  const outputAttrs = [];
3445
- if (state.recordOutputs) {
3642
+ if (state2.recordOutputs) {
3446
3643
  outputAttrs.push(
3447
3644
  attrString("ai.response.finishReason", event.finishReason),
3448
3645
  attrString("ai.response.text", capText2((_c = event.text) != null ? _c : void 0)),
@@ -3487,7 +3684,7 @@ var RaindropTelemetryIntegration = class {
3487
3684
  if (usage) {
3488
3685
  const usageMetrics = extractUsageMetricsFromUsage(
3489
3686
  usage,
3490
- state.stepProvider,
3687
+ state2.stepProvider,
3491
3688
  event.providerMetadata
3492
3689
  );
3493
3690
  outputAttrs.push(
@@ -3500,51 +3697,51 @@ var RaindropTelemetryIntegration = class {
3500
3697
  ...buildRawModelUsageAttributes(usageMetrics)
3501
3698
  );
3502
3699
  }
3503
- this.emitProviderExecutedToolSpans(event, state);
3504
- this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
3505
- state.stepSpan = void 0;
3506
- state.stepParent = void 0;
3507
- state.stepProvider = void 0;
3508
- state.stepModelId = void 0;
3700
+ this.emitProviderExecutedToolSpans(event, state2);
3701
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: outputAttrs });
3702
+ state2.stepSpan = void 0;
3703
+ state2.stepParent = void 0;
3704
+ state2.stepProvider = void 0;
3705
+ state2.stepModelId = void 0;
3509
3706
  };
3510
3707
  // ── onEmbedStart ────────────────────────────────────────────────────────
3511
3708
  this.onEmbedStart = (event) => {
3512
- const state = this.getState(event.callId);
3513
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
3514
- const { operationName, resourceName } = opName(event.operationId, state.functionId);
3515
- const inputAttrs = state.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3709
+ const state2 = this.getState(event.callId);
3710
+ if (!(state2 == null ? void 0 : state2.rootSpan) || !state2.rootParent) return;
3711
+ const { operationName, resourceName } = opName(event.operationId, state2.functionId);
3712
+ const inputAttrs = state2.recordInputs ? [attrString("ai.values", safeJsonWithUint8(event.values))] : [];
3516
3713
  const embedSpan = this.traceShipper.startSpan({
3517
3714
  name: event.operationId,
3518
- parent: state.rootParent,
3519
- eventId: state.eventId,
3520
- ...state.identity,
3715
+ parent: state2.rootParent,
3716
+ eventId: state2.eventId,
3717
+ ...state2.identity,
3521
3718
  operationId: event.operationId,
3522
3719
  attributes: [
3523
3720
  attrString("operation.name", operationName),
3524
3721
  attrString("resource.name", resourceName),
3525
- attrString("ai.telemetry.functionId", state.functionId),
3722
+ attrString("ai.telemetry.functionId", state2.functionId),
3526
3723
  ...inputAttrs,
3527
- ...handoffSpanAttrs(state.handoff)
3724
+ ...handoffSpanAttrs(state2.handoff)
3528
3725
  ]
3529
3726
  });
3530
- state.embedSpans.set(event.embedCallId, embedSpan);
3727
+ state2.embedSpans.set(event.embedCallId, embedSpan);
3531
3728
  };
3532
3729
  // ── onEmbedFinish ───────────────────────────────────────────────────────
3533
3730
  this.onEmbedFinish = (event) => {
3534
3731
  var _a;
3535
- const state = this.getState(event.callId);
3536
- if (!state) return;
3537
- const embedSpan = state.embedSpans.get(event.embedCallId);
3732
+ const state2 = this.getState(event.callId);
3733
+ if (!state2) return;
3734
+ const embedSpan = state2.embedSpans.get(event.embedCallId);
3538
3735
  if (!embedSpan) return;
3539
3736
  const outputAttrs = [];
3540
- if (state.recordOutputs) {
3737
+ if (state2.recordOutputs) {
3541
3738
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embeddings)));
3542
3739
  }
3543
3740
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
3544
3741
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
3545
3742
  }
3546
3743
  this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
3547
- state.embedSpans.delete(event.embedCallId);
3744
+ state2.embedSpans.delete(event.embedCallId);
3548
3745
  };
3549
3746
  // v7 canary.159 renamed `onEmbedFinish` -> `onEmbedEnd`. Both names forward
3550
3747
  // to the same implementation; the installed SDK only wires up whichever it
@@ -3552,16 +3749,16 @@ var RaindropTelemetryIntegration = class {
3552
3749
  this.onEmbedEnd = (event) => this.onEmbedFinish(event);
3553
3750
  // ── onFinish ────────────────────────────────────────────────────────────
3554
3751
  this.onFinish = (event) => {
3555
- const state = this.getState(event.callId);
3556
- if (!state) return;
3557
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3752
+ const state2 = this.getState(event.callId);
3753
+ if (!state2) return;
3754
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3558
3755
  if (isEmbed) {
3559
- this.finishEmbed(event, state);
3756
+ this.finishEmbed(event, state2);
3560
3757
  } else {
3561
- this.finishGenerate(event, state);
3758
+ this.finishGenerate(event, state2);
3562
3759
  }
3563
- if (state.subagentToolCallSpan) {
3564
- this.traceShipper.endSpan(state.subagentToolCallSpan);
3760
+ if (state2.subagentToolCallSpan) {
3761
+ this.traceShipper.endSpan(state2.subagentToolCallSpan);
3565
3762
  }
3566
3763
  this.cleanup(event.callId);
3567
3764
  };
@@ -3576,42 +3773,42 @@ var RaindropTelemetryIntegration = class {
3576
3773
  var _a;
3577
3774
  const event = error;
3578
3775
  if (!(event == null ? void 0 : event.callId)) return;
3579
- const state = this.getState(event.callId);
3580
- if (!state) return;
3776
+ const state2 = this.getState(event.callId);
3777
+ if (!state2) return;
3581
3778
  const actualError = (_a = event.error) != null ? _a : error;
3582
- if (state.stepSpan) {
3583
- this.traceShipper.endSpan(state.stepSpan, { error: actualError });
3584
- state.stepProvider = void 0;
3585
- state.stepModelId = void 0;
3779
+ if (state2.stepSpan) {
3780
+ this.traceShipper.endSpan(state2.stepSpan, { error: actualError });
3781
+ state2.stepProvider = void 0;
3782
+ state2.stepModelId = void 0;
3586
3783
  }
3587
- for (const embedSpan of state.embedSpans.values()) {
3784
+ for (const embedSpan of state2.embedSpans.values()) {
3588
3785
  this.traceShipper.endSpan(embedSpan, { error: actualError });
3589
3786
  }
3590
- state.embedSpans.clear();
3591
- for (const toolCallId of state.parentContextToolCallIds) {
3787
+ state2.embedSpans.clear();
3788
+ for (const toolCallId of state2.parentContextToolCallIds) {
3592
3789
  this.priorParentContexts.delete(toolCallId);
3593
3790
  }
3594
- state.parentContextToolCallIds.clear();
3595
- for (const toolSpan of state.toolSpans.values()) {
3791
+ state2.parentContextToolCallIds.clear();
3792
+ for (const toolSpan of state2.toolSpans.values()) {
3596
3793
  this.traceShipper.endSpan(toolSpan, { error: actualError });
3597
3794
  }
3598
- state.toolSpans.clear();
3795
+ state2.toolSpans.clear();
3599
3796
  const abortReason = describeAbortReason(actualError);
3600
- if (state.rootSpan) {
3601
- this.traceShipper.endSpan(state.rootSpan, {
3797
+ if (state2.rootSpan) {
3798
+ this.traceShipper.endSpan(state2.rootSpan, {
3602
3799
  error: actualError,
3603
- attributes: this.abortOutcomeAttrs(state, abortReason, "error")
3800
+ attributes: this.abortOutcomeAttrs(state2, abortReason, "error")
3604
3801
  });
3605
3802
  }
3606
- if (state.subagentToolCallSpan) {
3607
- this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
3803
+ if (state2.subagentToolCallSpan) {
3804
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, { error: actualError });
3608
3805
  }
3609
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3806
+ const isEmbed = state2.operationId === "ai.embed" || state2.operationId === "ai.embedMany";
3610
3807
  if (!isEmbed) {
3611
- const errorIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3808
+ const errorIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3612
3809
  this.finalizeGenerateEvent(
3613
- state,
3614
- state.accumulatedText || void 0,
3810
+ state2,
3811
+ state2.accumulatedText || void 0,
3615
3812
  void 0,
3616
3813
  false,
3617
3814
  errorIsTheRunsOutcome ? { fallbackOutput: abortReason } : void 0
@@ -3630,51 +3827,51 @@ var RaindropTelemetryIntegration = class {
3630
3827
  this.onAbort = (event) => {
3631
3828
  const callId = event == null ? void 0 : event.callId;
3632
3829
  if (!callId) return;
3633
- const state = this.getState(callId);
3634
- if (!state) return;
3830
+ const state2 = this.getState(callId);
3831
+ if (!state2) return;
3635
3832
  const abortedAttr = attrString("ai.response.aborted", "true");
3636
- if (state.stepSpan) {
3637
- this.traceShipper.endSpan(state.stepSpan, { attributes: [abortedAttr] });
3638
- state.stepSpan = void 0;
3639
- state.stepParent = void 0;
3640
- state.stepProvider = void 0;
3641
- state.stepModelId = void 0;
3833
+ if (state2.stepSpan) {
3834
+ this.traceShipper.endSpan(state2.stepSpan, { attributes: [abortedAttr] });
3835
+ state2.stepSpan = void 0;
3836
+ state2.stepParent = void 0;
3837
+ state2.stepProvider = void 0;
3838
+ state2.stepModelId = void 0;
3642
3839
  }
3643
- for (const embedSpan of state.embedSpans.values()) {
3840
+ for (const embedSpan of state2.embedSpans.values()) {
3644
3841
  this.traceShipper.endSpan(embedSpan, { attributes: [abortedAttr] });
3645
3842
  }
3646
- state.embedSpans.clear();
3647
- for (const toolCallId of state.parentContextToolCallIds) {
3843
+ state2.embedSpans.clear();
3844
+ for (const toolCallId of state2.parentContextToolCallIds) {
3648
3845
  this.priorParentContexts.delete(toolCallId);
3649
3846
  }
3650
- state.parentContextToolCallIds.clear();
3651
- for (const toolSpan of state.toolSpans.values()) {
3847
+ state2.parentContextToolCallIds.clear();
3848
+ for (const toolSpan of state2.toolSpans.values()) {
3652
3849
  this.traceShipper.endSpan(toolSpan, { attributes: [abortedAttr] });
3653
3850
  }
3654
- state.toolSpans.clear();
3655
- const abortIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3656
- if (state.rootSpan) {
3657
- this.traceShipper.endSpan(state.rootSpan, {
3851
+ state2.toolSpans.clear();
3852
+ const abortIsTheRunsOutcome = state2.handoff !== void 0 && !state2.nestedInEvent;
3853
+ if (state2.rootSpan) {
3854
+ this.traceShipper.endSpan(state2.rootSpan, {
3658
3855
  attributes: [
3659
3856
  abortedAttr,
3660
- attrInt("ai.toolCall.count", state.toolCallCount),
3857
+ attrInt("ai.toolCall.count", state2.toolCallCount),
3661
3858
  // An aborted detached child IS a cancelled sub-agent, and a cancelled
3662
3859
  // run is span-for-span identical to a finished one — spans close,
3663
3860
  // nothing errors, there is just no answer. So it is the one outcome
3664
3861
  // that has to be stated, and the child states it on itself.
3665
3862
  ...abortIsTheRunsOutcome ? cancelledSpanAttrs() : [],
3666
- ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3863
+ ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state2, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3667
3864
  ]
3668
3865
  });
3669
3866
  }
3670
- if (state.subagentToolCallSpan) {
3671
- this.traceShipper.endSpan(state.subagentToolCallSpan, {
3867
+ if (state2.subagentToolCallSpan) {
3868
+ this.traceShipper.endSpan(state2.subagentToolCallSpan, {
3672
3869
  attributes: [abortedAttr]
3673
3870
  });
3674
3871
  }
3675
3872
  this.finalizeGenerateEvent(
3676
- state,
3677
- state.accumulatedText || void 0,
3873
+ state2,
3874
+ state2.accumulatedText || void 0,
3678
3875
  void 0,
3679
3876
  false,
3680
3877
  abortIsTheRunsOutcome ? {
@@ -3682,7 +3879,7 @@ var RaindropTelemetryIntegration = class {
3682
3879
  properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
3683
3880
  } : void 0
3684
3881
  );
3685
- if (abortIsTheRunsOutcome) this.subagents.noteSettled(state.eventId);
3882
+ if (abortIsTheRunsOutcome) this.subagents.noteSettled(state2.eventId);
3686
3883
  this.cleanup(callId);
3687
3884
  };
3688
3885
  // ── executeTool ─────────────────────────────────────────────────────────
@@ -3691,14 +3888,14 @@ var RaindropTelemetryIntegration = class {
3691
3888
  toolCallId,
3692
3889
  execute
3693
3890
  }) => {
3694
- const state = this.getState(callId);
3695
- const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
3891
+ const state2 = this.getState(callId);
3892
+ const toolSpan = state2 == null ? void 0 : state2.toolSpans.get(toolCallId);
3696
3893
  if (!toolSpan) return execute();
3697
3894
  return runWithParentSpanContext(
3698
3895
  {
3699
3896
  traceIdB64: toolSpan.ids.traceIdB64,
3700
3897
  spanIdB64: toolSpan.ids.spanIdB64,
3701
- eventId: state.eventId
3898
+ eventId: state2.eventId
3702
3899
  },
3703
3900
  () => execute()
3704
3901
  );
@@ -3747,35 +3944,35 @@ var RaindropTelemetryIntegration = class {
3747
3944
  activeDispatch() {
3748
3945
  var _a;
3749
3946
  const parentTool = getCurrentParentToolContext();
3750
- let state = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3947
+ let state2 = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3751
3948
  const inheritedEventId = (_a = getContextManager().getParentSpanIds()) == null ? void 0 : _a.eventId;
3752
- if (!state && inheritedEventId) {
3949
+ if (!state2 && inheritedEventId) {
3753
3950
  for (const candidate of this.callStates.values()) {
3754
3951
  if (candidate.eventId === inheritedEventId) {
3755
- state = candidate;
3952
+ state2 = candidate;
3756
3953
  break;
3757
3954
  }
3758
3955
  }
3759
3956
  }
3760
- if (!state) return void 0;
3957
+ if (!state2) return void 0;
3761
3958
  return {
3762
- eventId: state.eventId,
3763
- userId: state.identity.userId,
3764
- convoId: state.identity.convoId,
3765
- dispatchSpan: parentTool ? state.toolSpans.get(parentTool.toolCallId) : void 0,
3766
- turnSpans: [state.rootSpan, state.stepSpan].filter(
3959
+ eventId: state2.eventId,
3960
+ userId: state2.identity.userId,
3961
+ convoId: state2.identity.convoId,
3962
+ dispatchSpan: parentTool ? state2.toolSpans.get(parentTool.toolCallId) : void 0,
3963
+ turnSpans: [state2.rootSpan, state2.stepSpan].filter(
3767
3964
  (span) => span !== void 0
3768
3965
  ),
3769
- recordInputs: state.recordInputs
3966
+ recordInputs: state2.recordInputs
3770
3967
  };
3771
3968
  }
3772
3969
  /** Spans still open for an event, so a late outcome can still be stated. */
3773
3970
  openSpansForEvent(eventId) {
3774
3971
  const spans = [];
3775
- for (const state of this.callStates.values()) {
3776
- if (state.eventId !== eventId) continue;
3777
- if (state.rootSpan) spans.push(state.rootSpan);
3778
- if (state.stepSpan) spans.push(state.stepSpan);
3972
+ for (const state2 of this.callStates.values()) {
3973
+ if (state2.eventId !== eventId) continue;
3974
+ if (state2.rootSpan) spans.push(state2.rootSpan);
3975
+ if (state2.stepSpan) spans.push(state2.stepSpan);
3779
3976
  }
3780
3977
  return spans;
3781
3978
  }
@@ -3795,10 +3992,10 @@ var RaindropTelemetryIntegration = class {
3795
3992
  * created from an LLM span with output, `ai.response.text` here would state
3796
3993
  * the run's outcome through the span while the turn is still working.
3797
3994
  */
3798
- abortOutcomeAttrs(state, reason, finishReason) {
3799
- if (!state.handoff || state.nestedInEvent) return [];
3995
+ abortOutcomeAttrs(state2, reason, finishReason) {
3996
+ if (!state2.handoff || state2.nestedInEvent) return [];
3800
3997
  return [
3801
- attrString("ai.response.text", capText2(state.accumulatedText || reason)),
3998
+ attrString("ai.response.text", capText2(state2.accumulatedText || reason)),
3802
3999
  attrString("ai.response.finishReason", finishReason)
3803
4000
  ];
3804
4001
  }
@@ -3812,19 +4009,19 @@ var RaindropTelemetryIntegration = class {
3812
4009
  spanParentRef(span) {
3813
4010
  return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
3814
4011
  }
3815
- emitLive(state, type, content, extra) {
4012
+ emitLive(state2, type, content, extra) {
3816
4013
  var _a, _b, _c, _d, _e, _f;
3817
- if (!localDebuggerEnabled() || !state.rootSpan) return;
3818
- const callMeta = this.extractRaindropMetadata(state.metadata);
4014
+ if (!localDebuggerEnabled() || !state2.rootSpan) return;
4015
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
3819
4016
  sendLocalDebuggerLiveEvent({
3820
- traceId: state.rootSpan.ids.traceIdB64,
4017
+ traceId: state2.rootSpan.ids.traceIdB64,
3821
4018
  type,
3822
4019
  content,
3823
4020
  metadata: {
3824
4021
  userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
3825
4022
  convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
3826
4023
  eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
3827
- eventId: state.eventId,
4024
+ eventId: state2.eventId,
3828
4025
  ...extra
3829
4026
  }
3830
4027
  });
@@ -3902,29 +4099,29 @@ var RaindropTelemetryIntegration = class {
3902
4099
  toolCallId: toolCall.toolCallId,
3903
4100
  toolName: toolCall.toolName
3904
4101
  });
3905
- const state = this.getState(event.callId);
3906
- state == null ? void 0 : state.parentContextToolCallIds.add(toolCall.toolCallId);
3907
- if (!(state == null ? void 0 : state.stepParent)) return;
3908
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
3909
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
4102
+ const state2 = this.getState(event.callId);
4103
+ state2 == null ? void 0 : state2.parentContextToolCallIds.add(toolCall.toolCallId);
4104
+ if (!(state2 == null ? void 0 : state2.stepParent)) return;
4105
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4106
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
3910
4107
  const toolSpan = this.traceShipper.startSpan({
3911
4108
  name: "ai.toolCall",
3912
- parent: state.stepParent,
3913
- eventId: state.eventId,
3914
- ...state.identity,
4109
+ parent: state2.stepParent,
4110
+ eventId: state2.eventId,
4111
+ ...state2.identity,
3915
4112
  operationId: "ai.toolCall",
3916
4113
  attributes: [
3917
4114
  attrString("operation.name", operationName),
3918
4115
  attrString("resource.name", resourceName),
3919
- attrString("ai.telemetry.functionId", state.functionId),
4116
+ attrString("ai.telemetry.functionId", state2.functionId),
3920
4117
  attrString("ai.toolCall.name", toolCall.toolName),
3921
4118
  attrString("ai.toolCall.id", toolCall.toolCallId),
3922
4119
  ...inputAttrs,
3923
- ...handoffSpanAttrs(state.handoff)
4120
+ ...handoffSpanAttrs(state2.handoff)
3924
4121
  ]
3925
4122
  });
3926
- state.toolSpans.set(toolCall.toolCallId, toolSpan);
3927
- this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
4123
+ state2.toolSpans.set(toolCall.toolCallId, toolSpan);
4124
+ this.emitLive(state2, "tool_start", toolCall.toolName, { args: toolCall.input });
3928
4125
  }
3929
4126
  toolExecutionEnd(event) {
3930
4127
  var _a;
@@ -3938,20 +4135,20 @@ var RaindropTelemetryIntegration = class {
3938
4135
  clearParentToolContext();
3939
4136
  }
3940
4137
  }
3941
- const state = this.getState(event.callId);
3942
- if (!state) return;
3943
- const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
4138
+ const state2 = this.getState(event.callId);
4139
+ if (!state2) return;
4140
+ const toolSpan = state2.toolSpans.get(event.toolCall.toolCallId);
3944
4141
  if (!toolSpan) return;
3945
- state.toolCallCount += 1;
4142
+ state2.toolCallCount += 1;
3946
4143
  const outcome = "toolOutput" in event ? event.toolOutput.type === "tool-result" ? { success: true, output: event.toolOutput.output } : { success: false, error: event.toolOutput.error } : event.success ? { success: true, output: event.output } : { success: false, error: event.error };
3947
4144
  if (outcome.success) {
3948
- const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
4145
+ const outputAttrs = state2.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(outcome.output))] : [];
3949
4146
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
3950
4147
  } else {
3951
4148
  this.traceShipper.endSpan(toolSpan, { error: outcome.error });
3952
4149
  }
3953
- this.emitLive(state, "tool_result", event.toolCall.toolName);
3954
- state.toolSpans.delete(event.toolCall.toolCallId);
4150
+ this.emitLive(state2, "tool_result", event.toolCall.toolName);
4151
+ state2.toolSpans.delete(event.toolCall.toolCallId);
3955
4152
  }
3956
4153
  // ── provider-executed tool calls ─────────────────────────────────────────
3957
4154
  //
@@ -3970,8 +4167,8 @@ var RaindropTelemetryIntegration = class {
3970
4167
  //
3971
4168
  // Client-executed tools are excluded (`providerExecuted` falsy) — they were
3972
4169
  // already spanned during execution, so this never double-emits.
3973
- emitProviderExecutedToolSpans(event, state) {
3974
- if (!state.stepParent) return;
4170
+ emitProviderExecutedToolSpans(event, state2) {
4171
+ if (!state2.stepParent) return;
3975
4172
  const content = Array.isArray(event.content) ? event.content : [];
3976
4173
  const providerToolCalls = content.filter(
3977
4174
  (part) => (part == null ? void 0 : part.type) === "tool-call" && part.providerExecuted === true
@@ -3984,42 +4181,42 @@ var RaindropTelemetryIntegration = class {
3984
4181
  }
3985
4182
  }
3986
4183
  for (const call of providerToolCalls) {
3987
- const { operationName, resourceName } = opName("ai.toolCall", state.functionId);
3988
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
4184
+ const { operationName, resourceName } = opName("ai.toolCall", state2.functionId);
4185
+ const inputAttrs = state2.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(call.input))] : [];
3989
4186
  const toolSpan = this.traceShipper.startSpan({
3990
4187
  name: "ai.toolCall",
3991
- parent: state.stepParent,
3992
- eventId: state.eventId,
3993
- ...state.identity,
4188
+ parent: state2.stepParent,
4189
+ eventId: state2.eventId,
4190
+ ...state2.identity,
3994
4191
  operationId: "ai.toolCall",
3995
4192
  attributes: [
3996
4193
  attrString("operation.name", operationName),
3997
4194
  attrString("resource.name", resourceName),
3998
- attrString("ai.telemetry.functionId", state.functionId),
4195
+ attrString("ai.telemetry.functionId", state2.functionId),
3999
4196
  attrString("ai.toolCall.name", call.toolName),
4000
4197
  attrString("ai.toolCall.id", call.toolCallId),
4001
4198
  attrString("ai.toolCall.providerExecuted", "true"),
4002
4199
  ...inputAttrs,
4003
- ...handoffSpanAttrs(state.handoff)
4200
+ ...handoffSpanAttrs(state2.handoff)
4004
4201
  ]
4005
4202
  });
4006
- state.toolCallCount += 1;
4007
- this.emitLive(state, "tool_start", call.toolName, { args: call.input });
4203
+ state2.toolCallCount += 1;
4204
+ this.emitLive(state2, "tool_start", call.toolName, { args: call.input });
4008
4205
  const resultPart = resultsByCallId.get(call.toolCallId);
4009
4206
  if ((resultPart == null ? void 0 : resultPart.type) === "tool-error") {
4010
4207
  this.traceShipper.endSpan(toolSpan, { error: resultPart.error });
4011
4208
  } else {
4012
- const outputAttrs = state.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4209
+ const outputAttrs = state2.recordOutputs && resultPart && "output" in resultPart ? [attrString("ai.toolCall.result", safeJsonWithUint8(resultPart.output))] : [];
4013
4210
  this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
4014
4211
  }
4015
- this.emitLive(state, "tool_result", call.toolName);
4212
+ this.emitLive(state2, "tool_result", call.toolName);
4016
4213
  }
4017
4214
  }
4018
- finishGenerate(event, state) {
4215
+ finishGenerate(event, state2) {
4019
4216
  var _a, _b, _c, _d, _e, _f;
4020
- if (state.rootSpan) {
4217
+ if (state2.rootSpan) {
4021
4218
  const outputAttrs = [];
4022
- if (state.recordOutputs) {
4219
+ if (state2.recordOutputs) {
4023
4220
  outputAttrs.push(
4024
4221
  attrString("ai.response.finishReason", event.finishReason),
4025
4222
  attrString("ai.response.text", capText2((_a = event.text) != null ? _a : void 0)),
@@ -4060,12 +4257,12 @@ var RaindropTelemetryIntegration = class {
4060
4257
  attrInt("ai.usage.cachedInputTokens", usageMetrics.cachedInputTokens)
4061
4258
  );
4062
4259
  }
4063
- outputAttrs.push(attrInt("ai.toolCall.count", state.toolCallCount));
4064
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4260
+ outputAttrs.push(attrInt("ai.toolCall.count", state2.toolCallCount));
4261
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4065
4262
  }
4066
4263
  this.finalizeGenerateEvent(
4067
- state,
4068
- (_e = event.text) != null ? _e : state.accumulatedText || void 0,
4264
+ state2,
4265
+ (_e = event.text) != null ? _e : state2.accumulatedText || void 0,
4069
4266
  (_f = event.response) == null ? void 0 : _f.modelId,
4070
4267
  hasUnresolvedToolApproval(event)
4071
4268
  );
@@ -4081,29 +4278,29 @@ var RaindropTelemetryIntegration = class {
4081
4278
  * is finalized by that resume — otherwise each execution would finalize the
4082
4279
  * same event ID into a separate canonical row.
4083
4280
  */
4084
- finalizeGenerateEvent(state, output, model, keepPending = false, detachedOutcome) {
4281
+ finalizeGenerateEvent(state2, output, model, keepPending = false, detachedOutcome) {
4085
4282
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
4086
- const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
4283
+ const suppressSubagentEvent = state2.subagentName !== void 0 && state2.subagentToolCallSpan !== void 0;
4087
4284
  if (!this.sendEvents || suppressSubagentEvent) return;
4088
- if (this.subagents.wasSettledExplicitly(state.eventId)) return;
4089
- const callMeta = this.extractRaindropMetadata(state.metadata);
4285
+ if (this.subagents.wasSettledExplicitly(state2.eventId)) return;
4286
+ const callMeta = this.extractRaindropMetadata(state2.metadata);
4090
4287
  const userId = (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId;
4091
4288
  if (!userId) return;
4092
- const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state.operationId;
4289
+ const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state2.operationId;
4093
4290
  const cappedOutput = capText2(output);
4094
- const reportedOutput = state.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4095
- const input = capText2(state.inputText);
4291
+ const reportedOutput = state2.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
4292
+ const input = capText2(state2.inputText);
4096
4293
  const properties = {
4097
4294
  ...(_f = this.defaultContext) == null ? void 0 : _f.properties,
4098
4295
  ...callMeta.properties,
4099
- ...state.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4296
+ ...state2.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
4100
4297
  };
4101
4298
  const featureFlags = {
4102
4299
  ...((_g = this.defaultContext) == null ? void 0 : _g.featureFlags) ? normalizeFeatureFlags(this.defaultContext.featureFlags) : {},
4103
4300
  ...callMeta.featureFlags
4104
4301
  };
4105
4302
  const convoId = (_i = callMeta.convoId) != null ? _i : (_h = this.defaultContext) == null ? void 0 : _h.convoId;
4106
- void this.eventShipper.patch(state.eventId, {
4303
+ void this.eventShipper.patch(state2.eventId, {
4107
4304
  eventName,
4108
4305
  userId,
4109
4306
  convoId,
@@ -4121,12 +4318,12 @@ var RaindropTelemetryIntegration = class {
4121
4318
  }
4122
4319
  });
4123
4320
  }
4124
- finishEmbed(event, state) {
4321
+ finishEmbed(event, state2) {
4125
4322
  var _a;
4126
- if (!state.rootSpan) return;
4323
+ if (!state2.rootSpan) return;
4127
4324
  const outputAttrs = [];
4128
- const isMany = state.operationId === "ai.embedMany";
4129
- if (state.recordOutputs) {
4325
+ const isMany = state2.operationId === "ai.embedMany";
4326
+ if (state2.recordOutputs) {
4130
4327
  if (isMany) {
4131
4328
  outputAttrs.push(attrString("ai.embeddings", safeJsonWithUint8(event.embedding)));
4132
4329
  } else {
@@ -4136,7 +4333,7 @@ var RaindropTelemetryIntegration = class {
4136
4333
  if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
4137
4334
  outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
4138
4335
  }
4139
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
4336
+ this.traceShipper.endSpan(state2.rootSpan, { attributes: outputAttrs });
4140
4337
  }
4141
4338
  };
4142
4339