@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
  import { AsyncLocalStorage } from 'async_hooks';
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;
@@ -1351,6 +1448,561 @@ function attrsFromGenAiRequest(options) {
1351
1448
  ];
1352
1449
  }
1353
1450
 
1451
+ // src/internal/raindrop-telemetry-integration.ts
1452
+ var RaindropTelemetryIntegration = class {
1453
+ constructor(opts) {
1454
+ this.callStates = /* @__PURE__ */ new Map();
1455
+ // ── onStart ─────────────────────────────────────────────────────────────
1456
+ this.onStart = (event) => {
1457
+ var _a, _b, _c, _d;
1458
+ if (event.isEnabled !== true) return;
1459
+ const isEmbed = event.operationId === "ai.embed" || event.operationId === "ai.embedMany";
1460
+ const recordInputs = event.recordInputs !== false;
1461
+ const recordOutputs = event.recordOutputs !== false;
1462
+ const functionId = event.functionId;
1463
+ const metadata = event.metadata;
1464
+ const callMeta = this.extractRaindropMetadata(metadata);
1465
+ const inherited = getContextManager().getParentSpanIds();
1466
+ const eventIdGenerated = (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === "true" || (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === true;
1467
+ const explicitEventId = callMeta.eventId && !eventIdGenerated ? callMeta.eventId : void 0;
1468
+ 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();
1469
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1470
+ const { operationName, resourceName } = opName(
1471
+ event.operationId,
1472
+ functionId
1473
+ );
1474
+ let rootSpan;
1475
+ if (this.sendTraces) {
1476
+ const promptAttrs = !isEmbed && recordInputs ? [
1477
+ attrString(
1478
+ "ai.prompt",
1479
+ safeJsonWithUint8({
1480
+ system: event.system,
1481
+ prompt: event.prompt,
1482
+ messages: event.messages
1483
+ })
1484
+ )
1485
+ ] : [];
1486
+ const embedAttrs = isEmbed && recordInputs ? event.operationId === "ai.embedMany" ? [
1487
+ attrString(
1488
+ "ai.values",
1489
+ safeJsonWithUint8(event.value)
1490
+ )
1491
+ ] : [attrString("ai.value", safeJsonWithUint8(event.value))] : [];
1492
+ rootSpan = this.traceShipper.startSpan({
1493
+ name: event.operationId,
1494
+ parent: inheritedParent,
1495
+ eventId,
1496
+ operationId: event.operationId,
1497
+ attributes: [
1498
+ attrString("operation.name", operationName),
1499
+ attrString("resource.name", resourceName),
1500
+ attrString("ai.telemetry.functionId", functionId),
1501
+ attrString("ai.model.provider", event.provider),
1502
+ attrString("ai.model.id", event.modelId),
1503
+ // Filter out raindrop.eventId from metadata attrs since TraceShipper
1504
+ // already sets it via the eventId arg. Without this, eventMetadata()'s
1505
+ // auto-generated ID would duplicate and override the resolved one.
1506
+ ...attrsFromTelemetryMetadata(
1507
+ metadata ? Object.fromEntries(
1508
+ Object.entries(metadata).filter(
1509
+ ([k]) => k !== "raindrop.eventId" && k !== "raindrop.internal.eventIdGenerated"
1510
+ )
1511
+ ) : void 0
1512
+ ),
1513
+ ...promptAttrs,
1514
+ ...embedAttrs
1515
+ ]
1516
+ });
1517
+ }
1518
+ this.callStates.set(event.callId, {
1519
+ operationId: event.operationId,
1520
+ eventId,
1521
+ rootSpan,
1522
+ rootParent: rootSpan ? this.spanParentRef(rootSpan) : inheritedParent,
1523
+ stepSpan: void 0,
1524
+ stepParent: void 0,
1525
+ toolSpans: /* @__PURE__ */ new Map(),
1526
+ embedSpans: /* @__PURE__ */ new Map(),
1527
+ recordInputs,
1528
+ recordOutputs,
1529
+ functionId,
1530
+ metadata,
1531
+ accumulatedText: "",
1532
+ inputText: isEmbed ? void 0 : this.extractInputText(event),
1533
+ toolCallCount: 0
1534
+ });
1535
+ };
1536
+ // ── onStepStart ─────────────────────────────────────────────────────────
1537
+ this.onStepStart = (event) => {
1538
+ const state = this.getState(event.callId);
1539
+ if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1540
+ const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
1541
+ const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
1542
+ const { operationName, resourceName } = opName(
1543
+ stepOperationId,
1544
+ state.functionId
1545
+ );
1546
+ const inputAttrs = [];
1547
+ if (state.recordInputs) {
1548
+ if (event.promptMessages) {
1549
+ inputAttrs.push(
1550
+ attrString(
1551
+ "ai.prompt.messages",
1552
+ safeJsonWithUint8(event.promptMessages)
1553
+ )
1554
+ );
1555
+ }
1556
+ if (event.stepTools) {
1557
+ inputAttrs.push(
1558
+ attrStringArray(
1559
+ "ai.prompt.tools",
1560
+ event.stepTools.map((t) => JSON.stringify(t))
1561
+ )
1562
+ );
1563
+ }
1564
+ if (event.stepToolChoice != null) {
1565
+ inputAttrs.push(
1566
+ attrString(
1567
+ "ai.prompt.toolChoice",
1568
+ JSON.stringify(event.stepToolChoice)
1569
+ )
1570
+ );
1571
+ }
1572
+ }
1573
+ const stepSpan = this.traceShipper.startSpan({
1574
+ name: stepOperationId,
1575
+ parent: state.rootParent,
1576
+ eventId: state.eventId,
1577
+ operationId: stepOperationId,
1578
+ attributes: [
1579
+ attrString("operation.name", operationName),
1580
+ attrString("resource.name", resourceName),
1581
+ attrString("ai.telemetry.functionId", state.functionId),
1582
+ attrString("ai.model.provider", event.provider),
1583
+ attrString("ai.model.id", event.modelId),
1584
+ attrString("gen_ai.system", event.provider),
1585
+ attrString("gen_ai.request.model", event.modelId),
1586
+ ...inputAttrs
1587
+ ]
1588
+ });
1589
+ state.stepSpan = stepSpan;
1590
+ state.stepParent = this.spanParentRef(stepSpan);
1591
+ };
1592
+ // ── onToolCallStart ─────────────────────────────────────────────────────
1593
+ this.onToolCallStart = (event) => {
1594
+ const state = this.getState(event.callId);
1595
+ if (!(state == null ? void 0 : state.stepParent)) return;
1596
+ const { toolCall } = event;
1597
+ const { operationName, resourceName } = opName(
1598
+ "ai.toolCall",
1599
+ state.functionId
1600
+ );
1601
+ const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
1602
+ const toolSpan = this.traceShipper.startSpan({
1603
+ name: "ai.toolCall",
1604
+ parent: state.stepParent,
1605
+ eventId: state.eventId,
1606
+ operationId: "ai.toolCall",
1607
+ attributes: [
1608
+ attrString("operation.name", operationName),
1609
+ attrString("resource.name", resourceName),
1610
+ attrString("ai.telemetry.functionId", state.functionId),
1611
+ attrString("ai.toolCall.name", toolCall.toolName),
1612
+ attrString("ai.toolCall.id", toolCall.toolCallId),
1613
+ ...inputAttrs
1614
+ ]
1615
+ });
1616
+ state.toolSpans.set(toolCall.toolCallId, toolSpan);
1617
+ this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
1618
+ };
1619
+ // ── onToolCallFinish ────────────────────────────────────────────────────
1620
+ this.onToolCallFinish = (event) => {
1621
+ const state = this.getState(event.callId);
1622
+ if (!state) return;
1623
+ const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
1624
+ if (!toolSpan) return;
1625
+ state.toolCallCount += 1;
1626
+ if (event.success) {
1627
+ const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(event.output))] : [];
1628
+ this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
1629
+ } else {
1630
+ this.traceShipper.endSpan(toolSpan, { error: event.error });
1631
+ }
1632
+ this.emitLive(state, "tool_result", event.toolCall.toolName);
1633
+ state.toolSpans.delete(event.toolCall.toolCallId);
1634
+ };
1635
+ // ── onChunk (streaming) ─────────────────────────────────────────────────
1636
+ this.onChunk = (event) => {
1637
+ var _a, _b, _c, _d, _e;
1638
+ const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
1639
+ if (!callId) return;
1640
+ const state = this.getState(callId);
1641
+ if (!state) return;
1642
+ const chunk = event.chunk;
1643
+ if (!chunk || typeof chunk !== "object") return;
1644
+ if (chunk.type === "text-delta") {
1645
+ const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
1646
+ if (typeof delta === "string") {
1647
+ state.accumulatedText += delta;
1648
+ this.emitLive(state, "text_delta", delta);
1649
+ }
1650
+ } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
1651
+ const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
1652
+ if (typeof text === "string") {
1653
+ this.emitLive(state, "reasoning_delta", text);
1654
+ }
1655
+ }
1656
+ };
1657
+ // ── onStepFinish ────────────────────────────────────────────────────────
1658
+ this.onStepFinish = (event) => {
1659
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1660
+ const state = this.getState(event.callId);
1661
+ if (!(state == null ? void 0 : state.stepSpan)) return;
1662
+ const outputAttrs = [];
1663
+ if (state.recordOutputs) {
1664
+ outputAttrs.push(
1665
+ attrString("ai.response.finishReason", event.finishReason),
1666
+ attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1667
+ attrString("ai.response.id", (_b = event.response) == null ? void 0 : _b.id),
1668
+ attrString("ai.response.model", (_c = event.response) == null ? void 0 : _c.modelId),
1669
+ attrString(
1670
+ "ai.response.timestamp",
1671
+ ((_d = event.response) == null ? void 0 : _d.timestamp) instanceof Date ? event.response.timestamp.toISOString() : (_e = event.response) == null ? void 0 : _e.timestamp
1672
+ ),
1673
+ attrString(
1674
+ "ai.response.providerMetadata",
1675
+ event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1676
+ )
1677
+ );
1678
+ if (((_f = event.toolCalls) == null ? void 0 : _f.length) > 0) {
1679
+ outputAttrs.push(
1680
+ attrString(
1681
+ "ai.response.toolCalls",
1682
+ JSON.stringify(
1683
+ event.toolCalls.map((tc) => ({
1684
+ toolCallId: tc.toolCallId,
1685
+ toolName: tc.toolName,
1686
+ input: tc.input
1687
+ }))
1688
+ )
1689
+ )
1690
+ );
1691
+ }
1692
+ if (((_g = event.reasoning) == null ? void 0 : _g.length) > 0) {
1693
+ const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1694
+ if (reasoningText) {
1695
+ outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1696
+ }
1697
+ }
1698
+ }
1699
+ outputAttrs.push(
1700
+ attrStringArray("gen_ai.response.finish_reasons", [event.finishReason]),
1701
+ attrString("gen_ai.response.id", (_h = event.response) == null ? void 0 : _h.id),
1702
+ attrString("gen_ai.response.model", (_i = event.response) == null ? void 0 : _i.modelId)
1703
+ );
1704
+ const usage = event.usage;
1705
+ if (usage) {
1706
+ outputAttrs.push(
1707
+ attrInt("ai.usage.inputTokens", usage.inputTokens),
1708
+ attrInt("ai.usage.outputTokens", usage.outputTokens),
1709
+ attrInt("ai.usage.totalTokens", usage.totalTokens),
1710
+ attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1711
+ attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens),
1712
+ attrInt("gen_ai.usage.input_tokens", usage.inputTokens),
1713
+ attrInt("gen_ai.usage.output_tokens", usage.outputTokens)
1714
+ );
1715
+ }
1716
+ this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
1717
+ state.stepSpan = void 0;
1718
+ state.stepParent = void 0;
1719
+ };
1720
+ // ── onEmbedStart ────────────────────────────────────────────────────────
1721
+ this.onEmbedStart = (event) => {
1722
+ const state = this.getState(event.callId);
1723
+ if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1724
+ const { operationName, resourceName } = opName(
1725
+ event.operationId,
1726
+ state.functionId
1727
+ );
1728
+ const inputAttrs = state.recordInputs ? [
1729
+ attrString(
1730
+ "ai.values",
1731
+ safeJsonWithUint8(event.values)
1732
+ )
1733
+ ] : [];
1734
+ const embedSpan = this.traceShipper.startSpan({
1735
+ name: event.operationId,
1736
+ parent: state.rootParent,
1737
+ eventId: state.eventId,
1738
+ operationId: event.operationId,
1739
+ attributes: [
1740
+ attrString("operation.name", operationName),
1741
+ attrString("resource.name", resourceName),
1742
+ attrString("ai.telemetry.functionId", state.functionId),
1743
+ ...inputAttrs
1744
+ ]
1745
+ });
1746
+ state.embedSpans.set(event.embedCallId, embedSpan);
1747
+ };
1748
+ // ── onEmbedFinish ───────────────────────────────────────────────────────
1749
+ this.onEmbedFinish = (event) => {
1750
+ var _a;
1751
+ const state = this.getState(event.callId);
1752
+ if (!state) return;
1753
+ const embedSpan = state.embedSpans.get(event.embedCallId);
1754
+ if (!embedSpan) return;
1755
+ const outputAttrs = [];
1756
+ if (state.recordOutputs) {
1757
+ outputAttrs.push(
1758
+ attrString(
1759
+ "ai.embeddings",
1760
+ safeJsonWithUint8(event.embeddings)
1761
+ )
1762
+ );
1763
+ }
1764
+ if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
1765
+ outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
1766
+ }
1767
+ this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
1768
+ state.embedSpans.delete(event.embedCallId);
1769
+ };
1770
+ // ── onFinish ────────────────────────────────────────────────────────────
1771
+ this.onFinish = (event) => {
1772
+ const state = this.getState(event.callId);
1773
+ if (!state) return;
1774
+ const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
1775
+ if (isEmbed) {
1776
+ this.finishEmbed(event, state);
1777
+ } else {
1778
+ this.finishGenerate(event, state);
1779
+ }
1780
+ this.cleanup(event.callId);
1781
+ };
1782
+ // ── onError ─────────────────────────────────────────────────────────────
1783
+ this.onError = (error) => {
1784
+ var _a;
1785
+ const event = error;
1786
+ if (!(event == null ? void 0 : event.callId)) return;
1787
+ const state = this.getState(event.callId);
1788
+ if (!state) return;
1789
+ const actualError = (_a = event.error) != null ? _a : error;
1790
+ if (state.stepSpan) {
1791
+ this.traceShipper.endSpan(state.stepSpan, { error: actualError });
1792
+ }
1793
+ for (const embedSpan of state.embedSpans.values()) {
1794
+ this.traceShipper.endSpan(embedSpan, { error: actualError });
1795
+ }
1796
+ state.embedSpans.clear();
1797
+ for (const toolSpan of state.toolSpans.values()) {
1798
+ this.traceShipper.endSpan(toolSpan, { error: actualError });
1799
+ }
1800
+ state.toolSpans.clear();
1801
+ if (state.rootSpan) {
1802
+ this.traceShipper.endSpan(state.rootSpan, { error: actualError });
1803
+ }
1804
+ this.cleanup(event.callId);
1805
+ };
1806
+ // ── executeTool ─────────────────────────────────────────────────────────
1807
+ this.executeTool = async ({
1808
+ callId,
1809
+ toolCallId,
1810
+ execute
1811
+ }) => {
1812
+ const state = this.getState(callId);
1813
+ const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
1814
+ if (!toolSpan) return execute();
1815
+ return runWithParentSpanContext(
1816
+ {
1817
+ traceIdB64: toolSpan.ids.traceIdB64,
1818
+ spanIdB64: toolSpan.ids.spanIdB64,
1819
+ eventId: state.eventId
1820
+ },
1821
+ () => execute()
1822
+ );
1823
+ };
1824
+ this.traceShipper = opts.traceShipper;
1825
+ this.eventShipper = opts.eventShipper;
1826
+ this.sendTraces = opts.sendTraces !== false;
1827
+ this.sendEvents = opts.sendEvents !== false;
1828
+ this.debug = opts.debug === true;
1829
+ this.defaultContext = opts.context;
1830
+ }
1831
+ // ── helpers ──────────────────────────────────────────────────────────────
1832
+ getState(callId) {
1833
+ return this.callStates.get(callId);
1834
+ }
1835
+ cleanup(callId) {
1836
+ this.callStates.delete(callId);
1837
+ }
1838
+ spanParentRef(span) {
1839
+ return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
1840
+ }
1841
+ emitLive(state, type, content, extra) {
1842
+ var _a, _b, _c, _d, _e, _f;
1843
+ if (!localDebuggerEnabled() || !state.rootSpan) return;
1844
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1845
+ sendLocalDebuggerLiveEvent({
1846
+ traceId: state.rootSpan.ids.traceIdB64,
1847
+ type,
1848
+ content,
1849
+ metadata: {
1850
+ userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
1851
+ convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
1852
+ eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
1853
+ eventId: state.eventId,
1854
+ ...extra
1855
+ }
1856
+ });
1857
+ }
1858
+ extractRaindropMetadata(metadata) {
1859
+ if (!metadata) return {};
1860
+ const result = {};
1861
+ const userId = metadata["raindrop.userId"];
1862
+ if (typeof userId === "string" && userId) result.userId = userId;
1863
+ const eventId = metadata["raindrop.eventId"];
1864
+ if (typeof eventId === "string" && eventId) result.eventId = eventId;
1865
+ const convoId = metadata["raindrop.convoId"];
1866
+ if (typeof convoId === "string" && convoId) result.convoId = convoId;
1867
+ const eventName = metadata["raindrop.eventName"];
1868
+ if (typeof eventName === "string" && eventName) result.eventName = eventName;
1869
+ const properties = metadata["raindrop.properties"];
1870
+ if (typeof properties === "string") {
1871
+ try {
1872
+ result.properties = JSON.parse(properties);
1873
+ } catch (e) {
1874
+ }
1875
+ } else if (properties && typeof properties === "object") {
1876
+ result.properties = properties;
1877
+ }
1878
+ return result;
1879
+ }
1880
+ /**
1881
+ * Extract the user-facing input text from an onStart event.
1882
+ * Mirrors the logic in the v4-v6 Proxy path (lastUserMessageTextFromArgs / extractInputFromArgs).
1883
+ */
1884
+ extractInputText(event) {
1885
+ if (typeof event.prompt === "string") return event.prompt;
1886
+ if (Array.isArray(event.messages)) {
1887
+ for (let i = event.messages.length - 1; i >= 0; i--) {
1888
+ const msg = event.messages[i];
1889
+ if ((msg == null ? void 0 : msg.role) === "user") {
1890
+ if (typeof msg.content === "string") return msg.content;
1891
+ if (Array.isArray(msg.content)) {
1892
+ const textPart = msg.content.find(
1893
+ (p) => (p == null ? void 0 : p.type) === "text" && typeof p.text === "string"
1894
+ );
1895
+ if (textPart) return textPart.text;
1896
+ }
1897
+ }
1898
+ }
1899
+ }
1900
+ return void 0;
1901
+ }
1902
+ finishGenerate(event, state) {
1903
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1904
+ if (state.rootSpan) {
1905
+ const outputAttrs = [];
1906
+ if (state.recordOutputs) {
1907
+ outputAttrs.push(
1908
+ attrString("ai.response.finishReason", event.finishReason),
1909
+ attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1910
+ attrString(
1911
+ "ai.response.providerMetadata",
1912
+ event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1913
+ )
1914
+ );
1915
+ if (((_b = event.toolCalls) == null ? void 0 : _b.length) > 0) {
1916
+ outputAttrs.push(
1917
+ attrString(
1918
+ "ai.response.toolCalls",
1919
+ JSON.stringify(
1920
+ event.toolCalls.map((tc) => ({
1921
+ toolCallId: tc.toolCallId,
1922
+ toolName: tc.toolName,
1923
+ input: tc.input
1924
+ }))
1925
+ )
1926
+ )
1927
+ );
1928
+ }
1929
+ if (((_c = event.reasoning) == null ? void 0 : _c.length) > 0) {
1930
+ const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1931
+ if (reasoningText) {
1932
+ outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1933
+ }
1934
+ }
1935
+ }
1936
+ const usage = (_d = event.totalUsage) != null ? _d : event.usage;
1937
+ if (usage) {
1938
+ outputAttrs.push(
1939
+ attrInt("ai.usage.inputTokens", usage.inputTokens),
1940
+ attrInt("ai.usage.outputTokens", usage.outputTokens),
1941
+ attrInt("ai.usage.totalTokens", usage.totalTokens),
1942
+ attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1943
+ attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens)
1944
+ );
1945
+ }
1946
+ outputAttrs.push(
1947
+ attrInt("ai.toolCall.count", state.toolCallCount)
1948
+ );
1949
+ this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
1950
+ }
1951
+ if (this.sendEvents) {
1952
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1953
+ const userId = (_f = callMeta.userId) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.userId;
1954
+ if (userId) {
1955
+ const eventName = (_i = (_h = callMeta.eventName) != null ? _h : (_g = this.defaultContext) == null ? void 0 : _g.eventName) != null ? _i : state.operationId;
1956
+ const output = (_j = event.text) != null ? _j : state.accumulatedText || void 0;
1957
+ const input = state.inputText;
1958
+ const model = (_k = event.response) == null ? void 0 : _k.modelId;
1959
+ const properties = {
1960
+ ...(_l = this.defaultContext) == null ? void 0 : _l.properties,
1961
+ ...callMeta.properties
1962
+ };
1963
+ const convoId = (_n = callMeta.convoId) != null ? _n : (_m = this.defaultContext) == null ? void 0 : _m.convoId;
1964
+ void this.eventShipper.patch(state.eventId, {
1965
+ eventName,
1966
+ userId,
1967
+ convoId,
1968
+ input,
1969
+ output,
1970
+ model,
1971
+ properties: Object.keys(properties).length > 0 ? properties : void 0,
1972
+ isPending: false
1973
+ }).catch((err) => {
1974
+ if (this.debug) {
1975
+ console.warn(
1976
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1977
+ );
1978
+ }
1979
+ });
1980
+ }
1981
+ }
1982
+ }
1983
+ finishEmbed(event, state) {
1984
+ var _a;
1985
+ if (!state.rootSpan) return;
1986
+ const outputAttrs = [];
1987
+ const isMany = state.operationId === "ai.embedMany";
1988
+ if (state.recordOutputs) {
1989
+ if (isMany) {
1990
+ outputAttrs.push(
1991
+ attrString("ai.embeddings", safeJsonWithUint8(event.embedding))
1992
+ );
1993
+ } else {
1994
+ outputAttrs.push(
1995
+ attrString("ai.embedding", safeJsonWithUint8(event.embedding))
1996
+ );
1997
+ }
1998
+ }
1999
+ if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
2000
+ outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
2001
+ }
2002
+ this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
2003
+ }
2004
+ };
2005
+
1354
2006
  // src/internal/wrap/wrapAISDK.ts
