@raindrop-ai/ai-sdk 0.0.19 → 0.0.21

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.
@@ -4,7 +4,7 @@ var async_hooks = require('async_hooks');
4
4
 
5
5
  // src/index.workers.ts
6
6
 
7
- // ../core/dist/chunk-H6VSZSLN.js
7
+ // ../core/dist/chunk-4UCYIEH4.js
8
8
  function getCrypto() {
9
9
  const c = globalThis.crypto;
10
10
  return c;
@@ -149,6 +149,7 @@ async function postJson(url, body, headers, opts) {
149
149
  );
150
150
  }
151
151
  var SpanStatusCode = {
152
+ UNSET: 0,
152
153
  ERROR: 2
153
154
  };
154
155
  function createSpanIds(parent) {
@@ -469,11 +470,66 @@ var EventShipper = class {
469
470
  }
470
471
  }
471
472
  };
473
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
474
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
475
+ var _a, _b, _c;
476
+ const resolved = (_b = baseUrl != null ? baseUrl : typeof process !== "undefined" ? (_a = process.env) == null ? void 0 : _a[LOCAL_DEBUGGER_ENV_VAR] : void 0) != null ? _b : null;
477
+ return resolved ? (_c = formatEndpoint(resolved)) != null ? _c : null : null;
478
+ }
479
+ function localDebuggerEnabled(baseUrl) {
480
+ return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
481
+ }
482
+ function normalizeLocalDebuggerLiveEventType(type) {
483
+ switch (type) {
484
+ case "text-delta":
485
+ return "text_delta";
486
+ case "reasoning":
487
+ case "reasoning-delta":
488
+ return "reasoning_delta";
489
+ case "tool-call":
490
+ return "tool_start";
491
+ case "tool-result":
492
+ return "tool_result";
493
+ default:
494
+ return type;
495
+ }
496
+ }
497
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
498
+ var _a;
499
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
500
+ if (!baseUrl) return;
501
+ void postJson(`${baseUrl}traces`, body, {}, {
502
+ maxAttempts: 1,
503
+ debug: (_a = options.debug) != null ? _a : false,
504
+ sdkName: options.sdkName
505
+ }).catch(() => {
506
+ });
507
+ }
508
+ function sendLocalDebuggerLiveEvent(event, options = {}) {
509
+ var _a, _b;
510
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
511
+ if (!baseUrl) return;
512
+ void postJson(
513
+ `${baseUrl}live`,
514
+ {
515
+ ...event,
516
+ type: normalizeLocalDebuggerLiveEventType(event.type),
517
+ timestamp: (_a = event.timestamp) != null ? _a : Date.now()
518
+ },
519
+ {},
520
+ {
521
+ maxAttempts: 1,
522
+ debug: (_b = options.debug) != null ? _b : false,
523
+ sdkName: options.sdkName
524
+ }
525
+ ).catch(() => {
526
+ });
527
+ }
472
528
  var TraceShipper = class {
473
529
  constructor(opts) {
474
530
  this.queue = [];
475
531
  this.inFlight = /* @__PURE__ */ new Set();
476
- var _a, _b, _c, _d, _e, _f, _g, _h;
532
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
477
533
  this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
478
534
  this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
479
535
  this.enabled = opts.enabled !== false;
@@ -486,6 +542,13 @@ var TraceShipper = class {
486
542
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
487
543
  this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
488
544
  this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
545
+ const localDebugger = typeof process !== "undefined" ? (_i = process.env) == null ? void 0 : _i.RAINDROP_LOCAL_DEBUGGER : void 0;
546
+ if (localDebugger) {
547
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(localDebugger)) != null ? _j : void 0;
548
+ if (this.debug) {
549
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
550
+ }
551
+ }
489
552
  }
490
553
  isDebugEnabled() {
491
554
  return this.debug;
@@ -502,7 +565,25 @@ var TraceShipper = class {
502
565
  attrString("ai.operationId", args.operationId)
503
566
  ];
504
567
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
505
- return { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
568
+ const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
569
+ if (this.localDebuggerUrl) {
570
+ const openSpan = buildOtlpSpan({
571
+ ids: span.ids,
572
+ name: span.name,
573
+ startTimeUnixNano: span.startTimeUnixNano,
574
+ endTimeUnixNano: span.startTimeUnixNano,
575
+ // placeholder — will be updated on endSpan
576
+ attributes: span.attributes,
577
+ status: { code: SpanStatusCode.UNSET }
578
+ });
579
+ const body = buildExportTraceServiceRequest([openSpan], this.serviceName, this.serviceVersion);
580
+ mirrorTraceExportToLocalDebugger(body, {
581
+ baseUrl: this.localDebuggerUrl,
582
+ debug: false,
583
+ sdkName: this.sdkName
584
+ });
585
+ }
586
+ return span;
506
587
  }
507
588
  endSpan(span, extra) {
508
589
  var _a, _b;
@@ -525,6 +606,14 @@ var TraceShipper = class {
525
606
  status
526
607
  });
527
608
  this.enqueue(otlp);
609
+ if (this.localDebuggerUrl) {
610
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
611
+ mirrorTraceExportToLocalDebugger(body, {
612
+ baseUrl: this.localDebuggerUrl,
613
+ debug: false,
614
+ sdkName: this.sdkName
615
+ });
616
+ }
528
617
  }
529
618
  createSpan(args) {
530
619
  var _a;
@@ -542,6 +631,14 @@ var TraceShipper = class {
542
631
  status: args.status
543
632
  });
544
633
  this.enqueue(otlp);
634
+ if (this.localDebuggerUrl) {
635
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
636
+ mirrorTraceExportToLocalDebugger(body, {
637
+ baseUrl: this.localDebuggerUrl,
638
+ debug: false,
639
+ sdkName: this.sdkName
640
+ });
641
+ }
545
642
  }
546
643
  enqueue(span) {
547
644
  if (!this.enabled) return;
@@ -737,7 +834,7 @@ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = async_hooks.AsyncLocalStorage;
737
834
  // package.json
738
835
  var package_default = {
739
836
  name: "@raindrop-ai/ai-sdk",
740
- version: "0.0.19"};
837
+ version: "0.0.21"};
741
838
 
742
839
  // src/internal/version.ts
