@raindrop-ai/ai-sdk 0.2.1 → 0.3.0

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,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- // ../core/dist/chunk-QNWZIOOY.js
3
+ // ../core/dist/chunk-YUIXRQWN.js
4
4
  function normalizeFeatureFlags(input) {
5
5
  if (Array.isArray(input)) {
6
6
  return Object.fromEntries(input.map((name) => [name, "true"]));
@@ -63,6 +63,311 @@ function base64Encode(bytes) {
63
63
  }
64
64
  return out;
65
65
  }
66
+ function base64ToHex(value) {
67
+ if (!value) return "";
68
+ const maybeBuffer = globalThis.Buffer;
69
+ if (maybeBuffer) {
70
+ return maybeBuffer.from(value, "base64").toString("hex");
71
+ }
72
+ const atobFn = globalThis.atob;
73
+ if (typeof atobFn !== "function") return "";
74
+ try {
75
+ const binary = atobFn(value);
76
+ let hex = "";
77
+ for (let i = 0; i < binary.length; i++) {
78
+ hex += (binary.charCodeAt(i) & 255).toString(16).padStart(2, "0");
79
+ }
80
+ return hex;
81
+ } catch (e) {
82
+ return "";
83
+ }
84
+ }
85
+ var HANDOFF_ATTRIBUTE_SUFFIXES = {
86
+ mode: "raindrop.handoff.mode",
87
+ childEventId: "raindrop.handoff.childEventId",
88
+ parentEventId: "raindrop.handoff.parentEventId",
89
+ parentSpanId: "raindrop.handoff.parentSpanId",
90
+ name: "raindrop.handoff.name",
91
+ terminal: "raindrop.handoff.terminal",
92
+ agentRole: "raindrop.agent.role"
93
+ };
94
+ var HANDOFF_ATTRIBUTE_PREFIXES = [
95
+ "ai.telemetry.metadata.",
96
+ "ai.settings.context.",
97
+ ""
98
+ ];
99
+ var AI_SDK_METADATA_PREFIX = "ai.telemetry.metadata.";
100
+ var DETACHED_MODE = "detached";
101
+ var SUBAGENT_AGENT_ROLE = "subagent";
102
+ var HANDOFF_TERMINAL_CANCELLED = "cancelled";
103
+ var TOOL_EVENTS_SUFFIX = "raindrop.toolEvents";
104
+ var TOOL_EVENTS_ALLOW = "allow";
105
+ var SUBAGENT_ABORT_OPERATION_ID = "ai.subagent.failed";
106
+ var SUBAGENT_ABORT_SPAN_NAME = SUBAGENT_ABORT_OPERATION_ID;
107
+ var DEFAULT_DISPATCH_SPAN_NAME = "launch_subagent";
108
+ var HANDOFF_TERMINAL_PROPERTY_KEY = HANDOFF_ATTRIBUTE_SUFFIXES.terminal;
109
+ function defined(entries) {
110
+ const out = {};
111
+ for (const [key, value] of Object.entries(entries)) {
112
+ if (typeof value === "string" && value.trim().length > 0) out[key] = value;
113
+ }
114
+ return out;
115
+ }
116
+ function detachedDispatchMetadata(dispatch) {
117
+ return defined({
118
+ [HANDOFF_ATTRIBUTE_SUFFIXES.mode]: DETACHED_MODE,
119
+ [HANDOFF_ATTRIBUTE_SUFFIXES.childEventId]: dispatch.childEventId,
120
+ [HANDOFF_ATTRIBUTE_SUFFIXES.name]: dispatch.name
121
+ });
122
+ }
123
+ function detachedChildMetadata(link) {
124
+ return defined({
125
+ [HANDOFF_ATTRIBUTE_SUFFIXES.parentEventId]: link.parentEventId,
126
+ [HANDOFF_ATTRIBUTE_SUFFIXES.parentSpanId]: link.parentSpanId,
127
+ [HANDOFF_ATTRIBUTE_SUFFIXES.name]: link.name,
128
+ [HANDOFF_ATTRIBUTE_SUFFIXES.agentRole]: SUBAGENT_AGENT_ROLE
129
+ });
130
+ }
131
+ function cancelledTerminalMetadata() {
132
+ return { [HANDOFF_ATTRIBUTE_SUFFIXES.terminal]: HANDOFF_TERMINAL_CANCELLED };
133
+ }
134
+ function cancelledTerminalAttributes() {
135
+ const bare = cancelledTerminalMetadata();
136
+ return { ...bare, ...withMetadataPrefix(bare) };
137
+ }
138
+ function toolEventsAllowMetadata() {
139
+ return { [TOOL_EVENTS_SUFFIX]: TOOL_EVENTS_ALLOW };
140
+ }
141
+ function withMetadataPrefix(metadata) {
142
+ const out = {};
143
+ for (const [key, value] of Object.entries(metadata)) {
144
+ out[key.startsWith(AI_SDK_METADATA_PREFIX) ? key : `${AI_SDK_METADATA_PREFIX}${key}`] = value;
145
+ }
146
+ return out;
147
+ }
148
+ function readHandoffField(metadata, suffix) {
149
+ for (const prefix of HANDOFF_ATTRIBUTE_PREFIXES) {
150
+ const value = metadata[`${prefix}${suffix}`];
151
+ if (typeof value === "string" && value.trim().length > 0) return value.trim();
152
+ }
153
+ return void 0;
154
+ }
155
+ function readDetachedChildLink(metadata) {
156
+ if (!metadata) return void 0;
157
+ const parentEventId = readHandoffField(metadata, HANDOFF_ATTRIBUTE_SUFFIXES.parentEventId);
158
+ if (!parentEventId) return void 0;
159
+ return {
160
+ parentEventId,
161
+ parentSpanId: readHandoffField(metadata, HANDOFF_ATTRIBUTE_SUFFIXES.parentSpanId),
162
+ name: readHandoffField(metadata, HANDOFF_ATTRIBUTE_SUFFIXES.name)
163
+ };
164
+ }
165
+ var BAGGAGE_KEYS = {
166
+ eventId: "raindrop-event-id",
167
+ childEventId: "raindrop-child-event-id",
168
+ name: "raindrop-handoff-name",
169
+ convoId: "raindrop-convo-id",
170
+ userId: "raindrop-user-id",
171
+ // The dispatch span and its trace, carried as fields as well as in
172
+ // `traceparent`. Not redundant: OTel's HTTP instrumentations rewrite
173
+ // `traceparent` from whatever span is current as the request goes out, so by
174
+ // the time the child reads it the ids name the HTTP client span and its trace
175
+ // instead of the dispatch. The child would then point its reverse reference at
176
+ // a span the launcher's UI does not know as a dispatch. A field states which
177
+ // span it means rather than meaning "whoever wrote this header last".
178
+ dispatchSpanId: "raindrop-dispatch-span-id",
179
+ traceId: "raindrop-trace-id"
180
+ };
181
+ var TRACEPARENT_HEADER = "traceparent";
182
+ var BAGGAGE_HEADER = "baggage";
183
+ var W3C_TRACE_ID = /^[0-9a-f]{32}$/;
184
+ var W3C_SPAN_ID = /^[0-9a-f]{16}$/;
185
+ function isW3CTraceId(value) {
186
+ return value !== void 0 && W3C_TRACE_ID.test(value);
187
+ }
188
+ function isW3CSpanId(value) {
189
+ return value !== void 0 && W3C_SPAN_ID.test(value);
190
+ }
191
+ var warnedNonConformantIds = false;
192
+ function warnNonConformantIdsOnce(traceId, spanId) {
193
+ if (warnedNonConformantIds) return;
194
+ warnedNonConformantIds = true;
195
+ console.warn(
196
+ `[raindrop] hand-off carrier ids are not W3C-shaped (traceId="${traceId}", spanId="${spanId}"). The child still reports as its own event, but its reverse reference names a span id the backend does not store, so the link back to the launcher will not resolve. A LangSmith carrier reads this way \u2014 its run ids are UUIDs; propagate Raindrop's own carrier (toHeaders) to link.`
197
+ );
198
+ }
199
+ var HANDOFF_HEADER = "x-raindrop-handoff";
200
+ var LANGSMITH_TRACE_HEADER = "langsmith-trace";
201
+ var LANGSMITH_METADATA_BAGGAGE_KEY = "langsmith-metadata";
202
+ function encodeBaggage(entries) {
203
+ return Object.entries(entries).filter((entry) => Boolean(entry[1])).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join(",");
204
+ }
205
+ function decodeBaggage(header) {
206
+ if (!header) return {};
207
+ const parsed = {};
208
+ for (const part of header.split(",")) {
209
+ const [rawKey, ...rest] = part.split("=");
210
+ if (!rawKey || rest.length === 0) continue;
211
+ const key = rawKey.trim();
212
+ let value;
213
+ try {
214
+ value = decodeURIComponent(rest.join("=").trim());
215
+ } catch (e) {
216
+ value = rest.join("=").trim();
217
+ }
218
+ if (key in parsed && parsed[key] !== value) throw new ConflictingCarrierError(key);
219
+ parsed[key] = value;
220
+ }
221
+ return parsed;
222
+ }
223
+ function carrierBaggage(carrier) {
224
+ return {
225
+ [BAGGAGE_KEYS.eventId]: carrier.eventId,
226
+ [BAGGAGE_KEYS.childEventId]: carrier.childEventId,
227
+ [BAGGAGE_KEYS.name]: carrier.name,
228
+ [BAGGAGE_KEYS.convoId]: carrier.convoId,
229
+ [BAGGAGE_KEYS.userId]: carrier.userId,
230
+ [BAGGAGE_KEYS.dispatchSpanId]: carrier.spanId,
231
+ [BAGGAGE_KEYS.traceId]: carrier.traceId
232
+ };
233
+ }
234
+ function toHeaders(carrier) {
235
+ const fields = encodeBaggage(carrierBaggage(carrier));
236
+ const headers = {
237
+ [BAGGAGE_HEADER]: fields,
238
+ [HANDOFF_HEADER]: fields
239
+ };
240
+ if (isW3CTraceId(carrier.traceId) && isW3CSpanId(carrier.spanId)) {
241
+ headers[TRACEPARENT_HEADER] = `00-${carrier.traceId}-${carrier.spanId}-01`;
242
+ }
243
+ return headers;
244
+ }
245
+ function langsmithStamp() {
246
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "000000");
247
+ }
248
+ function toLangSmithHeaders(carrier) {
249
+ const stamp = langsmithStamp();
250
+ const dottedOrder = `${stamp}Z${carrier.traceId}.${stamp}Z${carrier.spanId}`;
251
+ return {
252
+ [LANGSMITH_TRACE_HEADER]: dottedOrder,
253
+ [BAGGAGE_HEADER]: encodeBaggage({
254
+ [LANGSMITH_METADATA_BAGGAGE_KEY]: JSON.stringify(carrierBaggage(carrier))
255
+ }),
256
+ // Carried here too: a LangSmith-shaped carrier is rewritten in transit
257
+ // exactly like the native one, and an injected `traceparent` is preferred
258
+ // over the dotted order on read.
259
+ [HANDOFF_HEADER]: encodeBaggage(carrierBaggage(carrier))
260
+ };
261
+ }
262
+ function isHeaderLookup(headers) {
263
+ return "get" in headers && typeof headers.get === "function";
264
+ }
265
+ var ConflictingCarrierError = class extends Error {
266
+ };
267
+ function readHeader(headers, name) {
268
+ var _a, _b, _c;
269
+ if (isHeaderLookup(headers)) return (_a = headers.get(name)) != null ? _a : void 0;
270
+ const value = (_c = headers[name]) != null ? _c : (_b = Object.entries(headers).find(([key]) => key.toLowerCase() === name)) == null ? void 0 : _b[1];
271
+ if (!Array.isArray(value)) return value;
272
+ const distinct = new Set(value);
273
+ if (distinct.size > 1) throw new ConflictingCarrierError(name);
274
+ return value[0];
275
+ }
276
+ function readTraceHeader(headers, name) {
277
+ const value = readHeader(headers, name);
278
+ if (!(value == null ? void 0 : value.includes(","))) return value;
279
+ const copies = value.split(",").map((copy) => copy.trim());
280
+ if (new Set(copies).size > 1) throw new ConflictingCarrierError(name);
281
+ return copies[0];
282
+ }
283
+ function fromHeaders(headers) {
284
+ var _a, _b;
285
+ let baggage;
286
+ let handoff;
287
+ let traceparent;
288
+ let langsmithTrace;
289
+ try {
290
+ baggage = decodeBaggage(readHeader(headers, BAGGAGE_HEADER));
291
+ handoff = decodeBaggage(readHeader(headers, HANDOFF_HEADER));
292
+ traceparent = readTraceHeader(headers, TRACEPARENT_HEADER);
293
+ langsmithTrace = readTraceHeader(headers, LANGSMITH_TRACE_HEADER);
294
+ } catch (error) {
295
+ if (error instanceof ConflictingCarrierError) return null;
296
+ throw error;
297
+ }
298
+ const langsmithMetadata = baggage[LANGSMITH_METADATA_BAGGAGE_KEY];
299
+ const nested = langsmithMetadata ? safeParseStringRecord(langsmithMetadata) : {};
300
+ for (const [key, value] of Object.entries(nested)) {
301
+ if (key in baggage && baggage[key] !== value) return null;
302
+ }
303
+ const fields = {
304
+ ...baggage,
305
+ ...nested,
306
+ // Last, so it wins: the standard headers may have been rewritten in transit
307
+ // by a propagator, this one is only ever written by us.
308
+ ...handoff
309
+ };
310
+ let traceId;
311
+ let spanId;
312
+ if (traceparent) {
313
+ const [, parsedTraceId, parsedSpanId] = traceparent.split("-");
314
+ if (isW3CTraceId(parsedTraceId) && isW3CSpanId(parsedSpanId)) {
315
+ traceId = parsedTraceId;
316
+ spanId = parsedSpanId;
317
+ }
318
+ }
319
+ if (!traceId && !spanId && langsmithTrace) {
320
+ const segments = langsmithTrace.split(".");
321
+ traceId = (_a = segments[0]) == null ? void 0 : _a.split("Z").pop();
322
+ spanId = (_b = segments[segments.length - 1]) == null ? void 0 : _b.split("Z").pop();
323
+ }
324
+ traceId = fields[BAGGAGE_KEYS.traceId] || traceId;
325
+ spanId = fields[BAGGAGE_KEYS.dispatchSpanId] || spanId;
326
+ const eventId = fields[BAGGAGE_KEYS.eventId];
327
+ if (!traceId || !spanId || !eventId) return null;
328
+ if (!isW3CTraceId(traceId) || !isW3CSpanId(spanId)) {
329
+ warnNonConformantIdsOnce(traceId, spanId);
330
+ }
331
+ const carrier = { traceId, spanId, eventId };
332
+ const childEventId = fields[BAGGAGE_KEYS.childEventId];
333
+ if (childEventId) carrier.childEventId = childEventId;
334
+ const name = fields[BAGGAGE_KEYS.name];
335
+ if (name) carrier.name = name;
336
+ const convoId = fields[BAGGAGE_KEYS.convoId];
337
+ if (convoId) carrier.convoId = convoId;
338
+ const userId = fields[BAGGAGE_KEYS.userId];
339
+ if (userId) carrier.userId = userId;
340
+ return carrier;
341
+ }
342
+ var UNRESOLVED_CARRIER_WARNING = `[raindrop] resume: headers were supplied but no hand-off carrier was found on them (searched ${HANDOFF_HEADER}, ${TRACEPARENT_HEADER}, ${BAGGAGE_HEADER}). This run reports as an UNLINKED event, and the launcher that dispatched it will stay on "queued" forever because nothing ever references its child. Passing headers means a parent handed off, so no carrier on them is almost certainly a defect: a gateway or proxy stripping ${HANDOFF_HEADER}, a middleware overwriting ${BAGGAGE_HEADER}, a request forwarded without its headers, or a hand-built carrier whose field names do not match. Send every header the launcher's dispatch returned. Logged once per process; pass no headers for a directly-invoked sub-agent to silence it.`;
343
+ var UNRESOLVED_CARRIER_WARNED_KEY = /* @__PURE__ */ Symbol.for("raindrop.handoff.warnedUnresolvedCarrier");
344
+ function warnedHolder() {
345
+ return globalThis;
346
+ }
347
+ function resetUnresolvedCarrierWarning() {
348
+ warnedHolder()[UNRESOLVED_CARRIER_WARNED_KEY] = false;
349
+ }
350
+ function warnUnresolvedCarrier(headers, carrier) {
351
+ if (carrier) return;
352
+ if (!headers) return;
353
+ const holder = warnedHolder();
354
+ if (holder[UNRESOLVED_CARRIER_WARNED_KEY]) return;
355
+ holder[UNRESOLVED_CARRIER_WARNED_KEY] = true;
356
+ console.warn(UNRESOLVED_CARRIER_WARNING);
357
+ }
358
+ function safeParseStringRecord(raw) {
359
+ try {
360
+ const parsed = JSON.parse(raw);
361
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
362
+ const result = {};
363
+ for (const [key, value] of Object.entries(parsed)) {
364
+ if (typeof value === "string") result[key] = value;
365
+ }
366
+ return result;
367
+ } catch (e) {
368
+ return {};
369
+ }
370
+ }
66
371
  function runWithTracingSuppressed(fn) {
67
372
  const hook = globalThis.RAINDROP_SUPPRESS_TRACING;
68
373
  if (typeof hook !== "function") return fn();
@@ -1550,7 +1855,7 @@ async function* asyncGeneratorWithCurrent(span, gen) {
1550
1855
  // package.json
1551
1856
  var package_default = {
1552
1857
  name: "@raindrop-ai/ai-sdk",
1553
- version: "0.2.1"};
1858
+ version: "0.3.0"};
1554
1859
 
1555
1860
  // src/internal/version.ts
1556
1861
  var libraryName = package_default.name;
@@ -2438,6 +2743,353 @@ function runWithParentToolContext(ctx, fn) {
2438
2743
  return getStorage2().run(ctx, fn);
2439
2744
  }
2440
2745
 
2746
+ // src/internal/subagents.ts
2747
+ var SUBAGENT_CANCELLED_OUTPUT = "Cancelled before producing a result.";
2748
+ var SUBAGENT_ABORTED_OUTPUT = "Aborted before producing a result.";
2749
+ var SUBAGENT_FAILED_OPERATION_ID = SUBAGENT_ABORT_OPERATION_ID;
2750
+ var MAX_SETTLED_EVENT_IDS = 1024;
2751
+ function isTraceCarrier(value) {
2752
+ const candidate = value;
2753
+ return typeof candidate.traceId === "string" && typeof candidate.spanId === "string" && typeof candidate.eventId === "string";
2754
+ }
2755
+ function attrsFrom(metadata) {
2756
+ return Object.entries(withMetadataPrefix(metadata)).map(([key, value]) => attrString(key, value));
2757
+ }
2758
+ function attrsExact(attributes) {
2759
+ return Object.entries(attributes).map(([key, value]) => attrString(key, value));
2760
+ }
2761
+ function handoffSpanAttrs(link) {
2762
+ if (!link) return [];
2763
+ return attrsFrom(detachedChildMetadata(link));
2764
+ }
2765
+ function subagentNameAttrs(name, link) {
2766
+ if (!name || (link == null ? void 0 : link.name)) return [];
2767
+ return attrsFrom({ [HANDOFF_ATTRIBUTE_SUFFIXES.name]: name });
2768
+ }
2769
+ function cancelledSpanAttrs() {
2770
+ return attrsExact(cancelledTerminalAttributes());
2771
+ }
2772
+ function describeAbortReason(reason) {
2773
+ if (reason instanceof Error) return `Aborted: ${reason.message}`;
2774
+ if (typeof reason === "string" && reason.trim().length > 0) return reason;
2775
+ if (reason === void 0 || reason === null) return SUBAGENT_ABORTED_OUTPUT;
2776
+ const serialized = boundedStringify(reason);
2777
+ return serialized ? `Aborted: ${serialized}` : SUBAGENT_ABORTED_OUTPUT;
2778
+ }
2779
+ function stampOpenSpan(span, metadata) {
2780
+ if (span.endTimeUnixNano) return;
2781
+ span.attributes.push(...attrsFrom(metadata));
2782
+ }
2783
+ function stampOpenSpanExact(span, attributes) {
2784
+ if (span.endTimeUnixNano) return;
2785
+ span.attributes.push(...attrsExact(attributes));
2786
+ }
2787
+ var SubagentApi = class {
2788
+ constructor(opts) {
2789
+ var _a;
2790
+ this.opts = opts;
2791
+ this.settledEventIds = (_a = opts.settledEventIds) != null ? _a : /* @__PURE__ */ new Set();
2792
+ }
2793
+ /** True when this child's outcome has already been reported. */
2794
+ wasSettledExplicitly(eventId) {
2795
+ return this.settledEventIds.has(eventId);
2796
+ }
2797
+ /**
2798
+ * Record an outcome reported somewhere other than `cancel()` / `fail()`, so
2799
+ * first-outcome-wins holds across every path that can state one.
2800
+ *
2801
+ * An aborted generation is such a path: an AbortSignal cancellation IS the
2802
+ * run's outcome, and the `fail(err)` that a catch block around the aborted
2803
+ * call naturally reports would otherwise error the child's spans — which is
2804
+ * the only thing separating `failed` from `cancelled`.
2805
+ */
2806
+ noteSettled(eventId) {
2807
+ this.remember(eventId);
2808
+ }
2809
+ remember(eventId) {
2810
+ if (this.settledEventIds.has(eventId)) return;
2811
+ if (this.settledEventIds.size >= MAX_SETTLED_EVENT_IDS) {
2812
+ const oldest = this.settledEventIds.values().next();
2813
+ if (!oldest.done) this.settledEventIds.delete(oldest.value);
2814
+ }
2815
+ this.settledEventIds.add(eventId);
2816
+ }
2817
+ /**
2818
+ * Record a detached sub-agent on this turn: allocate the child's event id,
2819
+ * stamp the dispatch, and return the headers to send with the job.
2820
+ *
2821
+ * This dispatches nothing — you do, moments later, with the returned headers.
2822
+ * Nothing here waits for the child either, or claims to know how it is doing.
2823
+ * Readers derive that from the child's own event.
2824
+ */
2825
+ subagent(options = {}) {
2826
+ var _a;
2827
+ const childEventId = (_a = options.childEventId) != null ? _a : randomUUID();
2828
+ const name = options.name;
2829
+ try {
2830
+ return this.recordLaunch(childEventId, name, options);
2831
+ } catch (err) {
2832
+ if (this.opts.debug) {
2833
+ console.warn(
2834
+ `[raindrop-ai/ai-sdk] sub-agent dispatch not recorded: ${err instanceof Error ? err.message : err}`
2835
+ );
2836
+ }
2837
+ return { childEventId, name, headers: {}, carrier: null };
2838
+ }
2839
+ }
2840
+ recordLaunch(childEventId, name, options) {
2841
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2842
+ const active = (_a = this.opts.spanSource) == null ? void 0 : _a.activeDispatch();
2843
+ const inherited = getContextManager().getParentSpanIds();
2844
+ const eventId = (_e = (_c = (_b = options.eventId) != null ? _b : active == null ? void 0 : active.eventId) != null ? _c : inherited == null ? void 0 : inherited.eventId) != null ? _e : (_d = this.opts.defaultContext) == null ? void 0 : _d.eventId;
2845
+ const userId = (_h = (_f = options.userId) != null ? _f : active == null ? void 0 : active.userId) != null ? _h : (_g = this.opts.defaultContext) == null ? void 0 : _g.userId;
2846
+ const convoId = (_k = (_i = options.convoId) != null ? _i : active == null ? void 0 : active.convoId) != null ? _k : (_j = this.opts.defaultContext) == null ? void 0 : _j.convoId;
2847
+ if (!eventId) {
2848
+ return { childEventId, name, headers: {}, carrier: null };
2849
+ }
2850
+ const dispatch = detachedDispatchMetadata({ childEventId, name });
2851
+ const toolEvents = toolEventsAllowMetadata();
2852
+ for (const span of (_l = active == null ? void 0 : active.turnSpans) != null ? _l : []) {
2853
+ stampOpenSpan(span, toolEvents);
2854
+ }
2855
+ let dispatchIds;
2856
+ if (active == null ? void 0 : active.dispatchSpan) {
2857
+ stampOpenSpan(active.dispatchSpan, dispatch);
2858
+ dispatchIds = active.dispatchSpan.ids;
2859
+ } else if (this.opts.sendTraces) {
2860
+ dispatchIds = this.synthesizeDispatchSpan({
2861
+ childEventId,
2862
+ name,
2863
+ toolName: options.toolName,
2864
+ eventId,
2865
+ userId,
2866
+ convoId,
2867
+ input: options.input,
2868
+ // No active turn means no telemetry setting to honor: `input` is then
2869
+ // recorded on the explicit say-so of whoever passed it.
2870
+ recordInputs: (_m = active == null ? void 0 : active.recordInputs) != null ? _m : true,
2871
+ dispatch,
2872
+ parent: (inherited == null ? void 0 : inherited.eventId) === eventId ? inherited : void 0
2873
+ }).ids;
2874
+ }
2875
+ const traceId = base64ToHex((_o = (_n = dispatchIds == null ? void 0 : dispatchIds.traceIdB64) != null ? _n : inherited == null ? void 0 : inherited.traceIdB64) != null ? _o : "");
2876
+ const spanId = base64ToHex((_p = dispatchIds == null ? void 0 : dispatchIds.spanIdB64) != null ? _p : "");
2877
+ if (!traceId || !spanId) {
2878
+ if (this.opts.debug) {
2879
+ console.warn(
2880
+ "[raindrop-ai/ai-sdk] sub-agent dispatch recorded without a carrier: no dispatch span to reference (traces disabled?)"
2881
+ );
2882
+ }
2883
+ return { childEventId, name, headers: {}, carrier: null };
2884
+ }
2885
+ const carrier = {
2886
+ traceId,
2887
+ spanId,
2888
+ eventId,
2889
+ childEventId,
2890
+ ...name ? { name } : {},
2891
+ ...convoId ? { convoId } : {},
2892
+ ...userId ? { userId } : {}
2893
+ };
2894
+ return { childEventId, name, headers: toHeaders(carrier), carrier };
2895
+ }
2896
+ /**
2897
+ * Record a dispatch span for a launch with no open tool-call span to decorate:
2898
+ * a launch from outside a tool's `execute`, or from a caller that is not an
2899
+ * LLM turn at all (an HTTP handler that enqueues jobs). Shaped as a tool call
2900
+ * so it reads identically to a model-issued launch.
2901
+ */
2902
+ synthesizeDispatchSpan(args) {
2903
+ var _a;
2904
+ const spanName = (_a = args.toolName) != null ? _a : DEFAULT_DISPATCH_SPAN_NAME;
2905
+ const span = this.opts.traceShipper.startSpan({
2906
+ name: spanName,
2907
+ parent: args.parent,
2908
+ eventId: args.eventId,
2909
+ userId: args.userId,
2910
+ convoId: args.convoId,
2911
+ operationId: "ai.toolCall",
2912
+ attributes: [
2913
+ attrString("operation.name", "ai.toolCall"),
2914
+ attrString("resource.name", spanName),
2915
+ attrString("ai.toolCall.name", spanName),
2916
+ attrString("ai.toolCall.id", `call_${args.childEventId.replace(/-/g, "").slice(0, 12)}`),
2917
+ // Gated like every other input the turn's spans record: a caller that
2918
+ // disabled input capture must not leak the payload through the one
2919
+ // span this API synthesizes on its behalf.
2920
+ ...args.recordInputs ? [attrString("ai.toolCall.args", boundedStringify(args.input))] : [],
2921
+ ...attrsFrom(args.dispatch)
2922
+ ]
2923
+ });
2924
+ this.opts.traceShipper.endSpan(span, {
2925
+ // A dispatch returns a handle, not an answer — the answer is the child's.
2926
+ attributes: [
2927
+ attrString(
2928
+ "ai.toolCall.result",
2929
+ boundedStringify({ jobId: args.childEventId, status: "accepted" })
2930
+ )
2931
+ ]
2932
+ });
2933
+ return span;
2934
+ }
2935
+ /**
2936
+ * Adopt a carrier as the current run's parent reference.
2937
+ *
2938
+ * A missing carrier is a legitimate state — the child was invoked directly
2939
+ * rather than dispatched — so this always returns a usable run and leaves
2940
+ * `parent` null. Call sites stay unconditional.
2941
+ */
2942
+ resume(carrierOrHeaders, options = {}) {
2943
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2944
+ const carrier = carrierOrHeaders ? isTraceCarrier(carrierOrHeaders) ? carrierOrHeaders : this.readCarrier(carrierOrHeaders) : null;
2945
+ warnUnresolvedCarrier(carrierOrHeaders, carrier);
2946
+ const name = (_a = carrier == null ? void 0 : carrier.name) != null ? _a : options.name;
2947
+ const eventId = (_c = (_b = carrier == null ? void 0 : carrier.childEventId) != null ? _b : options.eventId) != null ? _c : randomUUID();
2948
+ const userId = (_f = (_d = carrier == null ? void 0 : carrier.userId) != null ? _d : options.userId) != null ? _f : (_e = this.opts.defaultContext) == null ? void 0 : _e.userId;
2949
+ const convoId = (_i = (_g = carrier == null ? void 0 : carrier.convoId) != null ? _g : options.convoId) != null ? _i : (_h = this.opts.defaultContext) == null ? void 0 : _h.convoId;
2950
+ const parent = carrier ? {
2951
+ parentEventId: carrier.eventId,
2952
+ ...carrier.spanId ? { parentSpanId: carrier.spanId } : {},
2953
+ ...name ? { name } : {}
2954
+ } : null;
2955
+ return {
2956
+ eventId,
2957
+ name,
2958
+ userId,
2959
+ convoId,
2960
+ parent,
2961
+ metadata: {
2962
+ eventId,
2963
+ ...userId ? { userId } : {},
2964
+ ...convoId ? { convoId } : {},
2965
+ ...parent ? { subagent: parent } : {}
2966
+ },
2967
+ cancel: (reason) => this.settle(eventId, { userId, convoId, name, cancelled: true, output: reason }),
2968
+ fail: (reason) => this.settle(eventId, {
2969
+ userId,
2970
+ convoId,
2971
+ name,
2972
+ handoff: parent != null ? parent : void 0,
2973
+ cancelled: false,
2974
+ output: describeAbortReason(reason),
2975
+ error: reason
2976
+ })
2977
+ };
2978
+ }
2979
+ /**
2980
+ * A carrier arrives from outside this process, so a hostile or merely broken
2981
+ * header bag must cost the job its link, never its run.
2982
+ */
2983
+ readCarrier(headers) {
2984
+ try {
2985
+ return fromHeaders(headers);
2986
+ } catch (err) {
2987
+ if (this.opts.debug) {
2988
+ console.warn(
2989
+ `[raindrop-ai/ai-sdk] sub-agent carrier ignored: ${err instanceof Error ? err.message : err}`
2990
+ );
2991
+ }
2992
+ return null;
2993
+ }
2994
+ }
2995
+ /**
2996
+ * Mark a failed child's own spans as errored.
2997
+ *
2998
+ * Reporting the reason as output is what gets the child an event at all, but
2999
+ * output alone is not enough: status is derived from span shape, and a child
3000
+ * with final output and no error spans derives `finished`. A failed job
3001
+ * reporting success is worse than one reporting nothing, so the failure has
3002
+ * to land on the telemetry too, not just in the text.
3003
+ *
3004
+ * This is the child describing its own run, not a caller writing a status it
3005
+ * cannot observe — the child's own spans are exactly where the contract puts
3006
+ * failure.
3007
+ */
3008
+ recordFailureOnSpans(eventId, args, reason) {
3009
+ var _a, _b, _c;
3010
+ if (!this.opts.sendTraces) return;
3011
+ const failure = (_a = args.error) != null ? _a : reason;
3012
+ let marked = 0;
3013
+ for (const span2 of (_c = (_b = this.opts.spanSource) == null ? void 0 : _b.openSpansForEvent(eventId)) != null ? _c : []) {
3014
+ if (span2.endTimeUnixNano) continue;
3015
+ this.opts.traceShipper.endSpan(span2, { error: failure });
3016
+ marked++;
3017
+ }
3018
+ if (marked > 0) return;
3019
+ const spanName = SUBAGENT_ABORT_SPAN_NAME;
3020
+ const span = this.opts.traceShipper.startSpan({
3021
+ name: spanName,
3022
+ eventId,
3023
+ userId: args.userId,
3024
+ convoId: args.convoId,
3025
+ // Required, not decorative: ingest drops any span carrying no
3026
+ // `ai.operationId` (or traceloop / `gen_ai.*` key) and still answers 200,
3027
+ // so without this the failure disappears silently. The value is
3028
+ // deliberately none of the generate/stream/tool/embed forms, which is
3029
+ // what classifies the span as INTERNAL rather than mislabelling a failed
3030
+ // job as a model call or a tool call.
3031
+ operationId: SUBAGENT_FAILED_OPERATION_ID,
3032
+ // Carries the reverse reference like every other span the child emits:
3033
+ // this is often the child's ONLY span, and a span read on its own is the
3034
+ // whole reason the reference cannot live on the root alone. The name is
3035
+ // stamped even for an unlinked run, which has no caller to reference —
3036
+ // `span_name` no longer says which sub-agent this was, so the attribute
3037
+ // is the only thing that can.
3038
+ attributes: [
3039
+ attrString("resource.name", spanName),
3040
+ ...handoffSpanAttrs(args.handoff),
3041
+ ...subagentNameAttrs(args.name, args.handoff)
3042
+ ]
3043
+ });
3044
+ this.opts.traceShipper.endSpan(span, { error: failure });
3045
+ }
3046
+ async settle(eventId, args) {
3047
+ var _a, _b;
3048
+ if (this.settledEventIds.has(eventId)) {
3049
+ if (this.opts.debug) {
3050
+ console.warn(
3051
+ `[raindrop-ai/ai-sdk] sub-agent ${eventId} already reported an outcome; ignoring the second one`
3052
+ );
3053
+ }
3054
+ return;
3055
+ }
3056
+ this.remember(eventId);
3057
+ const output = args.output && args.output.trim().length > 0 ? args.output : args.cancelled ? SUBAGENT_CANCELLED_OUTPUT : SUBAGENT_ABORTED_OUTPUT;
3058
+ try {
3059
+ if (args.cancelled) {
3060
+ for (const span of (_b = (_a = this.opts.spanSource) == null ? void 0 : _a.openSpansForEvent(eventId)) != null ? _b : []) {
3061
+ stampOpenSpanExact(span, cancelledTerminalAttributes());
3062
+ }
3063
+ } else {
3064
+ this.recordFailureOnSpans(eventId, args, output);
3065
+ }
3066
+ } catch (err) {
3067
+ if (this.opts.debug) {
3068
+ console.warn(
3069
+ `[raindrop-ai/ai-sdk] sub-agent outcome not recorded on spans: ${err instanceof Error ? err.message : err}`
3070
+ );
3071
+ }
3072
+ }
3073
+ if (!this.opts.sendEvents) return;
3074
+ await this.opts.eventShipper.patch(eventId, {
3075
+ userId: args.userId,
3076
+ convoId: args.convoId,
3077
+ // An event is only created from a run that reported something. A child
3078
+ // that dies silently produces no event at all, which pins the caller on
3079
+ // `queued` forever — indistinguishable from a job that never started.
3080
+ output,
3081
+ ...args.cancelled ? { properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED } } : {},
3082
+ isPending: false
3083
+ }).catch((err) => {
3084
+ if (this.opts.debug) {
3085
+ console.warn(
3086
+ `[raindrop-ai/ai-sdk] sub-agent outcome patch failed: ${err instanceof Error ? err.message : err}`
3087
+ );
3088
+ }
3089
+ });
3090
+ }
3091
+ };
3092
+
2441
3093
  // src/internal/usage.ts
