@raindrop-ai/ai-sdk 0.0.19-beta.3 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ var async_hooks = require('async_hooks');
4
4
 
5
5
  // src/index.node.ts
6
6
 
7
- // ../core/dist/chunk-FOHDGBT5.js
7
+ // ../core/dist/chunk-H6VSZSLN.js
8
8
  function getCrypto() {
9
9
  const c = globalThis.crypto;
10
10
  return c;
@@ -622,49 +622,25 @@ var NOOP_SPAN = {
622
622
  log() {
623
623
  }
624
624
  };
625
- function isPromiseLike(value) {
626
- return value !== null && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function";
625
+ function getAsyncLocalStorageCtor() {
626
+ return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
627
627
  }
628
- var PendingAsyncLocalStorage = class {
628
+ var SynchronousContextStorage = class {
629
629
  constructor() {
630
- this._real = null;
631
630
  this._stack = [];
632
631
  }
633
- setReal(real) {
634
- const current = this._stack.length ? this._stack[this._stack.length - 1] : void 0;
635
- this._real = real;
636
- if (current !== void 0 && typeof this._real.enterWith === "function") {
637
- this._real.enterWith(current);
638
- }
632
+ isEmpty() {
633
+ return this._stack.length === 0;
639
634
  }
640
635
  getStore() {
641
- var _a, _b;
642
- return (_b = (_a = this._real) == null ? void 0 : _a.getStore()) != null ? _b : this._stack[this._stack.length - 1];
636
+ return this._stack[this._stack.length - 1];
643
637
  }
644
638
  run(store, callback) {
645
- if (this._real) {
646
- return this._real.run(store, callback);
647
- }
648
639
  this._stack.push(store);
649
640
  try {
650
- const result = callback();
651
- if (isPromiseLike(result)) {
652
- return result.then(
653
- (value) => {
654
- this._stack.pop();
655
- return value;
656
- },
657
- (err) => {
658
- this._stack.pop();
659
- throw err;
660
- }
661
- );
662
- }
663
- this._stack.pop();
664
- return result;
665
- } catch (err) {
641
+ return callback();
642
+ } finally {
666
643
  this._stack.pop();
667
- throw err;
668
644
  }
669
645
  }
670
646
  };
@@ -672,53 +648,29 @@ var ContextManager = class {
672
648
  };
673
649
  var RaindropContextManager = class extends ContextManager {
674
650
  constructor() {
675
- var _a;
676
651
  super();
677
- this._storage = null;
678
- this._pending = null;
679
- this._initPromise = null;
680
- const isNode = typeof process !== "undefined" && typeof ((_a = process == null ? void 0 : process.versions) == null ? void 0 : _a.node) === "string";
681
- const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
652
+ this._fallback = null;
653
+ const Ctor = getAsyncLocalStorageCtor();
682
654
  if (Ctor) {
683
655
  this._storage = new Ctor();
684
- this._pending = null;
685
- this._initPromise = null;
686
656
  return;
687
657
  }
688
- if (isNode) {
689
- this._pending = new PendingAsyncLocalStorage();
690
- this._storage = this._pending;
691
- this._initPromise = this._initialize();
692
- } else {
693
- this._storage = null;
694
- this._pending = null;
695
- this._initPromise = null;
696
- }
658
+ this._fallback = new SynchronousContextStorage();
659
+ this._storage = this._fallback;
697
660
  }
698
- async _initialize() {
699
- try {
700
- const mod = await import('async_hooks');
701
- const real = new mod.AsyncLocalStorage();
702
- if (this._pending) {
703
- this._pending.setReal(real);
704
- }
705
- this._storage = real;
706
- } catch (e) {
707
- this._storage = null;
708
- }
709
- }
710
- async ensureReady() {
711
- if (this._initPromise) {
712
- await this._initPromise;
713
- this._initPromise = null;
714
- }
661
+ maybeAdoptAsyncLocalStorage() {
662
+ if (!this._fallback || !this._fallback.isEmpty()) return;
663
+ const Ctor = getAsyncLocalStorageCtor();
664
+ if (!Ctor) return;
665
+ this._storage = new Ctor();
666
+ this._fallback = null;
715
667
  }
716
668
  isReady() {
717
- return this._initPromise === null;
669
+ return true;
718
670
  }
719
671
  getParentSpanIds() {
720
- var _a;
721
- const span = (_a = this._storage) == null ? void 0 : _a.getStore();
672
+ this.maybeAdoptAsyncLocalStorage();
673
+ const span = this._storage.getStore();
722
674
  if (!span || span === NOOP_SPAN) return void 0;
723
675
  return {
724
676
  traceIdB64: span.traceIdB64,
@@ -727,12 +679,12 @@ var RaindropContextManager = class extends ContextManager {
727
679
  };
728
680
  }
729
681
  runInContext(span, callback) {
730
- if (!this._storage) return callback();
682
+ this.maybeAdoptAsyncLocalStorage();
731
683
  return this._storage.run(span, callback);
732
684
  }
733
685
  getCurrentSpan() {
734
- var _a;
735
- return (_a = this._storage) == null ? void 0 : _a.getStore();
686
+ this.maybeAdoptAsyncLocalStorage();
687
+ return this._storage.getStore();
736
688
  }
737
689
  };
738
690
  var _contextManager = null;
@@ -750,17 +702,10 @@ function withCurrent(span, callback) {
750
702
  return getContextManager().runInContext(span, callback);
751
703
  }
752
704
  async function getCurrentParentSpanContext() {
753
- const cm = getContextManager();
754
- if (cm instanceof RaindropContextManager) {
755
- await cm.ensureReady();
756
- }
757
- return cm.getParentSpanIds();
705
+ return getContextManager().getParentSpanIds();
758
706
  }
759
707
  async function runWithParentSpanContext(ctx, fn) {
760
708
  const cm = getContextManager();
761
- if (cm instanceof RaindropContextManager) {
762
- await cm.ensureReady();
763
- }
764
709
  const span = {
765
710
  traceIdB64: ctx.traceIdB64,
766
711
  spanIdB64: ctx.spanIdB64,
@@ -787,11 +732,12 @@ async function* asyncGeneratorWithCurrent(span, gen) {
787
732
  nextValue = yield result.value;
788
733
  }
789
734
  }
735
+ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = async_hooks.AsyncLocalStorage;
790
736
 
791
737
  // package.json
792
738
  var package_default = {
793
739
  name: "@raindrop-ai/ai-sdk",
794
- version: "0.0.19-beta.3"};
740
+ version: "0.0.19"};
795
741
 
796
742
  // src/internal/version.ts
797
743
  var libraryName = package_default.name;
@@ -810,6 +756,19 @@ var EventShipper2 = class extends EventShipper {
810
756
  }
811
757
  };
812
758
 
759
+ // src/internal/traces.ts
760
+ var TraceShipper2 = class extends TraceShipper {
761
+ constructor(opts) {
762
+ var _a, _b, _c;
763
+ super({
764
+ ...opts,
765
+ sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
766
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
767
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
768
+ });
769
+ }
770
+ };
771
+
813
772
  // src/internal/wrap/helpers.ts
814
773
  function isRecord(value) {
815
774
  return typeof value === "object" && value !== null;
@@ -1063,17 +1022,29 @@ function extractTextFromMessageContent(content) {
1063
1022
  }
1064
1023
  return result.length ? result : void 0;
1065
1024
  }
1066
- function extractInputAttachmentsFromArgs(args) {
1067
- if (!isRecord(args)) return void 0;
1025
+ function messagesFromArgs(args) {
1068
1026
  const messages = args["messages"];
1069
- if (!Array.isArray(messages)) return void 0;
1027
+ if (Array.isArray(messages)) return messages;
1028
+ const prompt = args["prompt"];
1029
+ if (Array.isArray(prompt)) return prompt;
1030
+ return void 0;
1031
+ }
1032
+ function lastUserMessageFromArgs(args) {
1033
+ const messages = messagesFromArgs(args);
1034
+ if (!messages) return void 0;
1070
1035
  for (let i = messages.length - 1; i >= 0; i--) {
1071
1036
  const message = messages[i];
1072
- if (!isRecord(message) || message["role"] !== "user") continue;
1073
- return attachmentsFromContent(message["content"], "input");
1037
+ if (isRecord(message) && message["role"] === "user") {
1038
+ return message;
1039
+ }
1074
1040
  }
1075
1041
  return void 0;
1076
1042
  }
1043
+ function extractInputAttachmentsFromArgs(args) {
1044
+ var _a;
1045
+ if (!isRecord(args)) return void 0;
1046
+ return attachmentsFromContent((_a = lastUserMessageFromArgs(args)) == null ? void 0 : _a["content"], "input");
1047
+ }
1077
1048
  async function extractOutputAttachmentsFromResult(result) {
1078
1049
  if (!isRecord(result)) return void 0;
1079
1050
  const fileAttachments = await outputAttachmentsFromFiles(result["files"]);
@@ -1087,26 +1058,20 @@ async function extractOutputAttachmentsFromResult(result) {
1087
1058
  return attachmentsFromContent(result["content"], "output");
1088
1059
  }
1089
1060
  function lastUserMessageTextFromArgs(args) {
1090
- var _a;
1061
+ var _a, _b;
1091
1062
  if (!isRecord(args)) return void 0;
1092
- const messages = args["messages"];
1093
- if (!Array.isArray(messages)) return void 0;
1094
- for (let i = messages.length - 1; i >= 0; i--) {
1095
- const message = messages[i];
1096
- if (!isRecord(message) || message["role"] !== "user") continue;
1097
- const content = message["content"];
1098
- const text = extractTextFromMessageContent(content);
1099
- if (text !== void 0) return text;
1100
- return (_a = safeJsonWithUint8(content)) != null ? _a : String(content);
1101
- }
1102
- return void 0;
1063
+ const content = (_a = lastUserMessageFromArgs(args)) == null ? void 0 : _a["content"];
1064
+ if (content === void 0) return void 0;
1065
+ const text = extractTextFromMessageContent(content);
1066
+ if (text !== void 0) return text;
1067
+ return (_b = safeJsonWithUint8(content)) != null ? _b : String(content);
1103
1068
  }
1104
1069
  function extractInputFromArgs(args) {
1105
1070
  var _a;
1106
1071
  if (!isRecord(args)) return void 0;
1107
1072
  const prompt = args["prompt"];
1108
1073
  if (typeof prompt === "string") return prompt;
1109
- const messages = args["messages"];
1074
+ const messages = messagesFromArgs(args);
1110
1075
  if (Array.isArray(messages) && messages.length > 0) {
1111
1076
  const last = messages[messages.length - 1];
1112
1077
  if (isRecord(last)) {
@@ -1128,7 +1093,7 @@ function coerceMessagesFromArgs(args) {
1128
1093
  if (typeof args["system"] === "string" && args["system"]) {
1129
1094
  result.push({ role: "system", content: args["system"] });
1130
1095
  }
1131
- const messages = args["messages"];
1096
+ const messages = messagesFromArgs(args);
1132
1097
  if (Array.isArray(messages)) {
1133
1098
  for (const message of messages) {
1134
1099
  if (isRecord(message) && typeof message["role"] === "string") {
@@ -1425,549 +1390,6 @@ function attrsFromGenAiRequest(options) {
1425
1390
  ];
1426
1391
  }
1427
1392
 
1428
- // src/internal/raindrop-telemetry-integration.ts
1429
- var RaindropTelemetryIntegration = class {
1430
- constructor(opts) {
1431
- this.callStates = /* @__PURE__ */ new Map();
1432
- // ── onStart ─────────────────────────────────────────────────────────────
1433
- this.onStart = (event) => {
1434
- var _a, _b, _c, _d;
1435
- if (event.isEnabled !== true) return;
1436
- const isEmbed = event.operationId === "ai.embed" || event.operationId === "ai.embedMany";
1437
- const recordInputs = event.recordInputs !== false;
1438
- const recordOutputs = event.recordOutputs !== false;
1439
- const functionId = event.functionId;
1440
- const metadata = event.metadata;
1441
- const callMeta = this.extractRaindropMetadata(metadata);
1442
- const inherited = getContextManager().getParentSpanIds();
1443
- const eventIdGenerated = (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === "true" || (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === true;
1444
- const explicitEventId = callMeta.eventId && !eventIdGenerated ? callMeta.eventId : void 0;
1445
- 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();
1446
- const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1447
- const { operationName, resourceName } = opName(
1448
- event.operationId,
1449
- functionId
1450
- );
1451
- let rootSpan;
1452
- if (this.sendTraces) {
1453
- const promptAttrs = !isEmbed && recordInputs ? [
1454
- attrString(
1455
- "ai.prompt",
1456
- safeJsonWithUint8({
1457
- system: event.system,
1458
- prompt: event.prompt,
1459
- messages: event.messages
1460
- })
1461
- )
1462
- ] : [];
1463
- const embedAttrs = isEmbed && recordInputs ? event.operationId === "ai.embedMany" ? [
1464
- attrString(
1465
- "ai.values",
1466
- safeJsonWithUint8(event.value)
1467
- )
1468
- ] : [attrString("ai.value", safeJsonWithUint8(event.value))] : [];
1469
- rootSpan = this.traceShipper.startSpan({
1470
- name: event.operationId,
1471
- parent: inheritedParent,
1472
- eventId,
1473
- operationId: event.operationId,
1474
- attributes: [
1475
- attrString("operation.name", operationName),
1476
- attrString("resource.name", resourceName),
1477
- attrString("ai.telemetry.functionId", functionId),
1478
- attrString("ai.model.provider", event.provider),
1479
- attrString("ai.model.id", event.modelId),
1480
- // Filter out raindrop.eventId from metadata attrs since TraceShipper
1481
- // already sets it via the eventId arg. Without this, eventMetadata()'s
1482
- // auto-generated ID would duplicate and override the resolved one.
1483
- ...attrsFromTelemetryMetadata(
1484
- metadata ? Object.fromEntries(
1485
- Object.entries(metadata).filter(
1486
- ([k]) => k !== "raindrop.eventId" && k !== "raindrop.internal.eventIdGenerated"
1487
- )
1488
- ) : void 0
1489
- ),
1490
- ...promptAttrs,
1491
- ...embedAttrs
1492
- ]
1493
- });
1494
- }
1495
- this.callStates.set(event.callId, {
1496
- operationId: event.operationId,
1497
- eventId,
1498
- rootSpan,
1499
- rootParent: rootSpan ? this.spanParentRef(rootSpan) : inheritedParent,
1500
- stepSpan: void 0,
1501
- stepParent: void 0,
1502
- toolSpans: /* @__PURE__ */ new Map(),
1503
- embedSpans: /* @__PURE__ */ new Map(),
1504
- recordInputs,
1505
- recordOutputs,
1506
- functionId,
1507
- metadata,
1508
- accumulatedText: "",
1509
- inputText: isEmbed ? void 0 : this.extractInputText(event),
1510
- toolCallCount: 0
1511
- });
1512
- };
1513
- // ── onStepStart ─────────────────────────────────────────────────────────
1514
- this.onStepStart = (event) => {
1515
- const state = this.getState(event.callId);
1516
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1517
- const isStream = state.operationId === "ai.streamText" || state.operationId === "ai.streamObject";
1518
- const stepOperationId = isStream ? `${state.operationId}.doStream` : `${state.operationId}.doGenerate`;
1519
- const { operationName, resourceName } = opName(
1520
- stepOperationId,
1521
- state.functionId
1522
- );
1523
- const inputAttrs = [];
1524
- if (state.recordInputs) {
1525
- if (event.promptMessages) {
1526
- inputAttrs.push(
1527
- attrString(
1528
- "ai.prompt.messages",
1529
- safeJsonWithUint8(event.promptMessages)
1530
- )
1531
- );
1532
- }
1533
- if (event.stepTools) {
1534
- inputAttrs.push(
1535
- attrStringArray(
1536
- "ai.prompt.tools",
1537
- event.stepTools.map((t) => JSON.stringify(t))
1538
- )
1539
- );
1540
- }
1541
- if (event.stepToolChoice != null) {
1542
- inputAttrs.push(
1543
- attrString(
1544
- "ai.prompt.toolChoice",
1545
- JSON.stringify(event.stepToolChoice)
1546
- )
1547
- );
1548
- }
1549
- }
1550
- const stepSpan = this.traceShipper.startSpan({
1551
- name: stepOperationId,
1552
- parent: state.rootParent,
1553
- eventId: state.eventId,
1554
- operationId: stepOperationId,
1555
- attributes: [
1556
- attrString("operation.name", operationName),
1557
- attrString("resource.name", resourceName),
1558
- attrString("ai.telemetry.functionId", state.functionId),
1559
- attrString("ai.model.provider", event.provider),
1560
- attrString("ai.model.id", event.modelId),
1561
- attrString("gen_ai.system", event.provider),
1562
- attrString("gen_ai.request.model", event.modelId),
1563
- ...inputAttrs
1564
- ]
1565
- });
1566
- state.stepSpan = stepSpan;
1567
- state.stepParent = this.spanParentRef(stepSpan);
1568
- };
1569
- // ── onToolCallStart ─────────────────────────────────────────────────────
1570
- this.onToolCallStart = (event) => {
1571
- const state = this.getState(event.callId);
1572
- if (!(state == null ? void 0 : state.stepParent)) return;
1573
- const { toolCall } = event;
1574
- const { operationName, resourceName } = opName(
1575
- "ai.toolCall",
1576
- state.functionId
1577
- );
1578
- const inputAttrs = state.recordInputs ? [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))] : [];
1579
- const toolSpan = this.traceShipper.startSpan({
1580
- name: "ai.toolCall",
1581
- parent: state.stepParent,
1582
- eventId: state.eventId,
1583
- operationId: "ai.toolCall",
1584
- attributes: [
1585
- attrString("operation.name", operationName),
1586
- attrString("resource.name", resourceName),
1587
- attrString("ai.telemetry.functionId", state.functionId),
1588
- attrString("ai.toolCall.name", toolCall.toolName),
1589
- attrString("ai.toolCall.id", toolCall.toolCallId),
1590
- ...inputAttrs
1591
- ]
1592
- });
1593
- state.toolSpans.set(toolCall.toolCallId, toolSpan);
1594
- };
1595
- // ── onToolCallFinish ────────────────────────────────────────────────────
1596
- this.onToolCallFinish = (event) => {
1597
- const state = this.getState(event.callId);
1598
- if (!state) return;
1599
- const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
1600
- if (!toolSpan) return;
1601
- state.toolCallCount += 1;
1602
- if (event.success) {
1603
- const outputAttrs = state.recordOutputs ? [attrString("ai.toolCall.result", safeJsonWithUint8(event.output))] : [];
1604
- this.traceShipper.endSpan(toolSpan, { attributes: outputAttrs });
1605
- } else {
1606
- this.traceShipper.endSpan(toolSpan, { error: event.error });
1607
- }
1608
- state.toolSpans.delete(event.toolCall.toolCallId);
1609
- };
1610
- // ── onChunk (streaming) ─────────────────────────────────────────────────
1611
- this.onChunk = (event) => {
1612
- var _a, _b, _c;
1613
- const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
1614
- if (!callId) return;
1615
- const state = this.getState(callId);
1616
- if (!state) return;
1617
- const chunk = event.chunk;
1618
- if (!chunk || typeof chunk !== "object") return;
1619
- if (chunk.type === "text-delta") {
1620
- const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
1621
- if (typeof delta === "string") {
1622
- state.accumulatedText += delta;
1623
- }
1624
- }
1625
- };
1626
- // ── onStepFinish ────────────────────────────────────────────────────────
1627
- this.onStepFinish = (event) => {
1628
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1629
- const state = this.getState(event.callId);
1630
- if (!(state == null ? void 0 : state.stepSpan)) return;
1631
- const outputAttrs = [];
1632
- if (state.recordOutputs) {
1633
- outputAttrs.push(
1634
- attrString("ai.response.finishReason", event.finishReason),
1635
- attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1636
- attrString("ai.response.id", (_b = event.response) == null ? void 0 : _b.id),
1637
- attrString("ai.response.model", (_c = event.response) == null ? void 0 : _c.modelId),
1638
- attrString(
1639
- "ai.response.timestamp",
1640
- ((_d = event.response) == null ? void 0 : _d.timestamp) instanceof Date ? event.response.timestamp.toISOString() : (_e = event.response) == null ? void 0 : _e.timestamp
1641
- ),
1642
- attrString(
1643
- "ai.response.providerMetadata",
1644
- event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1645
- )
1646
- );
1647
- if (((_f = event.toolCalls) == null ? void 0 : _f.length) > 0) {
1648
- outputAttrs.push(
1649
- attrString(
1650
- "ai.response.toolCalls",
1651
- JSON.stringify(
1652
- event.toolCalls.map((tc) => ({
1653
- toolCallId: tc.toolCallId,
1654
- toolName: tc.toolName,
1655
- input: tc.input
1656
- }))
1657
- )
1658
- )
1659
- );
1660
- }
1661
- if (((_g = event.reasoning) == null ? void 0 : _g.length) > 0) {
1662
- const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1663
- if (reasoningText) {
1664
- outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1665
- }
1666
- }
1667
- }
1668
- outputAttrs.push(
1669
- attrStringArray("gen_ai.response.finish_reasons", [event.finishReason]),
1670
- attrString("gen_ai.response.id", (_h = event.response) == null ? void 0 : _h.id),
1671
- attrString("gen_ai.response.model", (_i = event.response) == null ? void 0 : _i.modelId)
1672
- );
1673
- const usage = event.usage;
1674
- if (usage) {
1675
- outputAttrs.push(
1676
- attrInt("ai.usage.inputTokens", usage.inputTokens),
1677
- attrInt("ai.usage.outputTokens", usage.outputTokens),
1678
- attrInt("ai.usage.totalTokens", usage.totalTokens),
1679
- attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1680
- attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens),
1681
- attrInt("gen_ai.usage.input_tokens", usage.inputTokens),
1682
- attrInt("gen_ai.usage.output_tokens", usage.outputTokens)
1683
- );
1684
- }
1685
- this.traceShipper.endSpan(state.stepSpan, { attributes: outputAttrs });
1686
- state.stepSpan = void 0;
1687
- state.stepParent = void 0;
1688
- };
1689
- // ── onEmbedStart ────────────────────────────────────────────────────────
1690
- this.onEmbedStart = (event) => {
1691
- const state = this.getState(event.callId);
1692
- if (!(state == null ? void 0 : state.rootSpan) || !state.rootParent) return;
1693
- const { operationName, resourceName } = opName(
1694
- event.operationId,
1695
- state.functionId
1696
- );
1697
- const inputAttrs = state.recordInputs ? [
1698
- attrString(
1699
- "ai.values",
1700
- safeJsonWithUint8(event.values)
1701
- )
1702
- ] : [];
1703
- const embedSpan = this.traceShipper.startSpan({
1704
- name: event.operationId,
1705
- parent: state.rootParent,
1706
- eventId: state.eventId,
1707
- operationId: event.operationId,
1708
- attributes: [
1709
- attrString("operation.name", operationName),
1710
- attrString("resource.name", resourceName),
1711
- attrString("ai.telemetry.functionId", state.functionId),
1712
- ...inputAttrs
1713
- ]
1714
- });
1715
- state.embedSpans.set(event.embedCallId, embedSpan);
1716
- };
1717
- // ── onEmbedFinish ───────────────────────────────────────────────────────
1718
- this.onEmbedFinish = (event) => {
1719
- var _a;
1720
- const state = this.getState(event.callId);
1721
- if (!state) return;
1722
- const embedSpan = state.embedSpans.get(event.embedCallId);
1723
- if (!embedSpan) return;
1724
- const outputAttrs = [];
1725
- if (state.recordOutputs) {
1726
- outputAttrs.push(
1727
- attrString(
1728
- "ai.embeddings",
1729
- safeJsonWithUint8(event.embeddings)
1730
- )
1731
- );
1732
- }
1733
- if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
1734
- outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
1735
- }
1736
- this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
1737
- state.embedSpans.delete(event.embedCallId);
1738
- };
1739
- // ── onFinish ────────────────────────────────────────────────────────────
1740
- this.onFinish = (event) => {
1741
- const state = this.getState(event.callId);
1742
- if (!state) return;
1743
- const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
1744
- if (isEmbed) {
1745
- this.finishEmbed(event, state);
1746
- } else {
1747
- this.finishGenerate(event, state);
1748
- }
1749
- this.cleanup(event.callId);
1750
- };
1751
- // ── onError ─────────────────────────────────────────────────────────────
1752
- this.onError = (error) => {
1753
- var _a;
1754
- const event = error;
1755
- if (!(event == null ? void 0 : event.callId)) return;
1756
- const state = this.getState(event.callId);
1757
- if (!state) return;
1758
- const actualError = (_a = event.error) != null ? _a : error;
1759
- if (state.stepSpan) {
1760
- this.traceShipper.endSpan(state.stepSpan, { error: actualError });
1761
- }
1762
- for (const embedSpan of state.embedSpans.values()) {
1763
- this.traceShipper.endSpan(embedSpan, { error: actualError });
1764
- }
1765
- state.embedSpans.clear();
1766
- for (const toolSpan of state.toolSpans.values()) {
1767
- this.traceShipper.endSpan(toolSpan, { error: actualError });
1768
- }
1769
- state.toolSpans.clear();
1770
- if (state.rootSpan) {
1771
- this.traceShipper.endSpan(state.rootSpan, { error: actualError });
1772
- }
1773
- this.cleanup(event.callId);
1774
- };
1775
- // ── executeTool ─────────────────────────────────────────────────────────
1776
- this.executeTool = async ({
1777
- callId,
1778
- toolCallId,
1779
- execute
1780
- }) => {
1781
- const state = this.getState(callId);
1782
- const toolSpan = state == null ? void 0 : state.toolSpans.get(toolCallId);
1783
- if (!toolSpan) return execute();
1784
- return runWithParentSpanContext(
1785
- {
1786
- traceIdB64: toolSpan.ids.traceIdB64,
1787
- spanIdB64: toolSpan.ids.spanIdB64,
1788
- eventId: state.eventId
1789
- },
1790
- () => execute()
1791
- );
1792
- };
1793
- this.traceShipper = opts.traceShipper;
1794
- this.eventShipper = opts.eventShipper;
1795
- this.sendTraces = opts.sendTraces !== false;
1796
- this.sendEvents = opts.sendEvents !== false;
1797
- this.debug = opts.debug === true;
1798
- this.defaultContext = opts.context;
1799
- }
1800
- // ── helpers ──────────────────────────────────────────────────────────────
1801
- getState(callId) {
1802
- return this.callStates.get(callId);
1803
- }
1804
- cleanup(callId) {
1805
- this.callStates.delete(callId);
1806
- }
1807
- spanParentRef(span) {
1808
- return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
1809
- }
1810
- extractRaindropMetadata(metadata) {
1811
- if (!metadata) return {};
1812
- const result = {};
1813
- const userId = metadata["raindrop.userId"];
1814
- if (typeof userId === "string" && userId) result.userId = userId;
1815
- const eventId = metadata["raindrop.eventId"];
1816
- if (typeof eventId === "string" && eventId) result.eventId = eventId;
1817
- const convoId = metadata["raindrop.convoId"];
1818
- if (typeof convoId === "string" && convoId) result.convoId = convoId;
1819
- const eventName = metadata["raindrop.eventName"];
1820
- if (typeof eventName === "string" && eventName) result.eventName = eventName;
1821
- const properties = metadata["raindrop.properties"];
1822
- if (typeof properties === "string") {
1823
- try {
1824
- result.properties = JSON.parse(properties);
1825
- } catch (e) {
1826
- }
1827
- } else if (properties && typeof properties === "object") {
1828
- result.properties = properties;
1829
- }
1830
- return result;
1831
- }
1832
- /**
1833
- * Extract the user-facing input text from an onStart event.
1834
- * Mirrors the logic in the v4-v6 Proxy path (lastUserMessageTextFromArgs / extractInputFromArgs).
1835
- */
1836
- extractInputText(event) {
1837
- if (typeof event.prompt === "string") return event.prompt;
1838
- if (Array.isArray(event.messages)) {
1839
- for (let i = event.messages.length - 1; i >= 0; i--) {
1840
- const msg = event.messages[i];
1841
- if ((msg == null ? void 0 : msg.role) === "user") {
1842
- if (typeof msg.content === "string") return msg.content;
1843
- if (Array.isArray(msg.content)) {
1844
- const textPart = msg.content.find(
1845
- (p) => (p == null ? void 0 : p.type) === "text" && typeof p.text === "string"
1846
- );
1847
- if (textPart) return textPart.text;
1848
- }
1849
- }
1850
- }
1851
- }
1852
- return void 0;
1853
- }
1854
- finishGenerate(event, state) {
1855
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1856
- if (state.rootSpan) {
1857
- const outputAttrs = [];
1858
- if (state.recordOutputs) {
1859
- outputAttrs.push(
1860
- attrString("ai.response.finishReason", event.finishReason),
1861
- attrString("ai.response.text", (_a = event.text) != null ? _a : void 0),
1862
- attrString(
1863
- "ai.response.providerMetadata",
1864
- event.providerMetadata ? safeJsonWithUint8(event.providerMetadata) : void 0
1865
- )
1866
- );
1867
- if (((_b = event.toolCalls) == null ? void 0 : _b.length) > 0) {
1868
- outputAttrs.push(
1869
- attrString(
1870
- "ai.response.toolCalls",
1871
- JSON.stringify(
1872
- event.toolCalls.map((tc) => ({
1873
- toolCallId: tc.toolCallId,
1874
- toolName: tc.toolName,
1875
- input: tc.input
1876
- }))
1877
- )
1878
- )
1879
- );
1880
- }
1881
- if (((_c = event.reasoning) == null ? void 0 : _c.length) > 0) {
1882
- const reasoningText = event.reasoning.filter((part) => "text" in part).map((part) => part.text).join("\n");
1883
- if (reasoningText) {
1884
- outputAttrs.push(attrString("ai.response.reasoning", reasoningText));
1885
- }
1886
- }
1887
- }
1888
- const usage = (_d = event.totalUsage) != null ? _d : event.usage;
1889
- if (usage) {
1890
- outputAttrs.push(
1891
- attrInt("ai.usage.inputTokens", usage.inputTokens),
1892
- attrInt("ai.usage.outputTokens", usage.outputTokens),
1893
- attrInt("ai.usage.totalTokens", usage.totalTokens),
1894
- attrInt("ai.usage.reasoningTokens", usage.reasoningTokens),
1895
- attrInt("ai.usage.cachedInputTokens", usage.cachedInputTokens)
1896
- );
1897
- }
1898
- outputAttrs.push(
1899
- attrInt("ai.toolCall.count", state.toolCallCount)
1900
- );
1901
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
1902
- }
1903
- if (this.sendEvents) {
1904
- const callMeta = this.extractRaindropMetadata(state.metadata);
1905
- const userId = (_f = callMeta.userId) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.userId;
1906
- if (userId) {
1907
- const eventName = (_i = (_h = callMeta.eventName) != null ? _h : (_g = this.defaultContext) == null ? void 0 : _g.eventName) != null ? _i : state.operationId;
1908
- const output = (_j = event.text) != null ? _j : state.accumulatedText || void 0;
1909
- const input = state.inputText;
1910
- const model = (_k = event.response) == null ? void 0 : _k.modelId;
1911
- const properties = {
1912
- ...(_l = this.defaultContext) == null ? void 0 : _l.properties,
1913
- ...callMeta.properties
1914
- };
1915
- const convoId = (_n = callMeta.convoId) != null ? _n : (_m = this.defaultContext) == null ? void 0 : _m.convoId;
1916
- void this.eventShipper.patch(state.eventId, {
1917
- eventName,
1918
- userId,
1919
- convoId,
1920
- input,
1921
- output,
1922
- model,
1923
- properties: Object.keys(properties).length > 0 ? properties : void 0,
1924
- isPending: false
1925
- }).catch((err) => {
1926
- if (this.debug) {
1927
- console.warn(
1928
- `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1929
- );
1930
- }
1931
- });
1932
- }
1933
- }
1934
- }
1935
- finishEmbed(event, state) {
1936
- var _a;
1937
- if (!state.rootSpan) return;
1938
- const outputAttrs = [];
1939
- const isMany = state.operationId === "ai.embedMany";
1940
- if (state.recordOutputs) {
1941
- if (isMany) {
1942
- outputAttrs.push(
1943
- attrString("ai.embeddings", safeJsonWithUint8(event.embedding))
1944
- );
1945
- } else {
1946
- outputAttrs.push(
1947
- attrString("ai.embedding", safeJsonWithUint8(event.embedding))
1948
- );
1949
- }
1950
- }
1951
- if (((_a = event.usage) == null ? void 0 : _a.tokens) != null) {
1952
- outputAttrs.push(attrInt("ai.usage.tokens", event.usage.tokens));
1953
- }
1954
- this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
1955
- }
1956
- };
1957
-
1958
- // src/internal/traces.ts
1959
- var TraceShipper2 = class extends TraceShipper {
1960
- constructor(opts) {
1961
- var _a, _b, _c;
1962
- super({
1963
- ...opts,
1964
- sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
1965
- serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
1966
- serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
1967
- });
1968
- }
1969
- };
1970
-
1971
1393
  // src/internal/wrap/wrapAISDK.ts
1972
1394
  var AGENT_REPORTING_TOOL_NAME_DEFAULT = "__raindrop_report";
1973
1395
  var AGENT_REPORTING_SIGNALS_DEFAULT = {
@@ -2177,9 +1599,6 @@ function detectAISDKVersion(aiSDK) {
2177
1599
  if (isFunction(aiSDK["tool"])) return "5";
2178
1600
  return "4";
2179
1601
  }
2180
- function hasStructuredTelemetryEvents(aiSDK) {
2181
- return isRecord(aiSDK) && isFunction(aiSDK["registerTelemetryIntegration"]) && isFunction(aiSDK["experimental_streamModelCall"]);
2182
- }
2183
1602
  function asVercelSchema(jsonSchemaObj) {
2184
1603
  const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
2185
1604
  const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
@@ -2762,93 +2181,8 @@ async function executeNonStreamingOperation(params) {
2762
2181
  }
2763
2182
  }
2764
2183
  function wrapAISDK(aiSDK, deps) {
2765
- var _a, _b, _c, _d;
2184
+ var _a, _b;
2766
2185
  const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
2767
- if (deps.options.nativeTelemetry === true) {
2768
- if (!hasStructuredTelemetryEvents(aiSDK)) {
2769
- throw new Error(
2770
- "[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."
2771
- );
2772
- }
2773
- }
2774
- const useNative = deps.options.nativeTelemetry === true;
2775
- if (useNative) {
2776
- const wrapTimeCtx = resolveContext(deps.options.context, { operation: "wrap", args: void 0 });
2777
- const integration = new RaindropTelemetryIntegration({
2778
- traceShipper: deps.traceShipper,
2779
- eventShipper: deps.eventShipper,
2780
- sendTraces: ((_a = deps.options.send) == null ? void 0 : _a.traces) !== false,
2781
- sendEvents: ((_b = deps.options.send) == null ? void 0 : _b.events) !== false,
2782
- debug,
2783
- context: {
2784
- userId: wrapTimeCtx.userId,
2785
- eventId: wrapTimeCtx.eventId,
2786
- eventName: wrapTimeCtx.eventName,
2787
- convoId: wrapTimeCtx.convoId,
2788
- properties: wrapTimeCtx.properties
2789
- }
2790
- });
2791
- const registerFn = aiSDK["registerTelemetryIntegration"];
2792
- if (isFunction(registerFn)) {
2793
- registerFn(integration);
2794
- }
2795
- if (debug) {
2796
- console.log("[raindrop-ai/ai-sdk] nativeTelemetry: registered RaindropTelemetryIntegration (no Proxy)");
2797
- }
2798
- const selfDiagnostics2 = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2799
- if (selfDiagnostics2) {
2800
- const textOps = /* @__PURE__ */ new Set(["generateText", "streamText"]);
2801
- const jsonSchemaFactory = resolveJsonSchemaFactory(aiSDK);
2802
- const proxyTarget2 = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
2803
- return new Proxy(proxyTarget2, {
2804
- get(target, prop, receiver) {
2805
- const original = Reflect.get(target, prop, receiver);
2806
- if (typeof prop !== "string" || !textOps.has(prop) || !isFunction(original)) {
2807
- return original;
2808
- }
2809
- return (...callArgs) => {
2810
- var _a2, _b2;
2811
- const arg = callArgs[0];
2812
- if (!isRecord(arg)) return original.call(aiSDK, ...callArgs);
2813
- const telemetry = extractExperimentalTelemetry(arg);
2814
- const callMeta = (telemetry == null ? void 0 : telemetry.metadata) ? extractRaindropMetadata(telemetry.metadata) : {};
2815
- const perCallEventId = (_b2 = (_a2 = callMeta.eventId) != null ? _a2 : wrapTimeCtx.eventId) != null ? _b2 : randomUUID();
2816
- const perCallCtx = {
2817
- eventId: perCallEventId,
2818
- telemetry,
2819
- sendTraces: false,
2820
- debug,
2821
- eventShipper: deps.eventShipper,
2822
- traceShipper: deps.traceShipper,
2823
- rootParentForChildren: void 0,
2824
- jsonSchemaFactory,
2825
- selfDiagnostics: selfDiagnostics2,
2826
- aiSDKVersion: "7"
2827
- };
2828
- const tools = isRecord(arg["tools"]) ? { ...arg["tools"] } : {};
2829
- const toolName = selfDiagnostics2.toolName;
2830
- if (!(toolName in tools)) {
2831
- const reportTool = createSelfDiagnosticsTool(perCallCtx);
2832
- if (reportTool) tools[toolName] = reportTool;
2833
- }
2834
- const existingTelemetry = isRecord(arg["experimental_telemetry"]) ? arg["experimental_telemetry"] : {};
2835
- const existingMetadata = isRecord(existingTelemetry["metadata"]) ? existingTelemetry["metadata"] : {};
2836
- const mergedMetadata = existingMetadata["raindrop.eventId"] ? existingMetadata : { ...existingMetadata, "raindrop.eventId": perCallEventId };
2837
- callArgs[0] = {
2838
- ...arg,
2839
- tools,
2840
- experimental_telemetry: {
2841
- ...existingTelemetry,
2842
- metadata: mergedMetadata
2843
- }
2844
- };
2845
- return original.call(aiSDK, ...callArgs);
2846
- };
2847
- }
2848
- });
2849
- }
2850
- return aiSDK;
2851
- }
2852
2186
  const instrumentedOps = /* @__PURE__ */ new Set([
2853
2187
  "generateText",
2854
2188
  "streamText",
@@ -2856,8 +2190,8 @@ function wrapAISDK(aiSDK, deps) {
2856
2190
  "streamObject"
2857
2191
  ]);
2858
2192
  const agentClasses = /* @__PURE__ */ new Set(["Agent", "Experimental_Agent", "ToolLoopAgent"]);
2859
- const sendEvents = ((_c = deps.options.send) == null ? void 0 : _c.events) !== false;
2860
- const sendTraces = ((_d = deps.options.send) == null ? void 0 : _d.traces) !== false;
2193
+ const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
2194
+ const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
2861
2195
  const autoAttachmentEnabled = deps.options.autoAttachment !== false;
2862
2196
  const selfDiagnostics = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2863
2197
  const proxyTarget = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
@@ -3951,16 +3285,6 @@ function createRaindropAISDK(opts) {
3951
3285
  traceShipper
3952
3286
  });
3953
3287
  },
3954
- createTelemetryIntegration(context) {
3955
- return new RaindropTelemetryIntegration({
3956
- traceShipper,
3957
- eventShipper,
3958
- sendTraces: tracesEnabled,
3959
- sendEvents: eventsEnabled,
3960
- debug: envDebug,
3961
- context
3962
- });
3963
- },
3964
3288
  events: {
3965
3289
  async patch(eventId, patch) {
3966
3290
  await eventShipper.patch(eventId, patch);
@@ -3997,7 +3321,6 @@ function createRaindropAISDK(opts) {
3997
3321
  // src/index.node.ts
3998
3322
  globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = async_hooks.AsyncLocalStorage;
3999
3323
 
4000
- exports.RaindropTelemetryIntegration = RaindropTelemetryIntegration;
4001
3324
  exports._resetWarnedMissingUserId = _resetWarnedMissingUserId;
4002
3325
  exports.createRaindropAISDK = createRaindropAISDK;
4003
3326
  exports.currentSpan = currentSpan;