@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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- // ../core/dist/chunk-H6VSZSLN.js
3
+ // ../core/dist/chunk-4UCYIEH4.js
4
4
  function getCrypto() {
5
5
  const c = globalThis.crypto;
6
6
  return c;
@@ -145,6 +145,7 @@ async function postJson(url, body, headers, opts) {
145
145
  );
146
146
  }
147
147
  var SpanStatusCode = {
148
+ UNSET: 0,
148
149
  ERROR: 2
149
150
  };
150
151
  function createSpanIds(parent) {
@@ -465,11 +466,66 @@ var EventShipper = class {
465
466
  }
466
467
  }
467
468
  };
469
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
470
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
471
+ var _a, _b, _c;
472
+ 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;
473
+ return resolved ? (_c = formatEndpoint(resolved)) != null ? _c : null : null;
474
+ }
475
+ function localDebuggerEnabled(baseUrl) {
476
+ return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
477
+ }
478
+ function normalizeLocalDebuggerLiveEventType(type) {
479
+ switch (type) {
480
+ case "text-delta":
481
+ return "text_delta";
482
+ case "reasoning":
483
+ case "reasoning-delta":
484
+ return "reasoning_delta";
485
+ case "tool-call":
486
+ return "tool_start";
487
+ case "tool-result":
488
+ return "tool_result";
489
+ default:
490
+ return type;
491
+ }
492
+ }
493
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
494
+ var _a;
495
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
496
+ if (!baseUrl) return;
497
+ void postJson(`${baseUrl}traces`, body, {}, {
498
+ maxAttempts: 1,
499
+ debug: (_a = options.debug) != null ? _a : false,
500
+ sdkName: options.sdkName
501
+ }).catch(() => {
502
+ });
503
+ }
504
+ function sendLocalDebuggerLiveEvent(event, options = {}) {
505
+ var _a, _b;
506
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
507
+ if (!baseUrl) return;
508
+ void postJson(
509
+ `${baseUrl}live`,
510
+ {
511
+ ...event,
512
+ type: normalizeLocalDebuggerLiveEventType(event.type),
513
+ timestamp: (_a = event.timestamp) != null ? _a : Date.now()
514
+ },
515
+ {},
516
+ {
517
+ maxAttempts: 1,
518
+ debug: (_b = options.debug) != null ? _b : false,
519
+ sdkName: options.sdkName
520
+ }
521
+ ).catch(() => {
522
+ });
523
+ }
468
524
  var TraceShipper = class {
469
525
  constructor(opts) {
470
526
  this.queue = [];
471
527
  this.inFlight = /* @__PURE__ */ new Set();
472
- var _a, _b, _c, _d, _e, _f, _g, _h;
528
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
473
529
  this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
474
530
  this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
475
531
  this.enabled = opts.enabled !== false;
@@ -482,6 +538,13 @@ var TraceShipper = class {
482
538
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
483
539
  this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
484
540
  this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
541
+ const localDebugger = typeof process !== "undefined" ? (_i = process.env) == null ? void 0 : _i.RAINDROP_LOCAL_DEBUGGER : void 0;
542
+ if (localDebugger) {
543
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(localDebugger)) != null ? _j : void 0;
544
+ if (this.debug) {
545
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
546
+ }
547
+ }
485
548
  }
486
549
  isDebugEnabled() {
487
550
  return this.debug;
@@ -498,7 +561,25 @@ var TraceShipper = class {
498
561
  attrString("ai.operationId", args.operationId)
499
562
  ];
500
563
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
501
- return { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
564
+ const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
565
+ if (this.localDebuggerUrl) {
566
+ const openSpan = buildOtlpSpan({
567
+ ids: span.ids,
568
+ name: span.name,
569
+ startTimeUnixNano: span.startTimeUnixNano,
570
+ endTimeUnixNano: span.startTimeUnixNano,
571
+ // placeholder — will be updated on endSpan
572
+ attributes: span.attributes,
573
+ status: { code: SpanStatusCode.UNSET }
574
+ });
575
+ const body = buildExportTraceServiceRequest([openSpan], this.serviceName, this.serviceVersion);
576
+ mirrorTraceExportToLocalDebugger(body, {
577
+ baseUrl: this.localDebuggerUrl,
578
+ debug: false,
579
+ sdkName: this.sdkName
580
+ });
581
+ }
582
+ return span;
502
583
  }
503
584
  endSpan(span, extra) {
504
585
  var _a, _b;
@@ -521,6 +602,14 @@ var TraceShipper = class {
521
602
  status
522
603
  });
523
604
  this.enqueue(otlp);
605
+ if (this.localDebuggerUrl) {
606
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
607
+ mirrorTraceExportToLocalDebugger(body, {
608
+ baseUrl: this.localDebuggerUrl,
609
+ debug: false,
610
+ sdkName: this.sdkName
611
+ });
612
+ }
524
613
  }
525
614
  createSpan(args) {
526
615
  var _a;
@@ -538,6 +627,14 @@ var TraceShipper = class {
538
627
  status: args.status
539
628
  });
540
629
  this.enqueue(otlp);
630
+ if (this.localDebuggerUrl) {
631
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
632
+ mirrorTraceExportToLocalDebugger(body, {
633
+ baseUrl: this.localDebuggerUrl,
634
+ debug: false,
635
+ sdkName: this.sdkName
636
+ });
637
+ }
541
638
  }
542
639
  enqueue(span) {
543
640
  if (!this.enabled) return;
@@ -732,7 +829,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
732
829
  // package.json
733
830
  var package_default = {
734
831
  name: "@raindrop-ai/ai-sdk",
735
- version: "0.0.19"};
832
+ version: "0.0.21"};
736
833
 
737
834
  // src/internal/version.ts
738
835
  var libraryName = package_default.name;
@@ -751,19 +848,6 @@ var EventShipper2 = class extends EventShipper {
751
848
  }
752
849
  };
753
850
 
754
- // src/internal/traces.ts
755
- var TraceShipper2 = class extends TraceShipper {
756
- constructor(opts) {
757
- var _a, _b, _c;
758
- super({
759
- ...opts,
760
- sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
761
- serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
762
- serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
763
- });
764
- }
765
- };
766
-
767
851
  // src/internal/wrap/helpers.ts
