@raindrop-ai/ai-sdk 0.0.29 → 0.0.31

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.
@@ -1714,13 +1714,76 @@ function readRaindropCallMetadataFromArgs(args) {
1714
1714
  return meta;
1715
1715
  }
1716
1716
 
1717
+ // src/internal/parent-tool-context.ts
1718
+ var SyncFallbackStorage2 = class {
1719
+ constructor() {
1720
+ this._stack = [];
1721
+ }
1722
+ getStore() {
1723
+ return this._stack[this._stack.length - 1];
1724
+ }
1725
+ run(store, callback) {
1726
+ this._stack.push(store);
1727
+ try {
1728
+ return callback();
1729
+ } finally {
1730
+ this._stack.pop();
1731
+ }
1732
+ }
1733
+ // `enterWith` is intentionally absent on the sync fallback — the
1734
+ // event-driven enter/clear pattern only makes sense when the runtime
1735
+ // can propagate state across awaits, which the sync stack cannot.
1736
+ };
1737
+ var _storage2 = null;
1738
+ function getStorage2() {
1739
+ if (_storage2) return _storage2;
1740
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
1741
+ _storage2 = Ctor ? new Ctor() : new SyncFallbackStorage2();
1742
+ return _storage2;
1743
+ }
1744
+ function _resetParentToolContextStorage() {
1745
+ _storage2 = null;
1746
+ }
1747
+ function getCurrentParentToolContext() {
1748
+ return getStorage2().getStore();
1749
+ }
1750
+ function enterParentToolContext(ctx) {
1751
+ var _a;
1752
+ const storage = getStorage2();
1753
+ (_a = storage.enterWith) == null ? void 0 : _a.call(storage, ctx);
1754
+ }
1755
+ function clearParentToolContext() {
1756
+ var _a;
1757
+ const storage = getStorage2();
1758
+ (_a = storage.enterWith) == null ? void 0 : _a.call(storage, void 0);
1759
+ }
1760
+ function runWithParentToolContext(ctx, fn) {
1761
+ return getStorage2().run(ctx, fn);
1762
+ }
1763
+
1717
1764
  // src/internal/raindrop-telemetry-integration.ts
