@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.
@@ -1,4 +1,4 @@
1
- // ../core/dist/chunk-H6VSZSLN.js
1
+ // ../core/dist/chunk-4UCYIEH4.js
2
2
  function getCrypto() {
3
3
  const c = globalThis.crypto;
4
4
  return c;
@@ -143,6 +143,7 @@ async function postJson(url, body, headers, opts) {
143
143
  );
144
144
  }
145
145
  var SpanStatusCode = {
146
+ UNSET: 0,
146
147
  ERROR: 2
147
148
  };
148
149
  function createSpanIds(parent) {
@@ -157,6 +158,9 @@ function createSpanIds(parent) {
157
158
  function nowUnixNanoString() {
158
159
  return Date.now().toString() + "000000";
159
160
  }
161
+ function unixMsToNanoString(ms) {
162
+ return String(Math.floor(ms)) + "000000";
163
+ }
160
164
  function attrString(key, value) {
161
165
  if (value === void 0) return void 0;
162
166
  return { key, value: { stringValue: value } };
@@ -463,11 +467,66 @@ var EventShipper = class {
463
467
  }
464
468
  }
465
469
  };
470
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
471
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
472
+ var _a, _b, _c;
473
+ 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;
474
+ return resolved ? (_c = formatEndpoint(resolved)) != null ? _c : null : null;
475
+ }
476
+ function localDebuggerEnabled(baseUrl) {
477
+ return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
478
+ }
479
+ function normalizeLocalDebuggerLiveEventType(type) {
480
+ switch (type) {
481
+ case "text-delta":
482
+ return "text_delta";
483
+ case "reasoning":
484
+ case "reasoning-delta":
485
+ return "reasoning_delta";
486
+ case "tool-call":
487
+ return "tool_start";
488
+ case "tool-result":
489
+ return "tool_result";
490
+ default:
491
+ return type;
492
+ }
493
+ }
494
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
495
+ var _a;
496
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
497
+ if (!baseUrl) return;
498
+ void postJson(`${baseUrl}traces`, body, {}, {
499
+ maxAttempts: 1,
500
+ debug: (_a = options.debug) != null ? _a : false,
501
+ sdkName: options.sdkName
502
+ }).catch(() => {
503
+ });
504
+ }
505
+ function sendLocalDebuggerLiveEvent(event, options = {}) {
506
+ var _a, _b;
507
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
508
+ if (!baseUrl) return;
509
+ void postJson(
510
+ `${baseUrl}live`,
511
+ {
512
+ ...event,
513
+ type: normalizeLocalDebuggerLiveEventType(event.type),
514
+ timestamp: (_a = event.timestamp) != null ? _a : Date.now()
515
+ },
516
+ {},
517
+ {
518
+ maxAttempts: 1,
519
+ debug: (_b = options.debug) != null ? _b : false,
520
+ sdkName: options.sdkName
521
+ }
522
+ ).catch(() => {
523
+ });
524
+ }
466
525
  var TraceShipper = class {
467
526
  constructor(opts) {
468
527
  this.queue = [];
469
528
  this.inFlight = /* @__PURE__ */ new Set();
470
- var _a, _b, _c, _d, _e, _f, _g, _h;
529
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
471
530
  this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
472
531
  this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
473
532
  this.enabled = opts.enabled !== false;
@@ -480,6 +539,13 @@ var TraceShipper = class {
480
539
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
481
540
  this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
482
541
  this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
542
+ const localDebugger = typeof process !== "undefined" ? (_i = process.env) == null ? void 0 : _i.RAINDROP_LOCAL_DEBUGGER : void 0;
543
+ if (localDebugger) {
544
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(localDebugger)) != null ? _j : void 0;
545
+ if (this.debug) {
546
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
547
+ }
548
+ }
483
549
  }
484
550
  isDebugEnabled() {
485
551
  return this.debug;
@@ -496,7 +562,25 @@ var TraceShipper = class {
496
562
  attrString("ai.operationId", args.operationId)
497
563
  ];
498
564
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
499
- return { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
565
+ const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
566
+ if (this.localDebuggerUrl) {
567
+ const openSpan = buildOtlpSpan({
568
+ ids: span.ids,
569
+ name: span.name,
570
+ startTimeUnixNano: span.startTimeUnixNano,
571
+ endTimeUnixNano: span.startTimeUnixNano,
572
+ // placeholder — will be updated on endSpan
573
+ attributes: span.attributes,
574
+ status: { code: SpanStatusCode.UNSET }
575
+ });
576
+ const body = buildExportTraceServiceRequest([openSpan], this.serviceName, this.serviceVersion);
577
+ mirrorTraceExportToLocalDebugger(body, {
578
+ baseUrl: this.localDebuggerUrl,
579
+ debug: false,
580
+ sdkName: this.sdkName
581
+ });
582
+ }
583
+ return span;
500
584
  }
501
585
  endSpan(span, extra) {
502
586
  var _a, _b;
@@ -519,6 +603,14 @@ var TraceShipper = class {
519
603
  status
520
604
  });
521
605
  this.enqueue(otlp);
606
+ if (this.localDebuggerUrl) {
607
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
608
+ mirrorTraceExportToLocalDebugger(body, {
609
+ baseUrl: this.localDebuggerUrl,
610
+ debug: false,
611
+ sdkName: this.sdkName
612
+ });
613
+ }
522
614
  }
523
615
  createSpan(args) {
524
616
  var _a;
@@ -536,6 +628,14 @@ var TraceShipper = class {
536
628
  status: args.status
537
629
  });
538
630
  this.enqueue(otlp);
631
+ if (this.localDebuggerUrl) {
632
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
633
+ mirrorTraceExportToLocalDebugger(body, {
634
+ baseUrl: this.localDebuggerUrl,
635
+ debug: false,
636
+ sdkName: this.sdkName
637
+ });
638
+ }
539
639
  }