768
852
  function isRecord(value) {
769
853
  return typeof value === "object" && value !== null;
@@ -1385,6 +1469,574 @@ function attrsFromGenAiRequest(options) {
1385
1469
  ];
1386
1470
  }
1387
1471
 
1472
+ // src/internal/raindrop-telemetry-integration.ts
1473
+ var RaindropTelemetryIntegration = class {
1474
+ constructor(opts) {
1475
+ this.callStates = /* @__PURE__ */ new Map();
1476
+ // ── onStart ─────────────────────────────────────────────────────────────
1477
+ this.onStart = (event) => {
1478
+ var _a, _b, _c, _d;
1479
+ if (event.isEnabled !== true) return;
1480
+ const isEmbed = event.operationId === "ai.embed" || event.operationId === "ai.embedMany";
1481
+ const recordInputs = event.recordInputs !== false;
1482
+ const recordOutputs = event.recordOutputs !== false;
1483
+ const functionId = event.functionId;
1484
+ const metadata = event.metadata;
1485
+ const callMeta = this.extractRaindropMetadata(metadata);
1486
+ const inherited = getContextManager().getParentSpanIds();
1487
+ const eventIdGenerated = (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === "true" || (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === true;
1488
+ const explicitEventId = callMeta.eventId && !eventIdGenerated ? callMeta.eventId : void 0;
1489
+ 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();
1490
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1491
+ const { operationName, resourceName } = opName(
1492
+ event.operationId,
1493
+ functionId
1494
+ );
1495
+ let rootSpan;
1496
+ if (this.sendTraces) {
1497
+ const promptAttrs = !isEmbed && recordInputs ? [
1498
+ attrString(
1499
+ "ai.prompt",
1500
+ safeJsonWithUint8({
1501
+ system: event.system,
1502
+ prompt: event.prompt,
1503
+ messages: event.messages
1504
+ })
1505
+ )
1506
+ ] : [];
1507
+ const embedAttrs = isEmbed && recordInputs ? event.operationId === "ai.embedMany" ? [
1508
+ attrString(
1509
+ "ai.values",
1510
+ safeJsonWithUint8(event.value)
1511
+ )
1512
+ ] : [attrString("ai.value", safeJsonWithUint8(event.value))] : [];
1513
+ rootSpan = this.traceShipper.startSpan({
1514
+ name: event.operationId,
1515
+ parent: inheritedParent,
1516
+ eventId,
1517
+ operationId: event.operationId,
1518
+ attributes: [
1519
+ attrString("operation.name", operationName),
1520
+ attrString("resource.name", resourceName),
1521
+ attrString("ai.telemetry.functionId", functionId),
1522
+ attrString("ai.model.provider", event.provider),
1523
+ attrString("ai.model.id", event.modelId),
1524
+ // Filter out raindrop.eventId from metadata attrs since TraceShipper
1525
+ // already sets it via the eventId arg. Without this, eventMetadata()'s
1526
+ // auto-generated ID would duplicate and override the resolved one.
1527
+ ...attrsFromTelemetryMetadata(
1528
+ metadata ? Object.fromEntries(
1529
+ Object.entries(metadata).filter(
1530
+ ([k]) => k !== "raindrop.eventId" && k !== "raindrop.internal.eventIdGenerated"
1531
+ )
1532
+ ) : void 0
1533
+ ),
1534
+ ...promptAttrs,
1535
+ ...embedAttrs
1536
+ ]
1537
+ });
1538
+ }
1539
+ this.callStates.set(event.callId, {
1540
+ operationId: event.operationId,
1541
+ eventId,
1542
+ rootSpan,
1543
+ rootParent: rootSpan ? this.spanParentRef(rootSpan) : inheritedParent,
1544
+ stepSpan: void 0,
1545
+ stepParent: void 0,
1546
+ toolSpans: /* @__PURE__ */ new Map(),
1547
+ embedSpans: /* @__PURE__ */ new Map(),
1548
+ recordInputs,
1549
+ recordOutputs,
1550
+ functionId,
1551
+ metadata,
1552
+ accumulatedText: "",
1553
+ inputText: isEmbed ? void 0 : this.extractInputText(event),
1554
+ toolCallCount: 0
1555
+ });
1556
+ };
1557
+ // ── onStepStart ─────────────────────────────────────────────────────────
1558
+ this.onStepStart = (event) => {
1559
+ const state = this.getState(event.callId);
1560
+ if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1561
+ const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
1562
+ const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
1563
+ const { operationName, resourceName } = opName(
1564
+ stepOperationId,
1565
+ state.functionId
1566
+ );
1567
+ const inputAttrs = [];
1568
+ if (state.recordInputs) {
1569
+ if (event.promptMessages) {
1570
+ inputAttrs.push(
1571
+ attrString(
1572
+ "ai.prompt.messages",
1573
+ safeJsonWithUint8(event.promptMessages)
1574
+ )
1575
+ );
1576
+ }
1577
+ if (event.stepTools) {
1578
+ inputAttrs.push(
1579
+ attrStringArray(
1580
+ "ai.prompt.tools",
1581
+ event.stepTools.map((t) => JSON.stringify(t))
1582
+ )
1583
+ );
1584
+ }
1585
+ if (event.stepToolChoice != null) {
1586
+ inputAttrs.push(
1587
+ attrString(
1588
+ "ai.prompt.toolChoice",
1589
+ JSON.stringify(event.stepToolChoice)
1590
+ )
1591
+ );
1592
+ }
1593
+ }
1594
+ const stepSpan = this.traceShipper.startSpan({
1595
+ name: stepOperationId,
1596
+ parent: state.rootParent,
1597
+ eventId: state.eventId,
1598
+ operationId: stepOperationId,
1599
+ attributes: [
1600
+ attrString("operation.name", operationName),
1601
+ attrString("resource.name", resourceName),
1602
+ attrString("ai.telemetry.functionId", state.functionId),
1603
+ attrString("ai.model.provider", event.provider),
1604
+ attrString("ai.model.id", event.modelId),
1605
+ attrString("gen_ai.system", event.provider),
1606
+ attrString("gen_ai.request.model", event.modelId),
1607
+ ...inputAttrs
1608
+ ]
1609
+ });
1610
+ state.stepSpan = stepSpan;
1611
+ state.stepParent = this.spanParentRef(stepSpan);
1612
+ };
1613
+ // ── onToolCallStart ─────────────────────────────────────────────────────
1614
+ this.onToolCallStart = (event) => {
1615
+ const state = this.getState(event.callId);
1616
+ if (!(state == null ? void 0 : state.stepParent)) return;
1617
+ const { toolCall } = event;
1618
+ const { operationName, resourceName } = opName(
1619
+ "ai.toolCall",
1620
+ state.functionId
1621
+ );
1622
+ const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
1623
+ const toolSpan = this.traceShipper.startSpan({
1624
+ name: "ai.toolCall",
1625
+ parent: state.stepParent,
1626
+ eventId: state.eventId,
1627
+ operationId: "ai.toolCall",
1628
+ attributes: [
1629
+ attrString("operation.name", operationName),
1630
+ attrString("resource.name", resourceName),
1631
+ attrString("ai.telemetry.functionId", state.functionId),
1632
+ attrString("ai.toolCall.name", toolCall.toolName),
1633
+ attrString("ai.toolCall.id", toolCall.toolCallId),
1634
+ ...inputAttrs
1635
+ ]
1636
+ });
1637
+ state.toolSpans.set(toolCall.toolCallId, toolSpan);
1638
+ this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
1639
+ };
1640
+ // ── onToolCallFinish ────────────────────────────────────────────────────
1641
+ this.onToolCallFinish = (event) => {
1642
+ const state = this.getState(event.callId);
1643
+ if (!state) return;
1644
+ const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
1645
+ if (!toolSpan) return;
1646
+ state.toolCallCount += 1;
1647
+ if (event.success) {
1648
+ const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(event.output))] : [];
1649
+ this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
1650
+ } else {
1651
+ this.traceShipper.endSpan(toolSpan, { error: event.error });
1652
+ }
1653
+ this.emitLive(state, "tool_result", event.toolCall.toolName);
1654
+ state.toolSpans.delete(event.toolCall.toolCallId);
1655
+ };
1656
+ // ── onChunk (streaming) ─────────────────────────────────────────────────
1657
+ this.onChunk = (event) => {
1658
+ var _a, _b, _c, _d, _e;
1659
+ const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
1660
+ if (!callId) return;
1661
+ const state = this.getState(callId);
1662
+ if (!state) return;
1663
+ const chunk = event.chunk;
1664
+ if (!chunk || typeof chunk !== "object") return;
1665
+ if (chunk.type === "text-delta") {
1666
+ const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
1667
+ if (typeof delta === "string") {
1668
+ state.accumulatedText += delta;
1669
+ this.emitLive(state, "text_delta", delta);
1670
+ }
1671
+ } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
1672
+ const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
1673
+ if (typeof text === "string") {
1674
+ this.emitLive(state, "reasoning_delta", text);
1675
+ }
1676
+ }
1677
+ };
1678
+ // ── onStepFinish ────────────────────────────────────────────────────────
1679
+ this.onStepFinish = (event) => {
1680
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1681
+ const state = this.getState(event.callId);
1682
+ if (!(state == null ? void 0 : state.stepSpan)) return;
1683
+ const outputAttrs = [];
1684
+ if (state.recordOutputs) {
1685
+ outputAttrs.push(
1686
+ attrString("ai.response.finishReason", event.finishReason),
1687
+ attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1688
+ attrString("ai.response.id", (_b = event.response) == null ? void 0 : _b.id),
1689
+ attrString("ai.response.model", (_c = event.response) == null ? void 0 : _c.modelId),
1690
+ attrString(
1691
+ "ai.response.timestamp",
1692
+ ((_d = event.response) == null ? void 0 : _d.timestamp) instanceof Date ? event.response.timestamp.toISOString() : (_e = event.response) == null ? void 0 : _e.timestamp
1693
+ ),
1694
+ attrString(
1695
+ "ai.response.providerMetadata",
1696
+ event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1697
+ )
1698
+ );
1699
+ if (((_f = event.toolCalls) == null ? void 0 : _f.length) > 0) {
1700
+ outputAttrs.push(
1701
+ attrString(
1702
+ "ai.response.toolCalls",
1703
+ JSON.stringify(
1704
+ event.toolCalls.map((tc) => ({
1705
+ toolCallId: tc.toolCallId,
1706
+ toolName: tc.toolName,
1707
+ input: tc.input
1708
+ }))
1709
+ )
1710
+ )
1711
+ );
1712
+ }
1713
+ if (((_g = event.reasoning) == null ? void 0 : _g.length) > 0) {
1714
+ const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1715
+ if (reasoningText) {
1716
+ outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1717
+ }
1718
+ }
1719
+ }
1720
+ outputAttrs.push(
1721
+ attrStringArray("gen_ai.response.finish_reasons", [event.finishReason]),
1722
+ attrString("gen_ai.response.id", (_h = event.response) == null ? void 0 : _h.id),
1723
+ attrString("gen_ai.response.model", (_i = event.response) == null ? void 0 : _i.modelId)
1724
+ );
1725
+ const usage = event.usage;
1726
+ if (usage) {
1727
+ outputAttrs.push(
1728
+ attrInt("ai.usage.inputTokens", usage.inputTokens),
1729
+ attrInt("ai.usage.outputTokens", usage.outputTokens),
1730
+ attrInt("ai.usage.totalTokens", usage.totalTokens),
1731
+ attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1732
+ attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens),
1733
+ attrInt("gen_ai.usage.input_tokens", usage.inputTokens),
1734
+ attrInt("gen_ai.usage.output_tokens", usage.outputTokens)
1735
+ );
1736
+ }
1737
+ this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
1738
+ state.stepSpan = void 0;
1739
+ state.stepParent = void 0;
1740
+ };
1741
+ // ── onEmbedStart ────────────────────────────────────────────────────────
1742
+ this.onEmbedStart = (event) => {
1743
+ const state = this.getState(event.callId);
1744
+ if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1745
+ const { operationName, resourceName } = opName(
1746
+ event.operationId,
1747
+ state.functionId
1748
+ );
1749
+ const inputAttrs = state.recordInputs ? [
1750
+ attrString(
1751
+ "ai.values",
1752
+ safeJsonWithUint8(event.values)
1753
+ )
1754
+ ] : [];
1755
+ const embedSpan = this.traceShipper.startSpan({
1756
+ name: event.operationId,
1757
+ parent: state.rootParent,
1758
+ eventId: state.eventId,
1759
+ operationId: event.operationId,
1760
+ attributes: [
1761
+ attrString("operation.name", operationName),
1762
+ attrString("resource.name", resourceName),
1763
+ attrString("ai.telemetry.functionId", state.functionId),
1764
+ ...inputAttrs
1765
+ ]
1766
+ });
1767
+ state.embedSpans.set(event.embedCallId, embedSpan);
1768
+ };
1769
+ // ── onEmbedFinish ───────────────────────────────────────────────────────
1770
+ this.onEmbedFinish = (event) => {
1771
+ var _a;
1772
+ const state = this.getState(event.callId);
1773
+ if (!state) return;
1774
+ const embedSpan = state.embedSpans.get(event.embedCallId);
1775
+ if (!embedSpan) return;
1776
+ const outputAttrs = [];
1777
+ if (state.recordOutputs) {
1778
+ outputAttrs.push(
1779
+ attrString(
1780
+ "ai.embeddings",
1781
+ safeJsonWithUint8(event.embeddings)
1782
+ )
1783
+ );
1784
+ }
1785
+ if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
1786
+ outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
1787
+ }
1788
+ this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
1789
+ state.embedSpans.delete(event.embedCallId);
1790
+ };
1791
+ // ── onFinish ────────────────────────────────────────────────────────────
1792
+ this.onFinish = (event) => {
1793
+ const state = this.getState(event.callId);
1794
+ if (!state) return;
1795
+ const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
1796
+ if (isEmbed) {
1797
+ this.finishEmbed(event, state);
1798
+ } else {
1799
+ this.finishGenerate(event, state);
1800
+ }
1801
+ this.cleanup(event.callId);
1802
+ };
1803
+ // ── onError ─────────────────────────────────────────────────────────────
1804
+ this.onError = (error) => {
1805
+ var _a;
1806
+ const event = error;
1807
+ if (!(event == null ? void 0 : event.callId)) return;
1808
+ const state = this.getState(event.callId);
1809
+ if (!state) return;
1810
+ const actualError = (_a = event.error) != null ? _a : error;
1811
+ if (state.stepSpan) {
1812
+ this.traceShipper.endSpan(state.stepSpan, { error: actualError });
1813
+ }
1814
+ for (const embedSpan of state.embedSpans.values()) {
1815
+ this.traceShipper.endSpan(embedSpan, { error: actualError });
1816
+ }
1817
+ state.embedSpans.clear();
1818
+ for (const toolSpan of state.toolSpans.values()) {
1819
+ this.traceShipper.endSpan(toolSpan, { error: actualError });
1820
+ }
1821
+ state.toolSpans.clear();
1822
+ if (state.rootSpan) {
1823
+ this.traceShipper.endSpan(state.rootSpan, { error: actualError });
1824
+ }
1825
+ this.cleanup(event.callId);
1826
+ };
1827
+ // ── executeTool ─────────────────────────────────────────────────────────
1828
+ this.executeTool = async ({
1829
+ callId,
1830
+ toolCallId,
1831
+ execute
1832
+ }) => {
1833
+ const state = this.getState(callId);
1834
+ const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
1835
+ if (!toolSpan) return execute();
1836
+ return runWithParentSpanContext(
1837
+ {
1838
+ traceIdB64: toolSpan.ids.traceIdB64,
1839
+ spanIdB64: toolSpan.ids.spanIdB64,
1840
+ eventId: state.eventId
1841
+ },
1842
+ () => execute()
1843
+ );
1844
+ };
1845
+ this.traceShipper = opts.traceShipper;
1846
+ this.eventShipper = opts.eventShipper;
1847
+ this.sendTraces = opts.sendTraces !== false;
1848
+ this.sendEvents = opts.sendEvents !== false;
1849
+ this.debug = opts.debug === true;
1850
+ this.defaultContext = opts.context;
1851
+ }
1852
+ // ── helpers ──────────────────────────────────────────────────────────────
1853
+ getState(callId) {
1854
+ return this.callStates.get(callId);
1855
+ }
1856
+ cleanup(callId) {
1857
+ this.callStates.delete(callId);
1858
+ }
1859
+ spanParentRef(span) {
1860
+ return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
1861
+ }
1862
+ emitLive(state, type, content, extra) {
1863
+ var _a, _b, _c, _d, _e, _f;
1864
+ if (!localDebuggerEnabled() || !state.rootSpan) return;
1865
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1866
+ sendLocalDebuggerLiveEvent({
1867
+ traceId: state.rootSpan.ids.traceIdB64,
1868
+ type,
1869
+ content,
1870
+ metadata: {
1871
+ userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
1872
+ convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
1873
+ eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
1874
+ eventId: state.eventId,
1875
+ ...extra
1876
+ }
1877
+ });
1878
+ }
1879
+ extractRaindropMetadata(metadata) {
1880
+ if (!metadata) return {};
1881
+ const result = {};
1882
+ const userId = metadata["raindrop.userId"];
1883
+ if (typeof userId === "string" && userId) result.userId = userId;
1884
+ const eventId = metadata["raindrop.eventId"];
1885
+ if (typeof eventId === "string" && eventId) result.eventId = eventId;
1886
+ const convoId = metadata["raindrop.convoId"];
1887
+ if (typeof convoId === "string" && convoId) result.convoId = convoId;
1888
+ const eventName = metadata["raindrop.eventName"];
1889
+ if (typeof eventName === "string" && eventName) result.eventName = eventName;
1890
+ const properties = metadata["raindrop.properties"];
1891
+ if (typeof properties === "string") {
1892
+ try {
1893
+ result.properties = JSON.parse(properties);
1894
+ } catch (e) {
1895
+ }
1896
+ } else if (properties && typeof properties === "object") {
1897
+ result.properties = properties;
1898
+ }
1899
+ return result;
1900
+ }
1901
+ /**
1902
+ * Extract the user-facing input text from an onStart event.
1903
+ * Mirrors the logic in the v4-v6 Proxy path (lastUserMessageTextFromArgs / extractInputFromArgs).
1904
+ */
1905
+ extractInputText(event) {
1906
+ if (typeof event.prompt === "string") return event.prompt;
1907
+ if (Array.isArray(event.messages)) {
1908
+ for (let i = event.messages.length - 1; i >= 0; i--) {
1909
+ const msg = event.messages[i];
1910
+ if ((msg == null ? void 0 : msg.role) === "user") {
1911
+ if (typeof msg.content === "string") return msg.content;
1912
+ if (Array.isArray(msg.content)) {
1913
+ const textPart = msg.content.find(
1914
+ (p) => (p == null ? void 0 : p.type) === "text" && typeof p.text === "string"
1915
+ );
1916
+ if (textPart) return textPart.text;
1917
+ }
1918
+ }
1919
+ }
1920
+ }
1921
+ return void 0;
1922
+ }
1923
+ finishGenerate(event, state) {
1924
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1925
+ if (state.rootSpan) {
1926
+ const outputAttrs = [];
1927
+ if (state.recordOutputs) {
1928
+ outputAttrs.push(
1929
+ attrString("ai.response.finishReason", event.finishReason),
1930
+ attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1931
+ attrString(
1932
+ "ai.response.providerMetadata",
1933
+ event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1934
+ )
1935
+ );
1936
+ if (((_b = event.toolCalls) == null ? void 0 : _b.length) > 0) {
1937
+ outputAttrs.push(
1938
+ attrString(
1939
+ "ai.response.toolCalls",
1940
+ JSON.stringify(
1941
+ event.toolCalls.map((tc) => ({
1942
+ toolCallId: tc.toolCallId,
1943
+ toolName: tc.toolName,
1944
+ input: tc.input
1945
+ }))
1946
+ )
1947
+ )
1948
+ );
1949
+ }
1950
+ if (((_c = event.reasoning) == null ? void 0 : _c.length) > 0) {
1951
+ const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1952
+ if (reasoningText) {
1953
+ outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1954
+ }
1955
+ }
1956
+ }
1957
+ const usage = (_d = event.totalUsage) != null ? _d : event.usage;
1958
+ if (usage) {
1959
+ outputAttrs.push(
1960
+ attrInt("ai.usage.inputTokens", usage.inputTokens),
1961
+ attrInt("ai.usage.outputTokens", usage.outputTokens),
1962
+ attrInt("ai.usage.totalTokens", usage.totalTokens),
1963
+ attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1964
+ attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens)
1965
+ );
1966
+ }
1967
+ outputAttrs.push(
1968
+ attrInt("ai.toolCall.count", state.toolCallCount)
1969
+ );
1970
+ this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
1971
+ }
1972
+ if (this.sendEvents) {
1973
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1974
+ const userId = (_f = callMeta.userId) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.userId;
1975
+ if (userId) {
1976
+ const eventName = (_i = (_h = callMeta.eventName) != null ? _h : (_g = this.defaultContext) == null ? void 0 : _g.eventName) != null ? _i : state.operationId;
1977
+ const output = (_j = event.text) != null ? _j : state.accumulatedText || void 0;
1978
+ const input = state.inputText;
1979
+ const model = (_k = event.response) == null ? void 0 : _k.modelId;
1980
+ const properties = {
1981
+ ...(_l = this.defaultContext) == null ? void 0 : _l.properties,
1982
+ ...callMeta.properties
1983
+ };
1984
+ const convoId = (_n = callMeta.convoId) != null ? _n : (_m = this.defaultContext) == null ? void 0 : _m.convoId;
1985
+ void this.eventShipper.patch(state.eventId, {
1986
+ eventName,
1987
+ userId,
1988
+ convoId,
1989
+ input,
1990
+ output,
1991
+ model,
1992
+ properties: Object.keys(properties).length > 0 ? properties : void 0,
1993
+ isPending: false
1994
+ }).catch((err) => {
1995
+ if (this.debug) {
1996
+ console.warn(
1997
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1998
+ );
1999
+ }
2000
+ });
2001
+ }
2002
+ }
2003
+ }
2004
+ finishEmbed(event, state) {
2005
+ var _a;
2006
+ if (!state.rootSpan) return;
2007
+ const outputAttrs = [];
2008
+ const isMany = state.operationId === "ai.embedMany";
2009
+ if (state.recordOutputs) {
2010
+ if (isMany) {
2011
+ outputAttrs.push(
2012
+ attrString("ai.embeddings", safeJsonWithUint8(event.embedding))
2013
+ );
2014
+ } else {
2015
+ outputAttrs.push(
2016
+ attrString("ai.embedding", safeJsonWithUint8(event.embedding))
2017
+ );
2018
+ }
2019
+ }
2020
+ if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
2021
+ outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
2022
+ }
2023
+ this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
2024
+ }
2025
+ };
2026
+
2027
+ // src/internal/traces.ts
2028
+ var TraceShipper2 = class extends TraceShipper {
2029
+ constructor(opts) {
2030
+ var _a, _b, _c;
2031
+ super({
2032
+ ...opts,
2033
+ sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
2034
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
2035
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
2036
+ });
2037
+ }
2038
+ };
2039
+
1388
2040
  // src/internal/wrap/wrapAISDK.ts