743
840
  var libraryName = package_default.name;
@@ -756,19 +853,6 @@ var EventShipper2 = class extends EventShipper {
756
853
  }
757
854
  };
758
855
 
759
- // src/internal/traces.ts
760
- var TraceShipper2 = class extends TraceShipper {
761
- constructor(opts) {
762
- var _a, _b, _c;
763
- super({
764
- ...opts,
765
- sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
766
- serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
767
- serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
768
- });
769
- }
770
- };
771
-
772
856
  // src/internal/wrap/helpers.ts
773
857
  function isRecord(value) {
774
858
  return typeof value === "object" && value !== null;
@@ -1390,6 +1474,574 @@ function attrsFromGenAiRequest(options) {
1390
1474
  ];
1391
1475
  }
1392
1476
 
1477
+ // src/internal/raindrop-telemetry-integration.ts
1478
+ var RaindropTelemetryIntegration = class {
1479
+ constructor(opts) {
1480
+ this.callStates = /* @__PURE__ */ new Map();
1481
+ // ── onStart ─────────────────────────────────────────────────────────────
1482
+ this.onStart = (event) => {
1483
+ var _a, _b, _c, _d;
1484
+ if (event.isEnabled !== true) return;
1485
+ const isEmbed = event.operationId === "ai.embed" || event.operationId === "ai.embedMany";
1486
+ const recordInputs = event.recordInputs !== false;
1487
+ const recordOutputs = event.recordOutputs !== false;
1488
+ const functionId = event.functionId;
1489
+ const metadata = event.metadata;
1490
+ const callMeta = this.extractRaindropMetadata(metadata);
1491
+ const inherited = getContextManager().getParentSpanIds();
1492
+ const eventIdGenerated = (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === "true" || (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === true;
1493
+ const explicitEventId = callMeta.eventId && !eventIdGenerated ? callMeta.eventId : void 0;
1494
+ const eventId = (_d = (_c = (_b = explicitEventId != null ? explicitEventId : (_a = this.defaultContext) == null ? void 0 : _a.eventId) != null ? _b : inherited == null ? void 0 : inherited.eventId) != null ? _c : callMeta.eventId) != null ? _d : randomUUID();
1495
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1496
+ const { operationName, resourceName } = opName(
1497
+ event.operationId,
1498
+ functionId
1499
+ );
1500
+ let rootSpan;
1501
+ if (this.sendTraces) {
1502
+ const promptAttrs = !isEmbed && recordInputs ? [
1503
+ attrString(
1504
+ "ai.prompt",
1505
+ safeJsonWithUint8({
1506
+ system: event.system,
1507
+ prompt: event.prompt,
1508
+ messages: event.messages
1509
+ })
1510
+ )
1511
+ ] : [];
1512
+ const embedAttrs = isEmbed && recordInputs ? event.operationId === "ai.embedMany" ? [
1513
+ attrString(
1514
+ "ai.values",
1515
+ safeJsonWithUint8(event.value)
1516
+ )
1517
+ ] : [attrString("ai.value", safeJsonWithUint8(event.value))] : [];
1518
+ rootSpan = this.traceShipper.startSpan({
1519
+ name: event.operationId,
1520
+ parent: inheritedParent,
1521
+ eventId,
1522
+ operationId: event.operationId,
1523
+ attributes: [
1524
+ attrString("operation.name", operationName),
1525
+ attrString("resource.name", resourceName),
1526
+ attrString("ai.telemetry.functionId", functionId),
1527
+ attrString("ai.model.provider", event.provider),
1528
+ attrString("ai.model.id", event.modelId),
1529
+ // Filter out raindrop.eventId from metadata attrs since TraceShipper
1530
+ // already sets it via the eventId arg. Without this, eventMetadata()'s
1531
+ // auto-generated ID would duplicate and override the resolved one.
1532
+ ...attrsFromTelemetryMetadata(
1533
+ metadata ? Object.fromEntries(
1534
+ Object.entries(metadata).filter(
1535
+ ([k]) => k !== "raindrop.eventId" && k !== "raindrop.internal.eventIdGenerated"
1536
+ )
1537
+ ) : void 0
1538
+ ),
1539
+ ...promptAttrs,
1540
+ ...embedAttrs
1541
+ ]
1542
+ });
1543
+ }
1544
+ this.callStates.set(event.callId, {
1545
+ operationId: event.operationId,
1546
+ eventId,
1547
+ rootSpan,
1548
+ rootParent: rootSpan ? this.spanParentRef(rootSpan) : inheritedParent,
1549
+ stepSpan: void 0,
1550
+ stepParent: void 0,
1551
+ toolSpans: /* @__PURE__ */ new Map(),
1552
+ embedSpans: /* @__PURE__ */ new Map(),
1553
+ recordInputs,
1554
+ recordOutputs,
1555
+ functionId,
1556
+ metadata,
1557
+ accumulatedText: "",
1558
+ inputText: isEmbed ? void 0 : this.extractInputText(event),
1559
+ toolCallCount: 0
1560
+ });
1561
+ };
1562
+ // ── onStepStart ─────────────────────────────────────────────────────────
1563
+ this.onStepStart = (event) => {
1564
+ const state = this.getState(event.callId);
1565
+ if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1566
+ const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
1567
+ const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
1568
+ const { operationName, resourceName } = opName(
1569
+ stepOperationId,
1570
+ state.functionId
1571
+ );
1572
+ const inputAttrs = [];
1573
+ if (state.recordInputs) {
1574
+ if (event.promptMessages) {
1575
+ inputAttrs.push(
1576
+ attrString(
1577
+ "ai.prompt.messages",
1578
+ safeJsonWithUint8(event.promptMessages)
1579
+ )
1580
+ );
1581
+ }
1582
+ if (event.stepTools) {
1583
+ inputAttrs.push(
1584
+ attrStringArray(
1585
+ "ai.prompt.tools",
1586
+ event.stepTools.map((t) => JSON.stringify(t))
1587
+ )
1588
+ );
1589
+ }
1590
+ if (event.stepToolChoice != null) {
1591
+ inputAttrs.push(
1592
+ attrString(
1593
+ "ai.prompt.toolChoice",
1594
+ JSON.stringify(event.stepToolChoice)
1595
+ )
1596
+ );
1597
+ }
1598
+ }
1599
+ const stepSpan = this.traceShipper.startSpan({
1600
+ name: stepOperationId,
1601
+ parent: state.rootParent,
1602
+ eventId: state.eventId,
1603
+ operationId: stepOperationId,
1604
+ attributes: [
1605
+ attrString("operation.name", operationName),
1606
+ attrString("resource.name", resourceName),
1607
+ attrString("ai.telemetry.functionId", state.functionId),
1608
+ attrString("ai.model.provider", event.provider),
1609
+ attrString("ai.model.id", event.modelId),
1610
+ attrString("gen_ai.system", event.provider),
1611
+ attrString("gen_ai.request.model", event.modelId),
1612
+ ...inputAttrs
1613
+ ]
1614
+ });
1615
+ state.stepSpan = stepSpan;
1616
+ state.stepParent = this.spanParentRef(stepSpan);
1617
+ };
1618
+ // ── onToolCallStart ─────────────────────────────────────────────────────
1619
+ this.onToolCallStart = (event) => {
1620
+ const state = this.getState(event.callId);
1621
+ if (!(state == null ? void 0 : state.stepParent)) return;
1622
+ const { toolCall } = event;
1623
+ const { operationName, resourceName } = opName(
1624
+ "ai.toolCall",
1625
+ state.functionId
1626
+ );
1627
+ const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
1628
+ const toolSpan = this.traceShipper.startSpan({
1629
+ name: "ai.toolCall",
1630
+ parent: state.stepParent,
1631
+ eventId: state.eventId,
1632
+ operationId: "ai.toolCall",
1633
+ attributes: [
1634
+ attrString("operation.name", operationName),
1635
+ attrString("resource.name", resourceName),
1636
+ attrString("ai.telemetry.functionId", state.functionId),
1637
+ attrString("ai.toolCall.name", toolCall.toolName),
1638
+ attrString("ai.toolCall.id", toolCall.toolCallId),
1639
+ ...inputAttrs
1640
+ ]
1641
+ });
1642
+ state.toolSpans.set(toolCall.toolCallId, toolSpan);
1643
+ this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
1644
+ };
1645
+ // ── onToolCallFinish ────────────────────────────────────────────────────
1646
+ this.onToolCallFinish = (event) => {
1647
+ const state = this.getState(event.callId);
1648
+ if (!state) return;
1649
+ const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
1650
+ if (!toolSpan) return;
1651
+ state.toolCallCount += 1;
1652
+ if (event.success) {
1653
+ const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(event.output))] : [];
1654
+ this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
1655
+ } else {
1656
+ this.traceShipper.endSpan(toolSpan, { error: event.error });
1657
+ }
1658
+ this.emitLive(state, "tool_result", event.toolCall.toolName);
1659
+ state.toolSpans.delete(event.toolCall.toolCallId);
1660
+ };
1661
+ // ── onChunk (streaming) ─────────────────────────────────────────────────
1662
+ this.onChunk = (event) => {
1663
+ var _a, _b, _c, _d, _e;
1664
+ const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
1665
+ if (!callId) return;
1666
+ const state = this.getState(callId);
1667
+ if (!state) return;
1668
+ const chunk = event.chunk;
1669
+ if (!chunk || typeof chunk !== "object") return;
1670
+ if (chunk.type === "text-delta") {
1671
+ const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
1672
+ if (typeof delta === "string") {
1673
+ state.accumulatedText += delta;
1674
+ this.emitLive(state, "text_delta", delta);
1675
+ }
1676
+ } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
1677
+ const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
1678
+ if (typeof text === "string") {
1679
+ this.emitLive(state, "reasoning_delta", text);
1680
+ }
1681
+ }
1682
+ };
1683
+ // ── onStepFinish ────────────────────────────────────────────────────────
1684
+ this.onStepFinish = (event) => {
1685
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1686
+ const state = this.getState(event.callId);
1687
+ if (!(state == null ? void 0 : state.stepSpan)) return;
1688
+ const outputAttrs = [];
1689
+ if (state.recordOutputs) {
1690
+ outputAttrs.push(
1691
+ attrString("ai.response.finishReason", event.finishReason),
1692
+ attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1693
+ attrString("ai.response.id", (_b = event.response) == null ? void 0 : _b.id),
1694
+ attrString("ai.response.model", (_c = event.response) == null ? void 0 : _c.modelId),
1695
+ attrString(
1696
+ "ai.response.timestamp",
1697
+ ((_d = event.response) == null ? void 0 : _d.timestamp) instanceof Date ? event.response.timestamp.toISOString() : (_e = event.response) == null ? void 0 : _e.timestamp
1698
+ ),
1699
+ attrString(
1700
+ "ai.response.providerMetadata",
1701
+ event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1702
+ )
1703
+ );
1704
+ if (((_f = event.toolCalls) == null ? void 0 : _f.length) > 0) {
1705
+ outputAttrs.push(
1706
+ attrString(
1707
+ "ai.response.toolCalls",
1708
+ JSON.stringify(
1709
+ event.toolCalls.map((tc) => ({
1710
+ toolCallId: tc.toolCallId,
1711
+ toolName: tc.toolName,
1712
+ input: tc.input
1713
+ }))
1714
+ )
1715
+ )
1716
+ );
1717
+ }
1718
+ if (((_g = event.reasoning) == null ? void 0 : _g.length) > 0) {
1719
+ const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1720
+ if (reasoningText) {
1721
+ outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1722
+ }
1723
+ }
1724
+ }
1725
+ outputAttrs.push(
1726
+ attrStringArray("gen_ai.response.finish_reasons", [event.finishReason]),
1727
+ attrString("gen_ai.response.id", (_h = event.response) == null ? void 0 : _h.id),
1728
+ attrString("gen_ai.response.model", (_i = event.response) == null ? void 0 : _i.modelId)
1729
+ );
1730
+ const usage = event.usage;
1731
+ if (usage) {
1732
+ outputAttrs.push(
1733
+ attrInt("ai.usage.inputTokens", usage.inputTokens),
1734
+ attrInt("ai.usage.outputTokens", usage.outputTokens),
1735
+ attrInt("ai.usage.totalTokens", usage.totalTokens),
1736
+ attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1737
+ attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens),
1738
+ attrInt("gen_ai.usage.input_tokens", usage.inputTokens),
1739
+ attrInt("gen_ai.usage.output_tokens", usage.outputTokens)
1740
+ );
1741
+ }
1742
+ this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
1743
+ state.stepSpan = void 0;
1744
+ state.stepParent = void 0;
1745
+ };
1746
+ // ── onEmbedStart ────────────────────────────────────────────────────────
1747
+ this.onEmbedStart = (event) => {
1748
+ const state = this.getState(event.callId);
1749
+ if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1750
+ const { operationName, resourceName } = opName(
1751
+ event.operationId,
1752
+ state.functionId
1753
+ );
1754
+ const inputAttrs = state.recordInputs ? [
1755
+ attrString(
1756
+ "ai.values",
1757
+ safeJsonWithUint8(event.values)
1758
+ )
1759
+ ] : [];
1760
+ const embedSpan = this.traceShipper.startSpan({
1761
+ name: event.operationId,
1762
+ parent: state.rootParent,
1763
+ eventId: state.eventId,
1764
+ operationId: event.operationId,
1765
+ attributes: [
1766
+ attrString("operation.name", operationName),
1767
+ attrString("resource.name", resourceName),
1768
+ attrString("ai.telemetry.functionId", state.functionId),
1769
+ ...inputAttrs
1770
+ ]
1771
+ });
1772
+ state.embedSpans.set(event.embedCallId, embedSpan);
1773
+ };
1774
+ // ── onEmbedFinish ───────────────────────────────────────────────────────
1775
+ this.onEmbedFinish = (event) => {
1776
+ var _a;
1777
+ const state = this.getState(event.callId);
1778
+ if (!state) return;
1779
+ const embedSpan = state.embedSpans.get(event.embedCallId);
1780
+ if (!embedSpan) return;
1781
+ const outputAttrs = [];
1782
+ if (state.recordOutputs) {
1783
+ outputAttrs.push(
1784
+ attrString(
1785
+ "ai.embeddings",
1786
+ safeJsonWithUint8(event.embeddings)
1787
+ )
1788
+ );
1789
+ }
1790
+ if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
1791
+ outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
1792
+ }
1793
+ this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
1794
+ state.embedSpans.delete(event.embedCallId);
1795
+ };
1796
+ // ── onFinish ────────────────────────────────────────────────────────────
1797
+ this.onFinish = (event) => {
1798
+ const state = this.getState(event.callId);
1799
+ if (!state) return;
1800
+ const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
1801
+ if (isEmbed) {
1802
+ this.finishEmbed(event, state);
1803
+ } else {
1804
+ this.finishGenerate(event, state);
1805
+ }
1806
+ this.cleanup(event.callId);
1807
+ };
1808
+ // ── onError ─────────────────────────────────────────────────────────────
1809
+ this.onError = (error) => {
1810
+ var _a;
1811
+ const event = error;
1812
+ if (!(event == null ? void 0 : event.callId)) return;
1813
+ const state = this.getState(event.callId);
1814
+ if (!state) return;
1815
+ const actualError = (_a = event.error) != null ? _a : error;
1816
+ if (state.stepSpan) {
1817
+ this.traceShipper.endSpan(state.stepSpan, { error: actualError });
1818
+ }
1819
+ for (const embedSpan of state.embedSpans.values()) {
1820
+ this.traceShipper.endSpan(embedSpan, { error: actualError });
1821
+ }
1822
+ state.embedSpans.clear();
1823
+ for (const toolSpan of state.toolSpans.values()) {
1824
+ this.traceShipper.endSpan(toolSpan, { error: actualError });
1825
+ }
1826
+ state.toolSpans.clear();
1827
+ if (state.rootSpan) {
1828
+ this.traceShipper.endSpan(state.rootSpan, { error: actualError });
1829
+ }
1830
+ this.cleanup(event.callId);
1831
+ };
1832
+ // ── executeTool ─────────────────────────────────────────────────────────
1833
+ this.executeTool = async ({
1834
+ callId,
1835
+ toolCallId,
1836
+ execute
1837
+ }) => {
1838
+ const state = this.getState(callId);
1839
+ const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
1840
+ if (!toolSpan) return execute();
1841
+ return runWithParentSpanContext(
1842
+ {
1843
+ traceIdB64: toolSpan.ids.traceIdB64,
1844
+ spanIdB64: toolSpan.ids.spanIdB64,
1845
+ eventId: state.eventId
1846
+ },
1847
+ () => execute()
1848
+ );
1849
+ };
1850
+ this.traceShipper = opts.traceShipper;
1851
+ this.eventShipper = opts.eventShipper;
1852
+ this.sendTraces = opts.sendTraces !== false;
1853
+ this.sendEvents = opts.sendEvents !== false;
1854
+ this.debug = opts.debug === true;
1855
+ this.defaultContext = opts.context;
1856
+ }
1857
+ // ── helpers ──────────────────────────────────────────────────────────────
1858
+ getState(callId) {
1859
+ return this.callStates.get(callId);
1860
+ }
1861
+ cleanup(callId) {
1862
+ this.callStates.delete(callId);
1863
+ }
1864
+ spanParentRef(span) {
1865
+ return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
1866
+ }
1867
+ emitLive(state, type, content, extra) {
1868
+ var _a, _b, _c, _d, _e, _f;
1869
+ if (!localDebuggerEnabled() || !state.rootSpan) return;
1870
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1871
+ sendLocalDebuggerLiveEvent({
1872
+ traceId: state.rootSpan.ids.traceIdB64,
1873
+ type,
1874
+ content,
1875
+ metadata: {
1876
+ userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
1877
+ convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
1878
+ eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
1879
+ eventId: state.eventId,
1880
+ ...extra
1881
+ }
1882
+ });
1883
+ }
1884
+ extractRaindropMetadata(metadata) {
1885
+ if (!metadata) return {};
1886
+ const result = {};
1887
+ const userId = metadata["raindrop.userId"];
1888
+ if (typeof userId === "string" && userId) result.userId = userId;
1889
+ const eventId = metadata["raindrop.eventId"];
1890
+ if (typeof eventId === "string" && eventId) result.eventId = eventId;
1891
+ const convoId = metadata["raindrop.convoId"];
1892
+ if (typeof convoId === "string" && convoId) result.convoId = convoId;
1893
+ const eventName = metadata["raindrop.eventName"];
1894
+ if (typeof eventName === "string" && eventName) result.eventName = eventName;
1895
+ const properties = metadata["raindrop.properties"];
1896
+ if (typeof properties === "string") {
1897
+ try {
1898
+ result.properties = JSON.parse(properties);
1899
+ } catch (e) {
1900
+ }
1901
+ } else if (properties && typeof properties === "object") {
1902
+ result.properties = properties;
1903
+ }
1904
+ return result;
1905
+ }
1906
+ /**
1907
+ * Extract the user-facing input text from an onStart event.
1908
+ * Mirrors the logic in the v4-v6 Proxy path (lastUserMessageTextFromArgs / extractInputFromArgs).
1909
+ */
1910
+ extractInputText(event) {
1911
+ if (typeof event.prompt === "string") return event.prompt;
1912
+ if (Array.isArray(event.messages)) {
1913
+ for (let i = event.messages.length - 1; i >= 0; i--) {
1914
+ const msg = event.messages[i];
1915
+ if ((msg == null ? void 0 : msg.role) === "user") {
1916
+ if (typeof msg.content === "string") return msg.content;
1917
+ if (Array.isArray(msg.content)) {
1918
+ const textPart = msg.content.find(
1919
+ (p) => (p == null ? void 0 : p.type) === "text" && typeof p.text === "string"
1920
+ );
1921
+ if (textPart) return textPart.text;
1922
+ }
1923
+ }
1924
+ }
1925
+ }
1926
+ return void 0;
1927
+ }
1928
+ finishGenerate(event, state) {
1929
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1930
+ if (state.rootSpan) {
1931
+ const outputAttrs = [];
1932
+ if (state.recordOutputs) {
1933
+ outputAttrs.push(
1934
+ attrString("ai.response.finishReason", event.finishReason),
1935
+ attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1936
+ attrString(
1937
+ "ai.response.providerMetadata",
1938
+ event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1939
+ )
1940
+ );
1941
+ if (((_b = event.toolCalls) == null ? void 0 : _b.length) > 0) {
1942
+ outputAttrs.push(
1943
+ attrString(
1944
+ "ai.response.toolCalls",
1945
+ JSON.stringify(
1946
+ event.toolCalls.map((tc) => ({
1947
+ toolCallId: tc.toolCallId,
1948
+ toolName: tc.toolName,
1949
+ input: tc.input
1950
+ }))
1951
+ )
1952
+ )
1953
+ );
1954
+ }
1955
+ if (((_c = event.reasoning) == null ? void 0 : _c.length) > 0) {
1956
+ const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1957
+ if (reasoningText) {
1958
+ outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1959
+ }
1960
+ }
1961
+ }
1962
+ const usage = (_d = event.totalUsage) != null ? _d : event.usage;
1963
+ if (usage) {
1964
+ outputAttrs.push(
1965
+ attrInt("ai.usage.inputTokens", usage.inputTokens),
1966
+ attrInt("ai.usage.outputTokens", usage.outputTokens),
1967
+ attrInt("ai.usage.totalTokens", usage.totalTokens),
1968
+ attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1969
+ attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens)
1970
+ );
1971
+ }
1972
+ outputAttrs.push(
1973
+ attrInt("ai.toolCall.count", state.toolCallCount)
1974
+ );
1975
+ this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
1976
+ }
1977
+ if (this.sendEvents) {
1978
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1979
+ const userId = (_f = callMeta.userId) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.userId;
1980
+ if (userId) {
1981
+ const eventName = (_i = (_h = callMeta.eventName) != null ? _h : (_g = this.defaultContext) == null ? void 0 : _g.eventName) != null ? _i : state.operationId;
1982
+ const output = (_j = event.text) != null ? _j : state.accumulatedText || void 0;
1983
+ const input = state.inputText;
1984
+ const model = (_k = event.response) == null ? void 0 : _k.modelId;
1985
+ const properties = {
1986
+ ...(_l = this.defaultContext) == null ? void 0 : _l.properties,
1987
+ ...callMeta.properties
1988
+ };
1989
+ const convoId = (_n = callMeta.convoId) != null ? _n : (_m = this.defaultContext) == null ? void 0 : _m.convoId;
1990
+ void this.eventShipper.patch(state.eventId, {
1991
+ eventName,
1992
+ userId,
1993
+ convoId,
1994
+ input,
1995
+ output,
1996
+ model,
1997
+ properties: Object.keys(properties).length > 0 ? properties : void 0,
1998
+ isPending: false
1999
+ }).catch((err) => {
2000
+ if (this.debug) {
2001
+ console.warn(
2002
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
2003
+ );
2004
+ }
2005
+ });
2006
+ }
2007
+ }
2008
+ }
2009
+ finishEmbed(event, state) {
2010
+ var _a;
2011
+ if (!state.rootSpan) return;
2012
+ const outputAttrs = [];
2013
+ const isMany = state.operationId === "ai.embedMany";
2014
+ if (state.recordOutputs) {
2015
+ if (isMany) {
2016
+ outputAttrs.push(
2017
+ attrString("ai.embeddings", safeJsonWithUint8(event.embedding))
2018
+ );
2019
+ } else {
2020
+ outputAttrs.push(
2021
+ attrString("ai.embedding", safeJsonWithUint8(event.embedding))
2022
+ );
2023
+ }
2024
+ }
2025
+ if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
2026
+ outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
2027
+ }
2028
+ this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
2029
+ }
2030
+ };
2031
+
2032
+ // src/internal/traces.ts
2033
+ var TraceShipper2 = class extends TraceShipper {
2034
+ constructor(opts) {
2035
+ var _a, _b, _c;
2036
+ super({
2037
+ ...opts,
2038
+ sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
2039
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
2040
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
2041
+ });
2042
+ }
2043
+ };
2044
+
1393
2045
  // src/internal/wrap/wrapAISDK.ts
