@raindrop-ai/ai-sdk 0.0.20 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ var async_hooks = require('async_hooks');
4
4
 
5
5
  // src/index.workers.ts
6
6
 
7
- // ../core/dist/chunk-H6VSZSLN.js
7
+ // ../core/dist/chunk-4UCYIEH4.js
8
8
  function getCrypto() {
9
9
  const c = globalThis.crypto;
10
10
  return c;
@@ -149,6 +149,7 @@ async function postJson(url, body, headers, opts) {
149
149
  );
150
150
  }
151
151
  var SpanStatusCode = {
152
+ UNSET: 0,
152
153
  ERROR: 2
153
154
  };
154
155
  function createSpanIds(parent) {
@@ -163,6 +164,9 @@ function createSpanIds(parent) {
163
164
  function nowUnixNanoString() {
164
165
  return Date.now().toString() + "000000";
165
166
  }
167
+ function unixMsToNanoString(ms) {
168
+ return String(Math.floor(ms)) + "000000";
169
+ }
166
170
  function attrString(key, value) {
167
171
  if (value === void 0) return void 0;
168
172
  return { key, value: { stringValue: value } };
@@ -469,11 +473,66 @@ var EventShipper = class {
469
473
  }
470
474
  }
471
475
  };
476
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
477
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
478
+ var _a, _b, _c;
479
+ const resolved = (_b = baseUrl != null ? baseUrl : typeof process !== "undefined" ? (_a = process.env) == null ? void 0 : _a[LOCAL_DEBUGGER_ENV_VAR] : void 0) != null ? _b : null;
480
+ return resolved ? (_c = formatEndpoint(resolved)) != null ? _c : null : null;
481
+ }
482
+ function localDebuggerEnabled(baseUrl) {
483
+ return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
484
+ }
485
+ function normalizeLocalDebuggerLiveEventType(type) {
486
+ switch (type) {
487
+ case "text-delta":
488
+ return "text_delta";
489
+ case "reasoning":
490
+ case "reasoning-delta":
491
+ return "reasoning_delta";
492
+ case "tool-call":
493
+ return "tool_start";
494
+ case "tool-result":
495
+ return "tool_result";
496
+ default:
497
+ return type;
498
+ }
499
+ }
500
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
501
+ var _a;
502
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
503
+ if (!baseUrl) return;
504
+ void postJson(`${baseUrl}traces`, body, {}, {
505
+ maxAttempts: 1,
506
+ debug: (_a = options.debug) != null ? _a : false,
507
+ sdkName: options.sdkName
508
+ }).catch(() => {
509
+ });
510
+ }
511
+ function sendLocalDebuggerLiveEvent(event, options = {}) {
512
+ var _a, _b;
513
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
514
+ if (!baseUrl) return;
515
+ void postJson(
516
+ `${baseUrl}live`,
517
+ {
518
+ ...event,
519
+ type: normalizeLocalDebuggerLiveEventType(event.type),
520
+ timestamp: (_a = event.timestamp) != null ? _a : Date.now()
521
+ },
522
+ {},
523
+ {
524
+ maxAttempts: 1,
525
+ debug: (_b = options.debug) != null ? _b : false,
526
+ sdkName: options.sdkName
527
+ }
528
+ ).catch(() => {
529
+ });
530
+ }
472
531
  var TraceShipper = class {
473
532
  constructor(opts) {
474
533
  this.queue = [];
475
534
  this.inFlight = /* @__PURE__ */ new Set();
476
- var _a, _b, _c, _d, _e, _f, _g, _h;
535
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
477
536
  this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
478
537
  this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
479
538
  this.enabled = opts.enabled !== false;
@@ -486,6 +545,13 @@ var TraceShipper = class {
486
545
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
487
546
  this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
488
547
  this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
548
+ const localDebugger = typeof process !== "undefined" ? (_i = process.env) == null ? void 0 : _i.RAINDROP_LOCAL_DEBUGGER : void 0;
549
+ if (localDebugger) {
550
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(localDebugger)) != null ? _j : void 0;
551
+ if (this.debug) {
552
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
553
+ }
554
+ }
489
555
  }
490
556
  isDebugEnabled() {
491
557
  return this.debug;
@@ -502,7 +568,25 @@ var TraceShipper = class {
502
568
  attrString("ai.operationId", args.operationId)
503
569
  ];
504
570
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
505
- return { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
571
+ const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
572
+ if (this.localDebuggerUrl) {
573
+ const openSpan = buildOtlpSpan({
574
+ ids: span.ids,
575
+ name: span.name,
576
+ startTimeUnixNano: span.startTimeUnixNano,
577
+ endTimeUnixNano: span.startTimeUnixNano,
578
+ // placeholder — will be updated on endSpan
579
+ attributes: span.attributes,
580
+ status: { code: SpanStatusCode.UNSET }
581
+ });
582
+ const body = buildExportTraceServiceRequest([openSpan], this.serviceName, this.serviceVersion);
583
+ mirrorTraceExportToLocalDebugger(body, {
584
+ baseUrl: this.localDebuggerUrl,
585
+ debug: false,
586
+ sdkName: this.sdkName
587
+ });
588
+ }
589
+ return span;
506
590
  }
507
591
  endSpan(span, extra) {
508
592
  var _a, _b;
@@ -525,6 +609,14 @@ var TraceShipper = class {
525
609
  status
526
610
  });
527
611
  this.enqueue(otlp);
612
+ if (this.localDebuggerUrl) {
613
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
614
+ mirrorTraceExportToLocalDebugger(body, {
615
+ baseUrl: this.localDebuggerUrl,
616
+ debug: false,
617
+ sdkName: this.sdkName
618
+ });
619
+ }
528
620
  }
529
621
  createSpan(args) {
530
622
  var _a;
@@ -542,6 +634,14 @@ var TraceShipper = class {
542
634
  status: args.status
543
635
  });
544
636
  this.enqueue(otlp);
637
+ if (this.localDebuggerUrl) {
638
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
639
+ mirrorTraceExportToLocalDebugger(body, {
640
+ baseUrl: this.localDebuggerUrl,
641
+ debug: false,
642
+ sdkName: this.sdkName
643
+ });
644
+ }
545
645
  }
