@raindrop-ai/ai-sdk 0.0.3 → 0.0.5

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.
@@ -84,7 +84,7 @@ async function postJson(url, body, headers, opts) {
84
84
  // package.json
85
85
  var package_default = {
86
86
  name: "@raindrop-ai/ai-sdk",
87
- version: "0.0.3"};
87
+ version: "0.0.5"};
88
88
 
89
89
  // src/internal/version.ts
90
90
  var libraryName = package_default.name;
@@ -761,9 +761,6 @@ async function* asyncGeneratorWithCurrent(span, gen) {
761
761
  nextValue = yield result.value;
762
762
  }
763
763
  }
764
- function isAsyncGenerator(value) {
765
- return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value.next === "function";
766
- }
767
764
 
768
765
  // src/internal/wrap/helpers.ts
769
766
  function isRecord(value) {
@@ -848,31 +845,6 @@ function extractObjectOutput(result) {
848
845
  if (obj === void 0) return void 0;
849
846
  return (_a = safeJson(obj)) != null ? _a : String(obj);
850
847
  }
851
- function extractUsage(result) {
852
- if (!isRecord(result)) return void 0;
853
- const usage = isRecord(result["totalUsage"]) ? result["totalUsage"] : result["usage"];
854
- if (!isRecord(usage)) return void 0;
855
- let inputTokens;
856
- const inputVal = usage["inputTokens"];
857
- if (typeof inputVal === "number") {
858
- inputTokens = inputVal;
859
- } else if (isRecord(inputVal) && typeof inputVal["total"] === "number") {
860
- inputTokens = inputVal["total"];
861
- } else if (typeof usage["promptTokens"] === "number") {
862
- inputTokens = usage["promptTokens"];
863
- }
864
- let outputTokens;
865
- const outputVal = usage["outputTokens"];
866
- if (typeof outputVal === "number") {
867
- outputTokens = outputVal;
868
- } else if (isRecord(outputVal) && typeof outputVal["total"] === "number") {
869
- outputTokens = outputVal["total"];
870
- } else if (typeof usage["completionTokens"] === "number") {
871
- outputTokens = usage["completionTokens"];
872
- }
873
- if (inputTokens === void 0 && outputTokens === void 0) return void 0;
874
- return { inputTokens, outputTokens };
875
- }
876
848
  function isAgentClass(value) {
877
849
  if (typeof value !== "function") return false;
878
850
  const proto = value.prototype;
@@ -882,7 +854,13 @@ function isAgentClass(value) {
882
854
  function extractModel(result) {
883
855
  if (!isRecord(result)) return void 0;
884
856
  const model = result["model"];
885
- return typeof model === "string" && model.length ? model : void 0;
857
+ if (typeof model === "string" && model.length) return model;
858
+ const response = result["response"];
859
+ if (isRecord(response)) {
860
+ const modelId = response["modelId"];
861
+ if (typeof modelId === "string" && modelId.length) return modelId;
862
+ }
863
+ return void 0;
886
864
  }
887
865
  function extractFinishReason(result) {
888
866
  if (!isRecord(result)) return void 0;
@@ -1297,10 +1275,391 @@ function mergeContexts(wrapTime, callTime) {
1297
1275
  }
1298
1276
  return result;
1299
1277
  }
1278
+ function getCurrentParentSpanContextSync() {
1279
+ return getContextManager().getParentSpanIds();
1280
+ }
1281
+ function runWithParentSpanContextSync(ctx, fn) {
1282
+ const cm = getContextManager();
1283
+ const span = {
1284
+ traceIdB64: ctx.traceIdB64,
1285
+ spanIdB64: ctx.spanIdB64,
1286
+ eventId: ctx.eventId
1287
+ };
1288
+ return cm.runInContext(span, fn);
1289
+ }
1290
+ function isAsyncIterable(value) {
1291
+ return value !== null && typeof value === "object" && Symbol.asyncIterator in value;
1292
+ }
1293
+ function firstFiniteNumber(...values) {
1294
+ for (const value of values) {
1295
+ if (typeof value === "number" && Number.isFinite(value)) {
1296
+ return value;
1297
+ }
1298
+ }
1299
+ return void 0;
1300
+ }
1301
+ function resolveUsageRecord(result) {
1302
+ if (!isRecord(result)) return void 0;
1303
+ let usage;
1304
+ try {
1305
+ if (isRecord(result["totalUsage"])) {
1306
+ usage = result["totalUsage"];
1307
+ } else if (isRecord(result["usage"])) {
1308
+ usage = result["usage"];
1309
+ }
1310
+ } catch (e) {
1311
+ return void 0;
1312
+ }
1313
+ return isRecord(usage) ? usage : void 0;
1314
+ }
1315
+ function extractUsageMetrics(result) {
1316
+ const usage = resolveUsageRecord(result);
1317
+ if (!usage) return {};
1318
+ const inputTokenValue = usage["inputTokens"];
1319
+ const outputTokenValue = usage["outputTokens"];
1320
+ const inputTokens = firstFiniteNumber(
1321
+ isRecord(inputTokenValue) ? inputTokenValue["total"] : void 0,
1322
+ inputTokenValue,
1323
+ usage["promptTokens"],
1324
+ usage["prompt_tokens"]
1325
+ );
1326
+ const outputTokens = firstFiniteNumber(
1327
+ isRecord(outputTokenValue) ? outputTokenValue["total"] : void 0,
1328
+ outputTokenValue,
1329
+ usage["completionTokens"],
1330
+ usage["completion_tokens"]
1331
+ );
1332
+ const totalTokens = firstFiniteNumber(
1333
+ usage["totalTokens"],
1334
+ usage["tokens"],
1335
+ usage["total_tokens"],
1336
+ inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0
1337
+ );
1338
+ const reasoningTokens = firstFiniteNumber(
1339
+ isRecord(outputTokenValue) ? outputTokenValue["reasoning"] : void 0,
1340
+ usage["reasoningTokens"],
1341
+ usage["completionReasoningTokens"],
1342
+ usage["completion_reasoning_tokens"],
1343
+ usage["reasoning_tokens"],
1344
+ usage["thinkingTokens"],
1345
+ usage["thinking_tokens"]
1346
+ );
1347
+ const cachedInputTokens = firstFiniteNumber(
1348
+ isRecord(inputTokenValue) ? inputTokenValue["cacheRead"] : void 0,
1349
+ usage["cachedInputTokens"],
1350
+ usage["promptCachedTokens"],
1351
+ usage["prompt_cached_tokens"]
1352
+ );
1353
+ return {
1354
+ inputTokens,
1355
+ outputTokens,
1356
+ totalTokens,
1357
+ reasoningTokens,
1358
+ cachedInputTokens
1359
+ };
1360
+ }
1361
+ function isObjectOperation(operation) {
1362
+ return operation === "generateObject" || operation === "streamObject";
1363
+ }
1364
+ function logFinalizeError(debug, err) {
1365
+ if (debug) {
1366
+ console.warn(
1367
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1368
+ );
1369
+ }
1370
+ }
1371
+ async function safeFinalize(finalize, debug, result, error) {
1372
+ try {
1373
+ await finalize(result, error);
1374
+ } catch (finalizeErr) {
1375
+ logFinalizeError(debug, finalizeErr);
1376
+ }
1377
+ }
1378
+ function runWithRootContextSync(rootSpan, eventId, fn) {
1379
+ if (!rootSpan) return fn();
1380
+ return runWithParentSpanContextSync(
1381
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1382
+ fn
1383
+ );
1384
+ }
1385
+ async function runWithRootContextAsync(rootSpan, eventId, fn) {
1386
+ if (!rootSpan) return await fn();
1387
+ return await runWithParentSpanContext(
1388
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1389
+ fn
1390
+ );
1391
+ }
1392
+ function teeStreamObjectBaseStream(result) {
1393
+ if (!result || !isRecord(result)) return;
1394
+ const baseStream = result["baseStream"];
1395
+ if (!(baseStream && typeof baseStream === "object" && "tee" in baseStream)) return;
1396
+ try {
1397
+ const [consumeStream, userStream] = baseStream.tee();
1398
+ result["baseStream"] = userStream;
1399
+ consumeStream.pipeTo(new WritableStream({ write() {
1400
+ } })).catch(() => {
1401
+ });
1402
+ } catch (e) {
1403
+ }
1404
+ }
1405
+ function setupOperation(params) {
1406
+ var _a, _b, _c;
1407
+ const { operation, arg, inherited, aiSDK, options, traceShipper, sendTraces } = params;
1408
+ const wrapTimeCtx = resolveContext(options.context, { operation, args: arg });
1409
+ const telemetry = extractExperimentalTelemetry(arg);
1410
+ const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1411
+ const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1412
+ const eventId = (_c = (_b = (_a = callTimeCtx.eventId) != null ? _a : mergedCtx.eventId) != null ? _b : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1413
+ const ctx = { ...mergedCtx, eventId };
1414
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1415
+ const outerOperationId = `ai.${operation}`;
1416
+ const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
1417
+ const modelInfoFromArgs = isRecord(arg) ? extractModelInfo(arg["model"]) : {};
1418
+ const rootSpan = sendTraces ? traceShipper.startSpan({
1419
+ name: outerOperationId,
1420
+ parent: inheritedParent,
1421
+ eventId,
1422
+ operationId: outerOperationId,
1423
+ attributes: [
1424
+ attrString("operation.name", operationName),
1425
+ attrString("resource.name", resourceName),
1426
+ attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1427
+ attrString("ai.model.provider", modelInfoFromArgs.provider),
1428
+ attrString("ai.model.id", modelInfoFromArgs.modelId),
1429
+ ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1430
+ ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1431
+ ...attrsFromSettings(arg),
1432
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1433
+ attrString(
1434
+ "ai.prompt",
1435
+ safeJsonWithUint8({
1436
+ system: isRecord(arg) ? arg["system"] : void 0,
1437
+ prompt: isRecord(arg) ? arg["prompt"] : void 0,
1438
+ messages: isRecord(arg) ? arg["messages"] : void 0
1439
+ })
1440
+ )
1441
+ ]
1442
+ ]
1443
+ }) : void 0;
1444
+ const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1445
+ const wrapCtx = {
1446
+ eventId,
1447
+ telemetry,
1448
+ sendTraces,
1449
+ traceShipper,
1450
+ rootParentForChildren
1451
+ };
1452
+ const toolCalls = [];
1453
+ const argsWithWrappedTools = wrapTools(arg, wrapCtx, toolCalls);
1454
+ const wrappedArgs = wrapModel(argsWithWrappedTools, aiSDK, outerOperationId, wrapCtx);
1455
+ return {
1456
+ eventId,
1457
+ ctx,
1458
+ telemetry,
1459
+ rootSpan,
1460
+ wrappedArgs,
1461
+ toolCalls
1462
+ };
1463
+ }
1464
+ function createFinalize(params) {
1465
+ const {
1466
+ operation,
1467
+ arg,
1468
+ setup,
1469
+ autoAttachmentEnabled,
1470
+ sendEvents,
1471
+ debug,
1472
+ options,
1473
+ eventShipper,
1474
+ traceShipper
1475
+ } = params;
1476
+ return async (result, error) => {
1477
+ var _a, _b, _c, _d;
1478
+ const usage = extractUsageMetrics(result);
1479
+ const model = extractModel(result);
1480
+ const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(arg) : void 0;
1481
+ const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
1482
+ const baseMessages = coerceMessagesFromArgs(arg);
1483
+ const responseMessages = extractResponseMessages(result);
1484
+ const allMessages = [...baseMessages, ...responseMessages];
1485
+ const outputText = extractTextOutput(result);
1486
+ const outputObjectJson = extractObjectOutput(result);
1487
+ const defaultOutput = isObjectOperation(operation) ? outputObjectJson : outputText;
1488
+ const defaultPatch = {
1489
+ eventName: (_a = setup.ctx.eventName) != null ? _a : operation,
1490
+ input: (_b = lastUserMessageTextFromArgs(arg)) != null ? _b : extractInputFromArgs(arg),
1491
+ output: defaultOutput,
1492
+ model,
1493
+ properties: setup.ctx.properties,
1494
+ attachments: mergeAttachments(setup.ctx.attachments, inputAttachments, outputAttachments)
1495
+ };
1496
+ const built = await maybeBuildEvent(options.buildEvent, allMessages);
1497
+ const patch = mergeBuildEventPatch(defaultPatch, built);
1498
+ const output = patch.output;
1499
+ const finalModel = (_c = patch.model) != null ? _c : model;
1500
+ if (setup.rootSpan) {
1501
+ const finishReason = extractFinishReason(result);
1502
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1503
+ const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : setup.toolCalls.length ? safeJsonWithUint8(setup.toolCalls) : void 0;
1504
+ traceShipper.endSpan(setup.rootSpan, {
1505
+ attributes: [
1506
+ ...((_d = setup.telemetry) == null ? void 0 : _d.recordOutputs) === false ? [] : [
1507
+ attrString("ai.response.finishReason", finishReason),
1508
+ isObjectOperation(operation) ? attrString("ai.response.object", output) : attrString("ai.response.text", output),
1509
+ attrString("ai.response.toolCalls", resultToolCalls),
1510
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1511
+ ],
1512
+ attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1513
+ attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1514
+ attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1515
+ attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1516
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
1517
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
1518
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
1519
+ attrInt("ai.toolCall.count", setup.toolCalls.length),
1520
+ ...error ? [
1521
+ attrString(
1522
+ "error.message",
1523
+ error instanceof Error ? error.message : String(error)
1524
+ )
1525
+ ] : []
1526
+ ]
1527
+ });
1528
+ }
1529
+ if (sendEvents) {
1530
+ void eventShipper.patch(setup.eventId, {
1531
+ eventName: patch.eventName,
1532
+ userId: setup.ctx.userId,
1533
+ convoId: setup.ctx.convoId,
1534
+ input: patch.input,
1535
+ output,
1536
+ model: finalModel,
1537
+ properties: patch.properties,
1538
+ attachments: patch.attachments,
1539
+ isPending: false
1540
+ }).catch((err) => {
1541
+ if (debug) {
1542
+ console.warn(
1543
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1544
+ );
1545
+ }
1546
+ });
1547
+ }
1548
+ };
1549
+ }
1550
+ function executeStreamingOperation(params) {
1551
+ const {
1552
+ operation,
1553
+ arg,
1554
+ callArgs,
1555
+ aiSDK,
1556
+ original,
1557
+ deps,
1558
+ sendEvents,
1559
+ sendTraces,
1560
+ autoAttachmentEnabled,
1561
+ debug
1562
+ } = params;
1563
+ const setup = setupOperation({
1564
+ operation,
1565
+ arg,
1566
+ inherited: getCurrentParentSpanContextSync(),
1567
+ aiSDK,
1568
+ options: deps.options,
1569
+ traceShipper: deps.traceShipper,
1570
+ sendTraces
1571
+ });
1572
+ const finalize = createFinalize({
1573
+ operation,
1574
+ arg,
1575
+ setup,
1576
+ autoAttachmentEnabled,
1577
+ sendEvents,
1578
+ debug,
1579
+ options: deps.options,
1580
+ eventShipper: deps.eventShipper,
1581
+ traceShipper: deps.traceShipper
1582
+ });
1583
+ const argWithOnFinish = wrapOnFinish(setup.wrappedArgs, async (result) => {
1584
+ await safeFinalize(finalize, debug, result);
1585
+ });
1586
+ const callOriginal = (...args) => {
1587
+ return original.call(aiSDK, ...args);
1588
+ };
1589
+ try {
1590
+ const result = runWithRootContextSync(setup.rootSpan, setup.eventId, () => {
1591
+ const nextArgs = [...callArgs];
1592
+ nextArgs[0] = argWithOnFinish;
1593
+ return callOriginal(...nextArgs);
1594
+ });
1595
+ if (operation === "streamObject") {
1596
+ teeStreamObjectBaseStream(result);
1597
+ }
1598
+ return result;
1599
+ } catch (error) {
1600
+ void safeFinalize(finalize, debug, void 0, error);
1601
+ throw error;
1602
+ }
1603
+ }
1604
+ async function executeNonStreamingOperation(params) {
1605
+ const {
1606
+ operation,
1607
+ arg,
1608
+ callArgs,
1609
+ aiSDK,
1610
+ original,
1611
+ deps,
1612
+ sendEvents,
1613
+ sendTraces,
1614
+ autoAttachmentEnabled,
1615
+ debug
1616
+ } = params;
1617
+ const inherited = await getCurrentParentSpanContext();
1618
+ const setup = setupOperation({
1619
+ operation,
1620
+ arg,
1621
+ inherited,
1622
+ aiSDK,
1623
+ options: deps.options,
1624
+ traceShipper: deps.traceShipper,
1625
+ sendTraces
1626
+ });
1627
+ const finalize = createFinalize({
1628
+ operation,
1629
+ arg,
1630
+ setup,
1631
+ autoAttachmentEnabled,
1632
+ sendEvents,
1633
+ debug,
1634
+ options: deps.options,
1635
+ eventShipper: deps.eventShipper,
1636
+ traceShipper: deps.traceShipper
1637
+ });
1638
+ const callOriginal = async (...args) => {
1639
+ return await original.call(aiSDK, ...args);
1640
+ };
1641
+ try {
1642
+ const result = await runWithRootContextAsync(setup.rootSpan, setup.eventId, async () => {
1643
+ const nextArgs = [...callArgs];
1644
+ nextArgs[0] = setup.wrappedArgs;
1645
+ return await callOriginal(...nextArgs);
1646
+ });
1647
+ await safeFinalize(finalize, debug, result);
1648
+ return result;
1649
+ } catch (error) {
1650
+ await safeFinalize(finalize, debug, void 0, error);
1651
+ throw error;
1652
+ }
1653
+ }
1300
1654
  function wrapAISDK(aiSDK, deps) {
1301
1655
  var _a, _b;
1302
1656
  const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
1303
- const instrumentedOps = /* @__PURE__ */ new Set(["generateText", "streamText", "generateObject", "streamObject"]);
1657
+ const instrumentedOps = /* @__PURE__ */ new Set([
1658
+ "generateText",
1659
+ "streamText",
1660
+ "generateObject",
1661
+ "streamObject"
1662
+ ]);
1304
1663
  const agentClasses = /* @__PURE__ */ new Set(["ToolLoopAgent"]);
1305
1664
  const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
1306
1665
  const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
@@ -1316,224 +1675,35 @@ function wrapAISDK(aiSDK, deps) {
1316
1675
  if (typeof prop !== "string" || !instrumentedOps.has(prop) || !isFunction(original)) {
1317
1676
  return original;
1318
1677
  }
1319
- return async (...callArgs) => {
1320
- var _a2, _b2, _c;
1321
- const arg = callArgs[0];
1678
+ return (...callArgs) => {
1322
1679
  const operation = prop;
1323
- const wrapTimeCtx = resolveContext(deps.options.context, { operation, args: arg });
1324
- const telemetry = extractExperimentalTelemetry(arg);
1325
- const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1326
- const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1327
- const inherited = await getCurrentParentSpanContext();
1328
- const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1329
- const ctx = { ...mergedCtx};
1330
- const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1331
- const outerOperationId = `ai.${operation}`;
1332
- const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
1333
- const modelInfoFromArgs = isRecord(arg) ? extractModelInfo(arg["model"]) : {};
1334
- const rootSpan = sendTraces ? deps.traceShipper.startSpan({
1335
- name: outerOperationId,
1336
- parent: inheritedParent,
1337
- eventId,
1338
- operationId: outerOperationId,
1339
- attributes: [
1340
- attrString("operation.name", operationName),
1341
- attrString("resource.name", resourceName),
1342
- attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1343
- attrString("ai.model.provider", modelInfoFromArgs.provider),
1344
- attrString("ai.model.id", modelInfoFromArgs.modelId),
1345
- ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1346
- ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1347
- ...attrsFromSettings(arg),
1348
- ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1349
- attrString(
1350
- "ai.prompt",
1351
- safeJsonWithUint8({
1352
- system: isRecord(arg) ? arg["system"] : void 0,
1353
- prompt: isRecord(arg) ? arg["prompt"] : void 0,
1354
- messages: isRecord(arg) ? arg["messages"] : void 0
1355
- })
1356
- )
1357
- ]
1358
- ]
1359
- }) : void 0;
1360
- const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1361
- const wrapCtx = {
1362
- eventId,
1363
- telemetry,
1364
- sendTraces,
1365
- traceShipper: deps.traceShipper,
1366
- rootParentForChildren
1367
- };
1368
- const toolCalls = [];
1369
- const argWithWrappedTools = wrapTools(arg, wrapCtx, toolCalls);
1370
- const argWithWrappedModel = wrapModel(
1371
- argWithWrappedTools,
1372
- aiSDK,
1373
- outerOperationId,
1374
- wrapCtx
1375
- );
1376
- const finalize = async (result, error) => {
1377
- var _a3, _b3, _c2;
1378
- const usage = extractUsage(result);
1379
- const model = extractModel(result);
1380
- const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(arg) : void 0;
1381
- const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
1382
- const baseMessages = coerceMessagesFromArgs(arg);
1383
- const responseMessages = extractResponseMessages(result);
1384
- const allMessages = [...baseMessages, ...responseMessages];
1385
- const outputText = extractTextOutput(result);
1386
- const outputObjectJson = extractObjectOutput(result);
1387
- const defaultOutput = operation === "generateObject" || operation === "streamObject" ? outputObjectJson : outputText;
1388
- const defaultPatch = {
1389
- eventName: (_a3 = ctx.eventName) != null ? _a3 : operation,
1390
- input: (_b3 = lastUserMessageTextFromArgs(arg)) != null ? _b3 : extractInputFromArgs(arg),
1391
- output: defaultOutput,
1392
- model,
1393
- properties: ctx.properties,
1394
- attachments: mergeAttachments(ctx.attachments, inputAttachments, outputAttachments)
1395
- };
1396
- const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
1397
- const patch = mergeBuildEventPatch(defaultPatch, built);
1398
- const output = patch.output;
1399
- const finalModel = (_c2 = patch.model) != null ? _c2 : model;
1400
- if (rootSpan) {
1401
- const finishReason = extractFinishReason(result);
1402
- const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1403
- const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1404
- const usageRec = isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1405
- const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1406
- const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1407
- const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1408
- deps.traceShipper.endSpan(rootSpan, {
1409
- attributes: [
1410
- ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
1411
- attrString("ai.response.finishReason", finishReason),
1412
- operation === "generateObject" || operation === "streamObject" ? attrString("ai.response.object", output) : attrString("ai.response.text", output),
1413
- attrString("ai.response.toolCalls", resultToolCalls),
1414
- attrString(
1415
- "ai.response.providerMetadata",
1416
- safeJsonWithUint8(providerMetadata)
1417
- )
1418
- ],
1419
- attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1420
- attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1421
- attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1422
- attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1423
- attrInt("ai.usage.totalTokens", totalTokens),
1424
- attrInt("ai.usage.reasoningTokens", reasoningTokens),
1425
- attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1426
- attrInt("ai.toolCall.count", toolCalls.length),
1427
- ...error ? [
1428
- attrString(
1429
- "error.message",
1430
- error instanceof Error ? error.message : String(error)
1431
- )
1432
- ] : []
1433
- ]
1434
- });
1435
- }
1436
- if (sendEvents) {
1437
- void deps.eventShipper.patch(eventId, {
1438
- eventName: patch.eventName,
1439
- userId: ctx.userId,
1440
- convoId: ctx.convoId,
1441
- input: patch.input,
1442
- output,
1443
- model: finalModel,
1444
- properties: patch.properties,
1445
- attachments: patch.attachments,
1446
- isPending: false
1447
- }).catch((err) => {
1448
- if (debug)
1449
- console.warn(
1450
- `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1451
- );
1452
- });
1453
- }
1454
- };
1455
- const callOriginal = async (...args) => {
1456
- return await original.call(
1457
- aiSDK,
1458
- ...args
1459
- );
1460
- };
1461
- const runWithContext = async (fn) => {
1462
- if (!rootSpan) return await fn();
1463
- return await runWithParentSpanContext(
1464
- { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1465
- fn
1466
- );
1467
- };
1680
+ const arg = callArgs[0];
1468
1681
  if (operation === "streamText" || operation === "streamObject") {
1469
- const argWithOnFinish = wrapOnFinish(argWithWrappedModel, async (result) => {
1470
- try {
1471
- await finalize(result);
1472
- } catch (err) {
1473
- if (debug)
1474
- console.warn(
1475
- `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1476
- );
1477
- }
1478
- });
1479
- try {
1480
- const result = await runWithContext(async () => {
1481
- const nextArgs = [...callArgs];
1482
- nextArgs[0] = argWithOnFinish;
1483
- return await callOriginal(...nextArgs);
1484
- });
1485
- if (operation === "streamObject" && result && isRecord(result)) {
1486
- const baseStream = result["baseStream"];
1487
- if (baseStream && typeof baseStream === "object" && "tee" in baseStream) {
1488
- try {
1489
- const [consumeStream, userStream] = baseStream.tee();
1490
- result["baseStream"] = userStream;
1491
- consumeStream.pipeTo(new WritableStream({ write() {
1492
- } })).catch(() => {
1493
- });
1494
- } catch (e) {
1495
- }
1496
- }
1497
- }
1498
- return result;
1499
- } catch (error) {
1500
- try {
1501
- await finalize(void 0, error);
1502
- } catch (err) {
1503
- if (debug)
1504
- console.warn(
1505
- `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1506
- );
1507
- }
1508
- throw error;
1509
- }
1510
- }
1511
- try {
1512
- const result = await runWithContext(async () => {
1513
- const nextArgs = [...callArgs];
1514
- nextArgs[0] = argWithWrappedModel;
1515
- return await callOriginal(...nextArgs);
1682
+ return executeStreamingOperation({
1683
+ operation,
1684
+ arg,
1685
+ callArgs,
1686
+ aiSDK,
1687
+ original,
1688
+ deps,
1689
+ sendEvents,
1690
+ sendTraces,
1691
+ autoAttachmentEnabled,
1692
+ debug
1516
1693
  });
1517
- try {
1518
- await finalize(result);
1519
- } catch (err) {
1520
- if (debug)
1521
- console.warn(
1522
- `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1523
- );
1524
- }
1525
- return result;
1526
- } catch (error) {
1527
- try {
1528
- await finalize(void 0, error);
1529
- } catch (err) {
1530
- if (debug)
1531
- console.warn(
1532
- `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1533
- );
1534
- }
1535
- throw error;
1536
1694
  }
1695
+ return executeNonStreamingOperation({
1696
+ operation,
1697
+ arg,
1698
+ callArgs,
1699
+ aiSDK,
1700
+ original,
1701
+ deps,
1702
+ sendEvents,
1703
+ sendTraces,
1704
+ autoAttachmentEnabled,
1705
+ debug
1706
+ });
1537
1707
  };
1538
1708
  }
1539
1709
  });
@@ -1634,10 +1804,17 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1634
1804
  rootParentForChildren
1635
1805
  };
1636
1806
  const toolCalls = [];
1637
- const callParamsWithWrappedTools = callParams ? wrapTools(callParams, wrapCtx, toolCalls) : callParams;
1807
+ const mergedArgsWithWrappedTools = wrapTools(mergedArgs, wrapCtx, toolCalls);
1808
+ const mergedArgsWithWrappedModel = wrapModel(
1809
+ mergedArgsWithWrappedTools,
1810
+ aiSDK,
1811
+ outerOperationId,
1812
+ wrapCtx
1813
+ );
1814
+ const callParamsWithWrappedToolsAndModel = mergedArgsWithWrappedModel != null ? mergedArgsWithWrappedModel : {};
1638
1815
  const finalize = async (result, error) => {
1639
1816
  var _a3, _b3, _c2;
1640
- const usage = extractUsage(result);
1817
+ const usage = extractUsageMetrics(result);
1641
1818
  const model = extractModel(result);
1642
1819
  const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(mergedArgs) : void 0;
1643
1820
  const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
@@ -1661,10 +1838,6 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1661
1838
  const finishReason = extractFinishReason(result);
1662
1839
  const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1663
1840
  const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1664
- const usageRec = isRecord(result) && isRecord(result["totalUsage"]) ? result["totalUsage"] : isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1665
- const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1666
- const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1667
- const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1668
1841
  deps.traceShipper.endSpan(rootSpan, {
1669
1842
  attributes: [
1670
1843
  ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
@@ -1677,9 +1850,9 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1677
1850
  attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1678
1851
  attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1679
1852
  attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1680
- attrInt("ai.usage.totalTokens", totalTokens),
1681
- attrInt("ai.usage.reasoningTokens", reasoningTokens),
1682
- attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1853
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
1854
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
1855
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
1683
1856
  attrInt("ai.toolCall.count", toolCalls.length),
1684
1857
  ...error ? [
1685
1858
  attrString(
@@ -1735,7 +1908,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1735
1908
  }
1736
1909
  try {
1737
1910
  const result = await runWithContext(async () => {
1738
- return await generate.call(instance, callParamsWithWrappedTools);
1911
+ return await generate.call(instance, callParamsWithWrappedToolsAndModel);
1739
1912
  });
1740
1913
  if (debug) {
1741
1914
  console.log(`[raindrop-ai/ai-sdk] Agent ${operation} completed, finalizing...`);
@@ -1818,10 +1991,17 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1818
1991
  rootParentForChildren
1819
1992
  };
1820
1993
  const toolCalls = [];
1821
- const callParamsWithWrappedTools = callParams ? wrapTools(callParams, wrapCtx, toolCalls) : callParams;
1994
+ const mergedArgsWithWrappedTools = wrapTools(mergedArgs, wrapCtx, toolCalls);
1995
+ const mergedArgsWithWrappedModel = wrapModel(
1996
+ mergedArgsWithWrappedTools,
1997
+ aiSDK,
1998
+ outerOperationId,
1999
+ wrapCtx
2000
+ );
2001
+ const callParamsWithWrappedToolsAndModel = mergedArgsWithWrappedModel != null ? mergedArgsWithWrappedModel : {};
1822
2002
  const finalize = async (result, error) => {
1823
2003
  var _a3, _b3, _c2;
1824
- const usage = extractUsage(result);
2004
+ const usage = extractUsageMetrics(result);
1825
2005
  const model = extractModel(result);
1826
2006
  const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(mergedArgs) : void 0;
1827
2007
  const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
@@ -1845,10 +2025,6 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1845
2025
  const finishReason = extractFinishReason(result);
1846
2026
  const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1847
2027
  const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1848
- const usageRec = isRecord(result) && isRecord(result["totalUsage"]) ? result["totalUsage"] : isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1849
- const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1850
- const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1851
- const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1852
2028
  deps.traceShipper.endSpan(rootSpan, {
1853
2029
  attributes: [
1854
2030
  ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
@@ -1861,9 +2037,9 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1861
2037
  attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1862
2038
  attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1863
2039
  attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1864
- attrInt("ai.usage.totalTokens", totalTokens),
1865
- attrInt("ai.usage.reasoningTokens", reasoningTokens),
1866
- attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
2040
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
2041
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
2042
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
1867
2043
  attrInt("ai.toolCall.count", toolCalls.length),
1868
2044
  ...error ? [
1869
2045
  attrString(
@@ -1918,7 +2094,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1918
2094
  });
1919
2095
  }
1920
2096
  const callParamsWithOnFinish = wrapOnFinish(
1921
- callParamsWithWrappedTools != null ? callParamsWithWrappedTools : {},
2097
+ callParamsWithWrappedToolsAndModel != null ? callParamsWithWrappedToolsAndModel : {},
1922
2098
  async (result) => {
1923
2099
  if (debug) {
1924
2100
  console.log(`[raindrop-ai/ai-sdk] Agent ${operation} onFinish callback, finalizing...`);
@@ -2003,20 +2179,26 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
2003
2179
  spanIdB64: span.ids.spanIdB64,
2004
2180
  eventId: ctx.eventId
2005
2181
  });
2006
- const wrappedExecute = (...execArgs) => {
2182
+ const wrappedExecute = function(...execArgs) {
2007
2183
  const toolArgs = execArgs[0];
2008
2184
  const execOptions = execArgs.length > 1 ? execArgs[1] : void 0;
2009
2185
  const toolCallId = isRecord(execOptions) && typeof execOptions["toolCallId"] === "string" ? execOptions["toolCallId"] : randomUUID();
2010
- const result = originalExecute(...execArgs);
2011
- if (isAsyncGenerator(result)) {
2186
+ const result = originalExecute.apply(this, execArgs);
2187
+ if (isAsyncIterable(result)) {
2012
2188
  return (async function* () {
2013
2189
  const parentCtx = await getCurrentParentSpanContext();
2014
2190
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2015
2191
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
2016
2192
  try {
2017
2193
  let lastValue;
2018
- const wrappedGen = toolSpan ? asyncGeneratorWithCurrent(createContextSpan(toolSpan), result) : result;
2019
- for await (const value of wrappedGen) {
2194
+ const iterator = result[Symbol.asyncIterator]();
2195
+ const wrappedIterable = toolSpan ? asyncGeneratorWithCurrent(
2196
+ createContextSpan(toolSpan),
2197
+ iterator
2198
+ ) : {
2199
+ [Symbol.asyncIterator]: () => iterator
2200
+ };
2201
+ for await (const value of wrappedIterable) {
2020
2202
  lastValue = value;
2021
2203
  yield value;
2022
2204
  }
@@ -2362,14 +2544,19 @@ function wrapOnFinish(args, onFinish) {
2362
2544
  return {
2363
2545
  ...args,
2364
2546
  onFinish: async (result) => {
2547
+ let userError;
2365
2548
  try {
2366
2549
  const maybePromise = existing(result);
2367
2550
  if (maybePromise && typeof maybePromise.then === "function") {
2368
2551
  await maybePromise;
2369
2552
  }
2370
- } catch (e) {
2553
+ } catch (error) {
2554
+ userError = error;
2371
2555
  }
2372
2556
  await onFinish(result);
2557
+ if (userError !== void 0) {
2558
+ throw userError;
2559
+ }
2373
2560
  }
2374
2561
  };
2375
2562
  }