1394
2046
  var AGENT_REPORTING_TOOL_NAME_DEFAULT = "__raindrop_report";
1395
2047
  var AGENT_REPORTING_SIGNALS_DEFAULT = {
@@ -1599,6 +2251,9 @@ function detectAISDKVersion(aiSDK) {
1599
2251
  if (isFunction(aiSDK["tool"])) return "5";
1600
2252
  return "4";
1601
2253
  }
2254
+ function hasStructuredTelemetryEvents(aiSDK) {
2255
+ return isRecord(aiSDK) && isFunction(aiSDK["registerTelemetryIntegration"]) && isFunction(aiSDK["experimental_streamModelCall"]);
2256
+ }
1602
2257
  function asVercelSchema(jsonSchemaObj) {
1603
2258
  const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
1604
2259
  const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
@@ -1771,6 +2426,36 @@ function shouldKeepEventPending(params) {
1771
2426
  if (params.error != null || !params.canKeepEventPending) return false;
1772
2427
  return params.finishReason === "tool-calls" || params.finishReason === "tool_calls";
1773
2428
  }
2429
+ function normalizePromptAttr(arg) {
2430
+ if (!isRecord(arg)) return arg;
2431
+ const system = arg["system"];
2432
+ const prompt = arg["prompt"];
2433
+ const messages = arg["messages"];
2434
+ if (Array.isArray(messages)) {
2435
+ if (system) {
2436
+ const sysContent = typeof system === "string" ? system : JSON.stringify(system);
2437
+ return [{ role: "system", content: sysContent }, ...messages];
2438
+ }
2439
+ return messages;
2440
+ }
2441
+ if (typeof prompt === "string") {
2442
+ const msgs = [];
2443
+ if (system) {
2444
+ msgs.push({ role: "system", content: typeof system === "string" ? system : JSON.stringify(system) });
2445
+ }
2446
+ msgs.push({ role: "user", content: prompt });
2447
+ return msgs;
2448
+ }
2449
+ return { system, prompt, messages };
2450
+ }
2451
+ function getLocalDebuggerMetadata(ctx) {
2452
+ return {
2453
+ eventId: ctx.eventId,
2454
+ ...ctx.eventName ? { eventName: ctx.eventName } : {},
2455
+ ...ctx.userId ? { userId: ctx.userId } : {},
2456
+ ...ctx.convoId ? { convoId: ctx.convoId } : {}
2457
+ };
2458
+ }
1774
2459
  async function safeFinalize(finalize, debug, result, error) {
1775
2460
  try {
1776
2461
  await finalize(result, error);
@@ -1843,17 +2528,17 @@ function setupOperation(params) {
1843
2528
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1844
2529
  attrString("ai.model.provider", modelInfoFromArgs.provider),
1845
2530
  attrString("ai.model.id", modelInfoFromArgs.modelId),
2531
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
2532
+ attrString("ai.telemetry.metadata.raindrop.eventName", mergedCtx.eventName),
2533
+ attrString("ai.telemetry.metadata.raindrop.userId", mergedCtx.userId),
2534
+ attrString("ai.telemetry.metadata.raindrop.convoId", mergedCtx.convoId),
1846
2535
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1847
2536
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1848
2537
  ...attrsFromSettings(arg),
1849
2538
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1850
2539
  attrString(
1851
2540
  "ai.prompt",
1852
- safeJsonWithUint8({
1853
- system: isRecord(arg) ? arg["system"] : void 0,
1854
- prompt: isRecord(arg) ? arg["prompt"] : void 0,
1855
- messages: isRecord(arg) ? arg["messages"] : void 0
1856
- })
2541
+ safeJsonWithUint8(normalizePromptAttr(arg))
1857
2542
  )
1858
2543
  ]
1859
2544
  ]
@@ -1862,6 +2547,7 @@ function setupOperation(params) {
1862
2547
  const operationSelfDiagnostics = isObjectOperation(operation) ? void 0 : selfDiagnostics;
1863
2548
  const wrapCtx = {
1864
2549
  eventId,
2550
+ context: mergedCtx,
1865
2551
  telemetry,
1866
2552
  sendTraces,
1867
2553
  debug,
@@ -2181,8 +2867,100 @@ async function executeNonStreamingOperation(params) {
2181
2867
  }
2182
2868
  }
2183
2869
  function wrapAISDK(aiSDK, deps) {
2184
- var _a, _b;
2870
+ var _a, _b, _c, _d;
2185
2871
  const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
2872
+ if (deps.options.nativeTelemetry === true) {
2873
+ if (!hasStructuredTelemetryEvents(aiSDK)) {
2874
+ throw new Error(
2875
+ "[raindrop-ai/ai-sdk] nativeTelemetry requires AI SDK v7+. The AI SDK module passed to wrap() does not support structured telemetry events. Remove nativeTelemetry or upgrade to AI SDK v7."
2876
+ );
2877
+ }
2878
+ }
2879
+ const useNative = deps.options.nativeTelemetry === true;
2880
+ if (useNative) {
2881
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
2882
+ const integration = new RaindropTelemetryIntegration({
2883
+ traceShipper: deps.traceShipper,
2884
+ eventShipper: deps.eventShipper,
2885
+ sendTraces: ((_a = deps.options.send) == null ? void 0 : _a.traces) !== false,
2886
+ sendEvents: ((_b = deps.options.send) == null ? void 0 : _b.events) !== false,
2887
+ debug,
2888
+ context: {
2889
+ userId: wrapTimeCtx.userId,
2890
+ eventId: wrapTimeCtx.eventId,
2891
+ eventName: wrapTimeCtx.eventName,
2892
+ convoId: wrapTimeCtx.convoId,
2893
+ properties: wrapTimeCtx.properties
2894
+ }
2895
+ });
2896
+ const registerFn = aiSDK["registerTelemetryIntegration"];
2897
+ if (isFunction(registerFn)) {
2898
+ registerFn(integration);
2899
+ }
2900
+ if (debug) {
2901
+ console.log("[raindrop-ai/ai-sdk] nativeTelemetry: registered RaindropTelemetryIntegration (no Proxy)");
2902
+ }
2903
+ const selfDiagnostics2 = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2904
+ if (selfDiagnostics2) {
2905
+ const textOps = /* @__PURE__ */ new Set(["generateText", "streamText"]);
2906
+ const jsonSchemaFactory = resolveJsonSchemaFactory(aiSDK);
2907
+ const proxyTarget2 = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
2908
+ return new Proxy(proxyTarget2, {
2909
+ get(target, prop, receiver) {
2910
+ const original = Reflect.get(target, prop, receiver);
2911
+ if (typeof prop !== "string" || !textOps.has(prop) || !isFunction(original)) {
2912
+ return original;
2913
+ }
2914
+ return (...callArgs) => {
2915
+ var _a2;
2916
+ const arg = callArgs[0];
2917
+ if (!isRecord(arg)) return original.call(aiSDK, ...callArgs);
2918
+ const telemetry = extractExperimentalTelemetry(arg);
2919
+ const callMeta = (telemetry == null ? void 0 : telemetry.metadata) ? extractRaindropMetadata(telemetry.metadata) : {};
2920
+ const perCallEventIdExplicit = (_a2 = callMeta.eventId) != null ? _a2 : wrapTimeCtx.eventId;
2921
+ const perCallEventId = perCallEventIdExplicit != null ? perCallEventIdExplicit : randomUUID();
2922
+ const perCallEventIdGenerated = !perCallEventIdExplicit;
2923
+ const perCallCtx = {
2924
+ eventId: perCallEventId,
2925
+ context: wrapTimeCtx,
2926
+ telemetry,
2927
+ sendTraces: false,
2928
+ debug,
2929
+ eventShipper: deps.eventShipper,
2930
+ traceShipper: deps.traceShipper,
2931
+ rootParentForChildren: void 0,
2932
+ jsonSchemaFactory,
2933
+ selfDiagnostics: selfDiagnostics2,
2934
+ aiSDKVersion: "7"
2935
+ };
2936
+ const tools = isRecord(arg["tools"]) ? { ...arg["tools"] } : {};
2937
+ const toolName = selfDiagnostics2.toolName;
2938
+ if (!(toolName in tools)) {
2939
+ const reportTool = createSelfDiagnosticsTool(perCallCtx);
2940
+ if (reportTool) tools[toolName] = reportTool;
2941
+ }
2942
+ const existingTelemetry = isRecord(arg["experimental_telemetry"]) ? arg["experimental_telemetry"] : {};
2943
+ const existingMetadata = isRecord(existingTelemetry["metadata"]) ? existingTelemetry["metadata"] : {};
2944
+ const mergedMetadata = existingMetadata["raindrop.eventId"] ? existingMetadata : {
2945
+ ...existingMetadata,
2946
+ "raindrop.eventId": perCallEventId,
2947
+ ...perCallEventIdGenerated ? { "raindrop.internal.eventIdGenerated": "true" } : {}
2948
+ };
2949
+ callArgs[0] = {
2950
+ ...arg,
2951
+ tools,
2952
+ experimental_telemetry: {
2953
+ ...existingTelemetry,
2954
+ metadata: mergedMetadata
2955
+ }
2956
+ };
2957
+ return original.call(aiSDK, ...callArgs);
2958
+ };
2959
+ }
2960
+ });
2961
+ }
2962
+ return aiSDK;
2963
+ }
2186
2964
  const instrumentedOps = /* @__PURE__ */ new Set([
2187
2965
  "generateText",
2188
2966
  "streamText",
@@ -2190,8 +2968,8 @@ function wrapAISDK(aiSDK, deps) {
2190
2968
  "streamObject"
2191
2969
  ]);
2192
2970
  const agentClasses = /* @__PURE__ */ new Set(["Agent", "Experimental_Agent", "ToolLoopAgent"]);
2193
- const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
2194
- const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
2971
+ const sendEvents = ((_c = deps.options.send) == null ? void 0 : _c.events) !== false;
2972
+ const sendTraces = ((_d = deps.options.send) == null ? void 0 : _d.traces) !== false;
2195
2973
  const autoAttachmentEnabled = deps.options.autoAttachment !== false;
2196
2974
  const selfDiagnostics = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2197
2975
  const proxyTarget = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
@@ -2299,7 +3077,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2299
3077
  if (!mergedCtx.userId) warnMissingUserIdOnce();
2300
3078
  const inherited = await getCurrentParentSpanContext();
2301
3079
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2302
- const ctx = { ...mergedCtx};
3080
+ const ctx = { ...mergedCtx, eventId };
2303
3081
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2304
3082
  const outerOperationId = `ai.${operation}`;
2305
3083
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -2315,17 +3093,17 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2315
3093
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2316
3094
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2317
3095
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3096
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3097
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3098
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3099
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
2318
3100
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2319
3101
  ...attrsFromHeaders(mergedArgs["headers"]),
2320
3102
  ...attrsFromSettings(mergedArgs),
2321
3103
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2322
3104
  attrString(
2323
3105
  "ai.prompt",
2324
- safeJsonWithUint8({
2325
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2326
- prompt: mergedArgs["prompt"],
2327
- messages: mergedArgs["messages"]
2328
- })
3106
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
2329
3107
  )
2330
3108
  ]
2331
3109
  ]
@@ -2333,6 +3111,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2333
3111
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2334
3112
  const wrapCtx = {
2335
3113
  eventId,
3114
+ context: ctx,
2336
3115
  telemetry,
2337
3116
  sendTraces,
2338
3117
  debug,
@@ -2506,7 +3285,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2506
3285
  if (!mergedCtx.userId) warnMissingUserIdOnce();
2507
3286
  const inherited = await getCurrentParentSpanContext();
2508
3287
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2509
- const ctx = { ...mergedCtx};
3288
+ const ctx = { ...mergedCtx, eventId };
2510
3289
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2511
3290
  const outerOperationId = `ai.${operation}`;
2512
3291
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -2522,17 +3301,17 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2522
3301
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2523
3302
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2524
3303
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3304
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3305
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3306
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3307
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
2525
3308
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2526
3309
  ...attrsFromHeaders(mergedArgs["headers"]),
2527
3310
  ...attrsFromSettings(mergedArgs),
2528
3311
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2529
3312
  attrString(
2530
3313
  "ai.prompt",
2531
- safeJsonWithUint8({
2532
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2533
- prompt: mergedArgs["prompt"],
2534
- messages: mergedArgs["messages"]
2535
- })
3314
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
2536
3315
  )
2537
3316
  ]
2538
3317
  ]
@@ -2540,6 +3319,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2540
3319
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2541
3320
  const wrapCtx = {
2542
3321
  eventId,
3322
+ context: ctx,
2543
3323
  telemetry,
2544
3324
  sendTraces,
2545
3325
  debug,
@@ -2763,6 +3543,21 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2763
3543
  });
2764
3544
  }
2765
3545
  };
