@raindrop-ai/ai-sdk 0.0.19-beta.3 → 0.0.19

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.
@@ -0,0 +1,3314 @@
1
+ // ../core/dist/chunk-H6VSZSLN.js
2
+ function getCrypto() {
3
+ const c = globalThis.crypto;
4
+ return c;
5
+ }
6
+ function randomBytes(length) {
7
+ const cryptoObj = getCrypto();
8
+ const out = new Uint8Array(length);
9
+ if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
10
+ cryptoObj.getRandomValues(out);
11
+ return out;
12
+ }
13
+ for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
14
+ return out;
15
+ }
16
+ function randomUUID() {
17
+ const cryptoObj = getCrypto();
18
+ if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
19
+ return cryptoObj.randomUUID();
20
+ }
21
+ const b = randomBytes(16);
22
+ b[6] = b[6] & 15 | 64;
23
+ b[8] = b[8] & 63 | 128;
24
+ const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
25
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
26
+ }
27
+ function base64Encode(bytes) {
28
+ const maybeBuffer = globalThis.Buffer;
29
+ if (maybeBuffer) {
30
+ return maybeBuffer.from(bytes).toString("base64");
31
+ }
32
+ let binary = "";
33
+ for (let i2 = 0; i2 < bytes.length; i2++) {
34
+ binary += String.fromCharCode(bytes[i2]);
35
+ }
36
+ const btoaFn = globalThis.btoa;
37
+ if (typeof btoaFn === "function") return btoaFn(binary);
38
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
39
+ let out = "";
40
+ let i = 0;
41
+ while (i < binary.length) {
42
+ const c1 = binary.charCodeAt(i++) & 255;
43
+ const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
44
+ const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
45
+ const e1 = c1 >> 2;
46
+ const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
47
+ const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
48
+ const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
49
+ out += alphabet.charAt(e1);
50
+ out += alphabet.charAt(e2);
51
+ out += e3 === 64 ? "=" : alphabet.charAt(e3);
52
+ out += e4 === 64 ? "=" : alphabet.charAt(e4);
53
+ }
54
+ return out;
55
+ }
56
+ function wait(ms) {
57
+ return new Promise((resolve) => setTimeout(resolve, ms));
58
+ }
59
+ function formatEndpoint(endpoint) {
60
+ if (!endpoint) return void 0;
61
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
62
+ }
63
+ function parseRetryAfter(headers) {
64
+ var _a;
65
+ const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
66
+ if (!value) return void 0;
67
+ const asNumber = Number(value);
68
+ if (value.trim() !== "" && !Number.isNaN(asNumber)) return asNumber * 1e3;
69
+ const asDate = new Date(value).getTime();
70
+ if (!Number.isNaN(asDate)) {
71
+ const delta = asDate - Date.now();
72
+ return delta > 0 ? delta : 0;
73
+ }
74
+ return void 0;
75
+ }
76
+ function getRetryDelayMs(attemptNumber, previousError) {
77
+ if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
78
+ const v = previousError.retryAfterMs;
79
+ if (typeof v === "number") return Math.max(0, v);
80
+ }
81
+ if (attemptNumber <= 1) return 0;
82
+ const base = 500;
83
+ const factor = Math.pow(2, attemptNumber - 2);
84
+ return base * factor;
85
+ }
86
+ async function withRetry(operation, opName2, opts) {
87
+ const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
88
+ let lastError = void 0;
89
+ for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
90
+ if (attemptNumber > 1) {
91
+ const delay = getRetryDelayMs(attemptNumber, lastError);
92
+ if (opts.debug) {
93
+ console.warn(
94
+ `${prefix} ${opName2} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
95
+ );
96
+ }
97
+ if (delay > 0) await wait(delay);
98
+ } else if (opts.debug) {
99
+ console.log(`${prefix} ${opName2} attempt ${attemptNumber}/${opts.maxAttempts}`);
100
+ }
101
+ try {
102
+ return await operation();
103
+ } catch (err) {
104
+ lastError = err;
105
+ if (opts.debug) {
106
+ const msg = err instanceof Error ? err.message : String(err);
107
+ console.warn(
108
+ `${prefix} ${opName2} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
109
+ );
110
+ }
111
+ if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
112
+ break;
113
+ if (attemptNumber === opts.maxAttempts) break;
114
+ }
115
+ }
116
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
117
+ }
118
+ async function postJson(url, body, headers, opts) {
119
+ const opName2 = `POST ${url}`;
120
+ await withRetry(
121
+ async () => {
122
+ const resp = await fetch(url, {
123
+ method: "POST",
124
+ headers: {
125
+ "Content-Type": "application/json",
126
+ ...headers
127
+ },
128
+ body: JSON.stringify(body)
129
+ });
130
+ if (!resp.ok) {
131
+ const text = await resp.text().catch(() => "");
132
+ const err = new Error(
133
+ `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
134
+ );
135
+ const retryAfterMs = parseRetryAfter(resp.headers);
136
+ if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
137
+ err.retryable = resp.status === 429 || resp.status >= 500;
138
+ throw err;
139
+ }
140
+ },
141
+ opName2,
142
+ opts
143
+ );
144
+ }
145
+ var SpanStatusCode = {
146
+ ERROR: 2
147
+ };
148
+ function createSpanIds(parent) {
149
+ const traceId = parent ? parent.traceIdB64 : base64Encode(randomBytes(16));
150
+ const spanId = base64Encode(randomBytes(8));
151
+ return {
152
+ traceIdB64: traceId,
153
+ spanIdB64: spanId,
154
+ parentSpanIdB64: parent ? parent.spanIdB64 : void 0
155
+ };
156
+ }
157
+ function nowUnixNanoString() {
158
+ return Date.now().toString() + "000000";
159
+ }
160
+ function attrString(key, value) {
161
+ if (value === void 0) return void 0;
162
+ return { key, value: { stringValue: value } };
163
+ }
164
+ function attrInt(key, value) {
165
+ if (value === void 0) return void 0;
166
+ if (!Number.isFinite(value)) return void 0;
167
+ return { key, value: { intValue: String(Math.trunc(value)) } };
168
+ }
169
+ function attrDouble(key, value) {
170
+ if (value === void 0) return void 0;
171
+ if (!Number.isFinite(value)) return void 0;
172
+ return { key, value: { doubleValue: value } };
173
+ }
174
+ function attrBool(key, value) {
175
+ if (value === void 0) return void 0;
176
+ return { key, value: { boolValue: value } };
177
+ }
178
+ function attrStringArray(key, values) {
179
+ if (!values || values.length === 0) return void 0;
180
+ return {
181
+ key,
182
+ value: {
183
+ arrayValue: {
184
+ values: values.filter((v) => typeof v === "string").map((v) => ({ stringValue: v }))
185
+ }
186
+ }
187
+ };
188
+ }
189
+ function buildOtlpSpan(args) {
190
+ const attrs = args.attributes.filter((x) => x !== void 0);
191
+ const span = {
192
+ traceId: args.ids.traceIdB64,
193
+ spanId: args.ids.spanIdB64,
194
+ name: args.name,
195
+ startTimeUnixNano: args.startTimeUnixNano,
196
+ endTimeUnixNano: args.endTimeUnixNano
197
+ };
198
+ if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
199
+ if (attrs.length) span.attributes = attrs;
200
+ if (args.status) span.status = args.status;
201
+ return span;
202
+ }
203
+ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", serviceVersion = "0.0.0") {
204
+ return {
205
+ resourceSpans: [
206
+ {
207
+ resource: {
208
+ attributes: [{ key: "service.name", value: { stringValue: serviceName } }]
209
+ },
210
+ scopeSpans: [
211
+ {
212
+ scope: { name: serviceName, version: serviceVersion },
213
+ spans
214
+ }
215
+ ]
216
+ }
217
+ ]
218
+ };
219
+ }
220
+ function mergePatches(target, source) {
221
+ var _a, _b, _c, _d;
222
+ const out = { ...target, ...source };
223
+ if (target.properties || source.properties) {
224
+ out.properties = { ...(_a = target.properties) != null ? _a : {}, ...(_b = source.properties) != null ? _b : {} };
225
+ }
226
+ if (target.attachments || source.attachments) {
227
+ out.attachments = [...(_c = target.attachments) != null ? _c : [], ...(_d = source.attachments) != null ? _d : []];
228
+ }
229
+ return out;
230
+ }
231
+ var EventShipper = class {
232
+ constructor(opts) {
233
+ this.buffers = /* @__PURE__ */ new Map();
234
+ this.sticky = /* @__PURE__ */ new Map();
235
+ this.timers = /* @__PURE__ */ new Map();
236
+ this.inFlight = /* @__PURE__ */ new Set();
237
+ var _a, _b, _c, _d, _e, _f, _g;
238
+ this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
239
+ this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
240
+ this.enabled = opts.enabled !== false;
241
+ this.debug = opts.debug;
242
+ this.partialFlushMs = (_c = opts.partialFlushMs) != null ? _c : 1e3;
243
+ this.sdkName = (_d = opts.sdkName) != null ? _d : "core";
244
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
245
+ this.defaultEventName = (_e = opts.defaultEventName) != null ? _e : "ai_generation";
246
+ const isNode = typeof process !== "undefined" && typeof process.version === "string";
247
+ this.context = {
248
+ library: {
249
+ name: (_f = opts.libraryName) != null ? _f : "@raindrop-ai/core",
250
+ version: (_g = opts.libraryVersion) != null ? _g : "0.0.0"
251
+ },
252
+ metadata: {
253
+ jsRuntime: isNode ? "node" : "web",
254
+ ...isNode ? { nodeVersion: process.version } : {}
255
+ }
256
+ };
257
+ }
258
+ isDebugEnabled() {
259
+ return this.debug;
260
+ }
261
+ authHeaders() {
262
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
263
+ }
264
+ async patch(eventId, patch) {
265
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
266
+ if (!this.enabled) return;
267
+ if (!eventId || !eventId.trim()) return;
268
+ if (this.debug) {
269
+ console.log(`${this.prefix} queue patch`, {
270
+ eventId,
271
+ userId: patch.userId,
272
+ convoId: patch.convoId,
273
+ eventName: patch.eventName,
274
+ hasInput: typeof patch.input === "string" && patch.input.length > 0,
275
+ hasOutput: typeof patch.output === "string" && patch.output.length > 0,
276
+ attachments: (_b = (_a = patch.attachments) == null ? void 0 : _a.length) != null ? _b : 0,
277
+ isPending: patch.isPending
278
+ });
279
+ }
280
+ const sticky = (_c = this.sticky.get(eventId)) != null ? _c : {};
281
+ const existing = (_d = this.buffers.get(eventId)) != null ? _d : {};
282
+ const merged = mergePatches(existing, patch);
283
+ merged.isPending = (_g = (_f = (_e = patch.isPending) != null ? _e : existing.isPending) != null ? _f : sticky.isPending) != null ? _g : true;
284
+ this.buffers.set(eventId, merged);
285
+ this.sticky.set(eventId, {
286
+ userId: (_h = merged.userId) != null ? _h : sticky.userId,
287
+ convoId: (_i = merged.convoId) != null ? _i : sticky.convoId,
288
+ eventName: (_j = merged.eventName) != null ? _j : sticky.eventName,
289
+ isPending: (_k = merged.isPending) != null ? _k : sticky.isPending
290
+ });
291
+ const t = this.timers.get(eventId);
292
+ if (t) clearTimeout(t);
293
+ if (merged.isPending === false) {
294
+ await this.flushOne(eventId);
295
+ return;
296
+ }
297
+ const timeout = setTimeout(() => {
298
+ void this.flushOne(eventId).catch(() => {
299
+ });
300
+ }, this.partialFlushMs);
301
+ this.timers.set(eventId, timeout);
302
+ }
303
+ async finish(eventId, patch) {
304
+ await this.patch(eventId, { ...patch, isPending: false });
305
+ }
306
+ async flush() {
307
+ if (!this.enabled) return;
308
+ const ids = [...this.buffers.keys()];
309
+ await Promise.all(ids.map((id) => this.flushOne(id)));
310
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
311
+ })));
312
+ }
313
+ async shutdown() {
314
+ for (const t of this.timers.values()) clearTimeout(t);
315
+ this.timers.clear();
316
+ await this.flush();
317
+ }
318
+ async trackSignal(signal) {
319
+ var _a, _b;
320
+ if (!this.enabled) return;
321
+ const body = [
322
+ {
323
+ event_id: signal.eventId,
324
+ signal_name: signal.name,
325
+ signal_type: (_a = signal.type) != null ? _a : "default",
326
+ timestamp: signal.timestamp,
327
+ sentiment: signal.sentiment,
328
+ attachment_id: signal.attachmentId,
329
+ properties: {
330
+ ...(_b = signal.properties) != null ? _b : {},
331
+ ...signal.comment ? { comment: signal.comment } : {},
332
+ ...signal.after ? { after: signal.after } : {}
333
+ }
334
+ }
335
+ ];
336
+ const url = `${this.baseUrl}signals/track`;
337
+ try {
338
+ await postJson(url, body, this.authHeaders(), {
339
+ maxAttempts: 3,
340
+ debug: this.debug,
341
+ sdkName: this.sdkName
342
+ });
343
+ } catch (err) {
344
+ const msg = err instanceof Error ? err.message : String(err);
345
+ console.warn(`${this.prefix} failed to send signal (dropping): ${msg}`);
346
+ }
347
+ }
348
+ async identify(users) {
349
+ if (!this.enabled) return;
350
+ const list = Array.isArray(users) ? users : [users];
351
+ const body = list.filter((user) => {
352
+ if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
353
+ if (this.debug) {
354
+ console.warn(`${this.prefix} skipping identify: missing userId`);
355
+ }
356
+ return false;
357
+ }
358
+ return true;
359
+ }).map((user) => {
360
+ var _a;
361
+ return {
362
+ user_id: user.userId,
363
+ traits: (_a = user.traits) != null ? _a : {}
364
+ };
365
+ });
366
+ if (body.length === 0) return;
367
+ const url = `${this.baseUrl}users/identify`;
368
+ try {
369
+ await postJson(url, body, this.authHeaders(), {
370
+ maxAttempts: 3,
371
+ debug: this.debug,
372
+ sdkName: this.sdkName
373
+ });
374
+ } catch (err) {
375
+ const msg = err instanceof Error ? err.message : String(err);
376
+ console.warn(`${this.prefix} failed to send identify (dropping): ${msg}`);
377
+ }
378
+ }
379
+ async flushOne(eventId) {
380
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
381
+ if (!this.enabled) return;
382
+ const timer = this.timers.get(eventId);
383
+ if (timer) {
384
+ clearTimeout(timer);
385
+ this.timers.delete(eventId);
386
+ }
387
+ const accumulated = this.buffers.get(eventId);
388
+ this.buffers.delete(eventId);
389
+ if (!accumulated) return;
390
+ const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
391
+ const eventName = (_c = (_b = accumulated.eventName) != null ? _b : sticky.eventName) != null ? _c : this.defaultEventName;
392
+ const userId = (_d = accumulated.userId) != null ? _d : sticky.userId;
393
+ if (!userId) {
394
+ if (this.debug) {
395
+ console.warn(`${this.prefix} skipping track_partial for ${eventId}: missing userId`);
396
+ }
397
+ this.sticky.delete(eventId);
398
+ return;
399
+ }
400
+ const { wizardSession, ...restProperties } = (_e = accumulated.properties) != null ? _e : {};
401
+ const convoId = (_f = accumulated.convoId) != null ? _f : sticky.convoId;
402
+ const isPending = (_h = (_g = accumulated.isPending) != null ? _g : sticky.isPending) != null ? _h : true;
403
+ const payload = {
404
+ event_id: eventId,
405
+ user_id: userId,
406
+ event: eventName,
407
+ timestamp: (_i = accumulated.timestamp) != null ? _i : (/* @__PURE__ */ new Date()).toISOString(),
408
+ ai_data: {
409
+ input: accumulated.input,
410
+ output: accumulated.output,
411
+ model: accumulated.model,
412
+ convo_id: convoId
413
+ },
414
+ properties: {
415
+ ...restProperties,
416
+ ...wizardSession ? { "raindrop.wizardSession": wizardSession } : {},
417
+ $context: this.context
418
+ },
419
+ attachments: accumulated.attachments,
420
+ is_pending: isPending
421
+ };
422
+ const url = `${this.baseUrl}events/track_partial`;
423
+ if (this.debug) {
424
+ console.log(`${this.prefix} sending track_partial`, {
425
+ eventId,
426
+ eventName,
427
+ userId,
428
+ convoId,
429
+ isPending,
430
+ inputPreview: typeof accumulated.input === "string" ? accumulated.input.slice(0, 120) : void 0,
431
+ outputPreview: typeof accumulated.output === "string" ? accumulated.output.slice(0, 120) : void 0,
432
+ attachments: (_k = (_j = accumulated.attachments) == null ? void 0 : _j.length) != null ? _k : 0,
433
+ attachmentKinds: (_m = (_l = accumulated.attachments) == null ? void 0 : _l.map((a) => ({
434
+ type: a.type,
435
+ role: a.role,
436
+ name: a.name,
437
+ valuePreview: a.value.slice(0, 60)
438
+ }))) != null ? _m : [],
439
+ endpoint: url
440
+ });
441
+ }
442
+ const p = postJson(url, payload, this.authHeaders(), {
443
+ maxAttempts: 3,
444
+ debug: this.debug,
445
+ sdkName: this.sdkName
446
+ });
447
+ this.inFlight.add(p);
448
+ try {
449
+ try {
450
+ await p;
451
+ if (this.debug) {
452
+ console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
453
+ }
454
+ } catch (err) {
455
+ const msg = err instanceof Error ? err.message : String(err);
456
+ console.warn(`${this.prefix} failed to send track_partial (dropping): ${msg}`);
457
+ }
458
+ } finally {
459
+ this.inFlight.delete(p);
460
+ }
461
+ if (!isPending) {
462
+ this.sticky.delete(eventId);
463
+ }
464
+ }
465
+ };
466
+ var TraceShipper = class {
467
+ constructor(opts) {
468
+ this.queue = [];
469
+ this.inFlight = /* @__PURE__ */ new Set();
470
+ var _a, _b, _c, _d, _e, _f, _g, _h;
471
+ this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
472
+ this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
473
+ this.enabled = opts.enabled !== false;
474
+ this.debug = opts.debug;
475
+ this.debugSpans = opts.debugSpans === true;
476
+ this.flushIntervalMs = (_c = opts.flushIntervalMs) != null ? _c : 1e3;
477
+ this.maxBatchSize = (_d = opts.maxBatchSize) != null ? _d : 50;
478
+ this.maxQueueSize = (_e = opts.maxQueueSize) != null ? _e : 5e3;
479
+ this.sdkName = (_f = opts.sdkName) != null ? _f : "core";
480
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
481
+ this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
482
+ this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
483
+ }
484
+ isDebugEnabled() {
485
+ return this.debug;
486
+ }
487
+ authHeaders() {
488
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
489
+ }
490
+ startSpan(args) {
491
+ var _a, _b;
492
+ const ids = createSpanIds(args.parent);
493
+ const started = (_a = args.startTimeUnixNano) != null ? _a : nowUnixNanoString();
494
+ const attrs = [
495
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
496
+ attrString("ai.operationId", args.operationId)
497
+ ];
498
+ if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
499
+ return { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
500
+ }
501
+ endSpan(span, extra) {
502
+ var _a, _b;
503
+ if (span.endTimeUnixNano) return;
504
+ span.endTimeUnixNano = (_a = extra == null ? void 0 : extra.endTimeUnixNano) != null ? _a : nowUnixNanoString();
505
+ if ((_b = extra == null ? void 0 : extra.attributes) == null ? void 0 : _b.length) {
506
+ span.attributes.push(...extra.attributes);
507
+ }
508
+ let status = extra == null ? void 0 : extra.status;
509
+ if (!status && (extra == null ? void 0 : extra.error) !== void 0) {
510
+ const message = extra.error instanceof Error ? extra.error.message : String(extra.error);
511
+ status = { code: SpanStatusCode.ERROR, message };
512
+ }
513
+ const otlp = buildOtlpSpan({
514
+ ids: span.ids,
515
+ name: span.name,
516
+ startTimeUnixNano: span.startTimeUnixNano,
517
+ endTimeUnixNano: span.endTimeUnixNano,
518
+ attributes: span.attributes,
519
+ status
520
+ });
521
+ this.enqueue(otlp);
522
+ }
523
+ createSpan(args) {
524
+ var _a;
525
+ const ids = createSpanIds(args.parent);
526
+ const attrs = [
527
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId)
528
+ ];
529
+ if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
530
+ const otlp = buildOtlpSpan({
531
+ ids,
532
+ name: args.name,
533
+ startTimeUnixNano: args.startTimeUnixNano,
534
+ endTimeUnixNano: args.endTimeUnixNano,
535
+ attributes: attrs,
536
+ status: args.status
537
+ });
538
+ this.enqueue(otlp);
539
+ }
540
+ enqueue(span) {
541
+ if (!this.enabled) return;
542
+ if (this.debugSpans) {
543
+ const short = (s) => s ? s.slice(-8) : "none";
544
+ console.log(
545
+ `${this.prefix}[span] name=${span.name} trace=${short(span.traceId)} span=${short(span.spanId)} parent=${short(
546
+ span.parentSpanId
547
+ )}`
548
+ );
549
+ }
550
+ if (this.queue.length >= this.maxQueueSize) {
551
+ this.queue.shift();
552
+ }
553
+ this.queue.push(span);
554
+ if (this.queue.length >= this.maxBatchSize) {
555
+ void this.flush().catch(() => {
556
+ });
557
+ return;
558
+ }
559
+ if (!this.timer) {
560
+ this.timer = setTimeout(() => {
561
+ this.timer = void 0;
562
+ void this.flush().catch(() => {
563
+ });
564
+ }, this.flushIntervalMs);
565
+ }
566
+ }
567
+ async flush() {
568
+ if (!this.enabled) return;
569
+ if (this.timer) {
570
+ clearTimeout(this.timer);
571
+ this.timer = void 0;
572
+ }
573
+ while (this.queue.length > 0) {
574
+ const batch = this.queue.splice(0, this.maxBatchSize);
575
+ const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
576
+ const url = `${this.baseUrl}traces`;
577
+ if (this.debug) {
578
+ console.log(`${this.prefix} sending traces batch`, {
579
+ spans: batch.length,
580
+ endpoint: url
581
+ });
582
+ }
583
+ const p = postJson(url, body, this.authHeaders(), {
584
+ maxAttempts: 3,
585
+ debug: this.debug,
586
+ sdkName: this.sdkName
587
+ });
588
+ this.inFlight.add(p);
589
+ try {
590
+ try {
591
+ await p;
592
+ if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
593
+ } catch (err) {
594
+ const msg = err instanceof Error ? err.message : String(err);
595
+ console.warn(`${this.prefix} failed to send ${batch.length} spans: ${msg}`);
596
+ }
597
+ } finally {
598
+ this.inFlight.delete(p);
599
+ }
600
+ }
601
+ }
602
+ async shutdown() {
603
+ if (this.timer) {
604
+ clearTimeout(this.timer);
605
+ this.timer = void 0;
606
+ }
607
+ await this.flush();
608
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
609
+ })));
610
+ }
611
+ };
612
+ var NOOP_SPAN = {
613
+ traceIdB64: "",
614
+ spanIdB64: "",
615
+ eventId: "",
616
+ log() {
617
+ }
618
+ };
619
+ function getAsyncLocalStorageCtor() {
620
+ return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
621
+ }
622
+ var SynchronousContextStorage = class {
623
+ constructor() {
624
+ this._stack = [];
625
+ }
626
+ isEmpty() {
627
+ return this._stack.length === 0;
628
+ }
629
+ getStore() {
630
+ return this._stack[this._stack.length - 1];
631
+ }
632
+ run(store, callback) {
633
+ this._stack.push(store);
634
+ try {
635
+ return callback();
636
+ } finally {
637
+ this._stack.pop();
638
+ }
639
+ }
640
+ };
641
+ var ContextManager = class {
642
+ };
643
+ var RaindropContextManager = class extends ContextManager {
644
+ constructor() {
645
+ super();
646
+ this._fallback = null;
647
+ const Ctor = getAsyncLocalStorageCtor();
648
+ if (Ctor) {
649
+ this._storage = new Ctor();
650
+ return;
651
+ }
652
+ this._fallback = new SynchronousContextStorage();
653
+ this._storage = this._fallback;
654
+ }
655
+ maybeAdoptAsyncLocalStorage() {
656
+ if (!this._fallback || !this._fallback.isEmpty()) return;
657
+ const Ctor = getAsyncLocalStorageCtor();
658
+ if (!Ctor) return;
659
+ this._storage = new Ctor();
660
+ this._fallback = null;
661
+ }
662
+ isReady() {
663
+ return true;
664
+ }
665
+ getParentSpanIds() {
666
+ this.maybeAdoptAsyncLocalStorage();
667
+ const span = this._storage.getStore();
668
+ if (!span || span === NOOP_SPAN) return void 0;
669
+ return {
670
+ traceIdB64: span.traceIdB64,
671
+ spanIdB64: span.spanIdB64,
672
+ eventId: span.eventId
673
+ };
674
+ }
675
+ runInContext(span, callback) {
676
+ this.maybeAdoptAsyncLocalStorage();
677
+ return this._storage.run(span, callback);
678
+ }
679
+ getCurrentSpan() {
680
+ this.maybeAdoptAsyncLocalStorage();
681
+ return this._storage.getStore();
682
+ }
683
+ };
684
+ var _contextManager = null;
685
+ function getContextManager() {
686
+ if (!_contextManager) {
687
+ _contextManager = globalThis.RAINDROP_CONTEXT_MANAGER ? new globalThis.RAINDROP_CONTEXT_MANAGER() : new RaindropContextManager();
688
+ }
689
+ return _contextManager;
690
+ }
691
+ function currentSpan() {
692
+ var _a;
693
+ return (_a = getContextManager().getCurrentSpan()) != null ? _a : NOOP_SPAN;
694
+ }
695
+ function withCurrent(span, callback) {
696
+ return getContextManager().runInContext(span, callback);
697
+ }
698
+ async function getCurrentParentSpanContext() {
699
+ return getContextManager().getParentSpanIds();
700
+ }
701
+ async function runWithParentSpanContext(ctx, fn) {
702
+ const cm = getContextManager();
703
+ const span = {
704
+ traceIdB64: ctx.traceIdB64,
705
+ spanIdB64: ctx.spanIdB64,
706
+ eventId: ctx.eventId
707
+ };
708
+ return cm.runInContext(span, fn);
709
+ }
710
+ async function* asyncGeneratorWithCurrent(span, gen) {
711
+ let nextValue;
712
+ while (true) {
713
+ const result = await withCurrent(span, async () => {
714
+ try {
715
+ return await gen.next(nextValue);
716
+ } catch (e) {
717
+ return { value: void 0, done: true, error: e };
718
+ }
719
+ });
720
+ if ("error" in result && result.error !== void 0) {
721
+ throw result.error;
722
+ }
723
+ if (result.done) {
724
+ return result.value;
725
+ }
726
+ nextValue = yield result.value;
727
+ }
728
+ }
729
+
730
+ // package.json
731
+ var package_default = {
732
+ name: "@raindrop-ai/ai-sdk",
733
+ version: "0.0.19"};
734
+
735
+ // src/internal/version.ts
736
+ var libraryName = package_default.name;
737
+ var libraryVersion = package_default.version;
738
+
739
+ // src/internal/events.ts
740
+ var EventShipper2 = class extends EventShipper {
741
+ constructor(opts) {
742
+ var _a, _b, _c;
743
+ super({
744
+ ...opts,
745
+ sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
746
+ libraryName: (_b = opts.libraryName) != null ? _b : libraryName,
747
+ libraryVersion: (_c = opts.libraryVersion) != null ? _c : libraryVersion
748
+ });
749
+ }
750
+ };
751
+
752
+ // src/internal/traces.ts
753
+ var TraceShipper2 = class extends TraceShipper {
754
+ constructor(opts) {
755
+ var _a, _b, _c;
756
+ super({
757
+ ...opts,
758
+ sdkName: (_a = opts.sdkName) != null ? _a : "ai-sdk",
759
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.ai-sdk",
760
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
761
+ });
762
+ }
763
+ };
764
+
765
+ // src/internal/wrap/helpers.ts
766
+ function isRecord(value) {
767
+ return typeof value === "object" && value !== null;
768
+ }
769
+ function isFunction(value) {
770
+ return typeof value === "function";
771
+ }
772
+ function isModuleNamespace(obj) {
773
+ var _a;
774
+ if (!obj || typeof obj !== "object") return false;
775
+ const asObject = obj;
776
+ if (((_a = asObject.constructor) == null ? void 0 : _a.name) === "Module") return true;
777
+ try {
778
+ const keys = Object.keys(obj);
779
+ if (keys.length === 0) return false;
780
+ const descriptor = Object.getOwnPropertyDescriptor(obj, keys[0]);
781
+ if (!descriptor) return false;
782
+ const isWritable = "writable" in descriptor ? descriptor.writable : true;
783
+ return !descriptor.configurable && !isWritable;
784
+ } catch (e) {
785
+ return false;
786
+ }
787
+ }
788
+ function safeJson(value) {
789
+ try {
790
+ return JSON.stringify(value);
791
+ } catch (e) {
792
+ return void 0;
793
+ }
794
+ }
795
+ function safeJsonWithUint8(value) {
796
+ try {
797
+ return JSON.stringify(value, (_key, v) => {
798
+ if (v instanceof Uint8Array) return base64Encode(v);
799
+ return v;
800
+ });
801
+ } catch (e) {
802
+ return void 0;
803
+ }
804
+ }
805
+ function extractModelInfo(model) {
806
+ if (typeof model === "string") {
807
+ const slashIndex2 = model.indexOf("/");
808
+ if (slashIndex2 > 0 && slashIndex2 < model.length - 1) {
809
+ return {
810
+ provider: model.slice(0, slashIndex2),
811
+ modelId: model.slice(slashIndex2 + 1)
812
+ };
813
+ }
814
+ return { modelId: model };
815
+ }
816
+ if (!isRecord(model)) return {};
817
+ const provider = typeof model["provider"] === "string" ? model["provider"] : void 0;
818
+ let modelIdRaw;
819
+ if (typeof model["modelId"] === "string") {
820
+ modelIdRaw = model["modelId"];
821
+ } else if (typeof model["model"] === "string") {
822
+ modelIdRaw = model["model"];
823
+ }
824
+ if (!modelIdRaw) {
825
+ return { provider };
826
+ }
827
+ const slashIndex = modelIdRaw.indexOf("/");
828
+ if (!provider && slashIndex > 0 && slashIndex < modelIdRaw.length - 1) {
829
+ return {
830
+ provider: modelIdRaw.slice(0, slashIndex),
831
+ modelId: modelIdRaw.slice(slashIndex + 1)
832
+ };
833
+ }
834
+ return { provider, modelId: modelIdRaw };
835
+ }
836
+ function extractTextOutput(result) {
837
+ if (!isRecord(result)) return void 0;
838
+ const text = result["text"];
839
+ return typeof text === "string" ? text : void 0;
840
+ }
841
+ function extractObjectOutput(result) {
842
+ var _a;
843
+ if (!isRecord(result)) return void 0;
844
+ const obj = result["object"];
845
+ if (obj === void 0) return void 0;
846
+ return (_a = safeJson(obj)) != null ? _a : String(obj);
847
+ }
848
+ function isAgentClass(value) {
849
+ if (typeof value !== "function") return false;
850
+ const proto = value.prototype;
851
+ if (!isRecord(proto)) return false;
852
+ return typeof proto["generate"] === "function" && typeof proto["stream"] === "function";
853
+ }
854
+ function extractModel(result) {
855
+ if (!isRecord(result)) return void 0;
856
+ const model = result["model"];
857
+ if (typeof model === "string" && model.length) return model;
858
+ const response = result["response"];
859
+ if (isRecord(response)) {
860
+ const modelId = response["modelId"];
861
+ if (typeof modelId === "string" && modelId.length) return modelId;
862
+ }
863
+ return void 0;
864
+ }
865
+ function extractFinishReason(result) {
866
+ if (!isRecord(result)) return void 0;
867
+ if (typeof result["finishReason"] === "string") return result["finishReason"];
868
+ if (isRecord(result["finishReason"]) && typeof result["finishReason"]["unified"] === "string") {
869
+ return result["finishReason"]["unified"];
870
+ }
871
+ return void 0;
872
+ }
873
+ function bytesToBase64(bytes) {
874
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
875
+ let binary = "";
876
+ for (let i = 0; i < bytes.length; i++) {
877
+ binary += String.fromCharCode(bytes[i]);
878
+ }
879
+ if (typeof btoa === "function") return btoa(binary);
880
+ return "";
881
+ }
882
+ function asDataUrl(value, mediaType) {
883
+ if (value instanceof URL) return value.toString();
884
+ if (typeof value === "string") {
885
+ if (value.startsWith("data:")) return value;
886
+ if (value.startsWith("http://") || value.startsWith("https://")) return value;
887
+ return `data:${mediaType};base64,${value}`;
888
+ }
889
+ if (value instanceof Uint8Array) {
890
+ const base64 = bytesToBase64(value);
891
+ if (!base64) return void 0;
892
+ return `data:${mediaType};base64,${base64}`;
893
+ }
894
+ if (value instanceof ArrayBuffer) {
895
+ const base64 = bytesToBase64(new Uint8Array(value));
896
+ if (!base64) return void 0;
897
+ return `data:${mediaType};base64,${base64}`;
898
+ }
899
+ return void 0;
900
+ }
901
+ function dataPartToAttachmentValue(value) {
902
+ if (typeof value === "string") return value;
903
+ if (value instanceof URL) return value.toString();
904
+ if (value instanceof Uint8Array) return `[binary:${value.byteLength} bytes]`;
905
+ if (value instanceof ArrayBuffer) return `[binary:${value.byteLength} bytes]`;
906
+ return void 0;
907
+ }
908
+ function attachmentMediaType(part) {
909
+ if (typeof part["mediaType"] === "string") return part["mediaType"];
910
+ if (typeof part["mimeType"] === "string") return part["mimeType"];
911
+ const file = part["file"];
912
+ if (isRecord(file)) {
913
+ if (typeof file["mediaType"] === "string") return file["mediaType"];
914
+ if (typeof file["mimeType"] === "string") return file["mimeType"];
915
+ }
916
+ return void 0;
917
+ }
918
+ function attachmentName(part) {
919
+ if (typeof part["filename"] === "string") return part["filename"];
920
+ if (typeof part["name"] === "string") return part["name"];
921
+ const file = part["file"];
922
+ if (isRecord(file)) {
923
+ if (typeof file["filename"] === "string") return file["filename"];
924
+ if (typeof file["name"] === "string") return file["name"];
925
+ }
926
+ return void 0;
927
+ }
928
+ function attachmentData(part) {
929
+ if ("data" in part) return part["data"];
930
+ const file = part["file"];
931
+ if (isRecord(file)) {
932
+ if ("file_data" in file) return file["file_data"];
933
+ if ("data" in file) return file["data"];
934
+ }
935
+ return void 0;
936
+ }
937
+ function contentPartToAttachment(part, role) {
938
+ var _a, _b, _c;
939
+ const partType = part["type"];
940
+ if (typeof partType !== "string") return void 0;
941
+ if (partType === "image") {
942
+ const mediaType = (_a = attachmentMediaType(part)) != null ? _a : "image/png";
943
+ const value = asDataUrl(part["image"], mediaType);
944
+ if (!value) return void 0;
945
+ return { type: "image", role, value };
946
+ }
947
+ if (partType === "image_url") {
948
+ const imageUrlPart = part["image_url"];
949
+ const imageUrlValue = isRecord(imageUrlPart) ? imageUrlPart["url"] : imageUrlPart;
950
+ const value = asDataUrl(imageUrlValue, "image/png");
951
+ if (!value) return void 0;
952
+ return { type: "image", role, value };
953
+ }
954
+ if (partType === "file") {
955
+ const mediaType = attachmentMediaType(part);
956
+ const data = attachmentData(part);
957
+ const isImage = (mediaType == null ? void 0 : mediaType.startsWith("image/")) === true;
958
+ const value = isImage && mediaType ? asDataUrl(data, mediaType) : dataPartToAttachmentValue(data);
959
+ if (!value) return void 0;
960
+ const name = (_c = (_b = attachmentName(part)) != null ? _b : mediaType) != null ? _c : "file";
961
+ return { type: isImage ? "image" : "text", role, name, value };
962
+ }
963
+ return void 0;
964
+ }
965
+ function attachmentsFromContent(content, role) {
966
+ if (!Array.isArray(content)) return void 0;
967
+ const attachments = [];
968
+ for (const part of content) {
969
+ if (!isRecord(part)) continue;
970
+ const attachment = contentPartToAttachment(part, role);
971
+ if (attachment) attachments.push(attachment);
972
+ }
973
+ return attachments.length ? attachments : void 0;
974
+ }
975
+ function generatedFileToAttachment(file) {
976
+ var _a, _b, _c, _d;
977
+ const mediaType = typeof file["mediaType"] === "string" ? file["mediaType"] : typeof file["mimeType"] === "string" ? file["mimeType"] : void 0;
978
+ const data = (_d = (_c = (_b = (_a = file["base64Data"]) != null ? _a : file["base64"]) != null ? _b : file["uint8ArrayData"]) != null ? _c : file["uint8Array"]) != null ? _d : file["data"];
979
+ const isImage = (mediaType == null ? void 0 : mediaType.startsWith("image/")) === true;
980
+ const value = isImage && mediaType ? asDataUrl(data, mediaType) : dataPartToAttachmentValue(data);
981
+ if (!value) return void 0;
982
+ const name = typeof file["filename"] === "string" ? file["filename"] : typeof file["name"] === "string" ? file["name"] : mediaType != null ? mediaType : "file";
983
+ return {
984
+ type: isImage ? "image" : "text",
985
+ role: "output",
986
+ name,
987
+ value
988
+ };
989
+ }
990
+ async function outputAttachmentsFromFiles(files) {
991
+ let resolvedFiles = files;
992
+ if (resolvedFiles && (typeof resolvedFiles === "object" || typeof resolvedFiles === "function") && typeof resolvedFiles.then === "function") {
993
+ try {
994
+ resolvedFiles = await resolvedFiles;
995
+ } catch (e) {
996
+ return void 0;
997
+ }
998
+ }
999
+ if (!Array.isArray(resolvedFiles)) return void 0;
1000
+ const attachments = [];
1001
+ for (const file of resolvedFiles) {
1002
+ if (!isRecord(file)) continue;
1003
+ const attachment = generatedFileToAttachment(file);
1004
+ if (attachment) attachments.push(attachment);
1005
+ }
1006
+ return attachments.length ? attachments : void 0;
1007
+ }
1008
+ function extractTextFromMessageContent(content) {
1009
+ if (typeof content === "string") return content;
1010
+ if (!Array.isArray(content)) return void 0;
1011
+ let result = "";
1012
+ for (const part of content) {
1013
+ if (!isRecord(part) || part["type"] !== "text" || typeof part["text"] !== "string") continue;
1014
+ result += part["text"];
1015
+ }
1016
+ return result.length ? result : void 0;
1017
+ }
1018
+ function messagesFromArgs(args) {
1019
+ const messages = args["messages"];
1020
+ if (Array.isArray(messages)) return messages;
1021
+ const prompt = args["prompt"];
1022
+ if (Array.isArray(prompt)) return prompt;
1023
+ return void 0;
1024
+ }
1025
+ function lastUserMessageFromArgs(args) {
1026
+ const messages = messagesFromArgs(args);
1027
+ if (!messages) return void 0;
1028
+ for (let i = messages.length - 1; i >= 0; i--) {
1029
+ const message = messages[i];
1030
+ if (isRecord(message) && message["role"] === "user") {
1031
+ return message;
1032
+ }
1033
+ }
1034
+ return void 0;
1035
+ }
1036
+ function extractInputAttachmentsFromArgs(args) {
1037
+ var _a;
1038
+ if (!isRecord(args)) return void 0;
1039
+ return attachmentsFromContent((_a = lastUserMessageFromArgs(args)) == null ? void 0 : _a["content"], "input");
1040
+ }
1041
+ async function extractOutputAttachmentsFromResult(result) {
1042
+ if (!isRecord(result)) return void 0;
1043
+ const fileAttachments = await outputAttachmentsFromFiles(result["files"]);
1044
+ if (fileAttachments == null ? void 0 : fileAttachments.length) return fileAttachments;
1045
+ const responseMessages = extractResponseMessages(result);
1046
+ for (let i = responseMessages.length - 1; i >= 0; i--) {
1047
+ const message = responseMessages[i];
1048
+ if (!isRecord(message) || message["role"] !== "assistant") continue;
1049
+ return attachmentsFromContent(message["content"], "output");
1050
+ }
1051
+ return attachmentsFromContent(result["content"], "output");
1052
+ }
1053
+ function lastUserMessageTextFromArgs(args) {
1054
+ var _a, _b;
1055
+ if (!isRecord(args)) return void 0;
1056
+ const content = (_a = lastUserMessageFromArgs(args)) == null ? void 0 : _a["content"];
1057
+ if (content === void 0) return void 0;
1058
+ const text = extractTextFromMessageContent(content);
1059
+ if (text !== void 0) return text;
1060
+ return (_b = safeJsonWithUint8(content)) != null ? _b : String(content);
1061
+ }
1062
+ function extractInputFromArgs(args) {
1063
+ var _a;
1064
+ if (!isRecord(args)) return void 0;
1065
+ const prompt = args["prompt"];
1066
+ if (typeof prompt === "string") return prompt;
1067
+ const messages = messagesFromArgs(args);
1068
+ if (Array.isArray(messages) && messages.length > 0) {
1069
+ const last = messages[messages.length - 1];
1070
+ if (isRecord(last)) {
1071
+ const content = last["content"];
1072
+ const text = extractTextFromMessageContent(content);
1073
+ if (text !== void 0) return text;
1074
+ const asJson = safeJson(content);
1075
+ if (asJson) return asJson;
1076
+ }
1077
+ return (_a = safeJson(messages)) != null ? _a : void 0;
1078
+ }
1079
+ const input = args["input"];
1080
+ if (typeof input === "string") return input;
1081
+ return safeJson(args);
1082
+ }
1083
+ function coerceMessagesFromArgs(args) {
1084
+ if (!isRecord(args)) return [];
1085
+ const result = [];
1086
+ if (typeof args["system"] === "string" && args["system"]) {
1087
+ result.push({ role: "system", content: args["system"] });
1088
+ }
1089
+ const messages = messagesFromArgs(args);
1090
+ if (Array.isArray(messages)) {
1091
+ for (const message of messages) {
1092
+ if (isRecord(message) && typeof message["role"] === "string") {
1093
+ result.push(message);
1094
+ }
1095
+ }
1096
+ return result;
1097
+ }
1098
+ if (typeof args["prompt"] === "string" && args["prompt"]) {
1099
+ result.push({ role: "user", content: args["prompt"] });
1100
+ }
1101
+ return result;
1102
+ }
1103
+ function extractResponseMessages(result) {
1104
+ if (!isRecord(result)) return [];
1105
+ const response = result["response"];
1106
+ if (isRecord(response) && Array.isArray(response["messages"])) {
1107
+ return response["messages"].filter(
1108
+ (message) => isRecord(message) && typeof message["role"] === "string" && "content" in message
1109
+ ).map((message) => message);
1110
+ }
1111
+ const steps = result["steps"];
1112
+ if (Array.isArray(steps) && steps.length > 0) {
1113
+ const lastStep = steps[steps.length - 1];
1114
+ if (isRecord(lastStep) && isRecord(lastStep["response"])) {
1115
+ const responseMessages = lastStep["response"]["messages"];
1116
+ if (Array.isArray(responseMessages)) {
1117
+ return responseMessages.filter(
1118
+ (message) => isRecord(message) && typeof message["role"] === "string" && "content" in message
1119
+ ).map((message) => message);
1120
+ }
1121
+ }
1122
+ }
1123
+ return [];
1124
+ }
1125
+ function buildToolCallMatchKey(info) {
1126
+ if (typeof info.toolCallId === "string" && info.toolCallId.length > 0) {
1127
+ return `id:${info.toolCallId}`;
1128
+ }
1129
+ if (typeof info.toolName === "string" && info.toolName.length > 0) {
1130
+ const inputJson = safeJsonWithUint8(info.input);
1131
+ return inputJson !== void 0 ? `name:${info.toolName}|input:${inputJson}` : `name:${info.toolName}`;
1132
+ }
1133
+ return void 0;
1134
+ }
1135
+ function isTranscriptToolResultError(part, result) {
1136
+ if (part["isError"] === true || part["type"] === "tool-error") {
1137
+ return true;
1138
+ }
1139
+ if (isRecord(result) && typeof result["type"] === "string") {
1140
+ return result["type"].startsWith("error") || result["type"] === "execution-denied";
1141
+ }
1142
+ return false;
1143
+ }
1144
+ function getTranscriptToolErrorMessage(result) {
1145
+ if (typeof result === "string" && result.length > 0) {
1146
+ return result;
1147
+ }
1148
+ if (isRecord(result)) {
1149
+ if (typeof result["value"] === "string" && result["value"].length > 0) {
1150
+ return result["value"];
1151
+ }
1152
+ if (typeof result["reason"] === "string" && result["reason"].length > 0) {
1153
+ return result["reason"];
1154
+ }
1155
+ if (typeof result["message"] === "string" && result["message"].length > 0) {
1156
+ return result["message"];
1157
+ }
1158
+ }
1159
+ return safeJsonWithUint8(result);
1160
+ }
1161
+ function getTranscriptMessageParts(message) {
1162
+ if (!isRecord(message)) return [];
1163
+ const content = message["content"];
1164
+ if (Array.isArray(content)) {
1165
+ return content.filter(isRecord);
1166
+ }
1167
+ return isRecord(content) ? [content] : [];
1168
+ }
1169
+ function getTranscriptToolCallInput(part) {
1170
+ return "input" in part ? part["input"] : "args" in part ? part["args"] : void 0;
1171
+ }
1172
+ function getTranscriptToolCallId(part) {
1173
+ const toolCallId = part["toolCallId"];
1174
+ return typeof toolCallId === "string" && toolCallId.length > 0 ? toolCallId : void 0;
1175
+ }
1176
+ function getTranscriptToolResultValue(part) {
1177
+ if ("output" in part) return part["output"];
1178
+ if ("result" in part) return part["result"];
1179
+ return part["error"];
1180
+ }
1181
+ function rememberPendingTranscriptToolCallKey(pendingKeysByToolName, toolName, key) {
1182
+ var _a;
1183
+ if (!toolName) return;
1184
+ const pendingKeys = (_a = pendingKeysByToolName.get(toolName)) != null ? _a : [];
1185
+ if (pendingKeys.includes(key)) return;
1186
+ pendingKeys.push(key);
1187
+ pendingKeysByToolName.set(toolName, pendingKeys);
1188
+ }
1189
+ function takePendingTranscriptToolCallKey(pendingKeysByToolName, toolName) {
1190
+ if (!toolName) return void 0;
1191
+ const pendingKeys = pendingKeysByToolName.get(toolName);
1192
+ if (!pendingKeys || pendingKeys.length === 0) return void 0;
1193
+ const key = pendingKeys.shift();
1194
+ if (key === void 0) return void 0;
1195
+ if (pendingKeys.length === 0) {
1196
+ pendingKeysByToolName.delete(toolName);
1197
+ }
1198
+ return key;
1199
+ }
1200
+ function mergeTranscriptToolCallPart(params) {
1201
+ var _a, _b, _c, _d;
1202
+ const { spans, pendingKeysByToolName, part } = params;
1203
+ const toolCallId = getTranscriptToolCallId(part);
1204
+ const toolName = typeof part["toolName"] === "string" ? part["toolName"] : void 0;
1205
+ const input = getTranscriptToolCallInput(part);
1206
+ const key = buildToolCallMatchKey({ toolCallId, toolName, input });
1207
+ if (!key) return;
1208
+ const placeholderKey = toolCallId == null ? buildToolCallMatchKey({ toolCallId: void 0, toolName, input: void 0 }) : void 0;
1209
+ const placeholder = placeholderKey && placeholderKey !== key ? spans.get(placeholderKey) : void 0;
1210
+ const existing = (_a = spans.get(key)) != null ? _a : placeholder;
1211
+ spans.set(key, {
1212
+ key,
1213
+ toolCallId: (_b = existing == null ? void 0 : existing.toolCallId) != null ? _b : toolCallId,
1214
+ toolName: (_c = existing == null ? void 0 : existing.toolName) != null ? _c : toolName,
1215
+ input: (_d = existing == null ? void 0 : existing.input) != null ? _d : input,
1216
+ result: existing == null ? void 0 : existing.result,
1217
+ status: existing == null ? void 0 : existing.status,
1218
+ errorMessage: existing == null ? void 0 : existing.errorMessage
1219
+ });
1220
+ if (placeholderKey && placeholderKey !== key) {
1221
+ spans.delete(placeholderKey);
1222
+ }
1223
+ if (!toolCallId && (existing == null ? void 0 : existing.result) === void 0) {
1224
+ rememberPendingTranscriptToolCallKey(pendingKeysByToolName, toolName, key);
1225
+ }
1226
+ }
1227
+ function mergeTranscriptToolResultPart(params) {
1228
+ var _a, _b, _c;
1229
+ const { spans, pendingKeysByToolName, part } = params;
1230
+ const toolCallId = getTranscriptToolCallId(part);
1231
+ const toolName = typeof part["toolName"] === "string" ? part["toolName"] : void 0;
1232
+ const result = getTranscriptToolResultValue(part);
1233
+ const fallbackKey = buildToolCallMatchKey({ toolCallId, toolName, input: void 0 });
1234
+ const key = toolCallId != null ? fallbackKey : (_a = takePendingTranscriptToolCallKey(pendingKeysByToolName, toolName)) != null ? _a : fallbackKey;
1235
+ if (!key) return;
1236
+ const existing = spans.get(key);
1237
+ const isError = isTranscriptToolResultError(part, result);
1238
+ spans.set(key, {
1239
+ key,
1240
+ toolCallId: (_b = existing == null ? void 0 : existing.toolCallId) != null ? _b : toolCallId,
1241
+ toolName: (_c = existing == null ? void 0 : existing.toolName) != null ? _c : toolName,
1242
+ input: existing == null ? void 0 : existing.input,
1243
+ result,
1244
+ status: isError ? "ERROR" : "OK",
1245
+ errorMessage: isError ? getTranscriptToolErrorMessage(result) : void 0
1246
+ });
1247
+ }
1248
+ function extractToolSpansFromMessages(messages) {
1249
+ const spans = /* @__PURE__ */ new Map();
1250
+ const pendingKeysByToolName = /* @__PURE__ */ new Map();
1251
+ for (const message of messages) {
1252
+ for (const part of getTranscriptMessageParts(message)) {
1253
+ if (part["type"] === "tool-call") {
1254
+ mergeTranscriptToolCallPart({ spans, pendingKeysByToolName, part });
1255
+ continue;
1256
+ }
1257
+ if (part["type"] === "tool-result" || part["type"] === "tool-error") {
1258
+ mergeTranscriptToolResultPart({ spans, pendingKeysByToolName, part });
1259
+ }
1260
+ }
1261
+ }
1262
+ return [...spans.values()];
1263
+ }
1264
+ function extractTextFromLmContent(content) {
1265
+ if (!Array.isArray(content)) return void 0;
1266
+ let result = "";
1267
+ for (const part of content) {
1268
+ if (isRecord(part) && part["type"] === "text" && typeof part["text"] === "string") {
1269
+ result += part["text"];
1270
+ }
1271
+ }
1272
+ return result.length ? result : void 0;
1273
+ }
1274
+ function extractToolCallsFromLmContent(content) {
1275
+ if (!Array.isArray(content)) return void 0;
1276
+ const calls = [];
1277
+ for (const part of content) {
1278
+ if (!isRecord(part) || part["type"] !== "tool-call") continue;
1279
+ const toolCallId = getTranscriptToolCallId(part);
1280
+ const toolName = typeof part["toolName"] === "string" ? part["toolName"] : void 0;
1281
+ if (toolCallId || toolName) {
1282
+ calls.push({ toolCallId, toolName, input: part["input"] });
1283
+ }
1284
+ }
1285
+ return calls.length ? calls : void 0;
1286
+ }
1287
+ function extractExperimentalTelemetry(args) {
1288
+ if (!isRecord(args)) return void 0;
1289
+ const telemetryConfig = args["experimental_telemetry"];
1290
+ if (!isRecord(telemetryConfig)) return void 0;
1291
+ return {
1292
+ functionId: typeof telemetryConfig["functionId"] === "string" ? telemetryConfig["functionId"] : void 0,
1293
+ isEnabled: typeof telemetryConfig["isEnabled"] === "boolean" ? telemetryConfig["isEnabled"] : void 0,
1294
+ recordInputs: typeof telemetryConfig["recordInputs"] === "boolean" ? telemetryConfig["recordInputs"] : void 0,
1295
+ recordOutputs: typeof telemetryConfig["recordOutputs"] === "boolean" ? telemetryConfig["recordOutputs"] : void 0,
1296
+ metadata: isRecord(telemetryConfig["metadata"]) ? telemetryConfig["metadata"] : void 0
1297
+ };
1298
+ }
1299
+ function opName(operationId, functionId) {
1300
+ return {
1301
+ operationName: `${operationId}${functionId ? ` ${functionId}` : ""}`,
1302
+ resourceName: functionId
1303
+ };
1304
+ }
1305
+ function toOtlpAttr(key, value) {
1306
+ if (value === void 0 || value === null) return void 0;
1307
+ if (typeof value === "string") return attrString(key, value);
1308
+ if (typeof value === "number")
1309
+ return Number.isInteger(value) ? attrInt(key, value) : attrDouble(key, value);
1310
+ if (typeof value === "boolean") return attrBool(key, value);
1311
+ if (Array.isArray(value) && value.every((v) => typeof v === "string"))
1312
+ return attrStringArray(key, value);
1313
+ const asJson = safeJsonWithUint8(value);
1314
+ return asJson ? attrString(key, asJson) : void 0;
1315
+ }
1316
+ function attrsFromTelemetryMetadata(metadata) {
1317
+ if (!metadata) return [];
1318
+ return Object.entries(metadata).filter(([k]) => !k.startsWith("raindrop.internal.")).map(([k, v]) => {
1319
+ const key = k === "raindrop.userId" ? "raindrop.ai.userId" : k;
1320
+ return toOtlpAttr(`ai.telemetry.metadata.${key}`, v);
1321
+ });
1322
+ }
1323
+ function attrsFromHeaders(headers) {
1324
+ if (!isRecord(headers)) return [];
1325
+ return Object.entries(headers).filter(([, v]) => typeof v === "string").map(([k, v]) => attrString(`ai.request.headers.${k}`, v));
1326
+ }
1327
+ function attrsFromSettings(args) {
1328
+ if (!isRecord(args)) return [];
1329
+ const result = [];
1330
+ const settingKeys = [
1331
+ "maxRetries",
1332
+ "timeout",
1333
+ "maxOutputTokens",
1334
+ "temperature",
1335
+ "topP",
1336
+ "topK",
1337
+ "presencePenalty",
1338
+ "frequencyPenalty",
1339
+ "seed",
1340
+ "stopSequences"
1341
+ ];
1342
+ for (const key of settingKeys) {
1343
+ if (!(key in args)) continue;
1344
+ const value = args[key];
1345
+ if (key === "stopSequences" && Array.isArray(value) && value.every((item) => typeof item === "string")) {
1346
+ result.push(attrStringArray(`ai.settings.${key}`, value));
1347
+ } else if (key === "timeout" && typeof value === "number") {
1348
+ result.push(attrInt(`ai.settings.${key}`, value));
1349
+ } else {
1350
+ result.push(toOtlpAttr(`ai.settings.${key}`, value));
1351
+ }
1352
+ }
1353
+ return result;
1354
+ }
1355
+ function attrsFromGenAiRequest(options) {
1356
+ if (!isRecord(options)) return [];
1357
+ return [
1358
+ attrDouble(
1359
+ "gen_ai.request.frequency_penalty",
1360
+ typeof options["frequencyPenalty"] === "number" ? options["frequencyPenalty"] : void 0
1361
+ ),
1362
+ attrInt(
1363
+ "gen_ai.request.max_tokens",
1364
+ typeof options["maxOutputTokens"] === "number" ? options["maxOutputTokens"] : void 0
1365
+ ),
1366
+ attrDouble(
1367
+ "gen_ai.request.presence_penalty",
1368
+ typeof options["presencePenalty"] === "number" ? options["presencePenalty"] : void 0
1369
+ ),
1370
+ ...Array.isArray(options["stopSequences"]) && options["stopSequences"].every((x) => typeof x === "string") ? [attrStringArray("gen_ai.request.stop_sequences", options["stopSequences"])] : [],
1371
+ attrDouble(
1372
+ "gen_ai.request.temperature",
1373
+ typeof options["temperature"] === "number" ? options["temperature"] : void 0
1374
+ ),
1375
+ attrInt(
1376
+ "gen_ai.request.top_k",
1377
+ typeof options["topK"] === "number" ? options["topK"] : void 0
1378
+ ),
1379
+ attrDouble(
1380
+ "gen_ai.request.top_p",
1381
+ typeof options["topP"] === "number" ? options["topP"] : void 0
1382
+ )
1383
+ ];
1384
+ }
1385
+
1386
+ // src/internal/wrap/wrapAISDK.ts
1387
+ var AGENT_REPORTING_TOOL_NAME_DEFAULT = "__raindrop_report";
1388
+ var AGENT_REPORTING_SIGNALS_DEFAULT = {
1389
+ missing_context: {
1390
+ description: "You cannot complete the task because critical information, credentials, or access is missing and the user cannot provide it. Do NOT report this for normal clarifying questions \u2014 only when you are blocked.",
1391
+ sentiment: "NEGATIVE"
1392
+ },
1393
+ repeatedly_broken_tool: {
1394
+ description: "A tool has failed or not returned the expected response on multiple distinct attempts in this conversation, preventing task completion. A single tool error is NOT enough \u2014 the tool must be persistently broken or aberrantly behaving across retries.",
1395
+ sentiment: "NEGATIVE"
1396
+ },
1397
+ capability_gap: {
1398
+ description: "The task requires a tool, permission, or capability that you do not have. For example, the user asks you to perform an action but no suitable tool exists, or you lack the necessary access. Do NOT report this if you simply need more information from the user \u2014 only when the gap is in your own capabilities.",
1399
+ sentiment: "NEGATIVE"
1400
+ },
1401
+ complete_task_failure: {
1402
+ description: "You were unable to accomplish what the user asked despite making genuine attempts. This might be things like, you genuinely do not have the capabilities the user is asking for. You have tried but run into a persistent bug in the environment etc. This is NOT a refusal or policy block \u2014 you tried and failed to deliver the result.",
1403
+ sentiment: "NEGATIVE"
1404
+ }
1405
+ };
1406
+ var AGENT_REPORTING_TOOL_PREAMBLE = "You have a diagnostic tool for flagging serious failures for developer review. Only call this when you hit a significant, unrecoverable problem \u2014 not for minor hiccups or routine clarifications. If you can still help the user, do that instead of calling this tool. This tool is invisible to the user \u2014 never mention it or its output.";
1407
+ var pendingStoresByShipper = /* @__PURE__ */ new WeakMap();
1408
+ var PendingToolSpanStore = class _PendingToolSpanStore {
1409
+ constructor() {
1410
+ this.spans = /* @__PURE__ */ new Map();
1411
+ }
1412
+ static for(traceShipper, eventId) {
1413
+ let byEvent = pendingStoresByShipper.get(traceShipper);
1414
+ if (!byEvent) {
1415
+ byEvent = /* @__PURE__ */ new Map();
1416
+ pendingStoresByShipper.set(traceShipper, byEvent);
1417
+ }
1418
+ let store = byEvent.get(eventId);
1419
+ if (!store) {
1420
+ store = new _PendingToolSpanStore();
1421
+ byEvent.set(eventId, store);
1422
+ }
1423
+ return store;
1424
+ }
1425
+ resolve(resolvedToolSpans, ctx) {
1426
+ for (const [key, span] of this.spans) {
1427
+ const toolCall = resolvedToolSpans.get(key);
1428
+ if (!toolCall) continue;
1429
+ finishToolSpan(toolCall, span, ctx, span.startTimeUnixNano);
1430
+ this.spans.delete(key);
1431
+ }
1432
+ }
1433
+ remember(toolCall, rootSpan, ctx, startTimeUnixNano) {
1434
+ if (this.spans.has(toolCall.key)) return;
1435
+ this.spans.set(toolCall.key, startToolSpan(toolCall, rootSpan, ctx, startTimeUnixNano));
1436
+ }
1437
+ closeAll(traceShipper) {
1438
+ for (const [, span] of this.spans) {
1439
+ traceShipper.endSpan(span, { endTimeUnixNano: span.startTimeUnixNano });
1440
+ }
1441
+ this.spans.clear();
1442
+ }
1443
+ cleanup(traceShipper, eventId) {
1444
+ if (this.spans.size > 0) return;
1445
+ const byEvent = pendingStoresByShipper.get(traceShipper);
1446
+ if (!byEvent) return;
1447
+ byEvent.delete(eventId);
1448
+ if (byEvent.size === 0) pendingStoresByShipper.delete(traceShipper);
1449
+ }
1450
+ };
1451
+ var warnedMissingUserId = false;
1452
+ function warnMissingUserIdOnce() {
1453
+ if (warnedMissingUserId) return;
1454
+ warnedMissingUserId = true;
1455
+ console.warn(
1456
+ "[raindrop-ai/ai-sdk] userId was not provided in wrap() context or via eventMetadata(). Events will be skipped unless a userId is provided."
1457
+ );
1458
+ }
1459
+ function _resetWarnedMissingUserId() {
1460
+ warnedMissingUserId = false;
1461
+ }
1462
+ function extractRaindropCallOptions(options) {
1463
+ if (!isRecord(options)) return {};
1464
+ const em = options["metadata"];
1465
+ if (isRecord(em)) return extractRaindropMetadata(em);
1466
+ const telemetry = extractExperimentalTelemetry(options);
1467
+ if (telemetry == null ? void 0 : telemetry.metadata) return extractRaindropMetadata(telemetry.metadata);
1468
+ return {};
1469
+ }
1470
+ function extractRaindropMetadata(metadata) {
1471
+ if (!metadata || typeof metadata !== "object") return {};
1472
+ const result = {};
1473
+ const userId = metadata["raindrop.userId"];
1474
+ if (typeof userId === "string" && userId) result.userId = userId;
1475
+ const eventId = metadata["raindrop.eventId"];
1476
+ if (typeof eventId === "string" && eventId) result.eventId = eventId;
1477
+ const eventIdGenerated = metadata["raindrop.internal.eventIdGenerated"];
1478
+ if (eventIdGenerated === true || eventIdGenerated === "true" || eventIdGenerated === "1") {
1479
+ result.eventIdGenerated = true;
1480
+ }
1481
+ const convoId = metadata["raindrop.convoId"];
1482
+ if (typeof convoId === "string" && convoId) result.convoId = convoId;
1483
+ const eventName = metadata["raindrop.eventName"];
1484
+ if (typeof eventName === "string" && eventName) result.eventName = eventName;
1485
+ const properties = metadata["raindrop.properties"];
1486
+ if (typeof properties === "string") {
1487
+ try {
1488
+ result.properties = JSON.parse(properties);
1489
+ } catch (e) {
1490
+ }
1491
+ } else if (properties && typeof properties === "object") {
1492
+ result.properties = properties;
1493
+ }
1494
+ return result;
1495
+ }
1496
+ function mergeContexts(wrapTime, callTime) {
1497
+ const result = { ...wrapTime };
1498
+ if (callTime.userId) result.userId = callTime.userId;
1499
+ if (callTime.eventId) result.eventId = callTime.eventId;
1500
+ if (callTime.convoId) result.convoId = callTime.convoId;
1501
+ if (callTime.eventName) result.eventName = callTime.eventName;
1502
+ if (callTime.properties) {
1503
+ result.properties = {
1504
+ ...wrapTime.properties,
1505
+ ...callTime.properties
1506
+ };
1507
+ }
1508
+ return result;
1509
+ }
1510
+ function normalizeSelfDiagnosticsSignals(signals) {
1511
+ if (!signals) return AGENT_REPORTING_SIGNALS_DEFAULT;
1512
+ const normalizedEntries = Object.entries(signals).map(([key, value]) => {
1513
+ var _a;
1514
+ const signalKey = key.trim();
1515
+ if (!signalKey || !value || typeof value !== "object") return void 0;
1516
+ const description = (_a = value.description) == null ? void 0 : _a.trim();
1517
+ if (!description) return void 0;
1518
+ const sentiment = value.sentiment;
1519
+ return [
1520
+ signalKey,
1521
+ {
1522
+ description,
1523
+ ...sentiment === "POSITIVE" || sentiment === "NEGATIVE" ? { sentiment } : {}
1524
+ }
1525
+ ];
1526
+ }).filter(
1527
+ (entry) => entry !== void 0
1528
+ );
1529
+ if (normalizedEntries.length === 0) return AGENT_REPORTING_SIGNALS_DEFAULT;
1530
+ return Object.fromEntries(normalizedEntries);
1531
+ }
1532
+ function normalizeSelfDiagnosticsConfig(options) {
1533
+ var _a, _b;
1534
+ if (!(options == null ? void 0 : options.enabled)) return void 0;
1535
+ const signalDefinitions = normalizeSelfDiagnosticsSignals(options.signals);
1536
+ const signalKeys = Object.keys(signalDefinitions);
1537
+ const signalDescriptions = {};
1538
+ const signalSentiments = {};
1539
+ for (const signalKey of signalKeys) {
1540
+ const def = signalDefinitions[signalKey];
1541
+ if (!def) continue;
1542
+ signalDescriptions[signalKey] = def.description;
1543
+ signalSentiments[signalKey] = def.sentiment;
1544
+ }
1545
+ const customGuidanceText = ((_a = options.guidance) == null ? void 0 : _a.trim()) || "";
1546
+ const toolName = ((_b = options.toolName) == null ? void 0 : _b.trim()) || AGENT_REPORTING_TOOL_NAME_DEFAULT;
1547
+ const signalList = signalKeys.map((signalKey) => {
1548
+ const sentiment = signalSentiments[signalKey];
1549
+ const sentimentTag = sentiment ? ` [${sentiment.toLowerCase()}]` : "";
1550
+ return `- ${signalKey}: ${signalDescriptions[signalKey]}${sentimentTag}`;
1551
+ }).join("\n");
1552
+ const guidanceBlock = customGuidanceText ? `
1553
+ Additional guidance: ${customGuidanceText}
1554
+ ` : "";
1555
+ const toolDescription = `${AGENT_REPORTING_TOOL_PREAMBLE}
1556
+
1557
+ When to call:
1558
+ - You are blocked from completing the task due to missing information or access that the user cannot provide.
1559
+ - A tool is persistently failing across multiple attempts, not just a single transient error.
1560
+ - The task requires a tool, permission, or capability you do not have.
1561
+ - You genuinely cannot deliver what the user asked for despite trying.
1562
+
1563
+ When NOT to call:
1564
+ - Normal clarifying questions or back-and-forth with the user.
1565
+ - A single tool error that you can recover from or retry.
1566
+ - You successfully completed the task, even if it was difficult.
1567
+ - Policy refusals or content filtering \u2014 those are working as intended.
1568
+
1569
+ Rules:
1570
+ 1. Pick the single best category.
1571
+ 2. Do not fabricate issues. Only report what is evident from the conversation.
1572
+ 3. Err on the side of NOT calling this tool. When in doubt, help the user instead.
1573
+ ${guidanceBlock}
1574
+ Categories:
1575
+ ${signalList}`;
1576
+ return {
1577
+ toolName,
1578
+ toolDescription,
1579
+ signalKeys,
1580
+ signalKeySet: new Set(signalKeys),
1581
+ signalDescriptions,
1582
+ signalSentiments
1583
+ };
1584
+ }
1585
+ function resolveJsonSchemaFactory(aiSDK) {
1586
+ if (!isRecord(aiSDK) || !isFunction(aiSDK["jsonSchema"])) return void 0;
1587
+ return aiSDK["jsonSchema"];
1588
+ }
1589
+ function detectAISDKVersion(aiSDK) {
1590
+ if (!isRecord(aiSDK)) return "unknown";
1591
+ if (isFunction(aiSDK["jsonSchema"])) return "6";
1592
+ if (isFunction(aiSDK["tool"])) return "5";
1593
+ return "4";
1594
+ }
1595
+ function asVercelSchema(jsonSchemaObj) {
1596
+ const validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
1597
+ const schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
1598
+ return {
1599
+ [schemaSymbol]: true,
1600
+ [validatorSymbol]: true,
1601
+ _type: void 0,
1602
+ jsonSchema: jsonSchemaObj,
1603
+ validate: (value) => ({ success: true, value })
1604
+ };
1605
+ }
1606
+ function createSelfDiagnosticsTool(ctx) {
1607
+ const config = ctx.selfDiagnostics;
1608
+ if (!config) return void 0;
1609
+ const schema = {
1610
+ type: "object",
1611
+ additionalProperties: false,
1612
+ properties: {
1613
+ category: {
1614
+ type: "string",
1615
+ enum: config.signalKeys,
1616
+ description: "The single best-matching category from the list above."
1617
+ },
1618
+ detail: {
1619
+ type: "string",
1620
+ description: "One sentence of factual context: what happened and why it matters. Do not include PII or secrets."
1621
+ }
1622
+ },
1623
+ required: ["category", "detail"]
1624
+ };
1625
+ const parameters = asVercelSchema(schema);
1626
+ let inputSchema = parameters;
1627
+ if (ctx.jsonSchemaFactory) {
1628
+ try {
1629
+ inputSchema = ctx.jsonSchemaFactory(schema);
1630
+ } catch (e) {
1631
+ inputSchema = parameters;
1632
+ }
1633
+ }
1634
+ const execute = async (rawInput) => {
1635
+ var _a;
1636
+ const input = isRecord(rawInput) ? rawInput : void 0;
1637
+ const fallbackCategory = (_a = config.signalKeys[0]) != null ? _a : "unknown";
1638
+ const categoryCandidate = typeof (input == null ? void 0 : input["category"]) === "string" ? input["category"].trim() : void 0;
1639
+ const category = categoryCandidate && config.signalKeySet.has(categoryCandidate) ? categoryCandidate : fallbackCategory;
1640
+ const detail = typeof (input == null ? void 0 : input["detail"]) === "string" ? input["detail"].trim() : "";
1641
+ const signalDescription = config.signalDescriptions[category];
1642
+ const signalSentiment = config.signalSentiments[category];
1643
+ void ctx.eventShipper.trackSignal({
1644
+ eventId: ctx.eventId,
1645
+ name: `self diagnostics - ${category}`,
1646
+ type: "agent",
1647
+ sentiment: signalSentiment,
1648
+ properties: {
1649
+ source: "agent_reporting_tool",
1650
+ category,
1651
+ signal_description: signalDescription,
1652
+ ai_sdk_version: ctx.aiSDKVersion,
1653
+ ...detail ? { detail } : {}
1654
+ }
1655
+ }).catch((err) => {
1656
+ if (ctx.debug) {
1657
+ const msg = err instanceof Error ? err.message : String(err);
1658
+ console.warn(`[raindrop-ai/ai-sdk] selfDiagnostics signal dispatch failed: ${msg}`);
1659
+ }
1660
+ });
1661
+ return { acknowledged: true, category };
1662
+ };
1663
+ return {
1664
+ description: config.toolDescription,
1665
+ execute,
1666
+ parameters,
1667
+ inputSchema
1668
+ };
1669
+ }
1670
+ function getCurrentParentSpanContextSync() {
1671
+ return getContextManager().getParentSpanIds();
1672
+ }
1673
+ function runWithParentSpanContextSync(ctx, fn) {
1674
+ const cm = getContextManager();
1675
+ const span = {
1676
+ traceIdB64: ctx.traceIdB64,
1677
+ spanIdB64: ctx.spanIdB64,
1678
+ eventId: ctx.eventId
1679
+ };
1680
+ return cm.runInContext(span, fn);
1681
+ }
1682
+ function isAsyncIterable(value) {
1683
+ return value !== null && typeof value === "object" && Symbol.asyncIterator in value;
1684
+ }
1685
+ function firstFiniteNumber(...values) {
1686
+ for (const value of values) {
1687
+ if (typeof value === "number" && Number.isFinite(value)) {
1688
+ return value;
1689
+ }
1690
+ }
1691
+ return void 0;
1692
+ }
1693
+ function resolveUsageRecord(result) {
1694
+ if (!isRecord(result)) return void 0;
1695
+ let usage;
1696
+ try {
1697
+ if (isRecord(result["totalUsage"])) {
1698
+ usage = result["totalUsage"];
1699
+ } else if (isRecord(result["usage"])) {
1700
+ usage = result["usage"];
1701
+ }
1702
+ } catch (e) {
1703
+ return void 0;
1704
+ }
1705
+ return isRecord(usage) ? usage : void 0;
1706
+ }
1707
+ function extractUsageMetrics(result) {
1708
+ const usage = resolveUsageRecord(result);
1709
+ if (!usage) return {};
1710
+ const inputTokenValue = usage["inputTokens"];
1711
+ const outputTokenValue = usage["outputTokens"];
1712
+ const inputTokens = firstFiniteNumber(
1713
+ isRecord(inputTokenValue) ? inputTokenValue["total"] : void 0,
1714
+ inputTokenValue,
1715
+ usage["promptTokens"],
1716
+ usage["prompt_tokens"]
1717
+ );
1718
+ const outputTokens = firstFiniteNumber(
1719
+ isRecord(outputTokenValue) ? outputTokenValue["total"] : void 0,
1720
+ outputTokenValue,
1721
+ usage["completionTokens"],
1722
+ usage["completion_tokens"]
1723
+ );
1724
+ const totalTokens = firstFiniteNumber(
1725
+ usage["totalTokens"],
1726
+ usage["tokens"],
1727
+ usage["total_tokens"],
1728
+ inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0
1729
+ );
1730
+ const reasoningTokens = firstFiniteNumber(
1731
+ isRecord(outputTokenValue) ? outputTokenValue["reasoning"] : void 0,
1732
+ usage["reasoningTokens"],
1733
+ usage["completionReasoningTokens"],
1734
+ usage["completion_reasoning_tokens"],
1735
+ usage["reasoning_tokens"],
1736
+ usage["thinkingTokens"],
1737
+ usage["thinking_tokens"]
1738
+ );
1739
+ const cachedInputTokens = firstFiniteNumber(
1740
+ isRecord(inputTokenValue) ? inputTokenValue["cacheRead"] : void 0,
1741
+ usage["cachedInputTokens"],
1742
+ usage["promptCachedTokens"],
1743
+ usage["prompt_cached_tokens"]
1744
+ );
1745
+ return {
1746
+ inputTokens,
1747
+ outputTokens,
1748
+ totalTokens,
1749
+ reasoningTokens,
1750
+ cachedInputTokens
1751
+ };
1752
+ }
1753
+ function isObjectOperation(operation) {
1754
+ return operation === "generateObject" || operation === "streamObject";
1755
+ }
1756
+ function logFinalizeError(debug, err) {
1757
+ if (debug) {
1758
+ console.warn(
1759
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1760
+ );
1761
+ }
1762
+ }
1763
+ function shouldKeepEventPending(params) {
1764
+ if (params.error != null || !params.canKeepEventPending) return false;
1765
+ return params.finishReason === "tool-calls" || params.finishReason === "tool_calls";
1766
+ }
1767
+ async function safeFinalize(finalize, debug, result, error) {
1768
+ try {
1769
+ await finalize(result, error);
1770
+ } catch (finalizeErr) {
1771
+ logFinalizeError(debug, finalizeErr);
1772
+ }
1773
+ }
1774
+ function runWithRootContextSync(rootSpan, eventId, fn) {
1775
+ if (!rootSpan) return fn();
1776
+ return runWithParentSpanContextSync(
1777
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1778
+ fn
1779
+ );
1780
+ }
1781
+ async function runWithRootContextAsync(rootSpan, eventId, fn) {
1782
+ if (!rootSpan) return await fn();
1783
+ return await runWithParentSpanContext(
1784
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1785
+ fn
1786
+ );
1787
+ }
1788
+ function teeStreamObjectBaseStream(result) {
1789
+ if (!result || !isRecord(result)) return;
1790
+ const baseStream = result["baseStream"];
1791
+ if (!(baseStream && typeof baseStream === "object" && "tee" in baseStream)) return;
1792
+ try {
1793
+ const [consumeStream, userStream] = baseStream.tee();
1794
+ result["baseStream"] = userStream;
1795
+ consumeStream.pipeTo(new WritableStream({ write() {
1796
+ } })).catch(() => {
1797
+ });
1798
+ } catch (e) {
1799
+ }
1800
+ }
1801
+ function setupOperation(params) {
1802
+ var _a, _b, _c;
1803
+ const {
1804
+ operation,
1805
+ arg,
1806
+ inherited,
1807
+ aiSDK,
1808
+ options,
1809
+ eventShipper,
1810
+ traceShipper,
1811
+ debug,
1812
+ selfDiagnostics,
1813
+ sendTraces
1814
+ } = params;
1815
+ const wrapTimeCtx = resolveContext(options.context, { operation, args: arg });
1816
+ const telemetry = extractExperimentalTelemetry(arg);
1817
+ const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1818
+ const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1819
+ if (!mergedCtx.userId) warnMissingUserIdOnce();
1820
+ const hasCallTimeEventId = callTimeCtx.eventId != null;
1821
+ const hasWrapTimeEventId = wrapTimeCtx.eventId != null;
1822
+ const eventId = (_c = (_b = (_a = callTimeCtx.eventId) != null ? _a : wrapTimeCtx.eventId) != null ? _b : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1823
+ const ctx = { ...mergedCtx, eventId };
1824
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1825
+ const outerOperationId = `ai.${operation}`;
1826
+ const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
1827
+ const modelInfoFromArgs = isRecord(arg) ? extractModelInfo(arg["model"]) : {};
1828
+ const rootSpan = sendTraces ? traceShipper.startSpan({
1829
+ name: outerOperationId,
1830
+ parent: inheritedParent,
1831
+ eventId,
1832
+ operationId: outerOperationId,
1833
+ attributes: [
1834
+ attrString("operation.name", operationName),
1835
+ attrString("resource.name", resourceName),
1836
+ attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1837
+ attrString("ai.model.provider", modelInfoFromArgs.provider),
1838
+ attrString("ai.model.id", modelInfoFromArgs.modelId),
1839
+ ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1840
+ ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1841
+ ...attrsFromSettings(arg),
1842
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1843
+ attrString(
1844
+ "ai.prompt",
1845
+ safeJsonWithUint8({
1846
+ system: isRecord(arg) ? arg["system"] : void 0,
1847
+ prompt: isRecord(arg) ? arg["prompt"] : void 0,
1848
+ messages: isRecord(arg) ? arg["messages"] : void 0
1849
+ })
1850
+ )
1851
+ ]
1852
+ ]
1853
+ }) : void 0;
1854
+ const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1855
+ const operationSelfDiagnostics = isObjectOperation(operation) ? void 0 : selfDiagnostics;
1856
+ const wrapCtx = {
1857
+ eventId,
1858
+ telemetry,
1859
+ sendTraces,
1860
+ debug,
1861
+ eventShipper,
1862
+ traceShipper,
1863
+ rootParentForChildren,
1864
+ jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
1865
+ selfDiagnostics: operationSelfDiagnostics,
1866
+ aiSDKVersion: detectAISDKVersion(aiSDK)
1867
+ };
1868
+ const toolCalls = [];
1869
+ const argsWithWrappedTools = wrapTools(arg, wrapCtx, toolCalls);
1870
+ const wrappedArgs = wrapModel(argsWithWrappedTools, aiSDK, outerOperationId, wrapCtx);
1871
+ return {
1872
+ eventId,
1873
+ ctx,
1874
+ canKeepEventPending: hasCallTimeEventId ? callTimeCtx.eventIdGenerated !== true : hasWrapTimeEventId,
1875
+ telemetry,
1876
+ rootSpan,
1877
+ wrappedArgs,
1878
+ toolCalls
1879
+ };
1880
+ }
1881
+ function createFinalize(params) {
1882
+ const {
1883
+ operation,
1884
+ arg,
1885
+ setup,
1886
+ autoAttachmentEnabled,
1887
+ sendEvents,
1888
+ debug,
1889
+ options,
1890
+ eventShipper,
1891
+ traceShipper
1892
+ } = params;
1893
+ return async (result, error) => {
1894
+ var _a, _b, _c, _d;
1895
+ const usage = extractUsageMetrics(result);
1896
+ const model = extractModel(result);
1897
+ const finishReason = extractFinishReason(result);
1898
+ const keepEventPending = shouldKeepEventPending({
1899
+ finishReason,
1900
+ error,
1901
+ canKeepEventPending: setup.canKeepEventPending
1902
+ });
1903
+ const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(arg) : void 0;
1904
+ const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
1905
+ const baseMessages = coerceMessagesFromArgs(arg);
1906
+ const responseMessages = extractResponseMessages(result);
1907
+ const allMessages = [...baseMessages, ...responseMessages];
1908
+ const outputText = extractTextOutput(result);
1909
+ const outputObjectJson = extractObjectOutput(result);
1910
+ const defaultOutput = isObjectOperation(operation) ? outputObjectJson : outputText;
1911
+ const defaultPatch = {
1912
+ eventName: (_a = setup.ctx.eventName) != null ? _a : operation,
1913
+ input: (_b = lastUserMessageTextFromArgs(arg)) != null ? _b : extractInputFromArgs(arg),
1914
+ output: defaultOutput,
1915
+ model,
1916
+ properties: setup.ctx.properties,
1917
+ attachments: mergeAttachments(setup.ctx.attachments, inputAttachments, outputAttachments)
1918
+ };
1919
+ const built = await maybeBuildEvent(options.buildEvent, allMessages);
1920
+ const patch = mergeBuildEventPatch(defaultPatch, built);
1921
+ const output = patch.output;
1922
+ const finalModel = (_c = patch.model) != null ? _c : model;
1923
+ if (setup.rootSpan) {
1924
+ const spanEndTimeUnixNano = nowUnixNanoString();
1925
+ const syntheticToolCallCount = emitTranscriptToolCallSpans({
1926
+ baseMessages,
1927
+ responseMessages,
1928
+ rootSpan: setup.rootSpan,
1929
+ eventId: setup.eventId,
1930
+ telemetry: setup.telemetry,
1931
+ toolCalls: setup.toolCalls,
1932
+ traceShipper,
1933
+ endTimeUnixNano: spanEndTimeUnixNano,
1934
+ keepEventPending
1935
+ });
1936
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1937
+ const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : setup.toolCalls.length ? safeJsonWithUint8(setup.toolCalls) : void 0;
1938
+ traceShipper.endSpan(setup.rootSpan, {
1939
+ attributes: [
1940
+ ...((_d = setup.telemetry) == null ? void 0 : _d.recordOutputs) === false ? [] : [
1941
+ attrString("ai.response.finishReason", finishReason),
1942
+ isObjectOperation(operation) ? attrString("ai.response.object", output) : attrString("ai.response.text", output),
1943
+ attrString("ai.response.toolCalls", resultToolCalls),
1944
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1945
+ ],
1946
+ attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1947
+ attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1948
+ attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1949
+ attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1950
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
1951
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
1952
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
1953
+ attrInt("ai.toolCall.count", setup.toolCalls.length + syntheticToolCallCount),
1954
+ ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
1955
+ ],
1956
+ error,
1957
+ endTimeUnixNano: spanEndTimeUnixNano
1958
+ });
1959
+ }
1960
+ if (sendEvents) {
1961
+ void eventShipper.patch(setup.eventId, {
1962
+ eventName: patch.eventName,
1963
+ userId: setup.ctx.userId,
1964
+ convoId: setup.ctx.convoId,
1965
+ input: patch.input,
1966
+ output,
1967
+ model: finalModel,
1968
+ properties: patch.properties,
1969
+ attachments: patch.attachments,
1970
+ isPending: keepEventPending
1971
+ }).catch((err) => {
1972
+ if (debug) {
1973
+ console.warn(
1974
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1975
+ );
1976
+ }
1977
+ });
1978
+ }
1979
+ };
1980
+ }
1981
+ function hasToolResult(toolCall) {
1982
+ return toolCall.result !== void 0 || toolCall.status === "ERROR";
1983
+ }
1984
+ function getExecutedToolCallKeys(toolCalls) {
1985
+ return new Set(
1986
+ toolCalls.map((tc) => buildToolCallMatchKey({ toolCallId: tc.id, toolName: tc.name, input: tc.args })).filter((key) => typeof key === "string" && key.length > 0)
1987
+ );
1988
+ }
1989
+ function getResolvedToolSpans(messages, executedKeys) {
1990
+ return new Map(
1991
+ extractToolSpansFromMessages(messages).filter((tc) => hasToolResult(tc) && !executedKeys.has(tc.key)).map((tc) => [tc.key, tc])
1992
+ );
1993
+ }
1994
+ function startToolSpan(toolCall, rootSpan, ctx, startTimeUnixNano) {
1995
+ var _a, _b, _c;
1996
+ const { operationName, resourceName } = opName("ai.toolCall", (_a = ctx.telemetry) == null ? void 0 : _a.functionId);
1997
+ return ctx.traceShipper.startSpan({
1998
+ name: "ai.toolCall",
1999
+ parent: { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 },
2000
+ eventId: ctx.eventId,
2001
+ operationId: "ai.toolCall",
2002
+ attributes: [
2003
+ attrString("operation.name", operationName),
2004
+ attrString("resource.name", resourceName),
2005
+ attrString("ai.telemetry.functionId", (_b = ctx.telemetry) == null ? void 0 : _b.functionId),
2006
+ attrString("ai.toolCall.name", toolCall.toolName),
2007
+ attrString("ai.toolCall.id", toolCall.toolCallId),
2008
+ ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [attrString("ai.toolCall.args", safeJsonWithUint8(toolCall.input))]
2009
+ ],
2010
+ startTimeUnixNano
2011
+ });
2012
+ }
2013
+ function finishToolSpan(toolCall, span, ctx, endTimeUnixNano) {
2014
+ var _a, _b, _c;
2015
+ const endAttributes = toolCall.status === "ERROR" ? [attrString("error.message", (_a = toolCall.errorMessage) != null ? _a : "Tool call failed")] : ((_b = ctx.telemetry) == null ? void 0 : _b.recordOutputs) === false ? [] : [attrString("ai.toolCall.result", safeJsonWithUint8(toolCall.result))];
2016
+ ctx.traceShipper.endSpan(span, {
2017
+ attributes: endAttributes,
2018
+ ...toolCall.status === "ERROR" ? { error: new Error((_c = toolCall.errorMessage) != null ? _c : "Tool call failed") } : {},
2019
+ endTimeUnixNano
2020
+ });
2021
+ }
2022
+ function emitToolSpan(toolCall, rootSpan, ctx, timeUnixNano) {
2023
+ const span = startToolSpan(toolCall, rootSpan, ctx, timeUnixNano);
2024
+ finishToolSpan(toolCall, span, ctx, timeUnixNano);
2025
+ }
2026
+ function emitTranscriptToolCallSpans(params) {
2027
+ const store = PendingToolSpanStore.for(params.traceShipper, params.eventId);
2028
+ const responseToolSpans = extractToolSpansFromMessages(params.responseMessages);
2029
+ if (responseToolSpans.length === 0 && params.baseMessages.length === 0) {
2030
+ if (!params.keepEventPending) {
2031
+ store.closeAll(params.traceShipper);
2032
+ }
2033
+ store.cleanup(params.traceShipper, params.eventId);
2034
+ return 0;
2035
+ }
2036
+ const ctx = {
2037
+ eventId: params.eventId,
2038
+ telemetry: params.telemetry,
2039
+ traceShipper: params.traceShipper
2040
+ };
2041
+ const executedKeys = getExecutedToolCallKeys(params.toolCalls);
2042
+ const resolvedSpans = getResolvedToolSpans(
2043
+ [...params.baseMessages, ...params.responseMessages],
2044
+ executedKeys
2045
+ );
2046
+ store.resolve(resolvedSpans, ctx);
2047
+ let syntheticToolCallCount = 0;
2048
+ for (const toolCall of responseToolSpans) {
2049
+ if (executedKeys.has(toolCall.key)) continue;
2050
+ executedKeys.add(toolCall.key);
2051
+ syntheticToolCallCount += 1;
2052
+ if (hasToolResult(toolCall) || !params.keepEventPending) {
2053
+ emitToolSpan(toolCall, params.rootSpan, ctx, params.endTimeUnixNano);
2054
+ } else {
2055
+ store.remember(toolCall, params.rootSpan, ctx, params.endTimeUnixNano);
2056
+ }
2057
+ }
2058
+ if (!params.keepEventPending) {
2059
+ store.closeAll(params.traceShipper);
2060
+ }
2061
+ store.cleanup(params.traceShipper, params.eventId);
2062
+ return syntheticToolCallCount;
2063
+ }
2064
+ function executeStreamingOperation(params) {
2065
+ const {
2066
+ operation,
2067
+ arg,
2068
+ callArgs,
2069
+ aiSDK,
2070
+ original,
2071
+ deps,
2072
+ sendEvents,
2073
+ sendTraces,
2074
+ selfDiagnostics,
2075
+ autoAttachmentEnabled,
2076
+ debug
2077
+ } = params;
2078
+ const setup = setupOperation({
2079
+ operation,
2080
+ arg,
2081
+ inherited: getCurrentParentSpanContextSync(),
2082
+ aiSDK,
2083
+ options: deps.options,
2084
+ eventShipper: deps.eventShipper,
2085
+ traceShipper: deps.traceShipper,
2086
+ debug,
2087
+ selfDiagnostics,
2088
+ sendTraces
2089
+ });
2090
+ const finalize = createFinalize({
2091
+ operation,
2092
+ arg,
2093
+ setup,
2094
+ autoAttachmentEnabled,
2095
+ sendEvents,
2096
+ debug,
2097
+ options: deps.options,
2098
+ eventShipper: deps.eventShipper,
2099
+ traceShipper: deps.traceShipper
2100
+ });
2101
+ const argWithOnFinish = wrapOnFinish(setup.wrappedArgs, async (result) => {
2102
+ await safeFinalize(finalize, debug, result);
2103
+ });
2104
+ const callOriginal = (...args) => {
2105
+ return original.call(aiSDK, ...args);
2106
+ };
2107
+ try {
2108
+ const result = runWithRootContextSync(setup.rootSpan, setup.eventId, () => {
2109
+ const nextArgs = [...callArgs];
2110
+ nextArgs[0] = argWithOnFinish;
2111
+ return callOriginal(...nextArgs);
2112
+ });
2113
+ if (operation === "streamObject") {
2114
+ teeStreamObjectBaseStream(result);
2115
+ }
2116
+ return result;
2117
+ } catch (error) {
2118
+ void safeFinalize(finalize, debug, void 0, error);
2119
+ throw error;
2120
+ }
2121
+ }
2122
+ async function executeNonStreamingOperation(params) {
2123
+ const {
2124
+ operation,
2125
+ arg,
2126
+ callArgs,
2127
+ aiSDK,
2128
+ original,
2129
+ deps,
2130
+ sendEvents,
2131
+ sendTraces,
2132
+ selfDiagnostics,
2133
+ autoAttachmentEnabled,
2134
+ debug
2135
+ } = params;
2136
+ const inherited = await getCurrentParentSpanContext();
2137
+ const setup = setupOperation({
2138
+ operation,
2139
+ arg,
2140
+ inherited,
2141
+ aiSDK,
2142
+ options: deps.options,
2143
+ eventShipper: deps.eventShipper,
2144
+ traceShipper: deps.traceShipper,
2145
+ debug,
2146
+ selfDiagnostics,
2147
+ sendTraces
2148
+ });
2149
+ const finalize = createFinalize({
2150
+ operation,
2151
+ arg,
2152
+ setup,
2153
+ autoAttachmentEnabled,
2154
+ sendEvents,
2155
+ debug,
2156
+ options: deps.options,
2157
+ eventShipper: deps.eventShipper,
2158
+ traceShipper: deps.traceShipper
2159
+ });
2160
+ const callOriginal = async (...args) => {
2161
+ return await original.call(aiSDK, ...args);
2162
+ };
2163
+ try {
2164
+ const result = await runWithRootContextAsync(setup.rootSpan, setup.eventId, async () => {
2165
+ const nextArgs = [...callArgs];
2166
+ nextArgs[0] = setup.wrappedArgs;
2167
+ return await callOriginal(...nextArgs);
2168
+ });
2169
+ await safeFinalize(finalize, debug, result);
2170
+ return result;
2171
+ } catch (error) {
2172
+ await safeFinalize(finalize, debug, void 0, error);
2173
+ throw error;
2174
+ }
2175
+ }
2176
+ function wrapAISDK(aiSDK, deps) {
2177
+ var _a, _b;
2178
+ const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
2179
+ const instrumentedOps = /* @__PURE__ */ new Set([
2180
+ "generateText",
2181
+ "streamText",
2182
+ "generateObject",
2183
+ "streamObject"
2184
+ ]);
2185
+ const agentClasses = /* @__PURE__ */ new Set(["Agent", "Experimental_Agent", "ToolLoopAgent"]);
2186
+ const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
2187
+ const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
2188
+ const autoAttachmentEnabled = deps.options.autoAttachment !== false;
2189
+ const selfDiagnostics = normalizeSelfDiagnosticsConfig(deps.options.selfDiagnostics);
2190
+ const proxyTarget = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
2191
+ return new Proxy(proxyTarget, {
2192
+ get(target, prop, receiver) {
2193
+ const original = Reflect.get(target, prop, receiver);
2194
+ if (typeof prop === "string" && agentClasses.has(prop) && isAgentClass(original)) {
2195
+ if (debug) console.log(`[raindrop-ai/ai-sdk] Wrapping Agent class: ${prop}`);
2196
+ return wrapAgentClass(original, aiSDK, deps, debug, selfDiagnostics);
2197
+ }
2198
+ if (typeof prop !== "string" || !instrumentedOps.has(prop) || !isFunction(original)) {
2199
+ return original;
2200
+ }
2201
+ return (...callArgs) => {
2202
+ const operation = prop;
2203
+ const arg = callArgs[0];
2204
+ if (operation === "streamText" || operation === "streamObject") {
2205
+ return executeStreamingOperation({
2206
+ operation,
2207
+ arg,
2208
+ callArgs,
2209
+ aiSDK,
2210
+ original,
2211
+ deps,
2212
+ sendEvents,
2213
+ sendTraces,
2214
+ selfDiagnostics,
2215
+ autoAttachmentEnabled,
2216
+ debug
2217
+ });
2218
+ }
2219
+ return executeNonStreamingOperation({
2220
+ operation,
2221
+ arg,
2222
+ callArgs,
2223
+ aiSDK,
2224
+ original,
2225
+ deps,
2226
+ sendEvents,
2227
+ sendTraces,
2228
+ selfDiagnostics,
2229
+ autoAttachmentEnabled,
2230
+ debug
2231
+ });
2232
+ };
2233
+ }
2234
+ });
2235
+ }
2236
+ function wrapAgentClass(AgentClass, aiSDK, deps, debug, selfDiagnostics) {
2237
+ return new Proxy(AgentClass, {
2238
+ construct(target, args, newTarget) {
2239
+ const instance = Reflect.construct(target, args, newTarget);
2240
+ const agentSettings = args[0];
2241
+ const className = (newTarget == null ? void 0 : newTarget.name) || target.name || "Agent";
2242
+ if (debug) console.log(`[raindrop-ai/ai-sdk] Creating wrapped ${className} instance`);
2243
+ return new Proxy(instance, {
2244
+ get(instanceTarget, prop, instanceReceiver) {
2245
+ const original = Reflect.get(instanceTarget, prop, instanceReceiver);
2246
+ if (prop === "generate" && isFunction(original)) {
2247
+ if (debug) console.log(`[raindrop-ai/ai-sdk] Wrapping ${className}.generate method`);
2248
+ return wrapAgentGenerate(
2249
+ original,
2250
+ instanceTarget,
2251
+ agentSettings,
2252
+ className,
2253
+ aiSDK,
2254
+ deps,
2255
+ debug,
2256
+ selfDiagnostics
2257
+ );
2258
+ }
2259
+ if (prop === "stream" && isFunction(original)) {
2260
+ if (debug) console.log(`[raindrop-ai/ai-sdk] Wrapping ${className}.stream method`);
2261
+ return wrapAgentStream(
2262
+ original,
2263
+ instanceTarget,
2264
+ agentSettings,
2265
+ className,
2266
+ aiSDK,
2267
+ deps,
2268
+ debug,
2269
+ selfDiagnostics
2270
+ );
2271
+ }
2272
+ return original;
2273
+ }
2274
+ });
2275
+ }
2276
+ });
2277
+ }
2278
+ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK, deps, debug, selfDiagnostics) {
2279
+ var _a, _b;
2280
+ const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
2281
+ const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
2282
+ const autoAttachmentEnabled = deps.options.autoAttachment !== false;
2283
+ return async (...callArgs) => {
2284
+ var _a2, _b2, _c, _d;
2285
+ const callParams = callArgs[0];
2286
+ const mergedArgs = { ...agentSettings, ...callParams };
2287
+ const operation = `${className}.generate`;
2288
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation, args: mergedArgs });
2289
+ const telemetry = extractExperimentalTelemetry(mergedArgs);
2290
+ const callTimeCtx = extractRaindropCallOptions(mergedArgs);
2291
+ const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
2292
+ if (!mergedCtx.userId) warnMissingUserIdOnce();
2293
+ const inherited = await getCurrentParentSpanContext();
2294
+ const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2295
+ const ctx = { ...mergedCtx};
2296
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2297
+ const outerOperationId = `ai.${operation}`;
2298
+ const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
2299
+ const modelInfoFromArgs = extractModelInfo(mergedArgs["model"]);
2300
+ const rootSpan = sendTraces ? deps.traceShipper.startSpan({
2301
+ name: outerOperationId,
2302
+ parent: inheritedParent,
2303
+ eventId,
2304
+ operationId: outerOperationId,
2305
+ attributes: [
2306
+ attrString("operation.name", operationName),
2307
+ attrString("resource.name", resourceName),
2308
+ attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2309
+ attrString("ai.model.provider", modelInfoFromArgs.provider),
2310
+ attrString("ai.model.id", modelInfoFromArgs.modelId),
2311
+ ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2312
+ ...attrsFromHeaders(mergedArgs["headers"]),
2313
+ ...attrsFromSettings(mergedArgs),
2314
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2315
+ attrString(
2316
+ "ai.prompt",
2317
+ safeJsonWithUint8({
2318
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2319
+ prompt: mergedArgs["prompt"],
2320
+ messages: mergedArgs["messages"]
2321
+ })
2322
+ )
2323
+ ]
2324
+ ]
2325
+ }) : void 0;
2326
+ const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2327
+ const wrapCtx = {
2328
+ eventId,
2329
+ telemetry,
2330
+ sendTraces,
2331
+ debug,
2332
+ eventShipper: deps.eventShipper,
2333
+ traceShipper: deps.traceShipper,
2334
+ rootParentForChildren,
2335
+ jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
2336
+ selfDiagnostics,
2337
+ aiSDKVersion: detectAISDKVersion(aiSDK)
2338
+ };
2339
+ const toolCalls = [];
2340
+ const mergedArgsWithWrappedTools = wrapTools(mergedArgs, wrapCtx, toolCalls);
2341
+ const mergedArgsWithWrappedModel = wrapModel(
2342
+ mergedArgsWithWrappedTools,
2343
+ aiSDK,
2344
+ outerOperationId,
2345
+ wrapCtx
2346
+ );
2347
+ const callParamsWithWrappedToolsAndModel = mergedArgsWithWrappedModel != null ? mergedArgsWithWrappedModel : {};
2348
+ const finalize = async (result, error) => {
2349
+ var _a3, _b3, _c2;
2350
+ const usage = extractUsageMetrics(result);
2351
+ const model = extractModel(result);
2352
+ const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(mergedArgs) : void 0;
2353
+ const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
2354
+ const baseMessages = coerceMessagesFromArgs(mergedArgs);
2355
+ const responseMessages = extractResponseMessages(result);
2356
+ const allMessages = [...baseMessages, ...responseMessages];
2357
+ const outputText = extractTextOutput(result);
2358
+ const defaultPatch = {
2359
+ eventName: (_a3 = ctx.eventName) != null ? _a3 : operation,
2360
+ input: (_b3 = lastUserMessageTextFromArgs(mergedArgs)) != null ? _b3 : extractInputFromArgs(mergedArgs),
2361
+ output: outputText,
2362
+ model,
2363
+ properties: ctx.properties,
2364
+ attachments: mergeAttachments(ctx.attachments, inputAttachments, outputAttachments)
2365
+ };
2366
+ const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
2367
+ const patch = mergeBuildEventPatch(defaultPatch, built);
2368
+ const output = patch.output;
2369
+ const finalModel = (_c2 = patch.model) != null ? _c2 : model;
2370
+ if (rootSpan) {
2371
+ const spanEndTimeUnixNano = nowUnixNanoString();
2372
+ const syntheticToolCallCount = emitTranscriptToolCallSpans({
2373
+ baseMessages,
2374
+ responseMessages,
2375
+ rootSpan,
2376
+ eventId,
2377
+ telemetry,
2378
+ toolCalls,
2379
+ traceShipper: deps.traceShipper,
2380
+ endTimeUnixNano: spanEndTimeUnixNano,
2381
+ keepEventPending: false
2382
+ });
2383
+ const finishReason = extractFinishReason(result);
2384
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
2385
+ const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
2386
+ deps.traceShipper.endSpan(rootSpan, {
2387
+ attributes: [
2388
+ ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
2389
+ attrString("ai.response.finishReason", finishReason),
2390
+ attrString("ai.response.text", output),
2391
+ attrString("ai.response.toolCalls", resultToolCalls),
2392
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
2393
+ ],
2394
+ attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
2395
+ attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
2396
+ attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
2397
+ attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
2398
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
2399
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
2400
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
2401
+ attrInt("ai.toolCall.count", toolCalls.length + syntheticToolCallCount),
2402
+ ...error ? [
2403
+ attrString(
2404
+ "error.message",
2405
+ error instanceof Error ? error.message : String(error)
2406
+ )
2407
+ ] : []
2408
+ ],
2409
+ error,
2410
+ endTimeUnixNano: spanEndTimeUnixNano
2411
+ });
2412
+ }
2413
+ if (sendEvents) {
2414
+ if (debug) {
2415
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} shipping event:`, {
2416
+ eventId,
2417
+ eventName: patch.eventName,
2418
+ userId: ctx.userId,
2419
+ hasOutput: !!output
2420
+ });
2421
+ }
2422
+ void deps.eventShipper.patch(eventId, {
2423
+ eventName: patch.eventName,
2424
+ userId: ctx.userId,
2425
+ convoId: ctx.convoId,
2426
+ input: patch.input,
2427
+ output,
2428
+ model: finalModel,
2429
+ properties: patch.properties,
2430
+ attachments: patch.attachments,
2431
+ isPending: false
2432
+ }).catch((err) => {
2433
+ if (debug)
2434
+ console.warn(
2435
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
2436
+ );
2437
+ });
2438
+ } else if (debug) {
2439
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} sendEvents=false, skipping event`);
2440
+ }
2441
+ };
2442
+ const runWithContext = async (fn) => {
2443
+ if (!rootSpan) return await fn();
2444
+ return await runWithParentSpanContext(
2445
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
2446
+ fn
2447
+ );
2448
+ };
2449
+ if (debug) {
2450
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} starting with context:`, {
2451
+ userId: ctx.userId,
2452
+ eventId,
2453
+ eventName: ctx.eventName
2454
+ });
2455
+ }
2456
+ try {
2457
+ const result = await runWithContext(async () => {
2458
+ return await generate.call(instance, callParamsWithWrappedToolsAndModel);
2459
+ });
2460
+ if (debug) {
2461
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} completed, finalizing...`);
2462
+ }
2463
+ try {
2464
+ await finalize(result);
2465
+ } catch (err) {
2466
+ if (debug)
2467
+ console.warn(
2468
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
2469
+ );
2470
+ }
2471
+ return result;
2472
+ } catch (error) {
2473
+ try {
2474
+ await finalize(void 0, error);
2475
+ } catch (err) {
2476
+ if (debug)
2477
+ console.warn(
2478
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
2479
+ );
2480
+ }
2481
+ throw error;
2482
+ }
2483
+ };
2484
+ }
2485
+ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps, debug, selfDiagnostics) {
2486
+ var _a, _b;
2487
+ const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
2488
+ const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
2489
+ const autoAttachmentEnabled = deps.options.autoAttachment !== false;
2490
+ return async (...callArgs) => {
2491
+ var _a2, _b2, _c, _d;
2492
+ const callParams = callArgs[0];
2493
+ const mergedArgs = { ...agentSettings, ...callParams };
2494
+ const operation = `${className}.stream`;
2495
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation, args: mergedArgs });
2496
+ const telemetry = extractExperimentalTelemetry(mergedArgs);
2497
+ const callTimeCtx = extractRaindropCallOptions(mergedArgs);
2498
+ const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
2499
+ if (!mergedCtx.userId) warnMissingUserIdOnce();
2500
+ const inherited = await getCurrentParentSpanContext();
2501
+ const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
2502
+ const ctx = { ...mergedCtx};
2503
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
2504
+ const outerOperationId = `ai.${operation}`;
2505
+ const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
2506
+ const modelInfoFromArgs = extractModelInfo(mergedArgs["model"]);
2507
+ const rootSpan = sendTraces ? deps.traceShipper.startSpan({
2508
+ name: outerOperationId,
2509
+ parent: inheritedParent,
2510
+ eventId,
2511
+ operationId: outerOperationId,
2512
+ attributes: [
2513
+ attrString("operation.name", operationName),
2514
+ attrString("resource.name", resourceName),
2515
+ attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
2516
+ attrString("ai.model.provider", modelInfoFromArgs.provider),
2517
+ attrString("ai.model.id", modelInfoFromArgs.modelId),
2518
+ ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
2519
+ ...attrsFromHeaders(mergedArgs["headers"]),
2520
+ ...attrsFromSettings(mergedArgs),
2521
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
2522
+ attrString(
2523
+ "ai.prompt",
2524
+ safeJsonWithUint8({
2525
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
2526
+ prompt: mergedArgs["prompt"],
2527
+ messages: mergedArgs["messages"]
2528
+ })
2529
+ )
2530
+ ]
2531
+ ]
2532
+ }) : void 0;
2533
+ const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
2534
+ const wrapCtx = {
2535
+ eventId,
2536
+ telemetry,
2537
+ sendTraces,
2538
+ debug,
2539
+ eventShipper: deps.eventShipper,
2540
+ traceShipper: deps.traceShipper,
2541
+ rootParentForChildren,
2542
+ jsonSchemaFactory: resolveJsonSchemaFactory(aiSDK),
2543
+ selfDiagnostics,
2544
+ aiSDKVersion: detectAISDKVersion(aiSDK)
2545
+ };
2546
+ const toolCalls = [];
2547
+ const mergedArgsWithWrappedTools = wrapTools(mergedArgs, wrapCtx, toolCalls);
2548
+ const mergedArgsWithWrappedModel = wrapModel(
2549
+ mergedArgsWithWrappedTools,
2550
+ aiSDK,
2551
+ outerOperationId,
2552
+ wrapCtx
2553
+ );
2554
+ const callParamsWithWrappedToolsAndModel = mergedArgsWithWrappedModel != null ? mergedArgsWithWrappedModel : {};
2555
+ const finalize = async (result, error) => {
2556
+ var _a3, _b3, _c2;
2557
+ const usage = extractUsageMetrics(result);
2558
+ const model = extractModel(result);
2559
+ const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(mergedArgs) : void 0;
2560
+ const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
2561
+ const baseMessages = coerceMessagesFromArgs(mergedArgs);
2562
+ const responseMessages = extractResponseMessages(result);
2563
+ const allMessages = [...baseMessages, ...responseMessages];
2564
+ const outputText = extractTextOutput(result);
2565
+ const defaultPatch = {
2566
+ eventName: (_a3 = ctx.eventName) != null ? _a3 : operation,
2567
+ input: (_b3 = lastUserMessageTextFromArgs(mergedArgs)) != null ? _b3 : extractInputFromArgs(mergedArgs),
2568
+ output: outputText,
2569
+ model,
2570
+ properties: ctx.properties,
2571
+ attachments: mergeAttachments(ctx.attachments, inputAttachments, outputAttachments)
2572
+ };
2573
+ const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
2574
+ const patch = mergeBuildEventPatch(defaultPatch, built);
2575
+ const output = patch.output;
2576
+ const finalModel = (_c2 = patch.model) != null ? _c2 : model;
2577
+ if (rootSpan) {
2578
+ const spanEndTimeUnixNano = nowUnixNanoString();
2579
+ const syntheticToolCallCount = emitTranscriptToolCallSpans({
2580
+ baseMessages,
2581
+ responseMessages,
2582
+ rootSpan,
2583
+ eventId,
2584
+ telemetry,
2585
+ toolCalls,
2586
+ traceShipper: deps.traceShipper,
2587
+ endTimeUnixNano: spanEndTimeUnixNano,
2588
+ keepEventPending: false
2589
+ });
2590
+ const finishReason = extractFinishReason(result);
2591
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
2592
+ const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
2593
+ deps.traceShipper.endSpan(rootSpan, {
2594
+ attributes: [
2595
+ ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
2596
+ attrString("ai.response.finishReason", finishReason),
2597
+ attrString("ai.response.text", output),
2598
+ attrString("ai.response.toolCalls", resultToolCalls),
2599
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
2600
+ ],
2601
+ attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
2602
+ attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
2603
+ attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
2604
+ attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
2605
+ attrInt("ai.usage.totalTokens", usage == null ? void 0 : usage.totalTokens),
2606
+ attrInt("ai.usage.reasoningTokens", usage == null ? void 0 : usage.reasoningTokens),
2607
+ attrInt("ai.usage.cachedInputTokens", usage == null ? void 0 : usage.cachedInputTokens),
2608
+ attrInt("ai.toolCall.count", toolCalls.length + syntheticToolCallCount),
2609
+ ...error ? [
2610
+ attrString(
2611
+ "error.message",
2612
+ error instanceof Error ? error.message : String(error)
2613
+ )
2614
+ ] : []
2615
+ ],
2616
+ error,
2617
+ endTimeUnixNano: spanEndTimeUnixNano
2618
+ });
2619
+ }
2620
+ if (sendEvents) {
2621
+ if (debug) {
2622
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} shipping event:`, {
2623
+ eventId,
2624
+ eventName: patch.eventName,
2625
+ userId: ctx.userId,
2626
+ hasOutput: !!output
2627
+ });
2628
+ }
2629
+ void deps.eventShipper.patch(eventId, {
2630
+ eventName: patch.eventName,
2631
+ userId: ctx.userId,
2632
+ convoId: ctx.convoId,
2633
+ input: patch.input,
2634
+ output,
2635
+ model: finalModel,
2636
+ properties: patch.properties,
2637
+ attachments: patch.attachments,
2638
+ isPending: false
2639
+ }).catch((err) => {
2640
+ if (debug)
2641
+ console.warn(
2642
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
2643
+ );
2644
+ });
2645
+ } else if (debug) {
2646
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} sendEvents=false, skipping event`);
2647
+ }
2648
+ };
2649
+ const runWithContext = async (fn) => {
2650
+ if (!rootSpan) return await fn();
2651
+ return await runWithParentSpanContext(
2652
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
2653
+ fn
2654
+ );
2655
+ };
2656
+ if (debug) {
2657
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} starting with context:`, {
2658
+ userId: ctx.userId,
2659
+ eventId,
2660
+ eventName: ctx.eventName
2661
+ });
2662
+ }
2663
+ const callParamsWithOnFinish = wrapOnFinish(
2664
+ callParamsWithWrappedToolsAndModel != null ? callParamsWithWrappedToolsAndModel : {},
2665
+ async (result) => {
2666
+ if (debug) {
2667
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} onFinish callback, finalizing...`);
2668
+ }
2669
+ try {
2670
+ await finalize(result);
2671
+ } catch (err) {
2672
+ if (debug)
2673
+ console.warn(
2674
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
2675
+ );
2676
+ }
2677
+ }
2678
+ );
2679
+ try {
2680
+ const result = await runWithContext(async () => {
2681
+ return await stream.call(instance, callParamsWithOnFinish);
2682
+ });
2683
+ return result;
2684
+ } catch (error) {
2685
+ try {
2686
+ await finalize(void 0, error);
2687
+ } catch (err) {
2688
+ if (debug)
2689
+ console.warn(
2690
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
2691
+ );
2692
+ }
2693
+ throw error;
2694
+ }
2695
+ };
2696
+ }
2697
+ function wrapTools(args, ctx, toolCalls) {
2698
+ if (!isRecord(args)) return args;
2699
+ const tools = isRecord(args["tools"]) ? { ...args["tools"] } : {};
2700
+ if (ctx.selfDiagnostics) {
2701
+ const reportToolName = ctx.selfDiagnostics.toolName;
2702
+ if (!(reportToolName in tools)) {
2703
+ const reportTool = createSelfDiagnosticsTool(ctx);
2704
+ if (reportTool !== void 0) {
2705
+ tools[reportToolName] = reportTool;
2706
+ }
2707
+ } else if (ctx.debug) {
2708
+ console.warn(
2709
+ `[raindrop-ai/ai-sdk] selfDiagnostics skipped: tool name collision for "${reportToolName}"`
2710
+ );
2711
+ }
2712
+ }
2713
+ if (Object.keys(tools).length === 0) return args;
2714
+ const wrapped = {};
2715
+ for (const [name, tool] of Object.entries(tools)) {
2716
+ wrapped[name] = wrapToolExecute(name, tool, ctx, toolCalls);
2717
+ }
2718
+ return { ...args, tools: wrapped };
2719
+ }
2720
+ function wrapToolExecute(name, tool, ctx, toolCalls) {
2721
+ var _a;
2722
+ if (!isRecord(tool) || !isFunction(tool["execute"])) return tool;
2723
+ const originalExecute = tool["execute"];
2724
+ const { operationName, resourceName } = opName("ai.toolCall", (_a = ctx.telemetry) == null ? void 0 : _a.functionId);
2725
+ const createToolSpan = (toolCallId, toolArgs, parent) => {
2726
+ var _a2, _b;
2727
+ if (!ctx.sendTraces || !parent) return void 0;
2728
+ return ctx.traceShipper.startSpan({
2729
+ name: "ai.toolCall",
2730
+ parent,
2731
+ eventId: ctx.eventId,
2732
+ operationId: "ai.toolCall",
2733
+ attributes: [
2734
+ attrString("operation.name", operationName),
2735
+ attrString("resource.name", resourceName),
2736
+ attrString("ai.telemetry.functionId", (_a2 = ctx.telemetry) == null ? void 0 : _a2.functionId),
2737
+ attrString("ai.toolCall.name", name),
2738
+ attrString("ai.toolCall.id", toolCallId),
2739
+ ...((_b = ctx.telemetry) == null ? void 0 : _b.recordInputs) === false ? [] : [attrString("ai.toolCall.args", safeJsonWithUint8(toolArgs))]
2740
+ ]
2741
+ });
2742
+ };
2743
+ const endToolSpan = (span, result, error) => {
2744
+ var _a2;
2745
+ if (!span) return;
2746
+ if (error) {
2747
+ ctx.traceShipper.endSpan(span, {
2748
+ attributes: [
2749
+ attrString("error.message", error instanceof Error ? error.message : String(error))
2750
+ ],
2751
+ error
2752
+ });
2753
+ } else {
2754
+ ctx.traceShipper.endSpan(span, {
2755
+ attributes: ((_a2 = ctx.telemetry) == null ? void 0 : _a2.recordOutputs) === false ? [] : [attrString("ai.toolCall.result", safeJsonWithUint8(result))]
2756
+ });
2757
+ }
2758
+ };
2759
+ const createContextSpan = (span) => ({
2760
+ traceIdB64: span.ids.traceIdB64,
2761
+ spanIdB64: span.ids.spanIdB64,
2762
+ eventId: ctx.eventId
2763
+ });
2764
+ const wrappedExecute = function(...execArgs) {
2765
+ const toolArgs = execArgs[0];
2766
+ const execOptions = execArgs.length > 1 ? execArgs[1] : void 0;
2767
+ const toolCallId = isRecord(execOptions) && typeof execOptions["toolCallId"] === "string" ? execOptions["toolCallId"] : randomUUID();
2768
+ const result = originalExecute.apply(this, execArgs);
2769
+ if (isAsyncIterable(result)) {
2770
+ return (async function* () {
2771
+ const parentCtx = await getCurrentParentSpanContext();
2772
+ const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2773
+ const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
2774
+ try {
2775
+ let lastValue;
2776
+ const iterator = result[Symbol.asyncIterator]();
2777
+ const wrappedIterable = toolSpan ? asyncGeneratorWithCurrent(
2778
+ createContextSpan(toolSpan),
2779
+ iterator
2780
+ ) : {
2781
+ [Symbol.asyncIterator]: () => iterator
2782
+ };
2783
+ for await (const value of wrappedIterable) {
2784
+ lastValue = value;
2785
+ yield value;
2786
+ }
2787
+ toolCalls.push({ id: toolCallId, name, args: toolArgs, result: lastValue, status: "OK" });
2788
+ endToolSpan(toolSpan, lastValue);
2789
+ } catch (error) {
2790
+ toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
2791
+ endToolSpan(toolSpan, void 0, error);
2792
+ throw error;
2793
+ }
2794
+ })();
2795
+ }
2796
+ return (async () => {
2797
+ const parentCtx = await getCurrentParentSpanContext();
2798
+ const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2799
+ const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
2800
+ const run = async () => {
2801
+ try {
2802
+ const awaitedResult = await result;
2803
+ toolCalls.push({
2804
+ id: toolCallId,
2805
+ name,
2806
+ args: toolArgs,
2807
+ result: awaitedResult,
2808
+ status: "OK"
2809
+ });
2810
+ endToolSpan(toolSpan, awaitedResult);
2811
+ return awaitedResult;
2812
+ } catch (error) {
2813
+ toolCalls.push({ id: toolCallId, name, args: toolArgs, status: "ERROR" });
2814
+ endToolSpan(toolSpan, void 0, error);
2815
+ throw error;
2816
+ }
2817
+ };
2818
+ if (!toolSpan) return await run();
2819
+ return await runWithParentSpanContext(
2820
+ {
2821
+ traceIdB64: toolSpan.ids.traceIdB64,
2822
+ spanIdB64: toolSpan.ids.spanIdB64,
2823
+ eventId: ctx.eventId
2824
+ },
2825
+ run
2826
+ );
2827
+ })();
2828
+ };
2829
+ return { ...tool, execute: wrappedExecute };
2830
+ }
2831
+ function wrapModel(args, aiSDK, outerOperationId, ctx) {
2832
+ if (!isRecord(args) || !("model" in args)) return args;
2833
+ let model = args["model"];
2834
+ if (typeof model === "string") {
2835
+ const maybeProvider = globalThis.AI_SDK_DEFAULT_PROVIDER;
2836
+ const gateway = isRecord(aiSDK) ? aiSDK["gateway"] : void 0;
2837
+ const provider = maybeProvider != null ? maybeProvider : gateway;
2838
+ if (isRecord(provider) && isFunction(provider["languageModel"])) {
2839
+ try {
2840
+ model = provider["languageModel"](model);
2841
+ } catch (e) {
2842
+ }
2843
+ }
2844
+ }
2845
+ if (!isRecord(model)) return args;
2846
+ const modelInfo = extractModelInfo(model);
2847
+ const doGenerateOpId = `${outerOperationId}.doGenerate`;
2848
+ const doStreamOpId = `${outerOperationId}.doStream`;
2849
+ const wrappedModel = new Proxy(model, {
2850
+ get(target, prop, receiver) {
2851
+ const original = Reflect.get(target, prop, receiver);
2852
+ if (prop === "doGenerate" && isFunction(original)) {
2853
+ return async (...callArgs) => {
2854
+ const options = callArgs[0];
2855
+ const parentCtx = await getCurrentParentSpanContext();
2856
+ const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2857
+ const span = ctx.sendTraces && parent ? startDoGenerateSpan(doGenerateOpId, options, modelInfo, parent, ctx) : void 0;
2858
+ try {
2859
+ const result = await original.apply(target, callArgs);
2860
+ if (span) endDoGenerateSpan(span, result, modelInfo, ctx);
2861
+ return result;
2862
+ } catch (error) {
2863
+ if (span)
2864
+ ctx.traceShipper.endSpan(span, {
2865
+ attributes: [
2866
+ attrString(
2867
+ "error.message",
2868
+ error instanceof Error ? error.message : String(error)
2869
+ )
2870
+ ],
2871
+ error
2872
+ });
2873
+ throw error;
2874
+ }
2875
+ };
2876
+ }
2877
+ if (prop === "doStream" && isFunction(original)) {
2878
+ return async (...callArgs) => {
2879
+ const options = callArgs[0];
2880
+ const parentCtx = await getCurrentParentSpanContext();
2881
+ const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
2882
+ const span = ctx.sendTraces && parent ? startDoStreamSpan(doStreamOpId, options, modelInfo, parent, ctx) : void 0;
2883
+ const startMs = Date.now();
2884
+ let firstChunkMs;
2885
+ let finishMs;
2886
+ let finishReason;
2887
+ let responseId;
2888
+ let responseModelId;
2889
+ let responseTimestampIso;
2890
+ let providerMetadata;
2891
+ let usage;
2892
+ let activeText = "";
2893
+ const toolCallsLocal = [];
2894
+ let result;
2895
+ try {
2896
+ result = await original.apply(target, callArgs);
2897
+ } catch (error) {
2898
+ if (span)
2899
+ ctx.traceShipper.endSpan(span, {
2900
+ attributes: [
2901
+ attrString(
2902
+ "error.message",
2903
+ error instanceof Error ? error.message : String(error)
2904
+ )
2905
+ ],
2906
+ error
2907
+ });
2908
+ throw error;
2909
+ }
2910
+ const stream = isRecord(result) ? result["stream"] : void 0;
2911
+ const RS = globalThis.ReadableStream;
2912
+ if (!RS || !(stream instanceof RS)) {
2913
+ if (span) ctx.traceShipper.endSpan(span);
2914
+ return result;
2915
+ }
2916
+ const reader = stream.getReader();
2917
+ let ended = false;
2918
+ const endSpan = (error) => {
2919
+ var _a;
2920
+ if (ended || !span) return;
2921
+ ended = true;
2922
+ const msToFirstChunk = firstChunkMs !== void 0 ? firstChunkMs - startMs : void 0;
2923
+ const msToFinish = finishMs !== void 0 ? finishMs - startMs : void 0;
2924
+ const inputTokens = extractNestedTokens(usage, "inputTokens");
2925
+ const outputTokens = extractNestedTokens(usage, "outputTokens");
2926
+ const avgOutTokensPerSecond = msToFinish && outputTokens !== void 0 && msToFinish > 0 ? 1e3 * outputTokens / msToFinish : void 0;
2927
+ ctx.traceShipper.endSpan(span, {
2928
+ attributes: [
2929
+ ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
2930
+ attrString("ai.response.finishReason", finishReason),
2931
+ attrString("ai.response.text", activeText.length ? activeText : void 0),
2932
+ attrString(
2933
+ "ai.response.toolCalls",
2934
+ safeJsonWithUint8(toolCallsLocal.length ? toolCallsLocal : void 0)
2935
+ ),
2936
+ attrString("ai.response.id", responseId),
2937
+ attrString("ai.response.model", responseModelId),
2938
+ attrString("ai.response.timestamp", responseTimestampIso),
2939
+ attrString(
2940
+ "ai.response.providerMetadata",
2941
+ safeJsonWithUint8(providerMetadata)
2942
+ )
2943
+ ],
2944
+ attrInt("ai.usage.inputTokens", inputTokens),
2945
+ attrInt("ai.usage.outputTokens", outputTokens),
2946
+ ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
2947
+ attrString("gen_ai.response.id", responseId),
2948
+ attrString("gen_ai.response.model", responseModelId),
2949
+ attrInt("gen_ai.usage.input_tokens", inputTokens),
2950
+ attrInt("gen_ai.usage.output_tokens", outputTokens),
2951
+ ...msToFirstChunk !== void 0 ? [attrInt("ai.stream.msToFirstChunk", msToFirstChunk)] : [],
2952
+ ...msToFinish !== void 0 ? [attrInt("ai.stream.msToFinish", msToFinish)] : [],
2953
+ ...avgOutTokensPerSecond !== void 0 ? [attrDouble("ai.stream.avgOutputTokensPerSecond", avgOutTokensPerSecond)] : [],
2954
+ ...error ? [
2955
+ attrString(
2956
+ "error.message",
2957
+ error instanceof Error ? error.message : String(error)
2958
+ )
2959
+ ] : []
2960
+ ],
2961
+ error
2962
+ });
2963
+ };
2964
+ const wrappedStream = new RS({
2965
+ async pull(controller) {
2966
+ try {
2967
+ const { done, value } = await reader.read();
2968
+ if (done) {
2969
+ finishMs = Date.now();
2970
+ endSpan();
2971
+ controller.close();
2972
+ return;
2973
+ }
2974
+ if (firstChunkMs === void 0) firstChunkMs = Date.now();
2975
+ if (isRecord(value)) {
2976
+ const type = value["type"];
2977
+ if (type === "text-delta") {
2978
+ let textDelta;
2979
+ if (typeof value["delta"] === "string") {
2980
+ textDelta = value["delta"];
2981
+ } else if (typeof value["textDelta"] === "string") {
2982
+ textDelta = value["textDelta"];
2983
+ }
2984
+ if (typeof textDelta === "string") activeText += textDelta;
2985
+ }
2986
+ if (type === "finish") finishReason = extractFinishReason(value);
2987
+ if (type === "tool-call") toolCallsLocal.push(value);
2988
+ if ("response" in value && isRecord(value["response"])) {
2989
+ const response = value["response"];
2990
+ if (typeof response["id"] === "string") responseId = response["id"];
2991
+ if (typeof response["modelId"] === "string")
2992
+ responseModelId = response["modelId"];
2993
+ if (response["timestamp"] instanceof Date)
2994
+ responseTimestampIso = response["timestamp"].toISOString();
2995
+ else if (typeof response["timestamp"] === "string")
2996
+ responseTimestampIso = response["timestamp"];
2997
+ }
2998
+ if ("usage" in value) usage = value["usage"];
2999
+ if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
3000
+ }
3001
+ controller.enqueue(value);
3002
+ } catch (error) {
3003
+ endSpan(error);
3004
+ controller.error(error);
3005
+ }
3006
+ },
3007
+ cancel(reason) {
3008
+ void reader.cancel(reason);
3009
+ endSpan(reason);
3010
+ }
3011
+ });
3012
+ return { ...result, stream: wrappedStream };
3013
+ };
3014
+ }
3015
+ return original;
3016
+ }
3017
+ });
3018
+ return { ...args, model: wrappedModel };
3019
+ }
3020
+ function startDoGenerateSpan(operationId, options, modelInfo, parent, ctx) {
3021
+ var _a, _b, _c;
3022
+ const { operationName, resourceName } = opName(operationId, (_a = ctx.telemetry) == null ? void 0 : _a.functionId);
3023
+ const tools = isRecord(options) ? options["tools"] : void 0;
3024
+ const toolsJson = Array.isArray(tools) && tools.length ? tools.map((tool) => safeJsonWithUint8(tool)).filter((json) => typeof json === "string" && json.length > 0) : void 0;
3025
+ const toolChoiceJson = isRecord(options) ? safeJsonWithUint8(options["toolChoice"]) : void 0;
3026
+ const promptJson = isRecord(options) ? safeJsonWithUint8(options["prompt"]) : safeJsonWithUint8(options);
3027
+ return ctx.traceShipper.startSpan({
3028
+ name: operationId,
3029
+ parent,
3030
+ eventId: ctx.eventId,
3031
+ operationId,
3032
+ attributes: [
3033
+ attrString("operation.name", operationName),
3034
+ attrString("resource.name", resourceName),
3035
+ attrString("ai.telemetry.functionId", (_b = ctx.telemetry) == null ? void 0 : _b.functionId),
3036
+ attrString("ai.model.provider", modelInfo.provider),
3037
+ attrString("ai.model.id", modelInfo.modelId),
3038
+ ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [
3039
+ attrString("ai.prompt.messages", promptJson),
3040
+ attrStringArray("ai.prompt.tools", toolsJson),
3041
+ attrString("ai.prompt.toolChoice", toolChoiceJson)
3042
+ ],
3043
+ attrString("gen_ai.system", modelInfo.provider),
3044
+ attrString("gen_ai.request.model", modelInfo.modelId),
3045
+ ...attrsFromGenAiRequest(options)
3046
+ ]
3047
+ });
3048
+ }
3049
+ function endDoGenerateSpan(span, result, modelInfo, ctx) {
3050
+ var _a;
3051
+ const finishReason = extractFinishReason(result);
3052
+ const content = isRecord(result) ? result["content"] : void 0;
3053
+ const response = isRecord(result) ? result["response"] : void 0;
3054
+ const usage = isRecord(result) ? result["usage"] : void 0;
3055
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
3056
+ let responseId;
3057
+ if (isRecord(response) && typeof response["id"] === "string") {
3058
+ responseId = response["id"];
3059
+ } else {
3060
+ responseId = randomUUID();
3061
+ }
3062
+ let responseModelId;
3063
+ if (isRecord(response) && typeof response["modelId"] === "string") {
3064
+ responseModelId = response["modelId"];
3065
+ } else {
3066
+ responseModelId = modelInfo.modelId;
3067
+ }
3068
+ let responseTimestampIso;
3069
+ if (isRecord(response) && response["timestamp"] instanceof Date) {
3070
+ responseTimestampIso = response["timestamp"].toISOString();
3071
+ } else if (isRecord(response) && typeof response["timestamp"] === "string") {
3072
+ responseTimestampIso = response["timestamp"];
3073
+ } else {
3074
+ responseTimestampIso = (/* @__PURE__ */ new Date()).toISOString();
3075
+ }
3076
+ const inputTokens = extractNestedTokens(usage, "inputTokens");
3077
+ const outputTokens = extractNestedTokens(usage, "outputTokens");
3078
+ ctx.traceShipper.endSpan(span, {
3079
+ attributes: [
3080
+ ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
3081
+ attrString("ai.response.finishReason", finishReason),
3082
+ attrString("ai.response.text", extractTextFromLmContent(content)),
3083
+ attrString(
3084
+ "ai.response.toolCalls",
3085
+ safeJsonWithUint8(extractToolCallsFromLmContent(content))
3086
+ ),
3087
+ attrString("ai.response.id", responseId),
3088
+ attrString("ai.response.model", responseModelId),
3089
+ attrString("ai.response.timestamp", responseTimestampIso),
3090
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
3091
+ ],
3092
+ attrInt("ai.usage.promptTokens", inputTokens),
3093
+ attrInt("ai.usage.completionTokens", outputTokens),
3094
+ ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
3095
+ attrString("gen_ai.response.id", responseId),
3096
+ attrString("gen_ai.response.model", responseModelId),
3097
+ attrInt("gen_ai.usage.input_tokens", inputTokens),
3098
+ attrInt("gen_ai.usage.output_tokens", outputTokens)
3099
+ ]
3100
+ });
3101
+ }
3102
+ function startDoStreamSpan(operationId, options, modelInfo, parent, ctx) {
3103
+ var _a, _b, _c;
3104
+ const { operationName, resourceName } = opName(operationId, (_a = ctx.telemetry) == null ? void 0 : _a.functionId);
3105
+ const tools = isRecord(options) ? options["tools"] : void 0;
3106
+ const toolsJson = Array.isArray(tools) && tools.length ? tools.map((tool) => safeJsonWithUint8(tool)).filter((json) => typeof json === "string" && json.length > 0) : void 0;
3107
+ const toolChoiceJson = isRecord(options) ? safeJsonWithUint8(options["toolChoice"]) : void 0;
3108
+ const promptJson = isRecord(options) ? safeJsonWithUint8(options["prompt"]) : safeJsonWithUint8(options);
3109
+ return ctx.traceShipper.startSpan({
3110
+ name: operationId,
3111
+ parent,
3112
+ eventId: ctx.eventId,
3113
+ operationId,
3114
+ attributes: [
3115
+ attrString("operation.name", operationName),
3116
+ attrString("resource.name", resourceName),
3117
+ attrString("ai.telemetry.functionId", (_b = ctx.telemetry) == null ? void 0 : _b.functionId),
3118
+ attrString("ai.model.provider", modelInfo.provider),
3119
+ attrString("ai.model.id", modelInfo.modelId),
3120
+ ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [
3121
+ attrString("ai.prompt.messages", promptJson),
3122
+ attrStringArray("ai.prompt.tools", toolsJson),
3123
+ attrString("ai.prompt.toolChoice", toolChoiceJson)
3124
+ ],
3125
+ attrString("gen_ai.system", modelInfo.provider),
3126
+ attrString("gen_ai.request.model", modelInfo.modelId),
3127
+ ...attrsFromGenAiRequest(options)
3128
+ ]
3129
+ });
3130
+ }
3131
+ function resolveContext(context, info) {
3132
+ if (context === void 0) return {};
3133
+ return typeof context === "function" ? context(info) : context;
3134
+ }
3135
+ function wrapOnFinish(args, onFinish) {
3136
+ if (!isRecord(args)) return args;
3137
+ const existing = args["onFinish"];
3138
+ if (existing === void 0) {
3139
+ return { ...args, onFinish: async (result) => onFinish(result) };
3140
+ }
3141
+ if (!isFunction(existing)) return args;
3142
+ return {
3143
+ ...args,
3144
+ onFinish: async (result) => {
3145
+ let userError;
3146
+ try {
3147
+ const maybePromise = existing(result);
3148
+ if (maybePromise && typeof maybePromise.then === "function") {
3149
+ await maybePromise;
3150
+ }
3151
+ } catch (error) {
3152
+ userError = error;
3153
+ }
3154
+ await onFinish(result);
3155
+ if (userError !== void 0) {
3156
+ throw userError;
3157
+ }
3158
+ }
3159
+ };
3160
+ }
3161
+ async function maybeBuildEvent(buildEvent, messages) {
3162
+ if (!buildEvent) return void 0;
3163
+ try {
3164
+ const r = buildEvent(messages);
3165
+ return r && typeof r === "object" ? r : void 0;
3166
+ } catch (e) {
3167
+ return void 0;
3168
+ }
3169
+ }
3170
+ function mergeBuildEventPatch(defaults, override) {
3171
+ var _a, _b, _c, _d, _e, _f, _g, _h;
3172
+ if (!override) return defaults;
3173
+ return {
3174
+ eventName: (_a = override.eventName) != null ? _a : defaults.eventName,
3175
+ input: (_b = override.input) != null ? _b : defaults.input,
3176
+ output: (_c = override.output) != null ? _c : defaults.output,
3177
+ model: (_d = override.model) != null ? _d : defaults.model,
3178
+ properties: override.properties !== void 0 ? { ...(_e = defaults.properties) != null ? _e : {}, ...(_f = override.properties) != null ? _f : {} } : defaults.properties,
3179
+ attachments: override.attachments !== void 0 ? [...(_g = defaults.attachments) != null ? _g : [], ...(_h = override.attachments) != null ? _h : []] : defaults.attachments
3180
+ };
3181
+ }
3182
+ function mergeAttachments(...groups) {
3183
+ const merged = [];
3184
+ for (const group of groups) {
3185
+ if (group == null ? void 0 : group.length) merged.push(...group);
3186
+ }
3187
+ return merged.length ? merged : void 0;
3188
+ }
3189
+ function extractNestedTokens(usage, key) {
3190
+ if (!isRecord(usage)) return void 0;
3191
+ const val = usage[key];
3192
+ if (typeof val === "number") return val;
3193
+ if (isRecord(val) && typeof val["total"] === "number") return val["total"];
3194
+ return void 0;
3195
+ }
3196
+
3197
+ // src/index.ts
3198
+ function eventMetadata(options) {
3199
+ const result = {};
3200
+ if (options.eventId) {
3201
+ result["raindrop.eventId"] = options.eventId;
3202
+ } else {
3203
+ result["raindrop.eventId"] = randomUUID();
3204
+ result["raindrop.internal.eventIdGenerated"] = "true";
3205
+ }
3206
+ if (options.userId) result["raindrop.userId"] = options.userId;
3207
+ if (options.convoId) result["raindrop.convoId"] = options.convoId;
3208
+ if (options.eventName) result["raindrop.eventName"] = options.eventName;
3209
+ if (options.properties) result["raindrop.properties"] = JSON.stringify(options.properties);
3210
+ return result;
3211
+ }
3212
+ function deriveChatTurnMessageId(request) {
3213
+ const messages = Array.isArray(request.messages) ? request.messages : [];
3214
+ for (let i = messages.length - 1; i >= 0; i--) {
3215
+ const message = messages[i];
3216
+ if ((message == null ? void 0 : message.role) === "user" && typeof message.id === "string" && message.id.length > 0) {
3217
+ return message.id;
3218
+ }
3219
+ }
3220
+ if (typeof request.messageId === "string" && request.messageId.length > 0) {
3221
+ return request.messageId;
3222
+ }
3223
+ return void 0;
3224
+ }
3225
+ function eventMetadataFromChatRequest(options) {
3226
+ var _a, _b;
3227
+ const { request, ...rest } = options;
3228
+ const convoId = (_a = rest.convoId) != null ? _a : typeof request.id === "string" && request.id.length > 0 ? request.id : void 0;
3229
+ const turnMessageId = deriveChatTurnMessageId(request);
3230
+ const eventId = (_b = rest.eventId) != null ? _b : turnMessageId ? convoId ? `chat:${convoId}:${turnMessageId}` : `chat:${turnMessageId}` : void 0;
3231
+ return eventMetadata({
3232
+ ...rest,
3233
+ ...convoId ? { convoId } : {},
3234
+ ...eventId ? { eventId } : {}
3235
+ });
3236
+ }
3237
+ function envDebugEnabled() {
3238
+ var _a;
3239
+ if (typeof process === "undefined") return false;
3240
+ const flag = (_a = process.env) == null ? void 0 : _a.RAINDROP_AI_DEBUG;
3241
+ return flag === "1" || flag === "true";
3242
+ }
3243
+ function createRaindropAISDK(opts) {
3244
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3245
+ const writeKey = opts.writeKey;
3246
+ const eventsRequested = ((_a = opts.events) == null ? void 0 : _a.enabled) !== false;
3247
+ const tracesRequested = ((_b = opts.traces) == null ? void 0 : _b.enabled) !== false;
3248
+ const eventsEnabled = eventsRequested && !!writeKey;
3249
+ const tracesEnabled = tracesRequested && !!writeKey;
3250
+ const envDebug = envDebugEnabled();
3251
+ if (!writeKey && (eventsRequested || tracesRequested)) {
3252
+ console.warn(
3253
+ "[raindrop-ai/ai-sdk] writeKey not provided; telemetry shipping is disabled"
3254
+ );
3255
+ }
3256
+ const eventShipper = new EventShipper2({
3257
+ writeKey,
3258
+ endpoint: opts.endpoint,
3259
+ enabled: eventsEnabled,
3260
+ debug: ((_c = opts.events) == null ? void 0 : _c.debug) === true || envDebug,
3261
+ partialFlushMs: (_d = opts.events) == null ? void 0 : _d.partialFlushMs
3262
+ });
3263
+ const traceShipper = new TraceShipper2({
3264
+ writeKey,
3265
+ endpoint: opts.endpoint,
3266
+ enabled: tracesEnabled,
3267
+ debug: ((_e = opts.traces) == null ? void 0 : _e.debug) === true || envDebug,
3268
+ debugSpans: ((_f = opts.traces) == null ? void 0 : _f.debugSpans) === true || envDebug,
3269
+ flushIntervalMs: (_g = opts.traces) == null ? void 0 : _g.flushIntervalMs,
3270
+ maxBatchSize: (_h = opts.traces) == null ? void 0 : _h.maxBatchSize,
3271
+ maxQueueSize: (_i = opts.traces) == null ? void 0 : _i.maxQueueSize
3272
+ });
3273
+ return {
3274
+ wrap(aiSDK, options) {
3275
+ return wrapAISDK(aiSDK, {
3276
+ options: options != null ? options : {},
3277
+ eventShipper,
3278
+ traceShipper
3279
+ });
3280
+ },
3281
+ events: {
3282
+ async patch(eventId, patch) {
3283
+ await eventShipper.patch(eventId, patch);
3284
+ },
3285
+ async addAttachments(eventId, attachments) {
3286
+ await eventShipper.patch(eventId, { attachments });
3287
+ },
3288
+ async setProperties(eventId, properties) {
3289
+ await eventShipper.patch(eventId, { properties });
3290
+ },
3291
+ async finish(eventId, patch) {
3292
+ await eventShipper.finish(eventId, patch);
3293
+ }
3294
+ },
3295
+ users: {
3296
+ async identify(users) {
3297
+ await eventShipper.identify(users);
3298
+ }
3299
+ },
3300
+ signals: {
3301
+ async track(signal) {
3302
+ await eventShipper.trackSignal(signal);
3303
+ }
3304
+ },
3305
+ async flush() {
3306
+ await Promise.all([eventShipper.flush(), traceShipper.flush()]);
3307
+ },
3308
+ async shutdown() {
3309
+ await Promise.all([eventShipper.shutdown(), traceShipper.shutdown()]);
3310
+ }
3311
+ };
3312
+ }
3313
+
3314
+ export { _resetWarnedMissingUserId, createRaindropAISDK, currentSpan, eventMetadata, eventMetadataFromChatRequest, getContextManager, withCurrent };