2442
3094
  function firstTokenCount(...values) {
2443
3095
  for (const value of values) {
@@ -2630,6 +3282,7 @@ var RaindropTelemetryIntegration = class {
2630
3282
  eventName: (_f = callMeta.eventName) != null ? _f : (_e = this.defaultContext) == null ? void 0 : _e.eventName
2631
3283
  };
2632
3284
  const inherited = getContextManager().getParentSpanIds();
3285
+ const handoff = readDetachedChildLink(metadata);
2633
3286
  const eventIdGenerated = (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === "true" || (metadata == null ? void 0 : metadata["raindrop.internal.eventIdGenerated"]) === true || (callContextMetadata == null ? void 0 : callContextMetadata.eventIdGenerated) === true;
2634
3287
  const explicitEventId = callMeta.eventId && !eventIdGenerated ? callMeta.eventId : void 0;
2635
3288
  const eventId = (_j = (_i = (_h = explicitEventId != null ? explicitEventId : (_g = this.defaultContext) == null ? void 0 : _g.eventId) != null ? _h : inherited == null ? void 0 : inherited.eventId) != null ? _i : callMeta.eventId) != null ? _j : randomUUID();
@@ -2659,7 +3312,10 @@ var RaindropTelemetryIntegration = class {
2659
3312
  attrString("ai.toolCall.name", subagentName),
2660
3313
  attrString("raindrop.subagent.name", subagentName),
2661
3314
  attrString("raindrop.agent.role", "subagent"),
2662
- ...parentAttrs
3315
+ ...parentAttrs,
3316
+ // Top of this child's tree, so the reverse reference matters as much
3317
+ // here as on the root: these are the spans a reader lands on first.
3318
+ ...handoffSpanAttrs(handoff)
2663
3319
  ]
2664
3320
  });
2665
3321
  const subagentParentRef = this.spanParentRef(subagentToolCallSpan);
@@ -2672,7 +3328,8 @@ var RaindropTelemetryIntegration = class {
2672
3328
  attributes: [
2673
3329
  attrString("operation.name", "agent.subagent"),
2674
3330
  attrString("raindrop.span.kind", "llm_call"),
2675
- attrString("raindrop.subagent.name", subagentName)
3331
+ attrString("raindrop.subagent.name", subagentName),
3332
+ ...handoffSpanAttrs(handoff)
2676
3333
  ]
2677
3334
  });
