@raindrop-ai/ai-sdk 0.0.18 → 0.0.19-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -785,7 +785,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
785
785
  // package.json
786
786
  var package_default = {
787
787
  name: "@raindrop-ai/ai-sdk",
788
- version: "0.0.18"};
788
+ version: "0.0.19-beta.2"};
789
789
 
790
790
  // src/internal/version.ts
791
791
  var libraryName = package_default.name;
@@ -804,19 +804,6 @@ var EventShipper2 = class extends EventShipper {
804
804
  }
805
805
  };
806
806
 
807
- // src/internal/traces.ts
808
- var TraceShipper2 = class extends TraceShipper {
809
- constructor(opts) {
810
- var _a, _b, _c;
811
- super({
812
- ...opts,
813
- sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
814
- serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
815
- serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
816
- });
817
- }
818
- };
819
-
820
807
  // src/internal/wrap/helpers.ts
821
808
  function isRecord(value) {
822
809
  return typeof value === "object" && value !== null;
@@ -1432,6 +1419,540 @@ function attrsFromGenAiRequest(options) {
1432
1419
  ];
1433
1420
  }
1434
1421
 
1422
+ // src/internal/raindrop-telemetry-integration.ts
1423
+ var RaindropTelemetryIntegration = class {
1424
+ constructor(opts) {
1425
+ this.callStates = /* @__PURE__ */ new Map();
1426
+ // ── onStart ─────────────────────────────────────────────────────────────
1427
+ this.onStart = (event) => {
1428
+ var _a, _b, _c, _d;
1429
+ if (event.isEnabled !== true) return;
1430
+ const isEmbed = event.operationId === "ai.embed" || event.operationId === "ai.embedMany";
1431
+ const recordInputs = event.recordInputs !== false;
1432
+ const recordOutputs = event.recordOutputs !== false;
1433
+ const functionId = event.functionId;
1434
+ const metadata = event.metadata;
1435
+ const callMeta = this.extractRaindropMetadata(metadata);
1436
+ const inherited = getContextManager().getParentSpanIds();
1437
+ const eventIdGenerated = (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === "true" || (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === true;
1438
+ const explicitEventId = callMeta.eventId && !eventIdGenerated ? callMeta.eventId : void 0;
1439
+ 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();
1440
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1441
+ const { operationName, resourceName } = opName(
1442
+ event.operationId,
1443
+ functionId
1444
+ );
1445
+ let rootSpan;
1446
+ if (this.sendTraces) {
1447
+ const promptAttrs = !isEmbed && recordInputs ? [
1448
+ attrString(
1449
+ "ai.prompt",
1450
+ safeJsonWithUint8({
1451
+ system: event.system,
1452
+ prompt: event.prompt,
1453
+ messages: event.messages
1454
+ })
1455
+ )
1456
+ ] : [];
1457
+ const embedAttrs = isEmbed && recordInputs ? event.operationId === "ai.embedMany" ? [
1458
+ attrString(
1459
+ "ai.values",
1460
+ safeJsonWithUint8(event.value)
1461
+ )
1462
+ ] : [attrString("ai.value", safeJsonWithUint8(event.value))] : [];
1463
+ rootSpan = this.traceShipper.startSpan({
1464
+ name: event.operationId,
1465
+ parent: inheritedParent,
1466
+ eventId,
1467
+ operationId: event.operationId,
1468
+ attributes: [
1469
+ attrString("operation.name", operationName),
1470
+ attrString("resource.name", resourceName),
1471
+ attrString("ai.telemetry.functionId", functionId),
1472
+ attrString("ai.model.provider", event.provider),
1473
+ attrString("ai.model.id", event.modelId),
1474
+ ...attrsFromTelemetryMetadata(metadata),
1475
+ ...promptAttrs,
1476
+ ...embedAttrs
1477
+ ]
1478
+ });
1479
+ }
1480
+ this.callStates.set(event.callId, {
1481
+ operationId: event.operationId,
1482
+ eventId,
1483
+ rootSpan,
1484
+ rootParent: rootSpan ? this.spanParentRef(rootSpan) : inheritedParent,
1485
+ stepSpan: void 0,
1486
+ stepParent: void 0,
1487
+ toolSpans: /* @__PURE__ */ new Map(),
1488
+ embedSpans: /* @__PURE__ */ new Map(),
1489
+ recordInputs,
1490
+ recordOutputs,
1491
+ functionId,
1492
+ metadata,
1493
+ accumulatedText: "",
1494
+ inputText: isEmbed ? void 0 : this.extractInputText(event),
1495
+ toolCallCount: 0
1496
+ });
1497
+ };
1498
+ // ── onStepStart ─────────────────────────────────────────────────────────
1499
+ this.onStepStart = (event) => {
1500
+ const state = this.getState(event.callId);
1501
+ if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1502
+ const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
1503
+ const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
1504
+ const { operationName, resourceName } = opName(
1505
+ stepOperationId,
1506
+ state.functionId
1507
+ );
1508
+ const inputAttrs = [];
1509
+ if (state.recordInputs) {
1510
+ if (event.promptMessages) {
1511
+ inputAttrs.push(
1512
+ attrString(
1513
+ "ai.prompt.messages",
1514
+ safeJsonWithUint8(event.promptMessages)
1515
+ )
1516
+ );
1517
+ }
1518
+ if (event.stepTools) {
1519
+ inputAttrs.push(
1520
+ attrStringArray(
1521
+ "ai.prompt.tools",
1522
+ event.stepTools.map((t) => JSON.stringify(t))
1523
+ )
1524
+ );
1525
+ }
1526
+ if (event.stepToolChoice != null) {
1527
+ inputAttrs.push(
1528
+ attrString(
1529
+ "ai.prompt.toolChoice",
1530
+ JSON.stringify(event.stepToolChoice)
1531
+ )
1532
+ );
1533
+ }
1534
+ }
1535
+ const stepSpan = this.traceShipper.startSpan({
1536
+ name: stepOperationId,
1537
+ parent: state.rootParent,
1538
+ eventId: state.eventId,
1539
+ operationId: stepOperationId,
1540
+ attributes: [
1541
+ attrString("operation.name", operationName),
1542
+ attrString("resource.name", resourceName),
1543
+ attrString("ai.telemetry.functionId", state.functionId),
1544
+ attrString("ai.model.provider", event.provider),
1545
+ attrString("ai.model.id", event.modelId),
1546
+ attrString("gen_ai.system", event.provider),
1547
+ attrString("gen_ai.request.model", event.modelId),
1548
+ ...inputAttrs
1549
+ ]
1550
+ });
1551
+ state.stepSpan = stepSpan;
1552
+ state.stepParent = this.spanParentRef(stepSpan);
1553
+ };
1554
+ // ── onToolCallStart ─────────────────────────────────────────────────────
1555
+ this.onToolCallStart = (event) => {
1556
+ const state = this.getState(event.callId);
1557
+ if (!(state == null ? void 0 : state.stepParent)) return;
1558
+ const { toolCall } = event;
1559
+ const { operationName, resourceName } = opName(
1560
+ "ai.toolCall",
1561
+ state.functionId
1562
+ );
1563
+ const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
1564
+ const toolSpan = this.traceShipper.startSpan({
1565
+ name: "ai.toolCall",
1566
+ parent: state.stepParent,
1567
+ eventId: state.eventId,
1568
+ operationId: "ai.toolCall",
1569
+ attributes: [
1570
+ attrString("operation.name", operationName),
1571
+ attrString("resource.name", resourceName),
1572
+ attrString("ai.telemetry.functionId", state.functionId),
1573
+ attrString("ai.toolCall.name", toolCall.toolName),
1574
+ attrString("ai.toolCall.id", toolCall.toolCallId),
1575
+ ...inputAttrs
1576
+ ]
1577
+ });
1578
+ state.toolSpans.set(toolCall.toolCallId, toolSpan);
1579
+ };
1580
+ // ── onToolCallFinish ────────────────────────────────────────────────────
1581
+ this.onToolCallFinish = (event) => {
1582
+ const state = this.getState(event.callId);
1583
+ if (!state) return;
1584
+ const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
1585
+ if (!toolSpan) return;
1586
+ state.toolCallCount += 1;
1587
+ if (event.success) {
1588
+ const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(event.output))] : [];
1589
+ this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
1590
+ } else {
1591
+ this.traceShipper.endSpan(toolSpan, { error: event.error });
1592
+ }
1593
+ state.toolSpans.delete(event.toolCall.toolCallId);
1594
+ };
1595
+ // ── onChunk (streaming) ─────────────────────────────────────────────────
1596
+ this.onChunk = (event) => {
1597
+ var _a, _b, _c;
1598
+ const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
1599
+ if (!callId) return;
1600
+ const state = this.getState(callId);
1601
+ if (!state) return;
1602
+ const chunk = event.chunk;
1603
+ if (!chunk || typeof chunk !== "object") return;
1604
+ if (chunk.type === "text-delta") {
1605
+ const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
1606
+ if (typeof delta === "string") {
1607
+ state.accumulatedText += delta;
1608
+ }
1609
+ }
1610
+ };
1611
+ // ── onStepFinish ────────────────────────────────────────────────────────
1612
+ this.onStepFinish = (event) => {
1613
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1614
+ const state = this.getState(event.callId);
1615
+ if (!(state == null ? void 0 : state.stepSpan)) return;
1616
+ const outputAttrs = [];
1617
+ if (state.recordOutputs) {
1618
+ outputAttrs.push(
1619
+ attrString("ai.response.finishReason", event.finishReason),
1620
+ attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1621
+ attrString("ai.response.id", (_b = event.response) == null ? void 0 : _b.id),
1622
+ attrString("ai.response.model", (_c = event.response) == null ? void 0 : _c.modelId),
1623
+ attrString(
1624
+ "ai.response.timestamp",
1625
+ ((_d = event.response) == null ? void 0 : _d.timestamp) instanceof Date ? event.response.timestamp.toISOString() : (_e = event.response) == null ? void 0 : _e.timestamp
1626
+ ),
1627
+ attrString(
1628
+ "ai.response.providerMetadata",
1629
+ event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1630
+ )
1631
+ );
1632
+ if (((_f = event.toolCalls) == null ? void 0 : _f.length) > 0) {
1633
+ outputAttrs.push(
1634
+ attrString(
1635
+ "ai.response.toolCalls",
1636
+ JSON.stringify(
1637
+ event.toolCalls.map((tc) => ({
1638
+ toolCallId: tc.toolCallId,
1639
+ toolName: tc.toolName,
1640
+ input: tc.input
1641
+ }))
1642
+ )
1643
+ )
1644
+ );
1645
+ }
1646
+ if (((_g = event.reasoning) == null ? void 0 : _g.length) > 0) {
1647
+ const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1648
+ if (reasoningText) {
1649
+ outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1650
+ }
1651
+ }
1652
+ }
1653
+ outputAttrs.push(
1654
+ attrStringArray("gen_ai.response.finish_reasons", [event.finishReason]),
1655
+ attrString("gen_ai.response.id", (_h = event.response) == null ? void 0 : _h.id),
1656
+ attrString("gen_ai.response.model", (_i = event.response) == null ? void 0 : _i.modelId)
1657
+ );
1658
+ const usage = event.usage;
1659
+ if (usage) {
1660
+ outputAttrs.push(
1661
+ attrInt("ai.usage.inputTokens", usage.inputTokens),
1662
+ attrInt("ai.usage.outputTokens", usage.outputTokens),
1663
+ attrInt("ai.usage.totalTokens", usage.totalTokens),
1664
+ attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1665
+ attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens),
1666
+ attrInt("gen_ai.usage.input_tokens", usage.inputTokens),
1667
+ attrInt("gen_ai.usage.output_tokens", usage.outputTokens)
1668
+ );
1669
+ }
1670
+ this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
1671
+ state.stepSpan = void 0;
1672
+ state.stepParent = void 0;
1673
+ };
1674
+ // ── onEmbedStart ────────────────────────────────────────────────────────
1675
+ this.onEmbedStart = (event) => {
1676
+ const state = this.getState(event.callId);
1677
+ if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1678
+ const { operationName, resourceName } = opName(
1679
+ event.operationId,
1680
+ state.functionId
1681
+ );
1682
+ const inputAttrs = state.recordInputs ? [
1683
+ attrString(
1684
+ "ai.values",
1685
+ safeJsonWithUint8(event.values)
1686
+ )
1687
+ ] : [];
1688
+ const embedSpan = this.traceShipper.startSpan({
1689
+ name: event.operationId,
1690
+ parent: state.rootParent,
1691
+ eventId: state.eventId,
1692
+ operationId: event.operationId,
1693
+ attributes: [
1694
+ attrString("operation.name", operationName),
1695
+ attrString("resource.name", resourceName),
1696
+ attrString("ai.telemetry.functionId", state.functionId),
1697
+ ...inputAttrs
1698
+ ]
1699
+ });
1700
+ state.embedSpans.set(event.embedCallId, embedSpan);
1701
+ };
1702
+ // ── onEmbedFinish ───────────────────────────────────────────────────────
1703
+ this.onEmbedFinish = (event) => {
1704
+ var _a;
1705
+ const state = this.getState(event.callId);
1706
+ if (!state) return;
1707
+ const embedSpan = state.embedSpans.get(event.embedCallId);
1708
+ if (!embedSpan) return;
1709
+ const outputAttrs = [];
1710
+ if (state.recordOutputs) {
1711
+ outputAttrs.push(
1712
+ attrString(
1713
+ "ai.embeddings",
1714
+ safeJsonWithUint8(event.embeddings)
1715
+ )
1716
+ );
1717
+ }
1718
+ if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
1719
+ outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
1720
+ }
1721
+ this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
1722
+ state.embedSpans.delete(event.embedCallId);
1723
+ };
1724
+ // ── onFinish ────────────────────────────────────────────────────────────
1725
+ this.onFinish = (event) => {
1726
+ const state = this.getState(event.callId);
1727
+ if (!state) return;
1728
+ const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
1729
+ if (isEmbed) {
1730
+ this.finishEmbed(event, state);
1731
+ } else {
1732
+ this.finishGenerate(event, state);
1733
+ }
1734
+ this.cleanup(event.callId);
1735
+ };
1736
+ // ── onError ─────────────────────────────────────────────────────────────
1737
+ this.onError = (error) => {
1738
+ var _a;
1739
+ const event = error;
1740
+ if (!(event == null ? void 0 : event.callId)) return;
1741
+ const state = this.getState(event.callId);
1742
+ if (!state) return;
1743
+ const actualError = (_a = event.error) != null ? _a : error;
1744
+ if (state.stepSpan) {
1745
+ this.traceShipper.endSpan(state.stepSpan, { error: actualError });
1746
+ }
1747
+ for (const embedSpan of state.embedSpans.values()) {
1748
+ this.traceShipper.endSpan(embedSpan, { error: actualError });
1749
+ }
1750
+ state.embedSpans.clear();
1751
+ for (const toolSpan of state.toolSpans.values()) {
1752
+ this.traceShipper.endSpan(toolSpan, { error: actualError });
1753
+ }
1754
+ state.toolSpans.clear();
1755
+ if (state.rootSpan) {
1756
+ this.traceShipper.endSpan(state.rootSpan, { error: actualError });
1757
+ }
1758
+ this.cleanup(event.callId);
1759
+ };
1760
+ // ── executeTool ─────────────────────────────────────────────────────────
1761
+ this.executeTool = async ({
1762
+ callId,
1763
+ toolCallId,
1764
+ execute
1765
+ }) => {
1766
+ const state = this.getState(callId);
1767
+ const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
1768
+ if (!toolSpan) return execute();
1769
+ return runWithParentSpanContext(
1770
+ {
1771
+ traceIdB64: toolSpan.ids.traceIdB64,
1772
+ spanIdB64: toolSpan.ids.spanIdB64,
1773
+ eventId: state.eventId
1774
+ },
1775
+ () => execute()
1776
+ );
1777
+ };
1778
+ this.traceShipper = opts.traceShipper;
1779
+ this.eventShipper = opts.eventShipper;
1780
+ this.sendTraces = opts.sendTraces !== false;
1781
+ this.sendEvents = opts.sendEvents !== false;
1782
+ this.debug = opts.debug === true;
1783
+ this.defaultContext = opts.context;
1784
+ }
1785
+ // ── helpers ──────────────────────────────────────────────────────────────
1786
+ getState(callId) {
1787
+ return this.callStates.get(callId);
1788
+ }
1789
+ cleanup(callId) {
1790
+ this.callStates.delete(callId);
1791
+ }
1792
+ spanParentRef(span) {
1793
+ return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
1794
+ }
1795
+ extractRaindropMetadata(metadata) {
1796
+ if (!metadata) return {};
1797
+ const result = {};
1798
+ const userId = metadata["raindrop.userId"];
1799
+ if (typeof userId === "string" && userId) result.userId = userId;
1800
+ const eventId = metadata["raindrop.eventId"];
1801
+ if (typeof eventId === "string" && eventId) result.eventId = eventId;
1802
+ const convoId = metadata["raindrop.convoId"];
1803
+ if (typeof convoId === "string" && convoId) result.convoId = convoId;
1804
+ const eventName = metadata["raindrop.eventName"];
1805
+ if (typeof eventName === "string" && eventName) result.eventName = eventName;
1806
+ const properties = metadata["raindrop.properties"];
1807
+ if (typeof properties === "string") {
1808
+ try {
1809
+ result.properties = JSON.parse(properties);
1810
+ } catch (e) {
1811
+ }
1812
+ } else if (properties && typeof properties === "object") {
1813
+ result.properties = properties;
1814
+ }
1815
+ return result;
1816
+ }
1817
+ /**
1818
+ * Extract the user-facing input text from an onStart event.
1819
+ * Mirrors the logic in the v4-v6 Proxy path (lastUserMessageTextFromArgs / extractInputFromArgs).
1820
+ */
1821
+ extractInputText(event) {
1822
+ if (typeof event.prompt === "string") return event.prompt;
1823
+ if (Array.isArray(event.messages)) {
1824
+ for (let i = event.messages.length - 1; i >= 0; i--) {
1825
+ const msg = event.messages[i];
1826
+ if ((msg == null ? void 0 : msg.role) === "user") {
1827
+ if (typeof msg.content === "string") return msg.content;
1828
+ if (Array.isArray(msg.content)) {
1829
+ const textPart = msg.content.find(
1830
+ (p) => (p == null ? void 0 : p.type) === "text" && typeof p.text === "string"
1831
+ );
1832
+ if (textPart) return textPart.text;
1833
+ }
1834
+ }
1835
+ }
1836
+ }
1837
+ return void 0;
1838
+ }
1839
+ finishGenerate(event, state) {
1840
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1841
+ if (state.rootSpan) {
1842
+ const outputAttrs = [];
1843
+ if (state.recordOutputs) {
1844
+ outputAttrs.push(
1845
+ attrString("ai.response.finishReason", event.finishReason),
1846
+ attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1847
+ attrString(
1848
+ "ai.response.providerMetadata",
1849
+ event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1850
+ )
1851
+ );
1852
+ if (((_b = event.toolCalls) == null ? void 0 : _b.length) > 0) {
1853
+ outputAttrs.push(
1854
+ attrString(
1855
+ "ai.response.toolCalls",
1856
+ JSON.stringify(
1857
+ event.toolCalls.map((tc) => ({
1858
+ toolCallId: tc.toolCallId,
1859
+ toolName: tc.toolName,
1860
+ input: tc.input
1861
+ }))
1862
+ )
1863
+ )
1864
+ );
1865
+ }
1866
+ if (((_c = event.reasoning) == null ? void 0 : _c.length) > 0) {
1867
+ const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1868
+ if (reasoningText) {
1869
+ outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1870
+ }
1871
+ }
1872
+ }
1873
+ const usage = (_d = event.totalUsage) != null ? _d : event.usage;
1874
+ if (usage) {
1875
+ outputAttrs.push(
1876
+ attrInt("ai.usage.inputTokens", usage.inputTokens),
1877
+ attrInt("ai.usage.outputTokens", usage.outputTokens),
1878
+ attrInt("ai.usage.totalTokens", usage.totalTokens),
1879
+ attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1880
+ attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens)
1881
+ );
1882
+ }
1883
+ outputAttrs.push(
1884
+ attrInt("ai.toolCall.count", state.toolCallCount)
1885
+ );
1886
+ this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
1887
+ }
1888
+ if (this.sendEvents) {
1889
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1890
+ const userId = (_f = callMeta.userId) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.userId;
1891
+ if (userId) {
1892
+ const eventName = (_i = (_h = callMeta.eventName) != null ? _h : (_g = this.defaultContext) == null ? void 0 : _g.eventName) != null ? _i : state.operationId;
1893
+ const output = (_j = event.text) != null ? _j : state.accumulatedText || void 0;
1894
+ const input = state.inputText;
1895
+ const model = (_k = event.response) == null ? void 0 : _k.modelId;
1896
+ const properties = {
1897
+ ...(_l = this.defaultContext) == null ? void 0 : _l.properties,
1898
+ ...callMeta.properties
1899
+ };
1900
+ const convoId = (_n = callMeta.convoId) != null ? _n : (_m = this.defaultContext) == null ? void 0 : _m.convoId;
1901
+ void this.eventShipper.patch(state.eventId, {
1902
+ eventName,
1903
+ userId,
1904
+ convoId,
1905
+ input,
1906
+ output,
1907
+ model,
1908
+ properties: Object.keys(properties).length > 0 ? properties : void 0,
1909
+ isPending: false
1910
+ }).catch((err) => {
1911
+ if (this.debug) {
1912
+ console.warn(
1913
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1914
+ );
1915
+ }
1916
+ });
1917
+ }
1918
+ }
1919
+ }
1920
+ finishEmbed(event, state) {
1921
+ var _a;
1922
+ if (!state.rootSpan) return;
1923
+ const outputAttrs = [];
1924
+ const isMany = state.operationId === "ai.embedMany";
1925
+ if (state.recordOutputs) {
1926
+ if (isMany) {
1927
+ outputAttrs.push(
1928
+ attrString("ai.embeddings", safeJsonWithUint8(event.embedding))
1929
+ );
1930
+ } else {
1931
+ outputAttrs.push(
1932
+ attrString("ai.embedding", safeJsonWithUint8(event.embedding))
1933
+ );
1934
+ }
1935
+ }
1936
+ if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
1937
+ outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
1938
+ }
1939
+ this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
1940
+ }
1941
+ };
1942
+
1943
+ // src/internal/traces.ts
1944
+ var TraceShipper2 = class extends TraceShipper {
1945
+ constructor(opts) {
1946
+ var _a, _b, _c;
1947
+ super({
1948
+ ...opts,
1949
+ sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
1950
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
1951
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
1952
+ });
1953
+ }
1954
+ };
1955
+
1435
1956
  // src/internal/wrap/wrapAISDK.ts