1389
2041
  var AGENT_REPORTING_TOOL_NAME_DEFAULT = "__raindrop_report";
1390
2042
  var AGENT_REPORTING_SIGNALS_DEFAULT = {
@@ -1594,6 +2246,9 @@ function detectAISDKVersion(aiSDK) {
1594
2246
  if (isFunction(aiSDK["tool"])) return "5";
1595
2247
  return "4";
1596
2248
  }
2249
+ function hasStructuredTelemetryEvents(aiSDK) {
2250
+ return isRecord(aiSDK) && isFunction(aiSDK["registerTelemetryIntegration"]) && isFunction(aiSDK["experimental_streamModelCall"]);
2251
+ }
1597
2252
  function asVercelSchema(jsonSchemaObj) {
1598
2253
  const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
1599
2254
  const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
@@ -1766,6 +2421,36 @@ function shouldKeepEventPending(params) {
1766
2421
  if (params.error != null || !params.canKeepEventPending) return false;
1767
2422
  return params.finishReason === "tool-calls" || params.finishReason === "tool_calls";
1768
2423
  }
2424
+ function normalizePromptAttr(arg) {
2425
+ if (!isRecord(arg)) return arg;
2426
+ const system = arg["system"];
2427
+ const prompt = arg["prompt"];
2428
+ const messages = arg["messages"];
2429
+ if (Array.isArray(messages)) {
2430
+ if (system) {
2431
+ const sysContent = typeof system === "string" ? system : JSON.stringify(system);
2432
+ return [{ role: "system", content: sysContent }, ...messages];
2433
+ }
2434
+ return messages;
2435
+ }
2436
+ if (typeof prompt === "string") {
2437
+ const msgs = [];
2438
+ if (system) {
2439
+ msgs.push({ role: "system", content: typeof system === "string" ? system : JSON.stringify(system) });
2440
+ }
2441
+ msgs.push({ role: "user", content: prompt });
2442
+ return msgs;
2443
+ }
2444
+ return { system, prompt, messages };
2445
+ }
2446
+ function getLocalDebuggerMetadata(ctx) {
2447
+ return {
2448
+ eventId: ctx.eventId,
2449
+ ...ctx.eventName ? { eventName: ctx.eventName } : {},
2450
+ ...ctx.userId ? { userId: ctx.userId } : {},
2451
+ ...ctx.convoId ? { convoId: ctx.convoId } : {}
2452
+ };
2453
+ }
1769
2454
  async function safeFinalize(finalize, debug, result, error) {
1770
2455
  try {
1771
2456
  await finalize(result, error);
@@ -1838,17 +2523,17 @@ function setupOperation(params) {
1838
2523
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1839
2524
  attrString("ai.model.provider", modelInfoFromArgs.provider),
1840
2525
  attrString("ai.model.id", modelInfoFromArgs.modelId),
2526
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
2527
+ attrString("ai.telemetry.metadata.raindrop.eventName", mergedCtx.eventName),
2528
+ attrString("ai.telemetry.metadata.raindrop.userId", mergedCtx.userId),
2529
+ attrString("ai.telemetry.metadata.raindrop.convoId", mergedCtx.convoId),
1841
2530
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1842
2531
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1843
2532
  ...attrsFromSettings(arg),
1844
2533
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1845
2534
  attrString(
1846
2535
  "ai.prompt",
1847
- safeJsonWithUint8({
1848
- system: isRecord(arg) ? arg["system"] : void 0,
1849
- prompt: isRecord(arg) ? arg["prompt"] : void 0,
1850
- messages: isRecord(arg) ? arg["messages"] : void 0
1851
- })
2536
+ safeJsonWithUint8(normalizePromptAttr(arg))
1852
2537
  )
1853
2538
  ]
1854
2539
  ]
@@ -1857,6 +2542,7 @@ function setupOperation(params) {
1857
2542
  const operationSelfDiagnostics = isObjectOperation(operation) ? void 0 : selfDiagnostics;
1858
2543
  const wrapCtx = {
1859
2544
  eventId,
2545
+ context: mergedCtx,
1860
2546
  telemetry,
1861
2547
  sendTraces,
1862
2548
  debug,
@@ -2176,8 +2862,100 @@ async function executeNonStreamingOperation(params) {
2176
2862
  }
2177
2863
  }
2178
2864
  function wrapAISDK(aiSDK, deps) {
2179
- var _a, _b;
2865
+ var _a, _b, _c, _d;
2180
2866
  const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
2867
+ if (deps.options.nativeTelemetry === true) {
2868
+ if (!hasStructuredTelemetryEvents(aiSDK)) {
2869
+ throw new Error(
2870
+ "[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."
2871
+ );
2872
+ }
2873
+ }
2874
+ const useNative = deps.options.nativeTelemetry === true;
2875
+ if (useNative) {
2876
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
2877
+ const integration = new RaindropTelemetryIntegration({
2878
+ traceShipper: deps.traceShipper,
2879
+ eventShipper: deps.eventShipper,
2880
+ sendTraces: ((_a = deps.options.send) == null ? void 0 : _a.traces) !== false,
2881
+ sendEvents: ((_b = deps.options.send) == null ? void 0 : _b.events) !== false,
2882
+ debug,
2883
+ context: {
2884
+ userId: wrapTimeCtx.userId,
2885
+ eventId: wrapTimeCtx.eventId,
2886
+ eventName: wrapTimeCtx.eventName,
2887
+ convoId: wrapTimeCtx.convoId,
2888
+ properties: wrapTimeCtx.properties
2889
+ }
2890
+ });
2891
+ const registerFn = aiSDK["registerTelemetryIntegration"];
2892
+ if (isFunction(registerFn)) {
2893
+ registerFn(integration);
2894
+ }
2895
+ if (debug) {
2896
+ console.log("[raindrop-ai/ai-sdk] nativeTelemetry: registered RaindropTelemetryIntegration (no Proxy)");
2897
+ }
2898
+ const selfDiagnostics2 = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2899
+ if (selfDiagnostics2) {
2900
+ const textOps = /* @__PURE__ */ new Set(["generateText", "streamText"]);
2901
+ const jsonSchemaFactory = resolveJsonSchemaFactory(aiSDK);
2902
+ const proxyTarget2 = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
2903
+ return new Proxy(proxyTarget2, {
2904
+ get(target, prop, receiver) {
2905
+ const original = Reflect.get(target, prop, receiver);
2906
+ if (typeof prop !== "string" || !textOps.has(prop) || !isFunction(original)) {
2907
+ return original;
2908
+ }
2909
+ return (...callArgs) => {
2910
+ var _a2;
2911
+ const arg = callArgs[0];
2912
+ if (!isRecord(arg)) return original.call(aiSDK, ...callArgs);
2913
+ const telemetry = extractExperimentalTelemetry(arg);
2914
+ const callMeta = (telemetry == null ? void 0 : telemetry.metadata) ? extractRaindropMetadata(telemetry.metadata) : {};
2915
+ const perCallEventIdExplicit = (_a2 = callMeta.eventId) != null ? _a2 : wrapTimeCtx.eventId;
2916
+ const perCallEventId = perCallEventIdExplicit != null ? perCallEventIdExplicit : randomUUID();
2917
+ const perCallEventIdGenerated = !perCallEventIdExplicit;
2918
+ const perCallCtx = {
2919
+ eventId: perCallEventId,
2920
+ context: wrapTimeCtx,
2921
+ telemetry,
2922
+ sendTraces: false,
2923
+ debug,
2924
+ eventShipper: deps.eventShipper,
2925
+ traceShipper: deps.traceShipper,
2926
+ rootParentForChildren: void 0,
2927
+ jsonSchemaFactory,
2928
+ selfDiagnostics: selfDiagnostics2,
2929
+ aiSDKVersion: "7"
2930
+ };
2931
+ const tools = isRecord(arg["tools"]) ? { ...arg["tools"] } : {};
2932
+ const toolName = selfDiagnostics2.toolName;
2933
+ if (!(toolName in tools)) {
2934
+ const reportTool = createSelfDiagnosticsTool(perCallCtx);
2935
+ if (reportTool) tools[toolName] = reportTool;
2936
+ }
2937
+ const existingTelemetry = isRecord(arg["experimental_telemetry"]) ? arg["experimental_telemetry"] : {};
2938
+ const existingMetadata = isRecord(existingTelemetry["metadata"]) ? existingTelemetry["metadata"] : {};
2939
+ const mergedMetadata = existingMetadata["raindrop.eventId"] ? existingMetadata : {
2940
+ ...existingMetadata,
2941
+ "raindrop.eventId": perCallEventId,
2942
+ ...perCallEventIdGenerated ? { "raindrop.internal.eventIdGenerated": "true" } : {}
2943
+ };
2944
+ callArgs[0] = {
2945
+ ...arg,
2946
+ tools,
2947
+ experimental_telemetry: {
2948
+ ...existingTelemetry,
2949
+ metadata: mergedMetadata
2950
+ }
2951
+ };
2952
+ return original.call(aiSDK, ...callArgs);
2953
+ };
2954
+ }
2955
+ });
2956
+ }
2957
+ return aiSDK;
2958
+ }
2181
2959
  const instrumentedOps = /* @__PURE__ */ new Set([
2182
2960
  "generateText",
2183
2961
  "streamText",
@@ -2185,8 +2963,8 @@ function wrapAISDK(aiSDK, deps) {
2185
2963
  "streamObject"
2186
2964
  ]);
2187
2965
  const agentClasses = /* @__PURE__ */ new Set(["Agent", "Experimental_Agent", "ToolLoopAgent"]);
2188
- const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
2189
- const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
2966
+ const sendEvents = ((_c = deps.options.send) == null ? void 0 : _c.events) !== false;
2967
+ const sendTraces = ((_d = deps.options.send) == null ? void 0 : _d.traces) !== false;
2190
2968
  const autoAttachmentEnabled = deps.options.autoAttachment !== false;
2191
2969
  const selfDiagnostics = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2192
2970
  const proxyTarget = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
@@ -2294,7 +3072,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2294
3072
  if (!mergedCtx.userId) warnMissingUserIdOnce();
2295
3073
  const inherited = await getCurrentParentSpanContext();
2296
3074
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2297
- const ctx = { ...mergedCtx};
3075
+ const ctx = { ...mergedCtx, eventId };
2298
3076
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2299
3077
  const outerOperationId = `ai.${operation}`;
2300
3078
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -2310,17 +3088,17 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2310
3088
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2311
3089
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2312
3090
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3091
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3092
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3093
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3094
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
2313
3095
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2314
3096
  ...attrsFromHeaders(mergedArgs["headers"]),
2315
3097
  ...attrsFromSettings(mergedArgs),
2316
3098
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2317
3099
  attrString(
2318
3100
  "ai.prompt",
2319
- safeJsonWithUint8({
2320
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2321
- prompt: mergedArgs["prompt"],
2322
- messages: mergedArgs["messages"]
2323
- })
3101
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
2324
3102
  )
2325
3103
  ]
2326
3104
  ]
@@ -2328,6 +3106,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2328
3106
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2329
3107
  const wrapCtx = {
2330
3108
  eventId,
3109
+ context: ctx,
2331
3110
  telemetry,
2332
3111
  sendTraces,
2333
3112
  debug,
@@ -2501,7 +3280,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2501
3280
  if (!mergedCtx.userId) warnMissingUserIdOnce();
2502
3281
  const inherited = await getCurrentParentSpanContext();
2503
3282
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2504
- const ctx = { ...mergedCtx};
3283
+ const ctx = { ...mergedCtx, eventId };
2505
3284
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2506
3285
  const outerOperationId = `ai.${operation}`;
2507
3286
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -2517,17 +3296,17 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2517
3296
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2518
3297
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2519
3298
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3299
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3300
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3301
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3302
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
2520
3303
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2521
3304
  ...attrsFromHeaders(mergedArgs["headers"]),
2522
3305
  ...attrsFromSettings(mergedArgs),
2523
3306
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2524
3307
  attrString(
2525
3308
  "ai.prompt",
2526
- safeJsonWithUint8({
2527
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2528
- prompt: mergedArgs["prompt"],
2529
- messages: mergedArgs["messages"]
2530
- })
3309
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
2531
3310
  )
2532
3311
  ]
2533
3312
  ]
@@ -2535,6 +3314,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2535
3314
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2536
3315
  const wrapCtx = {
2537
3316
  eventId,
3317
+ context: ctx,
2538
3318
  telemetry,
2539
3319
  sendTraces,
2540
3320
  debug,
@@ -2758,6 +3538,21 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2758
3538
  });
2759
3539
  }
2760
3540
  };