2678
3335
  this.traceShipper.endSpan(markerSpan);
@@ -2740,7 +3397,9 @@ var RaindropTelemetryIntegration = class {
2740
3397
  inputText: isEmbed ? void 0 : this.extractInputText(event),
2741
3398
  toolCallCount: 0,
2742
3399
  subagentName,
2743
- subagentToolCallSpan
3400
+ subagentToolCallSpan,
3401
+ handoff,
3402
+ nestedInEvent: inheritedParent !== void 0
2744
3403
  });
2745
3404
  };
2746
3405
  // ── onStepStart ─────────────────────────────────────────────────────────
@@ -2785,7 +3444,8 @@ var RaindropTelemetryIntegration = class {
2785
3444
  ...attrsFromModelProvider(event.provider),
2786
3445
  attrString("ai.model.id", event.modelId),
2787
3446
  attrString(MODEL_USAGE_ATTRIBUTES.requestModel, event.modelId),
2788
- ...inputAttrs
3447
+ ...inputAttrs,
3448
+ ...handoffSpanAttrs(state.handoff)
2789
3449
  ]
2790
3450
  });
2791
3451
  state.stepSpan = stepSpan;
@@ -2924,7 +3584,8 @@ var RaindropTelemetryIntegration = class {
2924
3584
  attrString("operation.name", operationName),
2925
3585
  attrString("resource.name", resourceName),
2926
3586
  attrString("ai.telemetry.functionId", state.functionId),
2927
- ...inputAttrs
3587
+ ...inputAttrs,
3588
+ ...handoffSpanAttrs(state.handoff)
2928
3589
  ]