1355
2007
  var AGENT_REPORTING_TOOL_NAME_DEFAULT = "__raindrop_report";
1356
2008
  var AGENT_REPORTING_SIGNALS_DEFAULT = {
@@ -1560,6 +2212,9 @@ function detectAISDKVersion(aiSDK) {
1560
2212
  if (isFunction(aiSDK["tool"])) return "5";
1561
2213
  return "4";
1562
2214
  }
2215
+ function hasStructuredTelemetryEvents(aiSDK) {
2216
+ return isRecord(aiSDK) && isFunction(aiSDK["registerTelemetryIntegration"]) && isFunction(aiSDK["experimental_streamModelCall"]);
2217
+ }
1563
2218
  function asVercelSchema(jsonSchemaObj) {
1564
2219
  const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
1565
2220
  const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
@@ -1732,6 +2387,36 @@ function shouldKeepEventPending(params) {
1732
2387
  if (params.error != null || !params.canKeepEventPending) return false;
1733
2388
  return params.finishReason === "tool-calls" || params.finishReason === "tool_calls";
1734
2389
  }
2390
+ function normalizePromptAttr(arg) {
2391
+ if (!isRecord(arg)) return arg;
2392
+ const system = arg["system"];
2393
+ const prompt = arg["prompt"];
2394
+ const messages = arg["messages"];
2395
+ if (Array.isArray(messages)) {
2396
+ if (system) {
2397
+ const sysContent = typeof system === "string" ? system : JSON.stringify(system);
2398
+ return [{ role: "system", content: sysContent }, ...messages];
2399
+ }
2400
+ return messages;
2401
+ }
2402
+ if (typeof prompt === "string") {
2403
+ const msgs = [];
2404
+ if (system) {
2405
+ msgs.push({ role: "system", content: typeof system === "string" ? system : JSON.stringify(system) });
2406
+ }
2407
+ msgs.push({ role: "user", content: prompt });
2408
+ return msgs;
2409
+ }
2410
+ return { system, prompt, messages };
2411
+ }
2412
+ function getLocalDebuggerMetadata(ctx) {
2413
+ return {
2414
+ eventId: ctx.eventId,
2415
+ ...ctx.eventName ? { eventName: ctx.eventName } : {},
2416
+ ...ctx.userId ? { userId: ctx.userId } : {},
2417
+ ...ctx.convoId ? { convoId: ctx.convoId } : {}
2418
+ };
2419
+ }
1735
2420
  async function safeFinalize(finalize, debug, result, error) {
1736
2421
  try {
1737
2422
  await finalize(result, error);
@@ -1804,17 +2489,17 @@ function setupOperation(params) {
1804
2489
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1805
2490
  attrString("ai.model.provider", modelInfoFromArgs.provider),
1806
2491
  attrString("ai.model.id", modelInfoFromArgs.modelId),
2492
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
2493
+ attrString("ai.telemetry.metadata.raindrop.eventName", mergedCtx.eventName),
2494
+ attrString("ai.telemetry.metadata.raindrop.userId", mergedCtx.userId),
2495
+ attrString("ai.telemetry.metadata.raindrop.convoId", mergedCtx.convoId),
1807
2496
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1808
2497
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1809
2498
  ...attrsFromSettings(arg),
1810
2499
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1811
2500
  attrString(
1812
2501
  "ai.prompt",
1813
- safeJsonWithUint8({
1814
- system: isRecord(arg) ? arg["system"] : void 0,
1815
- prompt: isRecord(arg) ? arg["prompt"] : void 0,
1816
- messages: isRecord(arg) ? arg["messages"] : void 0
1817
- })
2502
+ safeJsonWithUint8(normalizePromptAttr(arg))
1818
2503
  )
1819
2504
  ]
1820
2505
  ]
@@ -1823,6 +2508,7 @@ function setupOperation(params) {
1823
2508
  const operationSelfDiagnostics = isObjectOperation(operation) ? void 0 : selfDiagnostics;
1824
2509
  const wrapCtx = {
1825
2510
  eventId,
2511
+ context: mergedCtx,
1826
2512
  telemetry,
1827
2513
  sendTraces,
1828
2514
  debug,
@@ -2142,8 +2828,100 @@ async function executeNonStreamingOperation(params) {
2142
2828
  }
2143
2829
  }
2144
2830
  function wrapAISDK(aiSDK, deps) {
2145
- var _a, _b;
2831
+ var _a, _b, _c, _d;
2146
2832
  const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
2833
+ if (deps.options.nativeTelemetry === true) {
2834
+ if (!hasStructuredTelemetryEvents(aiSDK)) {
2835
+ throw new Error(
2836
+ "[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."
2837
+ );
2838
+ }
2839
+ }
2840
+ const useNative = deps.options.nativeTelemetry === true;
2841
+ if (useNative) {
2842
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
2843
+ const integration = new RaindropTelemetryIntegration({
2844
+ traceShipper: deps.traceShipper,
2845
+ eventShipper: deps.eventShipper,
2846
+ sendTraces: ((_a = deps.options.send) == null ? void 0 : _a.traces) !== false,
2847
+ sendEvents: ((_b = deps.options.send) == null ? void 0 : _b.events) !== false,
2848
+ debug,
2849
+ context: {
2850
+ userId: wrapTimeCtx.userId,
2851
+ eventId: wrapTimeCtx.eventId,
2852
+ eventName: wrapTimeCtx.eventName,
2853
+ convoId: wrapTimeCtx.convoId,
2854
+ properties: wrapTimeCtx.properties
2855
+ }
2856
+ });
2857
+ const registerFn = aiSDK["registerTelemetryIntegration"];
2858
+ if (isFunction(registerFn)) {
2859
+ registerFn(integration);
2860
+ }
2861
+ if (debug) {
2862
+ console.log("[raindrop-ai/ai-sdk] nativeTelemetry: registered RaindropTelemetryIntegration (no Proxy)");
2863
+ }
2864
+ const selfDiagnostics2 = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2865
+ if (selfDiagnostics2) {
2866
+ const textOps = /* @__PURE__ */ new Set(["generateText", "streamText"]);
2867
+ const jsonSchemaFactory = resolveJsonSchemaFactory(aiSDK);
2868
+ const proxyTarget2 = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
2869
+ return new Proxy(proxyTarget2, {
2870
+ get(target, prop, receiver) {
2871
+ const original = Reflect.get(target, prop, receiver);
2872
+ if (typeof prop !== "string" || !textOps.has(prop) || !isFunction(original)) {
2873
+ return original;
2874
+ }
2875
+ return (...callArgs) => {
2876
+ var _a2;
2877
+ const arg = callArgs[0];
2878
+ if (!isRecord(arg)) return original.call(aiSDK, ...callArgs);
2879
+ const telemetry = extractExperimentalTelemetry(arg);
2880
+ const callMeta = (telemetry == null ? void 0 : telemetry.metadata) ? extractRaindropMetadata(telemetry.metadata) : {};
2881
+ const perCallEventIdExplicit = (_a2 = callMeta.eventId) != null ? _a2 : wrapTimeCtx.eventId;
2882
+ const perCallEventId = perCallEventIdExplicit != null ? perCallEventIdExplicit : randomUUID();
2883
+ const perCallEventIdGenerated = !perCallEventIdExplicit;
2884
+ const perCallCtx = {
2885
+ eventId: perCallEventId,
2886
+ context: wrapTimeCtx,
2887
+ telemetry,
2888
+ sendTraces: false,
2889
+ debug,
2890
+ eventShipper: deps.eventShipper,
2891
+ traceShipper: deps.traceShipper,
2892
+ rootParentForChildren: void 0,
2893
+ jsonSchemaFactory,
2894
+ selfDiagnostics: selfDiagnostics2,
2895
+ aiSDKVersion: "7"
2896
+ };
2897
+ const tools = isRecord(arg["tools"]) ? { ...arg["tools"] } : {};
2898
+ const toolName = selfDiagnostics2.toolName;
2899
+ if (!(toolName in tools)) {
2900
+ const reportTool = createSelfDiagnosticsTool(perCallCtx);
2901
+ if (reportTool) tools[toolName] = reportTool;
2902
+ }
2903
+ const existingTelemetry = isRecord(arg["experimental_telemetry"]) ? arg["experimental_telemetry"] : {};
2904
+ const existingMetadata = isRecord(existingTelemetry["metadata"]) ? existingTelemetry["metadata"] : {};
2905
+ const mergedMetadata = existingMetadata["raindrop.eventId"] ? existingMetadata : {
2906
+ ...existingMetadata,
2907
+ "raindrop.eventId": perCallEventId,
2908
+ ...perCallEventIdGenerated ? { "raindrop.internal.eventIdGenerated": "true" } : {}
2909
+ };
2910
+ callArgs[0] = {
2911
+ ...arg,
2912
+ tools,
2913
+ experimental_telemetry: {
2914
+ ...existingTelemetry,
2915
+ metadata: mergedMetadata
2916
+ }
2917
+ };
2918
+ return original.call(aiSDK, ...callArgs);
2919
+ };
2920
+ }
2921
+ });
2922
+ }
2923
+ return aiSDK;
2924
+ }
2147
2925
  const instrumentedOps = /* @__PURE__ */ new Set([
2148
2926
  "generateText",
2149
2927
  "streamText",
@@ -2151,8 +2929,8 @@ function wrapAISDK(aiSDK, deps) {
2151
2929
  "streamObject"
2152
2930
  ]);
2153
2931
  const agentClasses = /* @__PURE__ */ new Set(["Agent", "Experimental_Agent", "ToolLoopAgent"]);
2154
- const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
2155
- const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
2932
+ const sendEvents = ((_c = deps.options.send) == null ? void 0 : _c.events) !== false;
2933
+ const sendTraces = ((_d = deps.options.send) == null ? void 0 : _d.traces) !== false;
2156
2934
  const autoAttachmentEnabled = deps.options.autoAttachment !== false;
2157
2935
  const selfDiagnostics = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2158
2936
  const proxyTarget = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
@@ -2260,7 +3038,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2260
3038
  if (!mergedCtx.userId) warnMissingUserIdOnce();
2261
3039
  const inherited = await getCurrentParentSpanContext();
2262
3040
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2263
- const ctx = { ...mergedCtx};
3041
+ const ctx = { ...mergedCtx, eventId };
2264
3042
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2265
3043
  const outerOperationId = `ai.${operation}`;
2266
3044
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -2276,17 +3054,17 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2276
3054
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2277
3055
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2278
3056
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3057
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3058
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3059
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3060
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
2279
3061
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2280
3062
  ...attrsFromHeaders(mergedArgs["headers"]),
2281
3063
  ...attrsFromSettings(mergedArgs),
2282
3064
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2283
3065
  attrString(
2284
3066
  "ai.prompt",
2285
- safeJsonWithUint8({
2286
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2287
- prompt: mergedArgs["prompt"],
2288
- messages: mergedArgs["messages"]
2289
- })
3067
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
2290
3068
  )
2291
3069
  ]
2292
3070
  ]
@@ -2294,6 +3072,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2294
3072
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2295
3073
  const wrapCtx = {
2296
3074
  eventId,
3075
+ context: ctx,
2297
3076
  telemetry,
2298
3077
  sendTraces,
2299
3078
  debug,
@@ -2467,7 +3246,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2467
3246
  if (!mergedCtx.userId) warnMissingUserIdOnce();
2468
3247
  const inherited = await getCurrentParentSpanContext();
2469
3248
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2470
- const ctx = { ...mergedCtx};
3249
+ const ctx = { ...mergedCtx, eventId };
2471
3250
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2472
3251
  const outerOperationId = `ai.${operation}`;
2473
3252
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -2483,17 +3262,17 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2483
3262
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2484
3263
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2485
3264
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3265
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3266
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3267
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3268
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
2486
3269
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2487
3270
  ...attrsFromHeaders(mergedArgs["headers"]),
2488
3271
  ...attrsFromSettings(mergedArgs),
2489
3272
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2490
3273
  attrString(
2491
3274
  "ai.prompt",
2492
- safeJsonWithUint8({
2493
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2494
- prompt: mergedArgs["prompt"],
2495
- messages: mergedArgs["messages"]
2496
- })
3275
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
2497
3276
  )
2498
3277
  ]
2499
3278
  ]
@@ -2501,6 +3280,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
2501
3280
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2502
3281
  const wrapCtx = {
2503
3282
  eventId,
3283
+ context: ctx,
2504
3284
  telemetry,
2505
3285
  sendTraces,
2506
3286
  debug,
@@ -2724,6 +3504,21 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2724
3504
  });
2725
3505
  }
2726
3506
  };