3546
+ const sendToolLiveEvent = (parent, type, metadata) => {
3547
+ if (!localDebuggerEnabled() || !parent) return;
3548
+ sendLocalDebuggerLiveEvent({
3549
+ traceId: parent.traceIdB64,
3550
+ type,
3551
+ content: name,
3552
+ metadata: {
3553
+ ...getLocalDebuggerMetadata({
3554
+ ...ctx.context,
3555
+ eventId: ctx.eventId
3556
+ }),
3557
+ ...metadata
3558
+ }
3559
+ });
3560
+ };
2766
3561
  const createContextSpan = (span) => ({
2767
3562
  traceIdB64: span.ids.traceIdB64,
2768
3563
  spanIdB64: span.ids.spanIdB64,
@@ -2778,6 +3573,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2778
3573
  const parentCtx = await getCurrentParentSpanContext();
2779
3574
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2780
3575
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3576
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
2781
3577
  try {
2782
3578
  let lastValue;
2783
3579
  const iterator = result[Symbol.asyncIterator]();
@@ -2793,9 +3589,13 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2793
3589
  }
2794
3590
  toolCalls.push({ id: toolCallId, name, args: toolArgs, result: lastValue, status: "OK" });
2795
3591
  endToolSpan(toolSpan, lastValue);
3592
+ sendToolLiveEvent(parent, "tool_result", { result: lastValue });
2796
3593
  } catch (error) {
2797
3594
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
2798
3595
  endToolSpan(toolSpan, void 0, error);
3596
+ sendToolLiveEvent(parent, "tool_result", {
3597
+ error: error instanceof Error ? error.message : String(error)
3598
+ });
2799
3599
  throw error;
2800
3600
  }
2801
3601
  })();