2929
3590
  });
2930
3591
  state.embedSpans.set(event.embedCallId, embedSpan);
@@ -2996,15 +3657,26 @@ var RaindropTelemetryIntegration = class {
2996
3657
  this.traceShipper.endSpan(toolSpan, { error: actualError });
2997
3658
  }
2998
3659
  state.toolSpans.clear();
3660
+ const abortReason = describeAbortReason(actualError);
2999
3661
  if (state.rootSpan) {
3000
- this.traceShipper.endSpan(state.rootSpan, { error: actualError });
3662
+ this.traceShipper.endSpan(state.rootSpan, {
3663
+ error: actualError,
3664
+ attributes: this.abortOutcomeAttrs(state, abortReason, "error")
3665
+ });
3001
3666
  }
3002
3667
  if (state.subagentToolCallSpan) {
3003
3668
  this.traceShipper.endSpan(state.subagentToolCallSpan, { error: actualError });
3004
3669
  }
3005
3670
  const isEmbed = state.operationId === "ai.embed" || state.operationId === "ai.embedMany";
3006
3671
  if (!isEmbed) {
3007
- this.finalizeGenerateEvent(state, state.accumulatedText || void 0, void 0);
3672
+ const errorIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3673
+ this.finalizeGenerateEvent(
3674
+ state,
3675
+ state.accumulatedText || void 0,
3676
+ void 0,
3677
+ false,
3678
+ errorIsTheRunsOutcome ? { fallbackOutput: abortReason } : void 0
3679
+ );
3008
3680
  }