3507
+ const sendToolLiveEvent = (parent, type, metadata) => {
3508
+ if (!localDebuggerEnabled() || !parent) return;
3509
+ sendLocalDebuggerLiveEvent({
3510
+ traceId: parent.traceIdB64,
3511
+ type,
3512
+ content: name,
3513
+ metadata: {
3514
+ ...getLocalDebuggerMetadata({
3515
+ ...ctx.context,
3516
+ eventId: ctx.eventId
3517
+ }),
3518
+ ...metadata
3519
+ }
3520
+ });
3521
+ };
2727
3522
  const createContextSpan = (span) => ({
2728
3523
  traceIdB64: span.ids.traceIdB64,
2729
3524
  spanIdB64: span.ids.spanIdB64,
@@ -2739,6 +3534,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2739
3534
  const parentCtx = await getCurrentParentSpanContext();
2740
3535
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2741
3536
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3537
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
2742
3538
  try {
2743
3539
  let lastValue;
2744
3540
  const iterator = result[Symbol.asyncIterator]();
@@ -2754,9 +3550,13 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2754
3550
  }
2755
3551
  toolCalls.push({ id: toolCallId, name, args: toolArgs, result: lastValue, status: "OK" });
2756
3552
  endToolSpan(toolSpan, lastValue);
3553
+ sendToolLiveEvent(parent, "tool_result", { result: lastValue });
2757
3554
  } catch (error) {
2758
3555
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
2759
3556
  endToolSpan(toolSpan, void 0, error);
3557
+ sendToolLiveEvent(parent, "tool_result", {
3558
+ error: error instanceof Error ? error.message : String(error)
3559
+ });
2760
3560
  throw error;
2761
3561
  }
2762
3562
  })();