540
640
  enqueue(span) {
541
641
  if (!this.enabled) return;
@@ -730,7 +830,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
730
830
  // package.json
731
831
  var package_default = {
732
832
  name: "@raindrop-ai/ai-sdk",
733
- version: "0.0.20"};
833
+ version: "0.0.22"};
734
834
 
735
835
  // src/internal/version.ts
736
836
  var libraryName = package_default.name;
@@ -1536,6 +1636,7 @@ var RaindropTelemetryIntegration = class {
1536
1636
  ]
1537
1637
  });
1538
1638
  state.toolSpans.set(toolCall.toolCallId, toolSpan);
1639
+ this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
1539
1640
  };
1540
1641
  // ── onToolCallFinish ────────────────────────────────────────────────────
1541
1642
  this.onToolCallFinish = (event) => {
@@ -1550,11 +1651,12 @@ var RaindropTelemetryIntegration = class {
1550
1651
  } else {
1551
1652
  this.traceShipper.endSpan(toolSpan, { error: event.error });
1552
1653
  }
1654
+ this.emitLive(state, "tool_result", event.toolCall.toolName);
1553
1655
  state.toolSpans.delete(event.toolCall.toolCallId);
1554
1656
  };
1555
1657
  // ── onChunk (streaming) ─────────────────────────────────────────────────
1556
1658
  this.onChunk = (event) => {
1557
- var _a, _b, _c;
1659
+ var _a, _b, _c, _d, _e;
1558
1660
  const callId = (_b = event.callId) != null ? _b : (_a = event.chunk) == null ? void 0 : _a.callId;
1559
1661
  if (!callId) return;
1560
1662
  const state = this.getState(callId);
@@ -1565,6 +1667,12 @@ var RaindropTelemetryIntegration = class {
1565
1667
  const delta = (_c = chunk.textDelta) != null ? _c : chunk.delta;
1566
1668
  if (typeof delta === "string") {
1567
1669
  state.accumulatedText += delta;
1670
+ this.emitLive(state, "text_delta", delta);
1671
+ }
1672
+ } else if (chunk.type === "reasoning" || chunk.type === "reasoning-delta") {
1673
+ const text = (_e = (_d = chunk.textDelta) != null ? _d : chunk.text) != null ? _e : chunk.delta;
1674
+ if (typeof text === "string") {
1675
+ this.emitLive(state, "reasoning_delta", text);
1568
1676
  }
1569
1677
  }
1570
1678
  };