3009
3681
  this.cleanup(event.callId);
3010
3682
  };
@@ -3041,9 +3713,19 @@ var RaindropTelemetryIntegration = class {
3041
3713
  this.traceShipper.endSpan(toolSpan, { attributes: [abortedAttr] });
3042
3714
  }
3043
3715
  state.toolSpans.clear();
3716
+ const abortIsTheRunsOutcome = state.handoff !== void 0 && !state.nestedInEvent;
3044
3717
  if (state.rootSpan) {
3045
3718
  this.traceShipper.endSpan(state.rootSpan, {
3046
- attributes: [abortedAttr, attrInt("ai.toolCall.count", state.toolCallCount)]
3719
+ attributes: [
3720
+ abortedAttr,
3721
+ attrInt("ai.toolCall.count", state.toolCallCount),
3722
+ // An aborted detached child IS a cancelled sub-agent, and a cancelled
3723
+ // run is span-for-span identical to a finished one — spans close,
3724
+ // nothing errors, there is just no answer. So it is the one outcome
3725
+ // that has to be stated, and the child states it on itself.
3726
+ ...abortIsTheRunsOutcome ? cancelledSpanAttrs() : [],
3727
+ ...abortIsTheRunsOutcome ? this.abortOutcomeAttrs(state, SUBAGENT_CANCELLED_OUTPUT, "stop") : []
3728
+ ]
3047
3729
  });
3048
3730
  }
