@raindrop-ai/ai-sdk 0.0.4 → 0.0.6

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.
package/dist/index.js CHANGED
@@ -86,7 +86,7 @@ async function postJson(url, body, headers, opts) {
86
86
  // package.json
87
87
  var package_default = {
88
88
  name: "@raindrop-ai/ai-sdk",
89
- version: "0.0.4"};
89
+ version: "0.0.6"};
90
90
 
91
91
  // src/internal/version.ts
92
92
  var libraryName = package_default.name;
@@ -763,9 +763,6 @@ async function* asyncGeneratorWithCurrent(span, gen) {
763
763
  nextValue = yield result.value;
764
764
  }
765
765
  }
766
- function isAsyncGenerator(value) {
767
- return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value.next === "function";
768
- }
769
766
 
770
767
  // src/internal/wrap/helpers.ts
771
768
  function isRecord(value) {
@@ -850,31 +847,6 @@ function extractObjectOutput(result) {
850
847
  if (obj === void 0) return void 0;
851
848
  return (_a = safeJson(obj)) != null ? _a : String(obj);
852
849
  }
853
- function extractUsage(result) {
854
- if (!isRecord(result)) return void 0;
855
- const usage = isRecord(result["totalUsage"]) ? result["totalUsage"] : result["usage"];
856
- if (!isRecord(usage)) return void 0;
857
- let inputTokens;
858
- const inputVal = usage["inputTokens"];
859
- if (typeof inputVal === "number") {
860
- inputTokens = inputVal;
861
- } else if (isRecord(inputVal) && typeof inputVal["total"] === "number") {
862
- inputTokens = inputVal["total"];
863
- } else if (typeof usage["promptTokens"] === "number") {
864
- inputTokens = usage["promptTokens"];
865
- }
866
- let outputTokens;
867
- const outputVal = usage["outputTokens"];
868
- if (typeof outputVal === "number") {
869
- outputTokens = outputVal;
870
- } else if (isRecord(outputVal) && typeof outputVal["total"] === "number") {
871
- outputTokens = outputVal["total"];
872
- } else if (typeof usage["completionTokens"] === "number") {
873
- outputTokens = usage["completionTokens"];
874
- }
875
- if (inputTokens === void 0 && outputTokens === void 0) return void 0;
876
- return { inputTokens, outputTokens };
877
- }
878
850
  function isAgentClass(value) {
879
851
  if (typeof value !== "function") return false;
880
852
  const proto = value.prototype;
@@ -1269,6 +1241,17 @@ function attrsFromGenAiRequest(options) {
1269
1241
  }
1270
1242
 
1271
1243
  // src/internal/wrap/wrapAISDK.ts
1244
+ var warnedMissingUserId = false;
1245
+ function warnMissingUserIdOnce() {
1246
+ if (warnedMissingUserId) return;
1247
+ warnedMissingUserId = true;
1248
+ console.warn(
1249
+ "[raindrop-ai/ai-sdk] userId was not provided in wrap() context or via eventMetadata(). Events will be skipped unless a userId is provided."
1250
+ );
1251
+ }
1252
+ function _resetWarnedMissingUserId() {
1253
+ warnedMissingUserId = false;
1254
+ }
1272
1255
  function extractRaindropMetadata(metadata) {
1273
1256
  if (!metadata || typeof metadata !== "object") return {};
1274
1257
  const result = {};
@@ -1305,10 +1288,392 @@ function mergeContexts(wrapTime, callTime) {
1305
1288
  }
1306
1289
  return result;
1307
1290
  }
1291
+ function getCurrentParentSpanContextSync() {
1292
+ return getContextManager().getParentSpanIds();
1293
+ }
1294
+ function runWithParentSpanContextSync(ctx, fn) {
1295
+ const cm = getContextManager();
1296
+ const span = {
1297
+ traceIdB64: ctx.traceIdB64,
1298
+ spanIdB64: ctx.spanIdB64,
1299
+ eventId: ctx.eventId
1300
+ };
1301
+ return cm.runInContext(span, fn);
1302
+ }
1303
+ function isAsyncIterable(value) {
1304
+ return value !== null && typeof value === "object" && Symbol.asyncIterator in value;
1305
+ }
1306
+ function firstFiniteNumber(...values) {
1307
+ for (const value of values) {
1308
+ if (typeof value === "number" && Number.isFinite(value)) {
1309
+ return value;
1310
+ }
1311
+ }
1312
+ return void 0;
1313
+ }
1314
+ function resolveUsageRecord(result) {
1315
+ if (!isRecord(result)) return void 0;
1316
+ let usage;
1317
+ try {
1318
+ if (isRecord(result["totalUsage"])) {
1319
+ usage = result["totalUsage"];
1320
+ } else if (isRecord(result["usage"])) {
1321
+ usage = result["usage"];
1322
+ }
1323
+ } catch (e) {
1324
+ return void 0;
1325
+ }
1326
+ return isRecord(usage) ? usage : void 0;
1327
+ }
1328
+ function extractUsageMetrics(result) {
1329
+ const usage = resolveUsageRecord(result);
1330
+ if (!usage) return {};
1331
+ const inputTokenValue = usage["inputTokens"];
1332
+ const outputTokenValue = usage["outputTokens"];
1333
+ const inputTokens = firstFiniteNumber(
1334
+ isRecord(inputTokenValue) ? inputTokenValue["total"] : void 0,
1335
+ inputTokenValue,
1336
+ usage["promptTokens"],
1337
+ usage["prompt_tokens"]
1338
+ );
1339
+ const outputTokens = firstFiniteNumber(
1340
+ isRecord(outputTokenValue) ? outputTokenValue["total"] : void 0,
1341
+ outputTokenValue,
1342
+ usage["completionTokens"],
1343
+ usage["completion_tokens"]
1344
+ );
1345
+ const totalTokens = firstFiniteNumber(
1346
+ usage["totalTokens"],
1347
+ usage["tokens"],
1348
+ usage["total_tokens"],
1349
+ inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0
1350
+ );
1351
+ const reasoningTokens = firstFiniteNumber(
1352
+ isRecord(outputTokenValue) ? outputTokenValue["reasoning"] : void 0,
1353
+ usage["reasoningTokens"],
1354
+ usage["completionReasoningTokens"],
1355
+ usage["completion_reasoning_tokens"],
1356
+ usage["reasoning_tokens"],
1357
+ usage["thinkingTokens"],
1358
+ usage["thinking_tokens"]
1359
+ );
1360
+ const cachedInputTokens = firstFiniteNumber(
1361
+ isRecord(inputTokenValue) ? inputTokenValue["cacheRead"] : void 0,
1362
+ usage["cachedInputTokens"],
1363
+ usage["promptCachedTokens"],
1364
+ usage["prompt_cached_tokens"]
1365
+ );
1366
+ return {
1367
+ inputTokens,
1368
+ outputTokens,
1369
+ totalTokens,
1370
+ reasoningTokens,
1371
+ cachedInputTokens
1372
+ };
1373
+ }
1374
+ function isObjectOperation(operation) {
1375
+ return operation === "generateObject" || operation === "streamObject";
1376
+ }
1377
+ function logFinalizeError(debug, err) {
1378
+ if (debug) {
1379
+ console.warn(
1380
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1381
+ );
1382
+ }
1383
+ }
1384
+ async function safeFinalize(finalize, debug, result, error) {
1385
+ try {
1386
+ await finalize(result, error);
1387
+ } catch (finalizeErr) {
1388
+ logFinalizeError(debug, finalizeErr);
1389
+ }
1390
+ }
1391
+ function runWithRootContextSync(rootSpan, eventId, fn) {
1392
+ if (!rootSpan) return fn();
1393
+ return runWithParentSpanContextSync(
1394
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1395
+ fn
1396
+ );
1397
+ }
1398
+ async function runWithRootContextAsync(rootSpan, eventId, fn) {
1399
+ if (!rootSpan) return await fn();
1400
+ return await runWithParentSpanContext(
1401
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1402
+ fn
1403
+ );
1404
+ }
1405
+ function teeStreamObjectBaseStream(result) {
1406
+ if (!result || !isRecord(result)) return;
1407
+ const baseStream = result["baseStream"];
1408
+ if (!(baseStream && typeof baseStream === "object" && "tee" in baseStream)) return;
1409
+ try {
1410
+ const [consumeStream, userStream] = baseStream.tee();
1411
+ result["baseStream"] = userStream;
1412
+ consumeStream.pipeTo(new WritableStream({ write() {
1413
+ } })).catch(() => {
1414
+ });
1415
+ } catch (e) {
1416
+ }
1417
+ }
1418
+ function setupOperation(params) {
1419
+ var _a, _b, _c;
1420
+ const { operation, arg, inherited, aiSDK, options, traceShipper, sendTraces } = params;
1421
+ const wrapTimeCtx = resolveContext(options.context, { operation, args: arg });
1422
+ const telemetry = extractExperimentalTelemetry(arg);
1423
+ const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1424
+ const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1425
+ if (!mergedCtx.userId) warnMissingUserIdOnce();
1426
+ const eventId = (_c = (_b = (_a = callTimeCtx.eventId) != null ? _a : mergedCtx.eventId) != null ? _b : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1427
+ const ctx = { ...mergedCtx, eventId };
1428
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1429
+ const outerOperationId = `ai.${operation}`;
1430
+ const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
1431
+ const modelInfoFromArgs = isRecord(arg) ? extractModelInfo(arg["model"]) : {};
1432
+ const rootSpan = sendTraces ? traceShipper.startSpan({
1433
+ name: outerOperationId,
1434
+ parent: inheritedParent,
1435
+ eventId,
1436
+ operationId: outerOperationId,
1437
+ attributes: [
1438
+ attrString("operation.name", operationName),
1439
+ attrString("resource.name", resourceName),
1440
+ attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1441
+ attrString("ai.model.provider", modelInfoFromArgs.provider),
1442
+ attrString("ai.model.id", modelInfoFromArgs.modelId),
1443
+ ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1444
+ ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1445
+ ...attrsFromSettings(arg),
1446
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1447
+ attrString(
1448
+ "ai.prompt",
1449
+ safeJsonWithUint8({
1450
+ system: isRecord(arg) ? arg["system"] : void 0,
1451
+ prompt: isRecord(arg) ? arg["prompt"] : void 0,
1452
+ messages: isRecord(arg) ? arg["messages"] : void 0
1453
+ })
1454
+ )
1455
+ ]
1456
+ ]
1457
+ }) : void 0;
1458
+ const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1459
+ const wrapCtx = {
1460
+ eventId,
1461
+ telemetry,
1462
+ sendTraces,
1463
+ traceShipper,
1464
+ rootParentForChildren
1465
+ };
1466
+ const toolCalls = [];
1467
+ const argsWithWrappedTools = wrapTools(arg, wrapCtx, toolCalls);
1468
+ const wrappedArgs = wrapModel(argsWithWrappedTools, aiSDK, outerOperationId, wrapCtx);
1469
+ return {
1470
+ eventId,
1471
+ ctx,
1472
+ telemetry,
1473
+ rootSpan,
1474
+ wrappedArgs,
1475
+ toolCalls
1476
+ };
1477
+ }
1478
+ function createFinalize(params) {
1479
+ const {
1480
+ operation,
1481
+ arg,
1482
+ setup,
1483
+ autoAttachmentEnabled,
1484
+ sendEvents,
1485
+ debug,
1486
+ options,
1487
+ eventShipper,
1488
+ traceShipper
1489
+ } = params;
1490
+ return async (result, error) => {
1491
+ var _a, _b, _c, _d;
1492
+ const usage = extractUsageMetrics(result);
1493
+ const model = extractModel(result);
1494
+ const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(arg) : void 0;
1495
+ const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
1496
+ const baseMessages = coerceMessagesFromArgs(arg);
1497
+ const responseMessages = extractResponseMessages(result);
1498
+ const allMessages = [...baseMessages, ...responseMessages];
1499
+ const outputText = extractTextOutput(result);
1500
+ const outputObjectJson = extractObjectOutput(result);
1501
+ const defaultOutput = isObjectOperation(operation) ? outputObjectJson : outputText;
1502
+ const defaultPatch = {
1503
+ eventName: (_a = setup.ctx.eventName) != null ? _a : operation,
1504
+ input: (_b = lastUserMessageTextFromArgs(arg)) != null ? _b : extractInputFromArgs(arg),
1505
+ output: defaultOutput,
1506
+ model,
1507
+ properties: setup.ctx.properties,
1508
+ attachments: mergeAttachments(setup.ctx.attachments, inputAttachments, outputAttachments)
1509
+ };
1510
+ const built = await maybeBuildEvent(options.buildEvent, allMessages);
1511
+ const patch = mergeBuildEventPatch(defaultPatch, built);
1512
+ const output = patch.output;
1513
+ const finalModel = (_c = patch.model) != null ? _c : model;
1514
+ if (setup.rootSpan) {
1515
+ const finishReason = extractFinishReason(result);
1516
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1517
+ const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : setup.toolCalls.length ? safeJsonWithUint8(setup.toolCalls) : void 0;
1518
+ traceShipper.endSpan(setup.rootSpan, {
1519
+ attributes: [
1520
+ ...((_d = setup.telemetry) == null ? void 0 : _d.recordOutputs) === false ? [] : [
1521
+ attrString("ai.response.finishReason", finishReason),
1522
+ isObjectOperation(operation) ? attrString("ai.response.object", output) : attrString("ai.response.text", output),
1523
+ attrString("ai.response.toolCalls", resultToolCalls),
1524
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1525
+ ],
1526
+ attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1527
+ attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1528
+ attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1529
+ attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1530
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
1531
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
1532
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
1533
+ attrInt("ai.toolCall.count", setup.toolCalls.length),
1534
+ ...error ? [
1535
+ attrString(
1536
+ "error.message",
1537
+ error instanceof Error ? error.message : String(error)
1538
+ )
1539
+ ] : []
1540
+ ]
1541
+ });
1542
+ }
1543
+ if (sendEvents) {
1544
+ void eventShipper.patch(setup.eventId, {
1545
+ eventName: patch.eventName,
1546
+ userId: setup.ctx.userId,
1547
+ convoId: setup.ctx.convoId,
1548
+ input: patch.input,
1549
+ output,
1550
+ model: finalModel,
1551
+ properties: patch.properties,
1552
+ attachments: patch.attachments,
1553
+ isPending: false
1554
+ }).catch((err) => {
1555
+ if (debug) {
1556
+ console.warn(
1557
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1558
+ );
1559
+ }
1560
+ });
1561
+ }
1562
+ };
1563
+ }
1564
+ function executeStreamingOperation(params) {
1565
+ const {
1566
+ operation,
1567
+ arg,
1568
+ callArgs,
1569
+ aiSDK,
1570
+ original,
1571
+ deps,
1572
+ sendEvents,
1573
+ sendTraces,
1574
+ autoAttachmentEnabled,
1575
+ debug
1576
+ } = params;
1577
+ const setup = setupOperation({
1578
+ operation,
1579
+ arg,
1580
+ inherited: getCurrentParentSpanContextSync(),
1581
+ aiSDK,
1582
+ options: deps.options,
1583
+ traceShipper: deps.traceShipper,
1584
+ sendTraces
1585
+ });
1586
+ const finalize = createFinalize({
1587
+ operation,
1588
+ arg,
1589
+ setup,
1590
+ autoAttachmentEnabled,
1591
+ sendEvents,
1592
+ debug,
1593
+ options: deps.options,
1594
+ eventShipper: deps.eventShipper,
1595
+ traceShipper: deps.traceShipper
1596
+ });
1597
+ const argWithOnFinish = wrapOnFinish(setup.wrappedArgs, async (result) => {
1598
+ await safeFinalize(finalize, debug, result);
1599
+ });
1600
+ const callOriginal = (...args) => {
1601
+ return original.call(aiSDK, ...args);
1602
+ };
1603
+ try {
1604
+ const result = runWithRootContextSync(setup.rootSpan, setup.eventId, () => {
1605
+ const nextArgs = [...callArgs];
1606
+ nextArgs[0] = argWithOnFinish;
1607
+ return callOriginal(...nextArgs);
1608
+ });
1609
+ if (operation === "streamObject") {
1610
+ teeStreamObjectBaseStream(result);
1611
+ }
1612
+ return result;
1613
+ } catch (error) {
1614
+ void safeFinalize(finalize, debug, void 0, error);
1615
+ throw error;
1616
+ }
1617
+ }
1618
+ async function executeNonStreamingOperation(params) {
1619
+ const {
1620
+ operation,
1621
+ arg,
1622
+ callArgs,
1623
+ aiSDK,
1624
+ original,
1625
+ deps,
1626
+ sendEvents,
1627
+ sendTraces,
1628
+ autoAttachmentEnabled,
1629
+ debug
1630
+ } = params;
1631
+ const inherited = await getCurrentParentSpanContext();
1632
+ const setup = setupOperation({
1633
+ operation,
1634
+ arg,
1635
+ inherited,
1636
+ aiSDK,
1637
+ options: deps.options,
1638
+ traceShipper: deps.traceShipper,
1639
+ sendTraces
1640
+ });
1641
+ const finalize = createFinalize({
1642
+ operation,
1643
+ arg,
1644
+ setup,
1645
+ autoAttachmentEnabled,
1646
+ sendEvents,
1647
+ debug,
1648
+ options: deps.options,
1649
+ eventShipper: deps.eventShipper,
1650
+ traceShipper: deps.traceShipper
1651
+ });
1652
+ const callOriginal = async (...args) => {
1653
+ return await original.call(aiSDK, ...args);
1654
+ };
1655
+ try {
1656
+ const result = await runWithRootContextAsync(setup.rootSpan, setup.eventId, async () => {
1657
+ const nextArgs = [...callArgs];
1658
+ nextArgs[0] = setup.wrappedArgs;
1659
+ return await callOriginal(...nextArgs);
1660
+ });
1661
+ await safeFinalize(finalize, debug, result);
1662
+ return result;
1663
+ } catch (error) {
1664
+ await safeFinalize(finalize, debug, void 0, error);
1665
+ throw error;
1666
+ }
1667
+ }
1308
1668
  function wrapAISDK(aiSDK, deps) {
1309
1669
  var _a, _b;
1310
1670
  const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
1311
- const instrumentedOps = /* @__PURE__ */ new Set(["generateText", "streamText", "generateObject", "streamObject"]);
1671
+ const instrumentedOps = /* @__PURE__ */ new Set([
1672
+ "generateText",
1673
+ "streamText",
1674
+ "generateObject",
1675
+ "streamObject"
1676
+ ]);
1312
1677
  const agentClasses = /* @__PURE__ */ new Set(["ToolLoopAgent"]);
1313
1678
  const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
1314
1679
  const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
@@ -1324,224 +1689,35 @@ function wrapAISDK(aiSDK, deps) {
1324
1689
  if (typeof prop !== "string" || !instrumentedOps.has(prop) || !isFunction(original)) {
1325
1690
  return original;
1326
1691
  }
1327
- return async (...callArgs) => {
1328
- var _a2, _b2, _c;
1329
- const arg = callArgs[0];
1692
+ return (...callArgs) => {
1330
1693
  const operation = prop;
1331
- const wrapTimeCtx = resolveContext(deps.options.context, { operation, args: arg });
1332
- const telemetry = extractExperimentalTelemetry(arg);
1333
- const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1334
- const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1335
- const inherited = await getCurrentParentSpanContext();
1336
- const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1337
- const ctx = { ...mergedCtx};
1338
- const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1339
- const outerOperationId = `ai.${operation}`;
1340
- const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
1341
- const modelInfoFromArgs = isRecord(arg) ? extractModelInfo(arg["model"]) : {};
1342
- const rootSpan = sendTraces ? deps.traceShipper.startSpan({
1343
- name: outerOperationId,
1344
- parent: inheritedParent,
1345
- eventId,
1346
- operationId: outerOperationId,
1347
- attributes: [
1348
- attrString("operation.name", operationName),
1349
- attrString("resource.name", resourceName),
1350
- attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1351
- attrString("ai.model.provider", modelInfoFromArgs.provider),
1352
- attrString("ai.model.id", modelInfoFromArgs.modelId),
1353
- ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1354
- ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1355
- ...attrsFromSettings(arg),
1356
- ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1357
- attrString(
1358
- "ai.prompt",
1359
- safeJsonWithUint8({
1360
- system: isRecord(arg) ? arg["system"] : void 0,
1361
- prompt: isRecord(arg) ? arg["prompt"] : void 0,
1362
- messages: isRecord(arg) ? arg["messages"] : void 0
1363
- })
1364
- )
1365
- ]
1366
- ]
1367
- }) : void 0;
1368
- const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1369
- const wrapCtx = {
1370
- eventId,
1371
- telemetry,
1372
- sendTraces,
1373
- traceShipper: deps.traceShipper,
1374
- rootParentForChildren
1375
- };
1376
- const toolCalls = [];
1377
- const argWithWrappedTools = wrapTools(arg, wrapCtx, toolCalls);
1378
- const argWithWrappedModel = wrapModel(
1379
- argWithWrappedTools,
1380
- aiSDK,
1381
- outerOperationId,
1382
- wrapCtx
1383
- );
1384
- const finalize = async (result, error) => {
1385
- var _a3, _b3, _c2;
1386
- const usage = extractUsage(result);
1387
- const model = extractModel(result);
1388
- const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(arg) : void 0;
1389
- const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
1390
- const baseMessages = coerceMessagesFromArgs(arg);
1391
- const responseMessages = extractResponseMessages(result);
1392
- const allMessages = [...baseMessages, ...responseMessages];
1393
- const outputText = extractTextOutput(result);
1394
- const outputObjectJson = extractObjectOutput(result);
1395
- const defaultOutput = operation === "generateObject" || operation === "streamObject" ? outputObjectJson : outputText;
1396
- const defaultPatch = {
1397
- eventName: (_a3 = ctx.eventName) != null ? _a3 : operation,
1398
- input: (_b3 = lastUserMessageTextFromArgs(arg)) != null ? _b3 : extractInputFromArgs(arg),
1399
- output: defaultOutput,
1400
- model,
1401
- properties: ctx.properties,
1402
- attachments: mergeAttachments(ctx.attachments, inputAttachments, outputAttachments)
1403
- };
1404
- const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
1405
- const patch = mergeBuildEventPatch(defaultPatch, built);
1406
- const output = patch.output;
1407
- const finalModel = (_c2 = patch.model) != null ? _c2 : model;
1408
- if (rootSpan) {
1409
- const finishReason = extractFinishReason(result);
1410
- const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1411
- const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1412
- const usageRec = isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1413
- const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1414
- const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1415
- const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1416
- deps.traceShipper.endSpan(rootSpan, {
1417
- attributes: [
1418
- ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
1419
- attrString("ai.response.finishReason", finishReason),
1420
- operation === "generateObject" || operation === "streamObject" ? attrString("ai.response.object", output) : attrString("ai.response.text", output),
1421
- attrString("ai.response.toolCalls", resultToolCalls),
1422
- attrString(
1423
- "ai.response.providerMetadata",
1424
- safeJsonWithUint8(providerMetadata)
1425
- )
1426
- ],
1427
- attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1428
- attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1429
- attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1430
- attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1431
- attrInt("ai.usage.totalTokens", totalTokens),
1432
- attrInt("ai.usage.reasoningTokens", reasoningTokens),
1433
- attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1434
- attrInt("ai.toolCall.count", toolCalls.length),
1435
- ...error ? [
1436
- attrString(
1437
- "error.message",
1438
- error instanceof Error ? error.message : String(error)
1439
- )
1440
- ] : []
1441
- ]
1442
- });
1443
- }
1444
- if (sendEvents) {
1445
- void deps.eventShipper.patch(eventId, {
1446
- eventName: patch.eventName,
1447
- userId: ctx.userId,
1448
- convoId: ctx.convoId,
1449
- input: patch.input,
1450
- output,
1451
- model: finalModel,
1452
- properties: patch.properties,
1453
- attachments: patch.attachments,
1454
- isPending: false
1455
- }).catch((err) => {
1456
- if (debug)
1457
- console.warn(
1458
- `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1459
- );
1460
- });
1461
- }
1462
- };
1463
- const callOriginal = async (...args) => {
1464
- return await original.call(
1465
- aiSDK,
1466
- ...args
1467
- );
1468
- };
1469
- const runWithContext = async (fn) => {
1470
- if (!rootSpan) return await fn();
1471
- return await runWithParentSpanContext(
1472
- { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1473
- fn
1474
- );
1475
- };
1694
+ const arg = callArgs[0];
1476
1695
  if (operation === "streamText" || operation === "streamObject") {
1477
- const argWithOnFinish = wrapOnFinish(argWithWrappedModel, async (result) => {
1478
- try {
1479
- await finalize(result);
1480
- } catch (err) {
1481
- if (debug)
1482
- console.warn(
1483
- `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1484
- );
1485
- }
1486
- });
1487
- try {
1488
- const result = await runWithContext(async () => {
1489
- const nextArgs = [...callArgs];
1490
- nextArgs[0] = argWithOnFinish;
1491
- return await callOriginal(...nextArgs);
1492
- });
1493
- if (operation === "streamObject" && result && isRecord(result)) {
1494
- const baseStream = result["baseStream"];
1495
- if (baseStream && typeof baseStream === "object" && "tee" in baseStream) {
1496
- try {
1497
- const [consumeStream, userStream] = baseStream.tee();
1498
- result["baseStream"] = userStream;
1499
- consumeStream.pipeTo(new WritableStream({ write() {
1500
- } })).catch(() => {
1501
- });
1502
- } catch (e) {
1503
- }
1504
- }
1505
- }
1506
- return result;
1507
- } catch (error) {
1508
- try {
1509
- await finalize(void 0, error);
1510
- } catch (err) {
1511
- if (debug)
1512
- console.warn(
1513
- `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1514
- );
1515
- }
1516
- throw error;
1517
- }
1518
- }
1519
- try {
1520
- const result = await runWithContext(async () => {
1521
- const nextArgs = [...callArgs];
1522
- nextArgs[0] = argWithWrappedModel;
1523
- return await callOriginal(...nextArgs);
1696
+ return executeStreamingOperation({
1697
+ operation,
1698
+ arg,
1699
+ callArgs,
1700
+ aiSDK,
1701
+ original,
1702
+ deps,
1703
+ sendEvents,
1704
+ sendTraces,
1705
+ autoAttachmentEnabled,
1706
+ debug
1524
1707
  });
1525
- try {
1526
- await finalize(result);
1527
- } catch (err) {
1528
- if (debug)
1529
- console.warn(
1530
- `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1531
- );
1532
- }
1533
- return result;
1534
- } catch (error) {
1535
- try {
1536
- await finalize(void 0, error);
1537
- } catch (err) {
1538
- if (debug)
1539
- console.warn(
1540
- `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1541
- );
1542
- }
1543
- throw error;
1544
1708
  }
1709
+ return executeNonStreamingOperation({
1710
+ operation,
1711
+ arg,
1712
+ callArgs,
1713
+ aiSDK,
1714
+ original,
1715
+ deps,
1716
+ sendEvents,
1717
+ sendTraces,
1718
+ autoAttachmentEnabled,
1719
+ debug
1720
+ });
1545
1721
  };
1546
1722
  }
1547
1723
  });
@@ -1600,6 +1776,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1600
1776
  const telemetry = extractExperimentalTelemetry(mergedArgs);
1601
1777
  const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1602
1778
  const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1779
+ if (!mergedCtx.userId) warnMissingUserIdOnce();
1603
1780
  const inherited = await getCurrentParentSpanContext();
1604
1781
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1605
1782
  const ctx = { ...mergedCtx};
@@ -1652,7 +1829,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1652
1829
  const callParamsWithWrappedToolsAndModel = mergedArgsWithWrappedModel != null ? mergedArgsWithWrappedModel : {};
1653
1830
  const finalize = async (result, error) => {
1654
1831
  var _a3, _b3, _c2;
1655
- const usage = extractUsage(result);
1832
+ const usage = extractUsageMetrics(result);
1656
1833
  const model = extractModel(result);
1657
1834
  const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(mergedArgs) : void 0;
1658
1835
  const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
@@ -1676,10 +1853,6 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1676
1853
  const finishReason = extractFinishReason(result);
1677
1854
  const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1678
1855
  const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1679
- const usageRec = isRecord(result) && isRecord(result["totalUsage"]) ? result["totalUsage"] : isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1680
- const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1681
- const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1682
- const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1683
1856
  deps.traceShipper.endSpan(rootSpan, {
1684
1857
  attributes: [
1685
1858
  ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
@@ -1692,9 +1865,9 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1692
1865
  attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1693
1866
  attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1694
1867
  attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1695
- attrInt("ai.usage.totalTokens", totalTokens),
1696
- attrInt("ai.usage.reasoningTokens", reasoningTokens),
1697
- attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1868
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
1869
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
1870
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
1698
1871
  attrInt("ai.toolCall.count", toolCalls.length),
1699
1872
  ...error ? [
1700
1873
  attrString(
@@ -1791,6 +1964,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1791
1964
  const telemetry = extractExperimentalTelemetry(mergedArgs);
1792
1965
  const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1793
1966
  const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1967
+ if (!mergedCtx.userId) warnMissingUserIdOnce();
1794
1968
  const inherited = await getCurrentParentSpanContext();
1795
1969
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1796
1970
  const ctx = { ...mergedCtx};
@@ -1843,7 +2017,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1843
2017
  const callParamsWithWrappedToolsAndModel = mergedArgsWithWrappedModel != null ? mergedArgsWithWrappedModel : {};
1844
2018
  const finalize = async (result, error) => {
1845
2019
  var _a3, _b3, _c2;
1846
- const usage = extractUsage(result);
2020
+ const usage = extractUsageMetrics(result);
1847
2021
  const model = extractModel(result);
1848
2022
  const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(mergedArgs) : void 0;
1849
2023
  const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
@@ -1867,10 +2041,6 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1867
2041
  const finishReason = extractFinishReason(result);
1868
2042
  const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1869
2043
  const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1870
- const usageRec = isRecord(result) && isRecord(result["totalUsage"]) ? result["totalUsage"] : isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1871
- const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1872
- const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1873
- const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1874
2044
  deps.traceShipper.endSpan(rootSpan, {
1875
2045
  attributes: [
1876
2046
  ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
@@ -1883,9 +2053,9 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1883
2053
  attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1884
2054
  attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1885
2055
  attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1886
- attrInt("ai.usage.totalTokens", totalTokens),
1887
- attrInt("ai.usage.reasoningTokens", reasoningTokens),
1888
- attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
2056
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
2057
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
2058
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
1889
2059
  attrInt("ai.toolCall.count", toolCalls.length),
1890
2060
  ...error ? [
1891
2061
  attrString(
@@ -2025,20 +2195,26 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2025
2195
  spanIdB64: span.ids.spanIdB64,
2026
2196
  eventId: ctx.eventId
2027
2197
  });
2028
- const wrappedExecute = (...execArgs) => {
2198
+ const wrappedExecute = function(...execArgs) {
2029
2199
  const toolArgs = execArgs[0];
2030
2200
  const execOptions = execArgs.length > 1 ? execArgs[1] : void 0;
2031
2201
  const toolCallId = isRecord(execOptions) && typeof execOptions["toolCallId"] === "string" ? execOptions["toolCallId"] : randomUUID();
2032
- const result = originalExecute(...execArgs);
2033
- if (isAsyncGenerator(result)) {
2202
+ const result = originalExecute.apply(this, execArgs);
2203
+ if (isAsyncIterable(result)) {
2034
2204
  return (async function* () {
2035
2205
  const parentCtx = await getCurrentParentSpanContext();
2036
2206
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2037
2207
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
2038
2208
  try {
2039
2209
  let lastValue;
2040
- const wrappedGen = toolSpan ? asyncGeneratorWithCurrent(createContextSpan(toolSpan), result) : result;
2041
- for await (const value of wrappedGen) {
2210
+ const iterator = result[Symbol.asyncIterator]();
2211
+ const wrappedIterable = toolSpan ? asyncGeneratorWithCurrent(
2212
+ createContextSpan(toolSpan),
2213
+ iterator
2214
+ ) : {
2215
+ [Symbol.asyncIterator]: () => iterator
2216
+ };
2217
+ for await (const value of wrappedIterable) {
2042
2218
  lastValue = value;
2043
2219
  yield value;
2044
2220
  }
@@ -2384,14 +2560,19 @@ function wrapOnFinish(args, onFinish) {
2384
2560
  return {
2385
2561
  ...args,
2386
2562
  onFinish: async (result) => {
2563
+ let userError;
2387
2564
  try {
2388
2565
  const maybePromise = existing(result);
2389
2566
  if (maybePromise && typeof maybePromise.then === "function") {
2390
2567
  await maybePromise;
2391
2568
  }
2392
- } catch (e) {
2569
+ } catch (error) {
2570
+ userError = error;
2393
2571
  }
2394
2572
  await onFinish(result);
2573
+ if (userError !== void 0) {
2574
+ throw userError;
2575
+ }
2395
2576
  }
2396
2577
  };
2397
2578
  }
@@ -2511,6 +2692,7 @@ function createRaindropAISDK(opts) {
2511
2692
  };
2512
2693
  }
2513
2694
 
2695
+ exports._resetWarnedMissingUserId = _resetWarnedMissingUserId;
2514
2696
  exports.createRaindropAISDK = createRaindropAISDK;
2515
2697
  exports.currentSpan = currentSpan;
2516
2698
  exports.eventMetadata = eventMetadata;