@@ -2804,6 +3604,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2804
3604
  const parentCtx = await getCurrentParentSpanContext();
2805
3605
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2806
3606
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3607
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
2807
3608
  const run = async () => {
2808
3609
  try {
2809
3610
  const awaitedResult = await result;
@@ -2815,10 +3616,14 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2815
3616
  status: "OK"
2816
3617
  });
2817
3618
  endToolSpan(toolSpan, awaitedResult);
3619
+ sendToolLiveEvent(parent, "tool_result", { result: awaitedResult });
2818
3620
  return awaitedResult;
2819
3621
  } catch (error) {
2820
3622
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
2821
3623
  endToolSpan(toolSpan, void 0, error);
3624
+ sendToolLiveEvent(parent, "tool_result", {
3625
+ error: error instanceof Error ? error.message : String(error)
3626
+ });
2822
3627
  throw error;
2823
3628
  }
2824
3629
  };
@@ -2858,6 +3663,7 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2858
3663
  const original = Reflect.get(target, prop, receiver);
2859
3664
  if (prop === "doGenerate" && isFunction(original)) {
2860
3665
  return async (...callArgs) => {
3666
+ var _a, _b;
2861
3667
  const options = callArgs[0];
2862
3668
  const parentCtx = await getCurrentParentSpanContext();
2863
3669
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
@@ -2865,6 +3671,22 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2865
3671
  try {
2866
3672
  const result = await original.apply(target, callArgs);
2867
3673
  if (span) endDoGenerateSpan(span, result, modelInfo, ctx);
3674
+ if (localDebuggerEnabled() && ctx.rootParentForChildren && isRecord(result)) {
3675
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3676
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3677
+ const content = result["content"];
3678
+ if (Array.isArray(content)) {
3679
+ for (const part of content) {
3680
+ if (isRecord(part)) {
3681
+ if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
3682
+ sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
3683
+ } else if (part["type"] === "text" && typeof part["text"] === "string") {
3684
+ sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
3685
+ }
3686
+ }
3687
+ }
3688
+ }
3689
+ }
2868
3690
  return result;
2869
3691
  } catch (error) {
2870
3692
  if (span)
@@ -3004,6 +3826,23 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
3004
3826
  }
3005
3827
  if ("usage" in value) usage = value["usage"];
3006
3828
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
3829
+ if (localDebuggerEnabled() && ctx.rootParentForChildren) {
3830
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3831
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3832
+ if (type === "text-delta") {
3833
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
3834
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
3835
+ } else if (type === "reasoning" || type === "reasoning-delta") {
3836
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
3837
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
3838
+ } else if (type === "tool-call") {
3839
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3840
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
3841
+ } else if (type === "tool-result") {
3842
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3843
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
3844
+ }
3845
+ }
3007
3846
  }