3049
3731
  if (state.subagentToolCallSpan) {
@@ -3051,7 +3733,17 @@ var RaindropTelemetryIntegration = class {
3051
3733
  attributes: [abortedAttr]
3052
3734
  });
3053
3735
  }
3054
- this.finalizeGenerateEvent(state, state.accumulatedText || void 0, void 0);
3736
+ this.finalizeGenerateEvent(
3737
+ state,
3738
+ state.accumulatedText || void 0,
3739
+ void 0,
3740
+ false,
3741
+ abortIsTheRunsOutcome ? {
3742
+ fallbackOutput: SUBAGENT_CANCELLED_OUTPUT,
3743
+ properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
3744
+ } : void 0
3745
+ );
3746
+ if (abortIsTheRunsOutcome) this.subagents.noteSettled(state.eventId);
3055
3747
  this.cleanup(callId);
3056
3748
  };
3057
3749
  // ── executeTool ─────────────────────────────────────────────────────────
@@ -3079,6 +3771,97 @@ var RaindropTelemetryIntegration = class {
3079
3771
  this.subagentWrapping = opts.subagentWrapping !== false;
3080
3772
  this.debug = opts.debug === true;
3081
3773
  this.defaultContext = opts.context;
3774
+ this.subagents = new SubagentApi({
3775
+ traceShipper: this.traceShipper,
3776
+ eventShipper: this.eventShipper,
3777
+ sendTraces: this.sendTraces,
3778
+ sendEvents: this.sendEvents,
3779
+ debug: this.debug,
3780
+ defaultContext: this.defaultContext,
3781
+ settledEventIds: opts.settledEventIds,
3782
+ spanSource: {
3783
+ activeDispatch: () => this.activeDispatch(),
3784
+ openSpansForEvent: (eventId) => this.openSpansForEvent(eventId)
3785
+ }
3786
+ });
3787
+ }
3788
+ /**
3789
+ * Record a detached sub-agent on the turn that is live right now.
3790
+ *
3791
+ * Returns the dispatch — the child's event id and the headers to send with
3792
+ * the job. Dispatching is still yours to do; this only states that you are
3793
+ * about to, so a reader can follow the link before the child exists.
3794
+ */
3795
+ subagent(options = {}) {
3796
+ return this.subagents.subagent(options);
3797
+ }
3798
+ // ── detached sub-agent hand-offs ─────────────────────────────────────────
3799
+ /**
3800
+ * The turn a `subagent()` dispatch is happening inside.
3801
+ *
3802
+ * Resolved from the parent-tool context first, which is the only way to reach
3803
+ * the EXACT span that dispatched: the tool call the model itself issued, still
3804
+ * open while its `execute` runs. Falling back to the event id lets a launch
3805
+ * from elsewhere in the turn (a queue producer called mid-generation) still
3806
+ * find the turn's spans, which is where the tool-events opt-in has to land.
3807
+ */
3808
+ activeDispatch() {
3809
+ var _a;
3810
+ const parentTool = getCurrentParentToolContext();
3811
+ let state = parentTool ? this.getState(parentTool.parentCallId) : void 0;
3812
+ const inheritedEventId = (_a = getContextManager().getParentSpanIds()) == null ? void 0 : _a.eventId;
3813
+ if (!state && inheritedEventId) {
3814
+ for (const candidate of this.callStates.values()) {
3815
+ if (candidate.eventId === inheritedEventId) {
3816
+ state = candidate;
3817
+ break;
3818
+ }
3819
+ }
3820
+ }
3821
+ if (!state) return void 0;
3822
+ return {
3823
+ eventId: state.eventId,
3824
+ userId: state.identity.userId,
3825
+ convoId: state.identity.convoId,
3826
+ dispatchSpan: parentTool ? state.toolSpans.get(parentTool.toolCallId) : void 0,
3827
+ turnSpans: [state.rootSpan, state.stepSpan].filter(
3828
+ (span) => span !== void 0
3829
+ ),
3830
+ recordInputs: state.recordInputs
3831
+ };
3832
+ }
3833
+ /** Spans still open for an event, so a late outcome can still be stated. */
3834
+ openSpansForEvent(eventId) {
3835
+ const spans = [];
3836
+ for (const state of this.callStates.values()) {
3837
+ if (state.eventId !== eventId) continue;
3838
+ if (state.rootSpan) spans.push(state.rootSpan);
3839
+ if (state.stepSpan) spans.push(state.stepSpan);
3840
+ }
3841
+ return spans;
3842
+ }
3843
+ /**
3844
+ * End-attributes that keep a detached child legible when it ends without an
3845
+ * answer — an error, an abort, a cancellation.
3846
+ *
3847
+ * An event is created from an LLM span only when it has a finish reason and
3848
+ * non-empty output, so a child that dies silently produces NO event, and the
3849
+ * caller's hand-off pill stays on `queued` forever — indistinguishable from a
3850
+ * job that never started. Reporting the abort reason as the run's output is
3851
+ * what makes the outcome visible. Only detached children get this: an inline
3852
+ * generation's failure is already legible from its caller's own event.
3853
+ *
3854
+ * And only the run's OUTERMOST generation gets it (see `nestedInEvent`): an
3855
+ * inner sub-call ending badly is not the run ending, and since an event is
3856
+ * created from an LLM span with output, `ai.response.text` here would state
3857
+ * the run's outcome through the span while the turn is still working.
3858
+ */
3859
+ abortOutcomeAttrs(state, reason, finishReason) {
3860
+ if (!state.handoff || state.nestedInEvent) return [];
3861
+ return [
3862
+ attrString("ai.response.text", capText2(state.accumulatedText || reason)),
3863
+ attrString("ai.response.finishReason", finishReason)
3864
+ ];
3082
3865
  }