3541
+ const sendToolLiveEvent = (parent, type, metadata) => {
3542
+ if (!localDebuggerEnabled() || !parent) return;
3543
+ sendLocalDebuggerLiveEvent({
3544
+ traceId: parent.traceIdB64,
3545
+ type,
3546
+ content: name,
3547
+ metadata: {
3548
+ ...getLocalDebuggerMetadata({
3549
+ ...ctx.context,
3550
+ eventId: ctx.eventId
3551
+ }),
3552
+ ...metadata
3553
+ }
3554
+ });
3555
+ };
2761
3556
  const createContextSpan = (span) => ({
2762
3557
  traceIdB64: span.ids.traceIdB64,
2763
3558
  spanIdB64: span.ids.spanIdB64,
@@ -2773,6 +3568,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2773
3568
  const parentCtx = await getCurrentParentSpanContext();
2774
3569
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2775
3570
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3571
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
2776
3572
  try {
2777
3573
  let lastValue;
2778
3574
  const iterator = result[Symbol.asyncIterator]();
@@ -2788,9 +3584,13 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2788
3584
  }
2789
3585
  toolCalls.push({ id: toolCallId, name, args: toolArgs, result: lastValue, status: "OK" });
2790
3586
  endToolSpan(toolSpan, lastValue);
3587
+ sendToolLiveEvent(parent, "tool_result", { result: lastValue });
2791
3588
  } catch (error) {
2792
3589
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
2793
3590
  endToolSpan(toolSpan, void 0, error);
3591
+ sendToolLiveEvent(parent, "tool_result", {
3592
+ error: error instanceof Error ? error.message : String(error)
3593
+ });
2794
3594
  throw error;
2795
3595
  }
2796
3596
  })();