@@ -1752,6 +1860,23 @@ var RaindropTelemetryIntegration = class {
1752
1860
  spanParentRef(span) {
1753
1861
  return { traceIdB64: span.ids.traceIdB64, spanIdB64: span.ids.spanIdB64 };
1754
1862
  }
1863
+ emitLive(state, type, content, extra) {
1864
+ var _a, _b, _c, _d, _e, _f;
1865
+ if (!localDebuggerEnabled() || !state.rootSpan) return;
1866
+ const callMeta = this.extractRaindropMetadata(state.metadata);
1867
+ sendLocalDebuggerLiveEvent({
1868
+ traceId: state.rootSpan.ids.traceIdB64,
1869
+ type,
1870
+ content,
1871
+ metadata: {
1872
+ userId: (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId,
1873
+ convoId: (_d = callMeta.convoId) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.convoId,
1874
+ eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName,
1875
+ eventId: state.eventId,
1876
+ ...extra
1877
+ }
1878
+ });
1879
+ }
1755
1880
  extractRaindropMetadata(metadata) {
1756
1881
  if (!metadata) return {};
1757
1882
  const result = {};
@@ -2297,6 +2422,36 @@ function shouldKeepEventPending(params) {
2297
2422
  if (params.error != null || !params.canKeepEventPending) return false;
2298
2423
  return params.finishReason === "tool-calls" || params.finishReason === "tool_calls";
2299
2424
  }
2425
+ function normalizePromptAttr(arg) {
2426
+ if (!isRecord(arg)) return arg;
2427
+ const system = arg["system"];
2428
+ const prompt = arg["prompt"];
2429
+ const messages = arg["messages"];
2430
+ if (Array.isArray(messages)) {
2431
+ if (system) {
2432
+ const sysContent = typeof system === "string" ? system : JSON.stringify(system);
2433
+ return [{ role: "system", content: sysContent }, ...messages];
2434
+ }
2435
+ return messages;
2436
+ }
2437
+ if (typeof prompt === "string") {
2438
+ const msgs = [];
2439
+ if (system) {
2440
+ msgs.push({ role: "system", content: typeof system === "string" ? system : JSON.stringify(system) });
2441
+ }
2442
+ msgs.push({ role: "user", content: prompt });
2443
+ return msgs;
2444
+ }
2445
+ return { system, prompt, messages };
2446
+ }
2447
+ function getLocalDebuggerMetadata(ctx) {
2448
+ return {
2449
+ eventId: ctx.eventId,
2450
+ ...ctx.eventName ? { eventName: ctx.eventName } : {},
2451
+ ...ctx.userId ? { userId: ctx.userId } : {},
2452
+ ...ctx.convoId ? { convoId: ctx.convoId } : {}
2453
+ };
2454
+ }
2300
2455
  async function safeFinalize(finalize, debug, result, error) {
2301
2456
  try {
2302
2457
  await finalize(result, error);
@@ -2369,17 +2524,17 @@ function setupOperation(params) {
2369
2524
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2370
2525
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2371
2526
  attrString("ai.model.id", modelInfoFromArgs.modelId),
2527
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
2528
+ attrString("ai.telemetry.metadata.raindrop.eventName", mergedCtx.eventName),
2529
+ attrString("ai.telemetry.metadata.raindrop.userId", mergedCtx.userId),
2530
+ attrString("ai.telemetry.metadata.raindrop.convoId", mergedCtx.convoId),
2372
2531
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2373
2532
  ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
2374
2533
  ...attrsFromSettings(arg),
2375
2534
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2376
2535
  attrString(
2377
2536
  "ai.prompt",
2378
- safeJsonWithUint8({
2379
- system: isRecord(arg) ? arg["system"] : void 0,
2380
- prompt: isRecord(arg) ? arg["prompt"] : void 0,
2381
- messages: isRecord(arg) ? arg["messages"] : void 0
2382
- })
2537
+ safeJsonWithUint8(normalizePromptAttr(arg))
2383
2538
  )
2384
2539
  ]
2385
2540
  ]
@@ -2388,6 +2543,7 @@ function setupOperation(params) {
2388
2543
  const operationSelfDiagnostics = isObjectOperation(operation) ? void 0 : selfDiagnostics;
2389
2544
  const wrapCtx = {
2390
2545
  eventId,
2546
+ context: mergedCtx,
2391
2547
  telemetry,
2392
2548
  sendTraces,
2393
2549
  debug,
@@ -2762,6 +2918,7 @@ function wrapAISDK(aiSDK, deps) {
2762
2918
  const perCallEventIdGenerated = !perCallEventIdExplicit;
2763
2919
  const perCallCtx = {
2764
2920
  eventId: perCallEventId,
2921
+ context: wrapTimeCtx,
2765
2922
  telemetry,
2766
2923
  sendTraces: false,
2767
2924
  debug,
@@ -2916,7 +3073,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2916
3073
  if (!mergedCtx.userId) warnMissingUserIdOnce();
2917
3074
  const inherited = await getCurrentParentSpanContext();
2918
3075
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2919
- const ctx = { ...mergedCtx};
3076
+ const ctx = { ...mergedCtx, eventId };
2920
3077
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2921
3078
  const outerOperationId = `ai.${operation}`;
2922
3079
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -2932,17 +3089,17 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2932
3089
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2933
3090
  attrString("ai.model.provider", modelInfoFromArgs.provider),
2934
3091
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3092
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3093
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3094
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3095
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
2935
3096
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2936
3097
  ...attrsFromHeaders(mergedArgs["headers"]),
2937
3098
  ...attrsFromSettings(mergedArgs),
2938
3099
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2939
3100
  attrString(
2940
3101
  "ai.prompt",
2941
- safeJsonWithUint8({
2942
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2943
- prompt: mergedArgs["prompt"],
2944
- messages: mergedArgs["messages"]
2945
- })
3102
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
2946
3103
  )
2947
3104
  ]
2948
3105
  ]
@@ -2950,6 +3107,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
2950
3107
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2951
3108
  const wrapCtx = {
2952
3109
  eventId,
3110
+ context: ctx,
2953
3111
  telemetry,
2954
3112
  sendTraces,
2955
3113
  debug,
@@ -3123,7 +3281,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
3123
3281
  if (!mergedCtx.userId) warnMissingUserIdOnce();
3124
3282
  const inherited = await getCurrentParentSpanContext();
3125
3283
  const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
3126
- const ctx = { ...mergedCtx};
3284
+ const ctx = { ...mergedCtx, eventId };
3127
3285
  const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
3128
3286
  const outerOperationId = `ai.${operation}`;
3129
3287
  const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
@@ -3139,17 +3297,17 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
3139
3297
  attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
3140
3298
  attrString("ai.model.provider", modelInfoFromArgs.provider),
3141
3299
  attrString("ai.model.id", modelInfoFromArgs.modelId),
3300
+ attrString("ai.telemetry.metadata.raindrop.eventId", eventId),
3301
+ attrString("ai.telemetry.metadata.raindrop.eventName", ctx.eventName),
3302
+ attrString("ai.telemetry.metadata.raindrop.userId", ctx.userId),
3303
+ attrString("ai.telemetry.metadata.raindrop.convoId", ctx.convoId),
3142
3304
  ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
3143
3305
  ...attrsFromHeaders(mergedArgs["headers"]),
3144
3306
  ...attrsFromSettings(mergedArgs),
3145
3307
  ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
3146
3308
  attrString(
3147
3309
  "ai.prompt",
3148
- safeJsonWithUint8({
3149
- system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
3150
- prompt: mergedArgs["prompt"],
3151
- messages: mergedArgs["messages"]
3152
- })
3310
+ safeJsonWithUint8(normalizePromptAttr({ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"], prompt: mergedArgs["prompt"], messages: mergedArgs["messages"] }))
3153
3311
  )
3154
3312
  ]
3155
3313
  ]
@@ -3157,6 +3315,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
3157
3315
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
3158
3316
  const wrapCtx = {
3159
3317
  eventId,
3318
+ context: ctx,
3160
3319
  telemetry,
3161
3320
  sendTraces,
3162
3321
  debug,
@@ -3380,6 +3539,21 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3380
3539
  });
3381
3540
  }
3382
3541
  };
3542
+ const sendToolLiveEvent = (parent, type, metadata) => {
3543
+ if (!localDebuggerEnabled() || !parent) return;
3544
+ sendLocalDebuggerLiveEvent({
3545
+ traceId: parent.traceIdB64,
3546
+ type,
3547
+ content: name,
3548
+ metadata: {
3549
+ ...getLocalDebuggerMetadata({
3550
+ ...ctx.context,
3551
+ eventId: ctx.eventId
3552
+ }),
3553
+ ...metadata
3554
+ }
3555
+ });
3556
+ };
3383
3557
  const createContextSpan = (span) => ({
3384
3558
  traceIdB64: span.ids.traceIdB64,
3385
3559
  spanIdB64: span.ids.spanIdB64,
@@ -3395,6 +3569,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3395
3569
  const parentCtx = await getCurrentParentSpanContext();
3396
3570
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
3397
3571
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3572
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
3398
3573
  try {
3399
3574
  let lastValue;
3400
3575
  const iterator = result[Symbol.asyncIterator]();
@@ -3410,9 +3585,13 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3410
3585
  }
3411
3586
  toolCalls.push({ id: toolCallId, name, args: toolArgs, result: lastValue, status: "OK" });
3412
3587
  endToolSpan(toolSpan, lastValue);
3588
+ sendToolLiveEvent(parent, "tool_result", { result: lastValue });
3413
3589
  } catch (error) {
3414
3590
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
3415
3591
  endToolSpan(toolSpan, void 0, error);
3592
+ sendToolLiveEvent(parent, "tool_result", {
3593
+ error: error instanceof Error ? error.message : String(error)
3594
+ });
3416
3595
  throw error;
3417
3596
  }
3418
3597
  })();
@@ -3421,6 +3600,7 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3421
3600
  const parentCtx = await getCurrentParentSpanContext();
3422
3601
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
3423
3602
  const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
3603
+ sendToolLiveEvent(parent, "tool_start", { args: toolArgs });
3424
3604
  const run = async () => {
3425
3605
  try {
3426
3606
  const awaitedResult = await result;
@@ -3432,10 +3612,14 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
3432
3612
  status: "OK"
3433
3613
  });
3434
3614
  endToolSpan(toolSpan, awaitedResult);
3615
+ sendToolLiveEvent(parent, "tool_result", { result: awaitedResult });
3435
3616
  return awaitedResult;
3436
3617
  } catch (error) {
3437
3618
  toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
3438
3619
  endToolSpan(toolSpan, void 0, error);
3620
+ sendToolLiveEvent(parent, "tool_result", {
3621
+ error: error instanceof Error ? error.message : String(error)
3622
+ });
3439
3623
  throw error;
3440
3624
  }
3441
3625
  };
@@ -3475,6 +3659,7 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
3475
3659
  const original = Reflect.get(target, prop, receiver);
3476
3660
  if (prop === "doGenerate" && isFunction(original)) {
3477
3661
  return async (...callArgs) => {
3662
+ var _a, _b;
3478
3663
  const options = callArgs[0];
3479
3664
  const parentCtx = await getCurrentParentSpanContext();
3480
3665
  const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
@@ -3482,6 +3667,22 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
3482
3667
  try {
3483
3668
  const result = await original.apply(target, callArgs);
3484
3669
  if (span) endDoGenerateSpan(span, result, modelInfo, ctx);
3670
+ if (localDebuggerEnabled() && ctx.rootParentForChildren && isRecord(result)) {
3671
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3672
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3673
+ const content = result["content"];
3674
+ if (Array.isArray(content)) {
3675
+ for (const part of content) {
3676
+ if (isRecord(part)) {
3677
+ if ((part["type"] === "reasoning" || part["type"] === "thinking") && typeof ((_a = part["text"]) != null ? _a : part["thinking"]) === "string") {
3678
+ sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: (_b = part["text"]) != null ? _b : part["thinking"], metadata: liveMeta });
3679
+ } else if (part["type"] === "text" && typeof part["text"] === "string") {
3680
+ sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: part["text"], metadata: liveMeta });
3681
+ }
3682
+ }
3683
+ }
3684
+ }
3685
+ }
3485
3686
  return result;
3486
3687
  } catch (error) {
3487
3688
  if (span)
@@ -3621,6 +3822,23 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
3621
3822
  }