@@ -2765,6 +3565,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2765
3565
  const parentCtx = await getCurrentParentSpanContext();
2766
3566
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2767
3567
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3568
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
2768
3569
  const run = async () => {
2769
3570
  try {
2770
3571
  const awaitedResult = await result;
@@ -2776,10 +3577,14 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2776
3577
  status: "OK"
2777
3578
  });
2778
3579
  endToolSpan(toolSpan, awaitedResult);
3580
+ sendToolLiveEvent(parent, "tool_result", { result: awaitedResult });
2779
3581
  return awaitedResult;
2780
3582
  } catch (error) {
2781
3583
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
2782
3584
  endToolSpan(toolSpan, void 0, error);
3585
+ sendToolLiveEvent(parent, "tool_result", {
3586
+ error: error instanceof Error ? error.message : String(error)
3587
+ });
2783
3588
  throw error;
2784
3589
  }
2785
3590
  };
@@ -2819,6 +3624,7 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2819
3624
  const original = Reflect.get(target, prop, receiver);
2820
3625
  if (prop === "doGenerate" && isFunction(original)) {
2821
3626
  return async (...callArgs) => {
3627
+ var _a, _b;
2822
3628
  const options = callArgs[0];
2823
3629
  const parentCtx = await getCurrentParentSpanContext();
2824
3630
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
@@ -2826,6 +3632,22 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2826
3632
  try {
2827
3633
  const result = await original.apply(target, callArgs);
2828
3634
  if (span) endDoGenerateSpan(span, result, modelInfo, ctx);
3635
+ if (localDebuggerEnabled() && ctx.rootParentForChildren && isRecord(result)) {
3636
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3637
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3638
+ const content = result["content"];
3639
+ if (Array.isArray(content)) {
3640
+ for (const part of content) {
3641
+ if (isRecord(part)) {
3642
+ if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
3643
+ sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
3644
+ } else if (part["type"] === "text" && typeof part["text"] === "string") {
3645
+ sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
3646
+ }
3647
+ }
3648
+ }
3649
+ }
3650
+ }
2829
3651
  return result;
2830
3652
  } catch (error) {
2831
3653
  if (span)
@@ -2965,6 +3787,23 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2965
3787
  }
2966
3788
  if ("usage" in value) usage = value["usage"];
2967
3789
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
3790
+ if (localDebuggerEnabled() && ctx.rootParentForChildren) {
3791
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3792
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3793
+ if (type === "text-delta") {
3794
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
3795
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
3796
+ } else if (type === "reasoning" || type === "reasoning-delta") {
3797
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
3798
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
3799
+ } else if (type === "tool-call") {
3800
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3801
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
3802
+ } else if (type === "tool-result") {
3803
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3804
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
3805
+ }
3806
+ }
2968
3807
  }