546
646
  enqueue(span) {
547
647
  if (!this.enabled) return;
@@ -737,7 +837,7 @@ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = async_hooks.AsyncLocalStorage;
737
837
  // package.json
738
838
  var package_default = {
739
839
  name: "@raindrop-ai/ai-sdk",
740
- version: "0.0.20"};
840
+ version: "0.0.22"};
741
841
 
742
842
  // src/internal/version.ts
743
843
  var libraryName = package_default.name;
@@ -1543,6 +1643,7 @@ var RaindropTelemetryIntegration = class {
1543
1643
  ]
1544
1644
  });
1545
1645
  state.toolSpans.set(toolCall.toolCallId, toolSpan);
1646
+ this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
1546
1647
  };
1547
1648
  // ── onToolCallFinish ────────────────────────────────────────────────────
1548
1649
  this.onToolCallFinish = (event) => {
@@ -1557,11 +1658,12 @@ var RaindropTelemetryIntegration = class {
1557
1658
  } else {
1558
1659
  this.traceShipper.endSpan(toolSpan, { error: event.error });
1559
1660
  }
1661
+ this.emitLive(state, "tool_result", event.toolCall.toolName);
1560
1662
  state.toolSpans.delete(event.toolCall.toolCallId);
1561
1663
  };
1562
1664
  // ── onChunk (streaming) ─────────────────────────────────────────────────
1563
1665
  this.onChunk = (event) => {
1564
- var _a, _b, _c;
1666
+ var _a, _b, _c, _d, _e;
1565
1667
  const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
1566
1668
  if (!callId) return;
1567
1669
  const state = this.getState(callId);
@@ -1572,6 +1674,12 @@ var RaindropTelemetryIntegration = class {
1572
1674
  const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
1573
1675
  if (typeof delta === "string") {
1574
1676
  state.accumulatedText += delta;
1677
+ this.emitLive(state, "text_delta", delta);
1678
+ }
1679
+ } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
1680
+ const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
1681
+ if (typeof text === "string") {
1682
+ this.emitLive(state, "reasoning_delta", text);
1575
1683
  }
1576
1684
  }
1577
1685
  };
