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