@@ -2799,6 +3599,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2799
3599
  const parentCtx = await getCurrentParentSpanContext();
2800
3600
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2801
3601
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3602
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
2802
3603
  const run = async () => {
2803
3604
  try {
2804
3605
  const awaitedResult = await result;
@@ -2810,10 +3611,14 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2810
3611
  status: "OK"
2811
3612
  });
2812
3613
  endToolSpan(toolSpan, awaitedResult);
3614
+ sendToolLiveEvent(parent, "tool_result", { result: awaitedResult });
2813
3615
  return awaitedResult;
2814
3616
  } catch (error) {
2815
3617
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
2816
3618
  endToolSpan(toolSpan, void 0, error);
3619
+ sendToolLiveEvent(parent, "tool_result", {
3620
+ error: error instanceof Error ? error.message : String(error)
3621
+ });
2817
3622
  throw error;
2818
3623
  }
2819
3624
  };
@@ -2853,6 +3658,7 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2853
3658
  const original = Reflect.get(target, prop, receiver);
2854
3659
  if (prop === "doGenerate" && isFunction(original)) {
2855
3660
  return async (...callArgs) => {
3661
+ var _a, _b;
2856
3662
  const options = callArgs[0];
2857
3663
  const parentCtx = await getCurrentParentSpanContext();
2858
3664
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
@@ -2860,6 +3666,22 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2860
3666
  try {
2861
3667
  const result = await original.apply(target, callArgs);
2862
3668
  if (span) endDoGenerateSpan(span, result, modelInfo, ctx);
3669
+ if (localDebuggerEnabled() && ctx.rootParentForChildren && isRecord(result)) {
3670
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3671
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3672
+ const content = result["content"];
3673
+ if (Array.isArray(content)) {
3674
+ for (const part of content) {
3675
+ if (isRecord(part)) {
3676
+ if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
3677
+ sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
3678
+ } else if (part["type"] === "text" && typeof part["text"] === "string") {
3679
+ sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
3680
+ }
3681
+ }
3682
+ }
3683
+ }
3684
+ }
2863
3685
  return result;
2864
3686
  } catch (error) {
2865
3687
  if (span)
@@ -2999,6 +3821,23 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2999
3821
  }
3000
3822
  if ("usage" in value) usage = value["usage"];
3001
3823
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
3824
+ if (localDebuggerEnabled() && ctx.rootParentForChildren) {
3825
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3826
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3827
+ if (type === "text-delta") {
3828
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
3829
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
3830
+ } else if (type === "reasoning" || type === "reasoning-delta") {
3831
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
3832
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
3833
+ } else if (type === "tool-call") {
3834
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3835
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
3836
+ } else if (type === "tool-result") {
3837
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3838
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
3839
+ }
3840
+ }
3002
3841
  }
3003
3842
  controller.enqueue(value);
3004
3843
  } catch (error) {
@@ -3280,6 +4119,16 @@ function createRaindropAISDK(opts) {
3280
4119
  traceShipper
3281
4120
  });
3282
4121
  },
4122
+ createTelemetryIntegration(context) {
4123
+ return new RaindropTelemetryIntegration({
4124
+ traceShipper,
4125
+ eventShipper,
4126
+ sendTraces: tracesEnabled,
4127
+ sendEvents: eventsEnabled,
4128
+ debug: envDebug,
4129
+ context
4130
+ });
4131
+ },
3283
4132
  events: {
3284
4133
  async patch(eventId, patch) {
3285
4134
  await eventShipper.patch(eventId, patch);
@@ -3313,6 +4162,7 @@ function createRaindropAISDK(opts) {
3313
4162
  };
3314
4163
  }
3315
4164
 
4165
+ exports.RaindropTelemetryIntegration = RaindropTelemetryIntegration;
3316
4166
  exports._resetWarnedMissingUserId = _resetWarnedMissingUserId;
3317
4167
  exports.createRaindropAISDK = createRaindropAISDK;
3318
4168
  exports.currentSpan = currentSpan;