@@ -1759,6 +1867,23 @@ var RaindropTelemetryIntegration = class {
1759
1867
  spanParentRef(span) {
1760
1868
  return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
1761
1869
  }
1870
+ emitLive(state, type, content, extra) {
1871
+ var _a, _b, _c, _d, _e, _f;
1872
+ if (!localDebuggerEnabled() || !state.rootSpan) return;
1873
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1874
+ sendLocalDebuggerLiveEvent({
1875
+ traceId: state.rootSpan.ids.traceIdB64,
1876
+ type,
1877
+ content,
1878
+ metadata: {
1879
+ userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
1880
+ convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
1881
+ eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
1882
+ eventId: state.eventId,
1883
+ ...extra
1884
+ }
1885
+ });
1886
+ }
1762
1887
  extractRaindropMetadata(metadata) {
1763
1888
  if (!metadata) return {};
1764
1889
  const result = {};
@@ -2304,6 +2429,36 @@ function shouldKeepEventPending(params) {
2304
2429
  if (params.error != null || !params.canKeepEventPending) return false;
2305
2430
  return params.finishReason === "tool-calls" || params.finishReason === "tool_calls";
2306
2431
  }
2432
+ function normalizePromptAttr(arg) {
2433
+ if (!isRecord(arg)) return arg;
2434
+ const system = arg["system"];
2435
+ const prompt = arg["prompt"];
2436
+ const messages = arg["messages"];
2437
+ if (Array.isArray(messages)) {
2438
+ if (system) {
2439
+ const sysContent = typeof system === "string" ? system : JSON.stringify(system);
2440
+ return [{ role: "system", content: sysContent }, ...messages];
2441
+ }
2442
+ return messages;
2443
+ }
2444
+ if (typeof prompt === "string") {
2445
+ const msgs = [];
2446
+ if (system) {
2447
+ msgs.push({ role: "system", content: typeof system === "string" ? system : JSON.stringify(system) });
2448
+ }
2449
+ msgs.push({ role: "user", content: prompt });
2450
+ return msgs;
2451
+ }
2452
+ return { system, prompt, messages };
2453
+ }
2454
+ function getLocalDebuggerMetadata(ctx) {
2455
+ return {
2456
+ eventId: ctx.eventId,
2457
+ ...ctx.eventName ? { eventName: ctx.eventName } : {},
2458
+ ...ctx.userId ? { userId: ctx.userId } : {},
2459
+ ...ctx.convoId ? { convoId: ctx.convoId } : {}
2460
+ };
2461
+ }
2307
2462
  async function safeFinalize(finalize, debug, result, error) {
2308
2463
  try {
2309
2464
  await finalize(result, error);
@@ -2376,17 +2531,17 @@ function setupOperation(params) {
2376
2531
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2377
2532
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2378
2533
  attrString("ai.model.id", modelInfoFromArgs.modelId),
2534
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
2535
+ attrString("ai.telemetry.metadata.raindrop.eventName", mergedCtx.eventName),
2536
+ attrString("ai.telemetry.metadata.raindrop.userId", mergedCtx.userId),
2537
+ attrString("ai.telemetry.metadata.raindrop.convoId", mergedCtx.convoId),
2379
2538
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2380
2539
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
2381
2540
  ...attrsFromSettings(arg),
2382
2541
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2383
2542
  attrString(
2384
2543
  "ai.prompt",
2385
- safeJsonWithUint8({
2386
- system: isRecord(arg) ? arg["system"] : void 0,
2387
- prompt: isRecord(arg) ? arg["prompt"] : void 0,
2388
- messages: isRecord(arg) ? arg["messages"] : void 0
2389
- })
2544
+ safeJsonWithUint8(normalizePromptAttr(arg))
2390
2545
  )
2391
2546
  ]
2392
2547
  ]
@@ -2395,6 +2550,7 @@ function setupOperation(params) {
2395
2550
  const operationSelfDiagnostics = isObjectOperation(operation) ? void 0 : selfDiagnostics;
2396
2551
  const wrapCtx = {
2397
2552
  eventId,
2553
+ context: mergedCtx,
2398
2554
  telemetry,
2399
2555
  sendTraces,
2400
2556
  debug,
@@ -2769,6 +2925,7 @@ function wrapAISDK(aiSDK, deps) {
2769
2925
  const perCallEventIdGenerated = !perCallEventIdExplicit;
2770
2926
  const perCallCtx = {
2771
2927
  eventId: perCallEventId,
2928
+ context: wrapTimeCtx,
2772
2929
  telemetry,
2773
2930
  sendTraces: false,
2774
2931
  debug,
@@ -2923,7 +3080,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2923
3080
  if (!mergedCtx.userId) warnMissingUserIdOnce();
2924
3081
  const inherited = await getCurrentParentSpanContext();
2925
3082
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2926
- const ctx = { ...mergedCtx};
3083
+ const ctx = { ...mergedCtx, eventId };
2927
3084
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2928
3085
  const outerOperationId = `ai.${operation}`;
2929
3086
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -2939,17 +3096,17 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2939
3096
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2940
3097
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2941
3098
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3099
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3100
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3101
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3102
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
2942
3103
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2943
3104
  ...attrsFromHeaders(mergedArgs["headers"]),
2944
3105
  ...attrsFromSettings(mergedArgs),
2945
3106
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2946
3107
  attrString(
2947
3108
  "ai.prompt",
2948
- safeJsonWithUint8({
2949
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2950
- prompt: mergedArgs["prompt"],
2951
- messages: mergedArgs["messages"]
2952
- })
3109
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
2953
3110
  )
2954
3111
  ]
2955
3112
  ]
@@ -2957,6 +3114,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2957
3114
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2958
3115
  const wrapCtx = {
2959
3116
  eventId,
3117
+ context: ctx,
2960
3118
  telemetry,
2961
3119
  sendTraces,
2962
3120
  debug,
@@ -3130,7 +3288,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
3130
3288
  if (!mergedCtx.userId) warnMissingUserIdOnce();
3131
3289
  const inherited = await getCurrentParentSpanContext();
3132
3290
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
3133
- const ctx = { ...mergedCtx};
3291
+ const ctx = { ...mergedCtx, eventId };
3134
3292
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
3135
3293
  const outerOperationId = `ai.${operation}`;
3136
3294
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -3146,17 +3304,17 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
3146
3304
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
3147
3305
  attrString("ai.model.provider", modelInfoFromArgs.provider),
3148
3306
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3307
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3308
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3309
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3310
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
3149
3311
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
3150
3312
  ...attrsFromHeaders(mergedArgs["headers"]),
3151
3313
  ...attrsFromSettings(mergedArgs),
3152
3314
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
3153
3315
  attrString(
3154
3316
  "ai.prompt",
3155
- safeJsonWithUint8({
3156
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
3157
- prompt: mergedArgs["prompt"],
3158
- messages: mergedArgs["messages"]
3159
- })
3317
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
3160
3318
  )
3161
3319
  ]
3162
3320
  ]
@@ -3164,6 +3322,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
3164
3322
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
3165
3323
  const wrapCtx = {
3166
3324
  eventId,
3325
+ context: ctx,
3167
3326
  telemetry,
3168
3327
  sendTraces,
3169
3328
  debug,
@@ -3387,6 +3546,21 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3387
3546
  });
3388
3547
  }
3389
3548
  };
3549
+ const sendToolLiveEvent = (parent, type, metadata) => {
3550
+ if (!localDebuggerEnabled() || !parent) return;
3551
+ sendLocalDebuggerLiveEvent({
3552
+ traceId: parent.traceIdB64,
3553
+ type,
3554
+ content: name,
3555
+ metadata: {
3556
+ ...getLocalDebuggerMetadata({
3557
+ ...ctx.context,
3558
+ eventId: ctx.eventId
3559
+ }),
3560
+ ...metadata
3561
+ }
3562
+ });
3563
+ };
3390
3564
  const createContextSpan = (span) => ({
3391
3565
  traceIdB64: span.ids.traceIdB64,
3392
3566
  spanIdB64: span.ids.spanIdB64,
@@ -3402,6 +3576,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3402
3576
  const parentCtx = await getCurrentParentSpanContext();
3403
3577
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
3404
3578
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3579
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
3405
3580
  try {
3406
3581
  let lastValue;
3407
3582
  const iterator = result[Symbol.asyncIterator]();
@@ -3417,9 +3592,13 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3417
3592
  }
3418
3593
  toolCalls.push({ id: toolCallId, name, args: toolArgs, result: lastValue, status: "OK" });
3419
3594
  endToolSpan(toolSpan, lastValue);
3595
+ sendToolLiveEvent(parent, "tool_result", { result: lastValue });
3420
3596
  } catch (error) {
3421
3597
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
3422
3598
  endToolSpan(toolSpan, void 0, error);
3599
+ sendToolLiveEvent(parent, "tool_result", {
3600
+ error: error instanceof Error ? error.message : String(error)
3601
+ });
3423
3602
  throw error;
3424
3603
  }
3425
3604
  })();