2969
3808
  controller.enqueue(value);
2970
3809
  } catch (error) {
@@ -3165,7 +4004,7 @@ function extractNestedTokens(usage, key) {
3165
4004
  // package.json
3166
4005
  var package_default = {
3167
4006
  name: "@raindrop-ai/ai-sdk",
3168
- version: "0.0.19"};
4007
+ version: "0.0.21"};
3169
4008
 
3170
4009
  // src/internal/version.ts
3171
4010
  var libraryName = package_default.name;
@@ -3281,6 +4120,16 @@ function createRaindropAISDK(opts) {
3281
4120
  traceShipper
3282
4121
  });
3283
4122
  },
4123
+ createTelemetryIntegration(context) {
4124
+ return new RaindropTelemetryIntegration({
4125
+ traceShipper,
4126
+ eventShipper,
4127
+ sendTraces: tracesEnabled,
4128
+ sendEvents: eventsEnabled,
4129
+ debug: envDebug,
4130
+ context
4131
+ });
4132
+ },
3284
4133
  events: {
3285
4134
  async patch(eventId, patch) {
3286
4135
  await eventShipper.patch(eventId, patch);
@@ -3314,4 +4163,4 @@ function createRaindropAISDK(opts) {
3314
4163
  };
3315
4164
  }
3316
4165
 
3317
- export { _resetWarnedMissingUserId, createRaindropAISDK, currentSpan, eventMetadata, eventMetadataFromChatRequest, getContextManager, withCurrent };
4166
+ export { RaindropTelemetryIntegration, _resetWarnedMissingUserId, createRaindropAISDK, currentSpan, eventMetadata, eventMetadataFromChatRequest, getContextManager, withCurrent };