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