@@ -3428,6 +3607,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3428
3607
  const parentCtx = await getCurrentParentSpanContext();
3429
3608
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
3430
3609
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3610
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
3431
3611
  const run = async () => {
3432
3612
  try {
3433
3613
  const awaitedResult = await result;
@@ -3439,10 +3619,14 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3439
3619
  status: "OK"
3440
3620
  });
3441
3621
  endToolSpan(toolSpan, awaitedResult);
3622
+ sendToolLiveEvent(parent, "tool_result", { result: awaitedResult });
3442
3623
  return awaitedResult;
3443
3624
  } catch (error) {
3444
3625
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
3445
3626
  endToolSpan(toolSpan, void 0, error);
3627
+ sendToolLiveEvent(parent, "tool_result", {
3628
+ error: error instanceof Error ? error.message : String(error)
3629
+ });
3446
3630
  throw error;
3447
3631
  }
3448
3632
  };
@@ -3482,6 +3666,7 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
3482
3666
  const original = Reflect.get(target, prop, receiver);
3483
3667
  if (prop === "doGenerate" && isFunction(original)) {
3484
3668
  return async (...callArgs) => {
3669
+ var _a, _b;
3485
3670
  const options = callArgs[0];
3486
3671
  const parentCtx = await getCurrentParentSpanContext();
3487
3672
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
@@ -3489,6 +3674,22 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
3489
3674
  try {
3490
3675
  const result = await original.apply(target, callArgs);
3491
3676
  if (span) endDoGenerateSpan(span, result, modelInfo, ctx);
3677
+ if (localDebuggerEnabled() && ctx.rootParentForChildren && isRecord(result)) {
3678
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3679
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3680
+ const content = result["content"];
3681
+ if (Array.isArray(content)) {
3682
+ for (const part of content) {
3683
+ if (isRecord(part)) {
3684
+ if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
3685
+ sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
3686
+ } else if (part["type"] === "text" && typeof part["text"] === "string") {
3687
+ sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
3688
+ }
3689
+ }
3690
+ }
3691
+ }
3692
+ }
3492
3693
  return result;
3493
3694
  } catch (error) {
3494
3695
  if (span)
@@ -3628,6 +3829,23 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
3628
3829
  }
3629
3830
  if ("usage" in value) usage = value["usage"];
3630
3831
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
3832
+ if (localDebuggerEnabled() && ctx.rootParentForChildren) {
3833
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3834
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3835
+ if (type === "text-delta") {
3836
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
3837
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
3838
+ } else if (type === "reasoning" || type === "reasoning-delta") {
3839
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
3840
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
3841
+ } else if (type === "tool-call") {
3842
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3843
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
3844
+ } else if (type === "tool-result") {
3845
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3846
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
3847
+ }
3848
+ }
3631
3849
  }