3083
3866
  // ── helpers ──────────────────────────────────────────────────────────────
3084
3867
  getState(callId) {
@@ -3197,7 +3980,8 @@ var RaindropTelemetryIntegration = class {
3197
3980
  attrString("ai.telemetry.functionId", state.functionId),
3198
3981
  attrString("ai.toolCall.name", toolCall.toolName),
3199
3982
  attrString("ai.toolCall.id", toolCall.toolCallId),
3200
- ...inputAttrs
3983
+ ...inputAttrs,
3984
+ ...handoffSpanAttrs(state.handoff)
3201
3985
  ]
3202
3986
  });
3203
3987
  state.toolSpans.set(toolCall.toolCallId, toolSpan);
@@ -3276,7 +4060,8 @@ var RaindropTelemetryIntegration = class {
3276
4060
  attrString("ai.toolCall.name", call.toolName),
3277
4061
  attrString("ai.toolCall.id", call.toolCallId),
3278
4062
  attrString("ai.toolCall.providerExecuted", "true"),
3279
- ...inputAttrs
4063
+ ...inputAttrs,
4064
+ ...handoffSpanAttrs(state.handoff)
3280
4065
  ]
3281
4066
  });
3282
4067
  state.toolCallCount += 1;
@@ -3357,19 +4142,22 @@ var RaindropTelemetryIntegration = class {
3357
4142
  * is finalized by that resume — otherwise each execution would finalize the
3358
4143
  * same event ID into a separate canonical row.
3359
4144
  */
3360
- finalizeGenerateEvent(state, output, model, keepPending = false) {
4145
+ finalizeGenerateEvent(state, output, model, keepPending = false, detachedOutcome) {
3361
4146
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3362
4147
  const suppressSubagentEvent = state.subagentName !== void 0 && state.subagentToolCallSpan !== void 0;
3363
4148
  if (!this.sendEvents || suppressSubagentEvent) return;
4149
+ if (this.subagents.wasSettledExplicitly(state.eventId)) return;
3364
4150
  const callMeta = this.extractRaindropMetadata(state.metadata);
3365
4151
  const userId = (_b = callMeta.userId) != null ? _b : (_a = this.defaultContext) == null ? void 0 : _a.userId;
3366
4152
  if (!userId) return;
3367
4153
  const eventName = (_e = (_d = callMeta.eventName) != null ? _d : (_c = this.defaultContext) == null ? void 0 : _c.eventName) != null ? _e : state.operationId;
3368
4154
  const cappedOutput = capText2(output);
4155
+ const reportedOutput = state.handoff && detachedOutcome && !(cappedOutput == null ? void 0 : cappedOutput.trim()) ? detachedOutcome.fallbackOutput : cappedOutput;
3369
4156
  const input = capText2(state.inputText);
3370
4157
  const properties = {
3371
4158
  ...(_f = this.defaultContext) == null ? void 0 : _f.properties,
3372
- ...callMeta.properties
4159
+ ...callMeta.properties,
4160
+ ...state.handoff ? detachedOutcome == null ? void 0 : detachedOutcome.properties : void 0
3373
4161
  };
3374
4162
  const featureFlags = {
3375
4163
  ...((_g = this.defaultContext) == null ? void 0 : _g.featureFlags) ? normalizeFeatureFlags(this.defaultContext.featureFlags) : {},
@@ -3381,7 +4169,7 @@ var RaindropTelemetryIntegration = class {
3381
4169
  userId,
3382
4170
  convoId,
3383
4171
  input,
3384
- output: cappedOutput,
4172
+ output: reportedOutput,
3385
4173
  model,
3386
4174
  properties: Object.keys(properties).length > 0 ? properties : void 0,
3387
4175
  featureFlags: Object.keys(featureFlags).length > 0 ? featureFlags : void 0,
@@ -4293,6 +5081,7 @@ function wrapAISDK(aiSDK, deps) {
4293
5081
  sendTraces: ((_a = deps.options.send) == null ? void 0 : _a.traces) !== false,
4294
5082
  sendEvents: ((_b = deps.options.send) == null ? void 0 : _b.events) !== false,
4295
5083
  debug,
5084
+ settledEventIds: deps.settledEventIds,
4296
5085
  context: {
4297
5086
  userId: wrapTimeCtx.userId,
4298
5087
  eventId: wrapTimeCtx.eventId,
@@ -5502,6 +6291,8 @@ function eventMetadata(options) {
5502
6291
  if (options.properties) result["raindrop.properties"] = JSON.stringify(options.properties);
5503
6292
  if (options.featureFlags)
5504
6293
  result["raindrop.featureFlags"] = JSON.stringify(normalizeFeatureFlags(options.featureFlags));
6294
+ if (options.subagent) Object.assign(result, detachedChildMetadata(options.subagent));
6295
+ if (options.toolEvents) result[TOOL_EVENTS_SUFFIX] = options.toolEvents;
5505
6296
  return result;
5506
6297
  }
5507
6298
  function deriveChatTurnMessageId(request) {
@@ -5584,12 +6375,22 @@ function createRaindropAISDK(opts) {
5584
6375
  transformSpan: (_j = opts.traces) == null ? void 0 : _j.transformSpan,
5585
6376
  disableDefaultRedaction: (_k = opts.traces) == null ? void 0 : _k.disableDefaultRedaction
5586
6377
  });
6378
+ const settledEventIds = /* @__PURE__ */ new Set();
6379
+ const subagentApi = new SubagentApi({
6380
+ traceShipper,
6381
+ eventShipper,
6382
+ sendTraces: tracesEnabled,
6383
+ sendEvents: eventsEnabled,
6384
+ debug: envDebug,
6385
+ settledEventIds
6386
+ });
5587
6387
  return {
5588
6388
  wrap(aiSDK, options) {
5589
6389
  return wrapAISDK(aiSDK, {
5590
6390
  options: options != null ? options : {},
5591
6391
  eventShipper,
5592
- traceShipper
6392
+ traceShipper,
6393
+ settledEventIds
5593
6394
  });
5594
6395
  },
5595
6396
  createSelfDiagnosticsTool(options = {}) {
@@ -5626,9 +6427,14 @@ function createRaindropAISDK(opts) {
5626
6427
  sendEvents: eventsEnabled,
5627
6428
  subagentWrapping,
5628
6429
  debug: envDebug,
6430
+ settledEventIds,
5629
6431
  context
5630
6432
  });
5631
6433
  },
6434
+ subagents: subagentApi,
6435
+ subagent(options = {}) {
6436
+ return subagentApi.subagent(options);
6437
+ },
5632
6438
  events: {
5633
6439
  async patch(eventId, patch) {
5634
6440
  await eventShipper.patch(eventId, patch);
@@ -5751,8 +6557,17 @@ function raindrop(options = {}) {
5751
6557
  exports.DEFAULT_MAX_TEXT_FIELD_CHARS = DEFAULT_MAX_TEXT_FIELD_CHARS2;
5752
6558
  exports.DEFAULT_REDACT_ATTRIBUTE_KEYS = DEFAULT_REDACT_ATTRIBUTE_KEYS;
5753
6559
  exports.DEFAULT_SECRET_KEY_NAMES = DEFAULT_SECRET_KEY_NAMES;
6560
+ exports.DETACHED_MODE = DETACHED_MODE;
6561
+ exports.HANDOFF_ATTRIBUTE_PREFIXES = HANDOFF_ATTRIBUTE_PREFIXES;
6562
+ exports.HANDOFF_ATTRIBUTE_SUFFIXES = HANDOFF_ATTRIBUTE_SUFFIXES;
6563
+ exports.HANDOFF_TERMINAL_CANCELLED = HANDOFF_TERMINAL_CANCELLED;
6564
+ exports.HANDOFF_TERMINAL_PROPERTY_KEY = HANDOFF_TERMINAL_PROPERTY_KEY;
5754
6565
  exports.REDACTED_PLACEHOLDER = REDACTED_PLACEHOLDER;
5755
6566
  exports.RaindropTelemetryIntegration = RaindropTelemetryIntegration;
6567
+ exports.SUBAGENT_ABORTED_OUTPUT = SUBAGENT_ABORTED_OUTPUT;
6568
+ exports.SUBAGENT_AGENT_ROLE = SUBAGENT_AGENT_ROLE;
6569
+ exports.SUBAGENT_CANCELLED_OUTPUT = SUBAGENT_CANCELLED_OUTPUT;
6570
+ exports.TOOL_EVENTS_ALLOW = TOOL_EVENTS_ALLOW;
5756
6571
  exports.TRUNCATION_MARKER = TRUNCATION_MARKER2;
5757
6572
  exports._resetParentToolContextStorage = _resetParentToolContextStorage;
5758
6573
  exports._resetRaindropCallMetadataStorage = _resetRaindropCallMetadataStorage;
@@ -5766,6 +6581,7 @@ exports.defaultTransformSpan = defaultTransformSpan;
5766
6581
  exports.enterParentToolContext = enterParentToolContext;
5767
6582
  exports.eventMetadata = eventMetadata;
5768
6583
  exports.eventMetadataFromChatRequest = eventMetadataFromChatRequest;
6584
+ exports.fromHeaders = fromHeaders;
5769
6585
  exports.getContextManager = getContextManager;
5770
6586
  exports.getCurrentParentToolContext = getCurrentParentToolContext;
5771
6587
  exports.getCurrentRaindropCallMetadata = getCurrentRaindropCallMetadata;
@@ -5774,6 +6590,9 @@ exports.raindrop = raindrop;
5774
6590
  exports.readRaindropCallMetadataFromArgs = readRaindropCallMetadataFromArgs;
5775
6591
  exports.redactJsonAttributeValue = redactJsonAttributeValue;
5776
6592
  exports.redactSecretsInObject = redactSecretsInObject;
6593
+ exports.resetUnresolvedCarrierWarning = resetUnresolvedCarrierWarning;
5777
6594
  exports.runWithParentToolContext = runWithParentToolContext;
5778
6595
  exports.runWithRaindropCallMetadata = runWithRaindropCallMetadata;
6596
+ exports.toHeaders = toHeaders;
6597
+ exports.toLangSmithHeaders = toLangSmithHeaders;
5779
6598
  exports.withCurrent = withCurrent;