3622
3823
  if ("usage" in value) usage = value["usage"];
3623
3824
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
3825
+ if (localDebuggerEnabled() && ctx.rootParentForChildren) {
3826
+ const traceId = ctx.rootParentForChildren.traceIdB64;
3827
+ const liveMeta = getLocalDebuggerMetadata({ ...ctx.context, eventId: ctx.eventId });
3828
+ if (type === "text-delta") {
3829
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["textDelta"] === "string" ? value["textDelta"] : typeof value["text"] === "string" ? value["text"] : void 0;
3830
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "text_delta", content: text, metadata: liveMeta });
3831
+ } else if (type === "reasoning" || type === "reasoning-delta") {
3832
+ const text = typeof value["delta"] === "string" ? value["delta"] : typeof value["text"] === "string" ? value["text"] : typeof value["thinking"] === "string" ? value["thinking"] : void 0;
3833
+ if (typeof text === "string" && text) sendLocalDebuggerLiveEvent({ traceId, type: "reasoning_delta", content: text, metadata: liveMeta });
3834
+ } else if (type === "tool-call") {
3835
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3836
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_start", content: toolName, metadata: { ...liveMeta, args: value["args"] } });
3837
+ } else if (type === "tool-result") {
3838
+ const toolName = typeof value["toolName"] === "string" ? value["toolName"] : "tool";
3839
+ sendLocalDebuggerLiveEvent({ traceId, type: "tool_result", content: toolName, metadata: { ...liveMeta, result: value["result"] } });
3840
+ }
3841
+ }
3624
3842
  }