3632
3850
  controller.enqueue(value);
3633
3851
  } catch (error) {
@@ -3865,6 +4083,14 @@ function eventMetadataFromChatRequest(options) {
3865
4083
  ...eventId ? { eventId } : {}
3866
4084
  });
3867
4085
  }
4086
+ function stringify(v) {
4087
+ if (typeof v === "string") return v;
4088
+ return JSON.stringify(v);
4089
+ }
4090
+ function userAttrsToOtlp(attrs) {
4091
+ if (!attrs) return [];
4092
+ return Object.entries(attrs).map(([key, value]) => attrString(key, value));
4093
+ }
3868
4094
  function envDebugEnabled() {
3869
4095
  var _a;
3870
4096
  if (typeof process === "undefined") return false;
@@ -3933,6 +4159,76 @@ function createRaindropAISDK(opts) {
3933
4159
  await eventShipper.finish(eventId, patch);
3934
4160
  }
3935
4161
  },
4162
+ traces: /* @__PURE__ */ (() => {
4163
+ const openSpans = /* @__PURE__ */ new Map();
4164
+ function toTraceSpan(internal) {
4165
+ return { traceId: internal.ids.traceIdB64, spanId: internal.ids.spanIdB64 };
4166
+ }
4167
+ return {
4168
+ startSpan(args) {
4169
+ const parent = args.parent ? { traceIdB64: args.parent.traceId, spanIdB64: args.parent.spanId } : void 0;
4170
+ const attrs = userAttrsToOtlp(args.attributes);
4171
+ if (args.operationId === "ai.toolCall") {
4172
+ attrs.push(attrString("ai.toolCall.name", args.name));
4173
+ }
4174
+ const internal = traceShipper.startSpan({
4175
+ name: args.name,
4176
+ eventId: args.eventId,
4177
+ parent,
4178
+ operationId: args.operationId,
4179
+ attributes: attrs
4180
+ });
4181
+ const handle = toTraceSpan(internal);
4182
+ openSpans.set(handle.spanId, internal);
4183
+ return handle;
4184
+ },
4185
+ endSpan(span, extra) {
4186
+ const internal = openSpans.get(span.spanId);
4187
+ if (!internal) return;
4188
+ openSpans.delete(span.spanId);
4189
+ const errorValue = extra == null ? void 0 : extra.error;
4190
+ const error = errorValue instanceof Error ? errorValue : typeof errorValue === "string" ? new Error(errorValue) : void 0;
4191
+ traceShipper.endSpan(internal, {
4192
+ attributes: userAttrsToOtlp(extra == null ? void 0 : extra.attributes),
4193
+ error
4194
+ });
4195
+ },
4196
+ createSpan(args) {
4197
+ var _a2;
4198
+ const parent = args.parent ? { traceIdB64: args.parent.traceId, spanIdB64: args.parent.spanId } : void 0;
4199
+ const startMs = (_a2 = args.startTime) != null ? _a2 : Date.now() - args.durationMs;
4200
+ const startAttrs = [...userAttrsToOtlp(args.attributes)];
4201
+ if (args.operationId === "ai.toolCall") {
4202
+ startAttrs.push(attrString("ai.toolCall.name", args.name));
4203
+ }
4204
+ if (args.input !== void 0) startAttrs.push(attrString("traceloop.entity.input", stringify(args.input)));
4205
+ if (args.operationId === "ai.toolCall" && args.input !== void 0) {
4206
+ startAttrs.push(attrString("ai.toolCall.args", stringify(args.input)));
4207
+ }
4208
+ const internal = traceShipper.startSpan({
4209
+ name: args.name,
4210
+ eventId: args.eventId,
4211
+ parent,
4212
+ operationId: args.operationId,
4213
+ attributes: startAttrs,
4214
+ startTimeUnixNano: unixMsToNanoString(startMs)
4215
+ });
4216
+ const endAttrs = [];
4217
+ if (args.output !== void 0) endAttrs.push(attrString("traceloop.entity.output", stringify(args.output)));
4218
+ if (args.operationId === "ai.toolCall" && args.output !== void 0) {
4219
+ endAttrs.push(attrString("ai.toolCall.result", stringify(args.output)));
4220
+ }
4221
+ const errorValue = args.error;
4222
+ const error = errorValue instanceof Error ? errorValue : typeof errorValue === "string" ? new Error(errorValue) : void 0;
4223
+ traceShipper.endSpan(internal, {
4224
+ attributes: endAttrs,
4225
+ error,
4226
+ endTimeUnixNano: unixMsToNanoString(startMs + args.durationMs)
4227
+ });
4228
+ return toTraceSpan(internal);
4229
+ }
4230
+ };
4231
+ })(),
3936
4232
  users: {
3937
4233
  async identify(users) {
3938
4234
  await eventShipper.identify(users);
@@ -1,4 +1,4 @@
1
- export { RaindropTelemetryIntegration, _resetWarnedMissingUserId, createRaindropAISDK, currentSpan, eventMetadata, eventMetadataFromChatRequest, getContextManager, withCurrent } from './chunk-FD5GVIE2.mjs';
1
+ export { RaindropTelemetryIntegration, _resetWarnedMissingUserId, createRaindropAISDK, currentSpan, eventMetadata, eventMetadataFromChatRequest, getContextManager, withCurrent } from './chunk-7NLWLLB4.mjs';
2
2
  import { AsyncLocalStorage } from 'async_hooks';
3
3
 
4
4
  if (!globalThis.RAINDROP_ASYNC_LOCAL_STORAGE) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raindrop-ai/ai-sdk",
3
- "version": "0.0.20",
3
+ "version": "0.0.22",
4
4
  "description": "Standalone Vercel AI SDK integration for Raindrop (events + OTLP/HTTP JSON traces, no OTEL runtime)",
5
5
  "main": "dist/index.node.js",
6
6
  "module": "dist/index.node.mjs",