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