3625
3843
  controller.enqueue(value);
3626
3844
  } catch (error) {
@@ -3858,6 +4076,14 @@ function eventMetadataFromChatRequest(options) {
3858
4076
  ...eventId ? { eventId } : {}
3859
4077
  });
3860
4078
  }
4079
+ function stringify(v) {
4080
+ if (typeof v === "string") return v;
4081
+ return JSON.stringify(v);
4082
+ }
4083
+ function userAttrsToOtlp(attrs) {
4084
+ if (!attrs) return [];
4085
+ return Object.entries(attrs).map(([key, value]) => attrString(key, value));
4086
+ }
3861
4087
  function envDebugEnabled() {
3862
4088
  var _a;
3863
4089
  if (typeof process === "undefined") return false;
@@ -3926,6 +4152,76 @@ function createRaindropAISDK(opts) {
3926
4152
  await eventShipper.finish(eventId, patch);
3927
4153
  }
3928
4154
  },
4155
+ traces: /* @__PURE__ */ (() => {
4156
+ const openSpans = /* @__PURE__ */ new Map();
4157
+ function toTraceSpan(internal) {
4158
+ return { traceId: internal.ids.traceIdB64, spanId: internal.ids.spanIdB64 };
4159
+ }
4160
+ return {
4161
+ startSpan(args) {
4162
+ const parent = args.parent ? { traceIdB64: args.parent.traceId, spanIdB64: args.parent.spanId } : void 0;
4163
+ const attrs = userAttrsToOtlp(args.attributes);
4164
+ if (args.operationId === "ai.toolCall") {
4165
+ attrs.push(attrString("ai.toolCall.name", args.name));
4166
+ }
4167
+ const internal = traceShipper.startSpan({
4168
+ name: args.name,
4169
+ eventId: args.eventId,
4170
+ parent,
4171
+ operationId: args.operationId,
4172
+ attributes: attrs
4173
+ });
4174
+ const handle = toTraceSpan(internal);
4175
+ openSpans.set(handle.spanId, internal);
4176
+ return handle;
4177
+ },
4178
+ endSpan(span, extra) {
4179
+ const internal = openSpans.get(span.spanId);
4180
+ if (!internal) return;
4181
+ openSpans.delete(span.spanId);
4182
+ const errorValue = extra == null ? void 0 : extra.error;
4183
+ const error = errorValue instanceof Error ? errorValue : typeof errorValue === "string" ? new Error(errorValue) : void 0;
4184
+ traceShipper.endSpan(internal, {
4185
+ attributes: userAttrsToOtlp(extra == null ? void 0 : extra.attributes),
4186
+ error
4187
+ });
4188
+ },
4189
+ createSpan(args) {
4190
+ var _a2;
4191
+ const parent = args.parent ? { traceIdB64: args.parent.traceId, spanIdB64: args.parent.spanId } : void 0;
4192
+ const startMs = (_a2 = args.startTime) != null ? _a2 : Date.now() - args.durationMs;
4193
+ const startAttrs = [...userAttrsToOtlp(args.attributes)];
4194
+ if (args.operationId === "ai.toolCall") {
4195
+ startAttrs.push(attrString("ai.toolCall.name", args.name));
4196
+ }
4197
+ if (args.input !== void 0) startAttrs.push(attrString("traceloop.entity.input", stringify(args.input)));
4198
+ if (args.operationId === "ai.toolCall" && args.input !== void 0) {
4199
+ startAttrs.push(attrString("ai.toolCall.args", stringify(args.input)));
4200
+ }
4201
+ const internal = traceShipper.startSpan({
4202
+ name: args.name,
4203
+ eventId: args.eventId,
4204
+ parent,
4205
+ operationId: args.operationId,
4206
+ attributes: startAttrs,
4207
+ startTimeUnixNano: unixMsToNanoString(startMs)
4208
+ });
4209
+ const endAttrs = [];
4210
+ if (args.output !== void 0) endAttrs.push(attrString("traceloop.entity.output", stringify(args.output)));
4211
+ if (args.operationId === "ai.toolCall" && args.output !== void 0) {
4212
+ endAttrs.push(attrString("ai.toolCall.result", stringify(args.output)));
4213
+ }
4214
+ const errorValue = args.error;
4215
+ const error = errorValue instanceof Error ? errorValue : typeof errorValue === "string" ? new Error(errorValue) : void 0;
4216
+ traceShipper.endSpan(internal, {
4217
+ attributes: endAttrs,
4218
+ error,
4219
+ endTimeUnixNano: unixMsToNanoString(startMs + args.durationMs)
4220
+ });
4221
+ return toTraceSpan(internal);
4222
+ }
4223
+ };
4224
+ })(),
3929
4225
  users: {
3930
4226
  async identify(users) {
3931
4227
  await eventShipper.identify(users);
@@ -1,4 +1,4 @@
1
- export { A as AISDKChatRequestLike, a as AISDKChatRequestMessageLike, b as AISDKMessage, c as AgentCallMetadata, d as AgentWithMetadata, e as Attachment, B as BuildEventPatch, C as ContextManager, f as ContextSpan, E as EventBuilder, g as EventMetadataOptions, I as IdentifyInput, R as RaindropAISDKClient, h as RaindropAISDKContext, i as RaindropAISDKOptions, j as RaindropTelemetryIntegration, k as RaindropTelemetryIntegrationOptions, S as SelfDiagnosticsOptions, l as SelfDiagnosticsSignalDefinition, m as SelfDiagnosticsSignalDefinitions, W as WrapAISDKOptions, n as WrappedAI, o as WrappedAISDK, _ as _resetWarnedMissingUserId, p as createRaindropAISDK, q as currentSpan, r as eventMetadata, s as eventMetadataFromChatRequest, t as getContextManager, w as withCurrent } from './index-DGziajf_.mjs';
1
+ export { A as AISDKChatRequestLike, a as AISDKChatRequestMessageLike, b as AISDKMessage, c as AgentCallMetadata, d as AgentWithMetadata, e as Attachment, B as BuildEventPatch, C as ContextManager, f as ContextSpan, g as CreateSpanArgs, E as EndSpanArgs, h as EventBuilder, i as EventMetadataOptions, I as IdentifyInput, R as RaindropAISDKClient, j as RaindropAISDKContext, k as RaindropAISDKOptions, l as RaindropTelemetryIntegration, m as RaindropTelemetryIntegrationOptions, S as SelfDiagnosticsOptions, n as SelfDiagnosticsSignalDefinition, o as SelfDiagnosticsSignalDefinitions, p as StartSpanArgs, T as TraceSpan, W as WrapAISDKOptions, q as WrappedAI, r as WrappedAISDK, _ as _resetWarnedMissingUserId, s as createRaindropAISDK, t as currentSpan, u as eventMetadata, v as eventMetadataFromChatRequest, w as getContextManager, x as withCurrent } from './index-sxjvhkYW.mjs';
2
2
 
3
3
  declare global {
4
4
  var RAINDROP_ASYNC_LOCAL_STORAGE: (new <T>() => {
@@ -1,4 +1,4 @@
1
- export { A as AISDKChatRequestLike, a as AISDKChatRequestMessageLike, b as AISDKMessage, c as AgentCallMetadata, d as AgentWithMetadata, e as Attachment, B as BuildEventPatch, C as ContextManager, f as ContextSpan, E as EventBuilder, g as EventMetadataOptions, I as IdentifyInput, R as RaindropAISDKClient, h as RaindropAISDKContext, i as RaindropAISDKOptions, j as RaindropTelemetryIntegration, k as RaindropTelemetryIntegrationOptions, S as SelfDiagnosticsOptions, l as SelfDiagnosticsSignalDefinition, m as SelfDiagnosticsSignalDefinitions, W as WrapAISDKOptions, n as WrappedAI, o as WrappedAISDK, _ as _resetWarnedMissingUserId, p as createRaindropAISDK, q as currentSpan, r as eventMetadata, s as eventMetadataFromChatRequest, t as getContextManager, w as withCurrent } from './index-DGziajf_.js';
1
+ export { A as AISDKChatRequestLike, a as AISDKChatRequestMessageLike, b as AISDKMessage, c as AgentCallMetadata, d as AgentWithMetadata, e as Attachment, B as BuildEventPatch, C as ContextManager, f as ContextSpan, g as CreateSpanArgs, E as EndSpanArgs, h as EventBuilder, i as EventMetadataOptions, I as IdentifyInput, R as RaindropAISDKClient, j as RaindropAISDKContext, k as RaindropAISDKOptions, l as RaindropTelemetryIntegration, m as RaindropTelemetryIntegrationOptions, S as SelfDiagnosticsOptions, n as SelfDiagnosticsSignalDefinition, o as SelfDiagnosticsSignalDefinitions, p as StartSpanArgs, T as TraceSpan, W as WrapAISDKOptions, q as WrappedAI, r as WrappedAISDK, _ as _resetWarnedMissingUserId, s as createRaindropAISDK, t as currentSpan, u as eventMetadata, v as eventMetadataFromChatRequest, w as getContextManager, x as withCurrent } from './index-sxjvhkYW.js';
2
2
 
3
3
  declare global {
4
4
  var RAINDROP_ASYNC_LOCAL_STORAGE: (new <T>() => {