1718
1765
  var RaindropTelemetryIntegration = class {
1719
1766
  constructor(opts) {
1720
1767
  this.callStates = /* @__PURE__ */ new Map();
1768
+ /**
1769
+ * Per-tool-call snapshot of the parent-tool ALS context taken right
1770
+ * before `enterParentToolContext` overwrites it in `toolExecutionStart`.
1771
+ * Kept at the integration level (rather than on `CallState`) so the
1772
+ * snapshot survives even when the parent generation has no tracked
1773
+ * `CallState` — e.g. the AI SDK dispatches a tool callback for a
1774
+ * `callId` we never registered via `onStart`. Without this, the
1775
+ * unconditional ALS enter in `toolExecutionStart` would leave
1776
+ * `toolExecutionEnd` no way to restore the prior context, so it would
1777
+ * clear and wipe whatever the outer scope had set.
1778
+ *
1779
+ * Keyed by `toolCallId` because that's the only identifier guaranteed
1780
+ * to round-trip between `toolExecutionStart` and `toolExecutionEnd`
1781
+ * (the `event.callId` can be the same for parallel sibling tools).
1782
+ */
1783
+ this.priorParentContexts = /* @__PURE__ */ new Map();
1721
1784
  // ── onStart ─────────────────────────────────────────────────────────────
1722
1785
  this.onStart = (event) => {
1723
- var _a, _b, _c, _d;
1786
+ var _a, _b, _c, _d, _e;
1724
1787
  if (event.isEnabled === false) return;
1725
1788
  const isEmbed = event.operationId === "ai.embed" || event.operationId === "ai.embedMany";
1726
1789
  const recordInputs = event.recordInputs !== false;
@@ -1739,6 +1802,47 @@ var RaindropTelemetryIntegration = class {
1739
1802
  event.operationId,
1740
1803
  functionId
1741
1804
  );
1805
+ const parentToolContext = !isEmbed && this.subagentWrapping ? getCurrentParentToolContext() : void 0;
1806
+ const metadataSubagentName = !isEmbed && this.subagentWrapping && parentToolContext === void 0 ? typeof (metadata == null ? void 0 : metadata["ash.subagent.name"]) === "string" ? metadata["ash.subagent.name"] : void 0 : void 0;
1807
+ const subagentName = (_e = parentToolContext == null ? void 0 : parentToolContext.toolName) != null ? _e : metadataSubagentName;
1808
+ let subagentToolCallSpan;
1809
+ let rootParentOverride;
1810
+ if (subagentName && this.sendTraces) {
1811
+ const parentAttrs = parentToolContext ? [
1812
+ attrString("raindrop.parent.callId", parentToolContext.parentCallId),
1813
+ attrString("raindrop.parent.toolCallId", parentToolContext.toolCallId),
1814
+ attrString("raindrop.parent.toolName", parentToolContext.toolName)
1815
+ ] : [];
1816
+ subagentToolCallSpan = this.traceShipper.startSpan({
1817
+ name: subagentName,
1818
+ parent: inheritedParent,
1819
+ eventId,
1820
+ operationId: "ai.toolCall",
1821
+ attributes: [
1822
+ attrString("operation.name", "ai.toolCall"),
1823
+ attrString("resource.name", subagentName),
1824
+ attrString("raindrop.span.kind", "tool_call"),
1825
+ attrString("ai.toolCall.name", subagentName),
1826
+ attrString("raindrop.subagent.name", subagentName),
1827
+ attrString("raindrop.agent.role", "subagent"),
1828
+ ...parentAttrs
1829
+ ]
1830
+ });
1831
+ const subagentParentRef = this.spanParentRef(subagentToolCallSpan);
1832
+ const markerSpan = this.traceShipper.startSpan({
1833
+ name: "agent.subagent",
1834
+ parent: subagentParentRef,
1835
+ eventId,
1836
+ operationId: "agent.subagent",
1837
+ attributes: [
1838
+ attrString("operation.name", "agent.subagent"),
1839
+ attrString("raindrop.span.kind", "llm_call"),
1840
+ attrString("raindrop.subagent.name", subagentName)
1841
+ ]
1842
+ });
1843
+ this.traceShipper.endSpan(markerSpan);
1844
+ rootParentOverride = subagentParentRef;
1845
+ }
1742
1846
  let rootSpan;
1743
1847
  if (this.sendTraces) {
1744
1848
  const promptAttrs = !isEmbed && recordInputs ? [
@@ -1759,7 +1863,7 @@ var RaindropTelemetryIntegration = class {
1759
1863
  ] : [attrString("ai.value", safeJsonWithUint8(event.value))] : [];
1760
1864
  rootSpan = this.traceShipper.startSpan({
1761
1865
  name: event.operationId,
1762
- parent: inheritedParent,
1866
+ parent: rootParentOverride != null ? rootParentOverride : inheritedParent,
1763
1867
  eventId,
1764
1868
  operationId: event.operationId,
1765
1869
  attributes: [
@@ -1787,18 +1891,21 @@ var RaindropTelemetryIntegration = class {
1787
1891
  operationId: event.operationId,
1788
1892
  eventId,
1789
1893
  rootSpan,
1790
- rootParent: rootSpan ? this.spanParentRef(rootSpan) : inheritedParent,
1894
+ rootParent: rootSpan ? this.spanParentRef(rootSpan) : rootParentOverride != null ? rootParentOverride : inheritedParent,
1791
1895
  stepSpan: void 0,
1792
1896
  stepParent: void 0,
1793
1897
  toolSpans: /* @__PURE__ */ new Map(),
1794
1898
  embedSpans: /* @__PURE__ */ new Map(),
1899
+ parentContextToolCallIds: /* @__PURE__ */ new Set(),
1795
1900
  recordInputs,
1796
1901
  recordOutputs,
1797
1902
  functionId,
1798
1903
  metadata,
1799
1904
  accumulatedText: "",
1800
1905
  inputText: isEmbed ? void 0 : this.extractInputText(event),
1801
- toolCallCount: 0
1906
+ toolCallCount: 0,
1907
+ subagentName,
1908
+ subagentToolCallSpan
1802
1909
  });
1803
1910
  };
1804
1911
  // ── onStepStart ─────────────────────────────────────────────────────────
@@ -2012,6 +2119,10 @@ var RaindropTelemetryIntegration = class {
2012
2119
  this.traceShipper.endSpan(embedSpan, { attributes: outputAttrs });
2013
2120
  state.embedSpans.delete(event.embedCallId);
2014
2121
  };
2122
+ // v7 canary.159 renamed `onEmbedFinish` -> `onEmbedEnd`. Both names forward
2123
+ // to the same implementation; the installed SDK only wires up whichever it
2124
+ // knows about, so there is no double dispatch.
2125
+ this.onEmbedEnd = (event) => this.onEmbedFinish(event);
2015
2126
  // ── onFinish ────────────────────────────────────────────────────────────
2016
2127
  this.onFinish = (event) => {
2017
2128
  const state = this.getState(event.callId);
@@ -2022,8 +2133,17 @@ var RaindropTelemetryIntegration = class {
2022
2133
  } else {
2023
2134
  this.finishGenerate(event, state);
2024
2135
  }
2136
+ if (state.subagentToolCallSpan) {
2137
+ this.traceShipper.endSpan(state.subagentToolCallSpan);
2138
+ }
2025
2139
  this.cleanup(event.callId);
2026
2140
  };
2141
+ // v7 < canary.159 dispatched `onFinish` as the operation finalizer; canary.159
2142
+ // renamed it to `onEnd` (the same change renamed onEmbedFinish -> onEmbedEnd
2143
+ // and onRerankFinish -> onRerankEnd). The event shape is unchanged, so this
2144
+ // is a thin alias to one implementation. The installed SDK wires up whichever
2145
+ // name it knows about, so old and new names never double dispatch.
2146
+ this.onEnd = (event) => this.onFinish(event);
2027
2147
  // ── onError ─────────────────────────────────────────────────────────────
2028
2148
  this.onError = (error) => {
2029
2149
  var _a;
@@ -2039,6 +2159,10 @@ var RaindropTelemetryIntegration = class {
2039
2159
  this.traceShipper.endSpan(embedSpan, { error: actualError });
2040
2160
  }
2041
2161
  state.embedSpans.clear();
2162
+ for (const toolCallId of state.parentContextToolCallIds) {
2163
+ this.priorParentContexts.delete(toolCallId);
2164
+ }
2165
+ state.parentContextToolCallIds.clear();
2042
2166
  for (const toolSpan of state.toolSpans.values()) {
2043
2167
  this.traceShipper.endSpan(toolSpan, { error: actualError });
2044
2168
  }
@@ -2046,6 +2170,9 @@ var RaindropTelemetryIntegration = class {
2046
2170
  if (state.rootSpan) {
2047
2171
  this.traceShipper.endSpan(state.rootSpan, { error: actualError });
2048
2172
  }
2173
+ if (state.subagentToolCallSpan) {
2174
+ this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
2175
+ }
2049
2176
  this.cleanup(event.callId);
2050
2177
  };
2051
2178
  // ── executeTool ─────────────────────────────────────────────────────────
@@ -2070,6 +2197,7 @@ var RaindropTelemetryIntegration = class {
2070
2197
  this.eventShipper = opts.eventShipper;
2071
2198
  this.sendTraces = opts.sendTraces !== false;
2072
2199
  this.sendEvents = opts.sendEvents !== false;
2200
+ this.subagentWrapping = opts.subagentWrapping !== false;
2073
2201
  this.debug = opts.debug === true;
2074
2202
  this.defaultContext = opts.context;
2075
2203
  }
@@ -2151,9 +2279,20 @@ var RaindropTelemetryIntegration = class {
2151
2279
  // (see https://github.com/vercel/ai/pull/14589). Event shape is identical.
2152
2280
  // Both names are exposed and forward to a single implementation.
2153
2281
  toolExecutionStart(event) {
2282
+ const { toolCall } = event;
2283
+ const priorParent = getCurrentParentToolContext();
2284
+ this.priorParentContexts.set(
2285
+ toolCall.toolCallId,
2286
+ priorParent != null ? priorParent : null
2287
+ );
2288
+ enterParentToolContext({
2289
+ parentCallId: event.callId,
2290
+ toolCallId: toolCall.toolCallId,
2291
+ toolName: toolCall.toolName
2292
+ });
2154
2293
  const state = this.getState(event.callId);
2294
+ state == null ? void 0 : state.parentContextToolCallIds.add(toolCall.toolCallId);
2155
2295
  if (!(state == null ? void 0 : state.stepParent)) return;
2156
- const { toolCall } = event;
2157
2296
  const { operationName, resourceName } = opName(
2158
2297
  "ai.toolCall",
2159
2298
  state.functionId
@@ -2177,6 +2316,17 @@ var RaindropTelemetryIntegration = class {
2177
2316
  this.emitLive(state, "tool_start", toolCall.toolName, { args: toolCall.input });
2178
2317
  }
2179
2318
  toolExecutionEnd(event) {
2319
+ var _a;
2320
+ const toolCallId = (_a = event.toolCall) == null ? void 0 : _a.toolCallId;
2321
+ if (toolCallId && this.priorParentContexts.has(toolCallId)) {
2322
+ const prior = this.priorParentContexts.get(toolCallId);
2323
+ this.priorParentContexts.delete(toolCallId);
2324
+ if (prior) {
2325
+ enterParentToolContext(prior);
2326
+ } else {
2327
+ clearParentToolContext();
2328
+ }
2329
+ }
2180
2330
  const state = this.getState(event.callId);
2181
2331
  if (!state) return;
2182
2332
  const toolSpan = state.toolSpans.get(event.toolCall.toolCallId);
@@ -2240,7 +2390,8 @@ var RaindropTelemetryIntegration = class {
2240
2390
  );
2241
2391
  this.traceShipper.endSpan(state.rootSpan, { attributes: outputAttrs });
2242
2392
  }
2243
- if (this.sendEvents) {
2393
+ const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
2394
+ if (this.sendEvents && !suppressSubagentEvent) {
2244
2395
  const callMeta = this.extractRaindropMetadata(state.metadata);
2245
2396
  const userId = (_f = callMeta.userId) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.userId;
2246
2397
  if (userId) {
@@ -4333,7 +4484,7 @@ function extractNestedTokens(usage, key) {
4333
4484
  // package.json
4334
4485
  var package_default = {
4335
4486
  name: "@raindrop-ai/ai-sdk",
4336
- version: "0.0.29"};
4487
+ version: "0.0.31"};
4337
4488
 
4338
4489
  // src/internal/version.ts
4339
4490
  var libraryName = package_default.name;
@@ -4424,12 +4575,16 @@ function createRaindropAISDK(opts) {
4424
4575
  const writeKey = opts.writeKey;
4425
4576
  const eventsRequested = ((_a = opts.events) == null ? void 0 : _a.enabled) !== false;
4426
4577
  const tracesRequested = ((_b = opts.traces) == null ? void 0 : _b.enabled) !== false;
4427
- const eventsEnabled = eventsRequested && !!writeKey;
4428
- const tracesEnabled = tracesRequested && !!writeKey;
4429
4578
  const envDebug = envDebugEnabled();
4430
- if (!writeKey && (eventsRequested || tracesRequested)) {
4579
+ const localWorkshopInput = opts.localWorkshopUrl === false ? null : opts.localWorkshopUrl;
4580
+ const resolvedLocalDebuggerUrl = resolveLocalDebuggerBaseUrl(localWorkshopInput);
4581
+ const localDebuggerUrl = localWorkshopInput === null ? null : resolvedLocalDebuggerUrl != null ? resolvedLocalDebuggerUrl : void 0;
4582
+ const hasDestination = !!writeKey || !!resolvedLocalDebuggerUrl;
4583
+ const eventsEnabled = eventsRequested && hasDestination;
4584
+ const tracesEnabled = tracesRequested && hasDestination;
4585
+ if (!hasDestination && (eventsRequested || tracesRequested)) {
4431
4586
  console.warn(
4432
- "[raindrop-ai/ai-sdk] writeKey not provided; telemetry shipping is disabled"
4587
+ "[raindrop-ai/ai-sdk] writeKey not provided and no local Workshop reachable; telemetry shipping is disabled"
4433
4588
  );
4434
4589
  }
4435
4590
  const eventShipper = new EventShipper2({
@@ -4437,9 +4592,9 @@ function createRaindropAISDK(opts) {
4437
4592
  endpoint: opts.endpoint,
4438
4593
  enabled: eventsEnabled,
4439
4594
  debug: ((_c = opts.events) == null ? void 0 : _c.debug) === true || envDebug,
4440
- partialFlushMs: (_d = opts.events) == null ? void 0 : _d.partialFlushMs
4595
+ partialFlushMs: (_d = opts.events) == null ? void 0 : _d.partialFlushMs,
4596
+ localDebuggerUrl
4441
4597
  });
4442
- const localDebuggerUrl = opts.localWorkshopUrl === false ? null : opts.localWorkshopUrl;
4443
4598
  const traceShipper = new TraceShipper2({
4444
4599
  writeKey,
4445
4600
  endpoint: opts.endpoint,
@@ -4461,12 +4616,30 @@ function createRaindropAISDK(opts) {
4461
4616
  traceShipper
4462
4617
  });
4463
4618
  },
4464
- createTelemetryIntegration(context) {
4619
+ createTelemetryIntegration(contextOrOptions) {
4620
+ const FLAT_CONTEXT_KEYS = [
4621
+ "userId",
4622
+ "eventId",
4623
+ "eventName",
4624
+ "convoId",
4625
+ "properties"
4626
+ ];
4627
+ let context;
4628
+ let subagentWrapping;
4629
+ if (contextOrOptions === void 0) ; else if ("context" in contextOrOptions) {
4630
+ context = contextOrOptions.context;
4631
+ subagentWrapping = contextOrOptions.subagentWrapping;
4632
+ } else if ("subagentWrapping" in contextOrOptions && !FLAT_CONTEXT_KEYS.some((k) => k in contextOrOptions)) {
4633
+ subagentWrapping = contextOrOptions.subagentWrapping;
4634
+ } else {
4635
+ context = contextOrOptions;
4636
+ }
4465
4637
  return new RaindropTelemetryIntegration({
4466
4638
  traceShipper,
4467
4639
  eventShipper,
4468
4640
  sendTraces: tracesEnabled,
4469
4641
  sendEvents: eventsEnabled,
4642
+ subagentWrapping,
4470
4643
  debug: envDebug,
4471
4644
  context
4472
4645
  });
@@ -4574,4 +4747,4 @@ function createRaindropAISDK(opts) {
4574
4747
  };
4575
4748
  }
4576
4749
 
4577
- export { DEFAULT_REDACT_ATTRIBUTE_KEYS, DEFAULT_SECRET_KEY_NAMES, REDACTED_PLACEHOLDER, RaindropTelemetryIntegration, _resetRaindropCallMetadataStorage, _resetWarnedMissingUserId, createRaindropAISDK, currentSpan, defaultTransformSpan, eventMetadata, eventMetadataFromChatRequest, getContextManager, getCurrentRaindropCallMetadata, readRaindropCallMetadataFromArgs, redactJsonAttributeValue, redactSecretsInObject, runWithRaindropCallMetadata, withCurrent };
4750
+ export { DEFAULT_REDACT_ATTRIBUTE_KEYS, DEFAULT_SECRET_KEY_NAMES, REDACTED_PLACEHOLDER, RaindropTelemetryIntegration, _resetParentToolContextStorage, _resetRaindropCallMetadataStorage, _resetWarnedMissingUserId, clearParentToolContext, createRaindropAISDK, currentSpan, defaultTransformSpan, enterParentToolContext, eventMetadata, eventMetadataFromChatRequest, getContextManager, getCurrentParentToolContext, getCurrentRaindropCallMetadata, readRaindropCallMetadataFromArgs, redactJsonAttributeValue, redactSecretsInObject, runWithParentToolContext, runWithRaindropCallMetadata, withCurrent };
@@ -378,7 +378,9 @@ interface TelemetryIntegration {
378
378
  onStepFinish?: Listener<any>;
379
379
  onEmbedStart?: Listener<any>;
380
380
  onEmbedFinish?: Listener<any>;
381
+ onEmbedEnd?: Listener<any>;
381
382
  onFinish?: Listener<any>;
383
+ onEnd?: Listener<any>;
382
384
  onError?: Listener<any>;
383
385
  executeTool?: <T>(params: {
384
386
  callId: string;
@@ -391,6 +393,19 @@ type RaindropTelemetryIntegrationOptions = {
391
393
  eventShipper: EventShipper;
392
394
  sendTraces?: boolean;
393
395
  sendEvents?: boolean;
396
+ /**
397
+ * When `true` (default), generations started inside a tool's `execute`
398
+ * callback on the same async branch are wrapped in a synthetic `TOOL_CALL`
399
+ * + `agent.subagent` LLM marker so observability backends can render them
400
+ * as an agent block (and so the inner LLM's `track_partial` is suppressed).
401
+ *
402
+ * This is the right semantic for any framework that lowers sub-agents to
403
+ * AI SDK tools (Ash, Mastra, Claude Agent SDK, hand-rolled tool loops),
404
+ * not Ash-specific. Set to `false` if you have a tool whose `execute`
405
+ * happens to call `streamText`/`generateText` for unrelated reasons (e.g.
406
+ * RAG enrichment) and don't want it labelled as a sub-agent.
407
+ */
408
+ subagentWrapping?: boolean;
394
409
  debug?: boolean;
395
410
  context?: {
396
411
  userId?: string;
@@ -405,9 +420,26 @@ declare class RaindropTelemetryIntegration implements TelemetryIntegration {
405
420
  private readonly eventShipper;
406
421
  private readonly sendTraces;
407
422
  private readonly sendEvents;
423
+ private readonly subagentWrapping;
408
424
  private readonly debug;
409
425
  private readonly defaultContext;
410
426
  private readonly callStates;
427
+ /**
428
+ * Per-tool-call snapshot of the parent-tool ALS context taken right
429
+ * before `enterParentToolContext` overwrites it in `toolExecutionStart`.
430
+ * Kept at the integration level (rather than on `CallState`) so the
431
+ * snapshot survives even when the parent generation has no tracked
432
+ * `CallState` — e.g. the AI SDK dispatches a tool callback for a
433
+ * `callId` we never registered via `onStart`. Without this, the
434
+ * unconditional ALS enter in `toolExecutionStart` would leave
435
+ * `toolExecutionEnd` no way to restore the prior context, so it would
436
+ * clear and wipe whatever the outer scope had set.
437
+ *
438
+ * Keyed by `toolCallId` because that's the only identifier guaranteed
439
+ * to round-trip between `toolExecutionStart` and `toolExecutionEnd`
440
+ * (the `event.callId` can be the same for parallel sibling tools).
441
+ */
442
+ private readonly priorParentContexts;
411
443
  constructor(opts: RaindropTelemetryIntegrationOptions);
412
444
  private getState;
413
445
  private cleanup;
@@ -433,7 +465,9 @@ declare class RaindropTelemetryIntegration implements TelemetryIntegration {
433
465
  onStepFinish: (event: any) => void;
434
466
  onEmbedStart: (event: any) => void;
435
467
  onEmbedFinish: (event: any) => void;
468
+ onEmbedEnd: (event: any) => void;
436
469
  onFinish: (event: any) => void;
470
+ onEnd: (event: any) => void;
437
471
  private finishGenerate;
438
472
  private finishEmbed;
439
473
  onError: (error: unknown) => void;
@@ -510,6 +544,92 @@ declare function readRaindropCallMetadataFromArgs(args: readonly unknown[]): Rai
510
544
 
511
545
  declare function _resetWarnedMissingUserId(): void;
512
546
 
547
+ /**
548
+ * Parent tool execution context propagation.
549
+ *
550
+ * Problem
551
+ * ───────
552
+ * When a tool's `execute` callback recursively calls `streamText` /
553
+ * `generateText` (which is exactly how Ash lowers sub-agents, but also a
554
+ * common pattern in hand-rolled agent loops, Mastra, Claude Agent SDK,
555
+ * etc.), the inner generation's telemetry events are dispatched with no
556
+ * connection back to the outer tool call. The AI SDK fires `onStart` for
557
+ * the inner generation with its own fresh `callId`; nothing on the event
558
+ * tells the integration "this generation was triggered from inside tool
559
+ * X's execute callback."
560
+ *
561
+ * Without that linkage, observability tools have to fall back to
562
+ * regex-matching the prompt to guess whether a call is a sub-agent
563
+ * dispatch — fragile, framework-specific, and easily spoofable by user
564
+ * input.
565
+ *
566
+ * Solution
567
+ * ────────
568
+ * We maintain an `AsyncLocalStorage` slot that holds the currently-active
569
+ * parent tool call. The integration's `onToolExecutionStart` enters the
570
+ * slot before the AI SDK awaits `tool.execute(...)`; the inner
571
+ * generation's `onStart` reads from the slot to recover parent linkage.
572
+ * `onToolExecutionEnd` clears the slot so subsequent code in the same
573
+ * async branch doesn't see stale state.
574
+ *
575
+ * Async-context scoping
576
+ * ─────────────────────
577
+ * `enterWith` modifies the *current* async context, which propagates
578
+ * downward into any `await` continuation and into child async resources
579
+ * (including the awaited `tool.execute` and anything it calls). Sibling
580
+ * branches are unaffected: when the AI SDK dispatches tool calls via
581
+ * `Promise.all(map(async (tc) => ...))`, each map callback runs in its
582
+ * own async branch, so `enterWith` in one branch is invisible to the
583
+ * others. This is exactly the behaviour we need for parallel sub-agent
584
+ * dispatch.
585
+ *
586
+ * On runtimes that don't expose `AsyncLocalStorage` (browser, Cloudflare
587
+ * Workers without `nodejs_compat`), we fall back to a synchronous stack
588
+ * via `runWithParentToolContext` — see the `SyncFallbackStorage` in
589
+ * `call-metadata.ts` for the established pattern. `enterWith` becomes a
590
+ * silent no-op on the sync fallback, so async tool execution on those
591
+ * runtimes won't have parent linkage and the inner generation will
592
+ * render as a top-level call instead of being grouped under its caller.
593
+ */
594
+ type ParentToolContext = {
595
+ /** The `callId` of the generation whose step kicked off this tool call. */
596
+ parentCallId: string;
597
+ /** The tool-call id from the parent generation's step. */
598
+ toolCallId: string;
599
+ /** The tool name the parent generation invoked. */
600
+ toolName: string;
601
+ };
602
+ /** Test helper — drop the storage so tests start from a fresh slot. */
603
+ declare function _resetParentToolContextStorage(): void;
604
+ /**
605
+ * Returns the active parent tool context, or `undefined` if no tool is
606
+ * currently executing in this async branch.
607
+ */
608
+ declare function getCurrentParentToolContext(): ParentToolContext | undefined;
609
+ /**
610
+ * Enter a parent tool context on the current async branch. Subsequent
611
+ * `await`-ed work (including the parent's `tool.execute` body) inherits
612
+ * the context until {@link clearParentToolContext} runs. No-op on
613
+ * runtimes without `enterWith` support (browser/edge sync fallback).
614
+ */
615
+ declare function enterParentToolContext(ctx: ParentToolContext): void;
616
+ /**
617
+ * Clear the parent tool context on the current async branch. Pairs with
618
+ * {@link enterParentToolContext}. No-op on runtimes without `enterWith`
619
+ * support.
620
+ *
621
+ * `enterWith(undefined)` is supported by Node's `AsyncLocalStorage` at
622
+ * runtime; the `as never` cast bypasses TypeScript's stricter typing on
623
+ * the shared global declaration (`store: T`).
624
+ */
625
+ declare function clearParentToolContext(): void;
626
+ /**
627
+ * Run `fn` with `ctx` bound as the parent tool context. The sync-fallback
628
+ * equivalent of `enter`/`clear` — useful in tests and any code path
629
+ * where you want strict block scoping.
630
+ */
631
+ declare function runWithParentToolContext<R>(ctx: ParentToolContext, fn: () => R): R;
632
+
513
633
  /**
514
634
  * Options for creating event metadata for call-time context override.
515
635
  */
@@ -860,8 +980,17 @@ type RaindropAISDKClient = {
860
980
  /**
861
981
  * Create a TelemetryIntegration instance for direct registration with AI SDK v7+.
862
982
  * Use with `registerTelemetryIntegration()` from the `ai` package.
983
+ *
984
+ * Accepts the same `context` it has always accepted, or a full options
985
+ * object exposing `{ context, subagentWrapping }`. Sub-agent wrapping
986
+ * defaults to `true`; pass `subagentWrapping: false` to opt out for
987
+ * consumers whose `tool.execute` happens to call `generateText` for
988
+ * non-agentic reasons (e.g. RAG enrichment).
863
989
  */
864
- createTelemetryIntegration(context?: RaindropTelemetryIntegrationOptions["context"]): RaindropTelemetryIntegration;
990
+ createTelemetryIntegration(contextOrOptions?: RaindropTelemetryIntegrationOptions["context"] | {
991
+ context?: RaindropTelemetryIntegrationOptions["context"];
992
+ subagentWrapping?: boolean;
993
+ }): RaindropTelemetryIntegration;
865
994
  events: {
866
995
  patch(eventId: string, patch: EventPatch): Promise<void>;
867
996
  addAttachments(eventId: string, attachments: Attachment[]): Promise<void>;
@@ -933,4 +1062,4 @@ type RaindropAISDKClient = {
933
1062
  };
934
1063
  declare function createRaindropAISDK(opts: RaindropAISDKOptions): RaindropAISDKClient;
935
1064
 
936
- export { type AISDKChatRequestLike as A, type BuildEventPatch as B, ContextManager as C, DEFAULT_REDACT_ATTRIBUTE_KEYS as D, type EndSpanArgs as E, defaultTransformSpan as F, eventMetadata as G, eventMetadataFromChatRequest as H, type IdentifyInput as I, getContextManager as J, getCurrentRaindropCallMetadata as K, readRaindropCallMetadataFromArgs as L, redactJsonAttributeValue as M, redactSecretsInObject as N, type OtlpAnyValue as O, runWithRaindropCallMetadata as P, withCurrent as Q, REDACTED_PLACEHOLDER as R, type SelfDiagnosticsOptions as S, type TraceSpan as T, type WrapAISDKOptions as W, _resetRaindropCallMetadataStorage as _, type AISDKChatRequestMessageLike as a, type AISDKMessage as b, type AgentCallMetadata as c, type AgentWithMetadata as d, type Attachment as e, type ContextSpan as f, type CreateSpanArgs as g, DEFAULT_SECRET_KEY_NAMES as h, type EventBuilder as i, type EventMetadataOptions as j, type OtlpSpan as k, type RaindropAISDKClient as l, type RaindropAISDKContext as m, type RaindropAISDKOptions as n, type RaindropCallMetadata as o, RaindropTelemetryIntegration as p, type RaindropTelemetryIntegrationOptions as q, type SelfDiagnosticsSignalDefinition as r, type SelfDiagnosticsSignalDefinitions as s, type StartSpanArgs as t, type TransformSpanHook as u, type WrappedAI as v, type WrappedAISDK as w, _resetWarnedMissingUserId as x, createRaindropAISDK as y, currentSpan as z };
1065
+ export { withCurrent as $, type AISDKChatRequestLike as A, type BuildEventPatch as B, ContextManager as C, DEFAULT_REDACT_ATTRIBUTE_KEYS as D, type EndSpanArgs as E, createRaindropAISDK as F, currentSpan as G, defaultTransformSpan as H, type IdentifyInput as I, enterParentToolContext as J, eventMetadata as K, eventMetadataFromChatRequest as L, getContextManager as M, getCurrentParentToolContext as N, type OtlpAnyValue as O, type ParentToolContext as P, getCurrentRaindropCallMetadata as Q, REDACTED_PLACEHOLDER as R, type SelfDiagnosticsOptions as S, type TraceSpan as T, readRaindropCallMetadataFromArgs as U, redactJsonAttributeValue as V, type WrapAISDKOptions as W, redactSecretsInObject as X, runWithParentToolContext as Y, runWithRaindropCallMetadata as Z, _resetParentToolContextStorage as _, type AISDKChatRequestMessageLike as a, type AISDKMessage as b, type AgentCallMetadata as c, type AgentWithMetadata as d, type Attachment as e, type ContextSpan as f, type CreateSpanArgs as g, DEFAULT_SECRET_KEY_NAMES as h, type EventBuilder as i, type EventMetadataOptions as j, type OtlpSpan as k, type RaindropAISDKClient as l, type RaindropAISDKContext as m, type RaindropAISDKOptions as n, type RaindropCallMetadata as o, RaindropTelemetryIntegration as p, type RaindropTelemetryIntegrationOptions as q, type SelfDiagnosticsSignalDefinition as r, type SelfDiagnosticsSignalDefinitions as s, type StartSpanArgs as t, type TransformSpanHook as u, type WrappedAI as v, type WrappedAISDK as w, _resetRaindropCallMetadataStorage as x, _resetWarnedMissingUserId as y, clearParentToolContext as z };