3008
3847
  controller.enqueue(value);
3009
3848
  } catch (error) {
@@ -3285,6 +4124,16 @@ function createRaindropAISDK(opts) {
3285
4124
  traceShipper
3286
4125
  });
3287
4126
  },
4127
+ createTelemetryIntegration(context) {
4128
+ return new RaindropTelemetryIntegration({
4129
+ traceShipper,
4130
+ eventShipper,
4131
+ sendTraces: tracesEnabled,
4132
+ sendEvents: eventsEnabled,
4133
+ debug: envDebug,
4134
+ context
4135
+ });
4136
+ },
3288
4137
  events: {
3289
4138
  async patch(eventId, patch) {
3290
4139
  await eventShipper.patch(eventId, patch);
@@ -3323,6 +4172,7 @@ if (!globalThis.RAINDROP_ASYNC_LOCAL_STORAGE) {
3323
4172
  globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = async_hooks.AsyncLocalStorage;
3324
4173
  }
3325
4174
 
4175
+ exports.RaindropTelemetryIntegration = RaindropTelemetryIntegration;
3326
4176
  exports._resetWarnedMissingUserId = _resetWarnedMissingUserId;
3327
4177
  exports.createRaindropAISDK = createRaindropAISDK;
3328
4178
  exports.currentSpan = currentSpan;