1436
1957
  var AGENT_REPORTING_TOOL_NAME_DEFAULT = "__raindrop_report";
1437
1958
  var AGENT_REPORTING_SIGNALS_DEFAULT = {
@@ -1641,6 +2162,9 @@ function detectAISDKVersion(aiSDK) {
1641
2162
  if (isFunction(aiSDK["tool"])) return "5";
1642
2163
  return "4";
1643
2164
  }
2165
+ function hasStructuredTelemetryEvents(aiSDK) {
2166
+ return isRecord(aiSDK) && isFunction(aiSDK["registerTelemetryIntegration"]) && isFunction(aiSDK["experimental_streamModelCall"]);
2167
+ }
1644
2168
  function asVercelSchema(jsonSchemaObj) {
1645
2169
  const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
1646
2170
  const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
@@ -2223,8 +2747,93 @@ async function executeNonStreamingOperation(params) {
2223
2747
  }
2224
2748
  }
2225
2749
  function wrapAISDK(aiSDK, deps) {
2226
- var _a, _b;
2750
+ var _a, _b, _c, _d;
2227
2751
  const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
2752
+ if (deps.options.nativeTelemetry === true) {
2753
+ if (!hasStructuredTelemetryEvents(aiSDK)) {
2754
+ throw new Error(
2755
+ "[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."
2756
+ );
2757
+ }
2758
+ }
2759
+ const useNative = deps.options.nativeTelemetry === true;
2760
+ if (useNative) {
2761
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
2762
+ const integration = new RaindropTelemetryIntegration({
2763
+ traceShipper: deps.traceShipper,
2764
+ eventShipper: deps.eventShipper,
2765
+ sendTraces: ((_a = deps.options.send) == null ? void 0 : _a.traces) !== false,
2766
+ sendEvents: ((_b = deps.options.send) == null ? void 0 : _b.events) !== false,
2767
+ debug,
2768
+ context: {
2769
+ userId: wrapTimeCtx.userId,
2770
+ eventId: wrapTimeCtx.eventId,
2771
+ eventName: wrapTimeCtx.eventName,
2772
+ convoId: wrapTimeCtx.convoId,
2773
+ properties: wrapTimeCtx.properties
2774
+ }
2775
+ });
2776
+ const registerFn = aiSDK["registerTelemetryIntegration"];
2777
+ if (isFunction(registerFn)) {
2778
+ registerFn(integration);
2779
+ }
2780
+ if (debug) {
2781
+ console.log("[raindrop-ai/ai-sdk] nativeTelemetry: registered RaindropTelemetryIntegration (no Proxy)");
2782
+ }
2783
+ const selfDiagnostics2 = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2784
+ if (selfDiagnostics2) {
2785
+ const textOps = /* @__PURE__ */ new Set(["generateText", "streamText"]);
2786
+ const jsonSchemaFactory = resolveJsonSchemaFactory(aiSDK);
2787
+ const proxyTarget2 = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
2788
+ return new Proxy(proxyTarget2, {
2789
+ get(target, prop, receiver) {
2790
+ const original = Reflect.get(target, prop, receiver);
2791
+ if (typeof prop !== "string" || !textOps.has(prop) || !isFunction(original)) {
2792
+ return original;
2793
+ }
2794
+ return (...callArgs) => {
2795
+ var _a2, _b2;
2796
+ const arg = callArgs[0];
2797
+ if (!isRecord(arg)) return original.call(aiSDK, ...callArgs);
2798
+ const telemetry = extractExperimentalTelemetry(arg);
2799
+ const callMeta = (telemetry == null ? void 0 : telemetry.metadata) ? extractRaindropMetadata(telemetry.metadata) : {};
2800
+ const perCallEventId = (_b2 = (_a2 = callMeta.eventId) != null ? _a2 : wrapTimeCtx.eventId) != null ? _b2 : randomUUID();
2801
+ const perCallCtx = {
2802
+ eventId: perCallEventId,
2803
+ telemetry,
2804
+ sendTraces: false,
2805
+ debug,
2806
+ eventShipper: deps.eventShipper,
2807
+ traceShipper: deps.traceShipper,
2808
+ rootParentForChildren: void 0,
2809
+ jsonSchemaFactory,
2810
+ selfDiagnostics: selfDiagnostics2,
2811
+ aiSDKVersion: "7"
2812
+ };
2813
+ const tools = isRecord(arg["tools"]) ? { ...arg["tools"] } : {};
2814
+ const toolName = selfDiagnostics2.toolName;
2815
+ if (!(toolName in tools)) {
2816
+ const reportTool = createSelfDiagnosticsTool(perCallCtx);
2817
+ if (reportTool) tools[toolName] = reportTool;
2818
+ }
2819
+ const existingTelemetry = isRecord(arg["experimental_telemetry"]) ? arg["experimental_telemetry"] : {};
2820
+ const existingMetadata = isRecord(existingTelemetry["metadata"]) ? existingTelemetry["metadata"] : {};
2821
+ const mergedMetadata = existingMetadata["raindrop.eventId"] ? existingMetadata : { ...existingMetadata, "raindrop.eventId": perCallEventId };
2822
+ callArgs[0] = {
2823
+ ...arg,
2824
+ tools,
2825
+ experimental_telemetry: {
2826
+ ...existingTelemetry,
2827
+ metadata: mergedMetadata
2828
+ }
2829
+ };
2830
+ return original.call(aiSDK, ...callArgs);
2831
+ };
2832
+ }
2833
+ });
2834
+ }
2835
+ return aiSDK;
2836
+ }
2228
2837
  const instrumentedOps = /* @__PURE__ */ new Set([
2229
2838
  "generateText",
2230
2839
  "streamText",
@@ -2232,8 +2841,8 @@ function wrapAISDK(aiSDK, deps) {
2232
2841
  "streamObject"
2233
2842
  ]);
2234
2843
  const agentClasses = /* @__PURE__ */ new Set(["Agent", "Experimental_Agent", "ToolLoopAgent"]);
2235
- const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
2236
- const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
2844
+ const sendEvents = ((_c = deps.options.send) == null ? void 0 : _c.events) !== false;
2845
+ const sendTraces = ((_d = deps.options.send) == null ? void 0 : _d.traces) !== false;
2237
2846
  const autoAttachmentEnabled = deps.options.autoAttachment !== false;
2238
2847
  const selfDiagnostics = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2239
2848
  const proxyTarget = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
@@ -3327,6 +3936,16 @@ function createRaindropAISDK(opts) {
3327
3936
  traceShipper
3328
3937
  });
3329
3938
  },
3939
+ createTelemetryIntegration(context) {
3940
+ return new RaindropTelemetryIntegration({
3941
+ traceShipper,
3942
+ eventShipper,
3943
+ sendTraces: tracesEnabled,
3944
+ sendEvents: eventsEnabled,
3945
+ debug: envDebug,
3946
+ context
3947
+ });
3948
+ },
3330
3949
  events: {
3331
3950
  async patch(eventId, patch) {
3332
3951
  await eventShipper.patch(eventId, patch);
@@ -3360,4 +3979,4 @@ function createRaindropAISDK(opts) {
3360
3979
  };
3361
3980
  }
3362
3981
 
3363
- export { _resetWarnedMissingUserId, createRaindropAISDK, currentSpan, eventMetadata, eventMetadataFromChatRequest, getContextManager, withCurrent };
3982
+ export { RaindropTelemetryIntegration, _resetWarnedMissingUserId, createRaindropAISDK, currentSpan, eventMetadata, eventMetadataFromChatRequest, getContextManager, withCurrent };