@raindrop-ai/ai-sdk 0.0.1

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,2068 @@
1
+ // src/internal/http.ts
2
+ function wait(ms) {
3
+ return new Promise((resolve) => setTimeout(resolve, ms));
4
+ }
5
+ function formatEndpoint(endpoint) {
6
+ if (!endpoint) return void 0;
7
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
8
+ }
9
+ function parseRetryAfter(headers) {
10
+ var _a;
11
+ const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
12
+ if (!value) return void 0;
13
+ const asNumber = Number(value);
14
+ if (!Number.isNaN(asNumber)) return asNumber * 1e3;
15
+ const asDate = new Date(value).getTime();
16
+ if (!Number.isNaN(asDate)) {
17
+ const delta = asDate - Date.now();
18
+ return delta > 0 ? delta : 0;
19
+ }
20
+ return void 0;
21
+ }
22
+ function getRetryDelayMs(attemptNumber, previousError) {
23
+ if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
24
+ const v = previousError.retryAfterMs;
25
+ if (typeof v === "number") return Math.max(0, v);
26
+ }
27
+ if (attemptNumber <= 1) return 0;
28
+ const base = 500;
29
+ const factor = Math.pow(2, attemptNumber - 2);
30
+ return base * factor;
31
+ }
32
+ async function withRetry(operation, opName2, opts) {
33
+ let lastError = void 0;
34
+ for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
35
+ if (attemptNumber > 1) {
36
+ const delay = getRetryDelayMs(attemptNumber, lastError);
37
+ if (opts.debug) {
38
+ console.warn(`[raindrop-ai/ai-sdk] ${opName2} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`);
39
+ }
40
+ if (delay > 0) await wait(delay);
41
+ } else if (opts.debug) {
42
+ console.log(`[raindrop-ai/ai-sdk] ${opName2} attempt ${attemptNumber}/${opts.maxAttempts}`);
43
+ }
44
+ try {
45
+ return await operation();
46
+ } catch (err) {
47
+ lastError = err;
48
+ if (opts.debug) {
49
+ const msg = err instanceof Error ? err.message : String(err);
50
+ console.warn(
51
+ `[raindrop-ai/ai-sdk] ${opName2} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
52
+ );
53
+ }
54
+ if (attemptNumber === opts.maxAttempts) break;
55
+ }
56
+ }
57
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
58
+ }
59
+ async function postJson(url, body, headers, opts) {
60
+ const opName2 = `POST ${url}`;
61
+ await withRetry(
62
+ async () => {
63
+ const resp = await fetch(url, {
64
+ method: "POST",
65
+ headers: {
66
+ "Content-Type": "application/json",
67
+ ...headers
68
+ },
69
+ body: JSON.stringify(body)
70
+ });
71
+ if (!resp.ok) {
72
+ const text = await resp.text().catch(() => "");
73
+ const err = new Error(`HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`);
74
+ const retryAfterMs = parseRetryAfter(resp.headers);
75
+ if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
76
+ throw err;
77
+ }
78
+ },
79
+ opName2,
80
+ opts
81
+ );
82
+ }
83
+
84
+ // src/internal/events.ts
85
+ function getRuntimeContext() {
86
+ const isNode = typeof process !== "undefined" && typeof process.version === "string";
87
+ return {
88
+ library: { name: "@raindrop-ai/ai-sdk", version: "0.0.1" },
89
+ metadata: {
90
+ jsRuntime: isNode ? "node" : "web",
91
+ ...isNode ? { nodeVersion: process.version } : {}
92
+ }
93
+ };
94
+ }
95
+ function mergePatches(target, source) {
96
+ var _a, _b, _c, _d;
97
+ const out = { ...target, ...source };
98
+ if (target.properties || source.properties) {
99
+ out.properties = { ...(_a = target.properties) != null ? _a : {}, ...(_b = source.properties) != null ? _b : {} };
100
+ }
101
+ if (target.attachments || source.attachments) {
102
+ out.attachments = [...(_c = target.attachments) != null ? _c : [], ...(_d = source.attachments) != null ? _d : []];
103
+ }
104
+ return out;
105
+ }
106
+ var EventShipper = class {
107
+ constructor(opts) {
108
+ this.buffers = /* @__PURE__ */ new Map();
109
+ this.sticky = /* @__PURE__ */ new Map();
110
+ this.timers = /* @__PURE__ */ new Map();
111
+ this.inFlight = /* @__PURE__ */ new Set();
112
+ var _a, _b;
113
+ if (!opts.writeKey) throw new Error("[raindrop-ai/ai-sdk] writeKey is required");
114
+ this.writeKey = opts.writeKey;
115
+ this.baseUrl = (_a = formatEndpoint(opts.endpoint)) != null ? _a : "https://api.raindrop.ai/v1/";
116
+ this.enabled = opts.enabled;
117
+ this.debug = opts.debug;
118
+ this.partialFlushMs = (_b = opts.partialFlushMs) != null ? _b : 1e3;
119
+ this.context = getRuntimeContext();
120
+ }
121
+ isDebugEnabled() {
122
+ return this.debug;
123
+ }
124
+ async patch(eventId, patch) {
125
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
126
+ if (!this.enabled) return;
127
+ if (!eventId) return;
128
+ const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
129
+ const existing = (_b = this.buffers.get(eventId)) != null ? _b : {};
130
+ const merged = mergePatches(existing, patch);
131
+ merged.isPending = (_e = (_d = (_c = patch.isPending) != null ? _c : existing.isPending) != null ? _d : sticky.isPending) != null ? _e : true;
132
+ this.buffers.set(eventId, merged);
133
+ this.sticky.set(eventId, {
134
+ userId: (_f = merged.userId) != null ? _f : sticky.userId,
135
+ convoId: (_g = merged.convoId) != null ? _g : sticky.convoId,
136
+ eventName: (_h = merged.eventName) != null ? _h : sticky.eventName,
137
+ isPending: (_i = merged.isPending) != null ? _i : sticky.isPending
138
+ });
139
+ const t = this.timers.get(eventId);
140
+ if (t) clearTimeout(t);
141
+ if (merged.isPending === false) {
142
+ await this.flushOne(eventId);
143
+ return;
144
+ }
145
+ const timeout = setTimeout(() => {
146
+ void this.flushOne(eventId).catch(() => {
147
+ });
148
+ }, this.partialFlushMs);
149
+ this.timers.set(eventId, timeout);
150
+ }
151
+ async finish(eventId, patch) {
152
+ await this.patch(eventId, { ...patch, isPending: false });
153
+ }
154
+ async flush() {
155
+ if (!this.enabled) return;
156
+ const ids = [...this.buffers.keys()];
157
+ await Promise.all(ids.map((id) => this.flushOne(id)));
158
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
159
+ })));
160
+ }
161
+ async shutdown() {
162
+ for (const t of this.timers.values()) clearTimeout(t);
163
+ this.timers.clear();
164
+ await this.flush();
165
+ }
166
+ async trackSignal(signal) {
167
+ var _a, _b;
168
+ if (!this.enabled) return;
169
+ const body = [
170
+ {
171
+ event_id: signal.eventId,
172
+ signal_name: signal.name,
173
+ signal_type: (_a = signal.type) != null ? _a : "default",
174
+ timestamp: signal.timestamp,
175
+ sentiment: signal.sentiment,
176
+ attachment_id: signal.attachmentId,
177
+ properties: {
178
+ ...(_b = signal.properties) != null ? _b : {},
179
+ ...signal.comment ? { comment: signal.comment } : {},
180
+ ...signal.after ? { after: signal.after } : {}
181
+ }
182
+ }
183
+ ];
184
+ const url = `${this.baseUrl}signals/track`;
185
+ try {
186
+ await postJson(
187
+ url,
188
+ body,
189
+ { Authorization: `Bearer ${this.writeKey}` },
190
+ { maxAttempts: 3, debug: this.debug }
191
+ );
192
+ } catch (err) {
193
+ if (this.debug) {
194
+ const msg = err instanceof Error ? err.message : String(err);
195
+ console.warn(`[raindrop-ai/ai-sdk] failed to send signal (dropping): ${msg}`);
196
+ }
197
+ }
198
+ }
199
+ async flushOne(eventId) {
200
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
201
+ if (!this.enabled) return;
202
+ const timer = this.timers.get(eventId);
203
+ if (timer) {
204
+ clearTimeout(timer);
205
+ this.timers.delete(eventId);
206
+ }
207
+ const accumulated = this.buffers.get(eventId);
208
+ this.buffers.delete(eventId);
209
+ if (!accumulated) return;
210
+ const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
211
+ const eventName = (_c = (_b = accumulated.eventName) != null ? _b : sticky.eventName) != null ? _c : "ai_generation";
212
+ const userId = (_d = accumulated.userId) != null ? _d : sticky.userId;
213
+ if (!userId) {
214
+ if (this.debug) {
215
+ console.warn(`[raindrop-ai/ai-sdk] skipping track_partial for ${eventId}: missing userId`);
216
+ }
217
+ return;
218
+ }
219
+ const payload = {
220
+ event_id: eventId,
221
+ user_id: userId,
222
+ event: eventName,
223
+ timestamp: (_e = accumulated.timestamp) != null ? _e : (/* @__PURE__ */ new Date()).toISOString(),
224
+ ai_data: {
225
+ input: accumulated.input,
226
+ output: accumulated.output,
227
+ model: accumulated.model,
228
+ convo_id: (_f = accumulated.convoId) != null ? _f : sticky.convoId
229
+ },
230
+ properties: {
231
+ ...(_g = accumulated.properties) != null ? _g : {},
232
+ $context: this.context
233
+ },
234
+ attachments: accumulated.attachments,
235
+ is_pending: ((_i = (_h = accumulated.isPending) != null ? _h : sticky.isPending) != null ? _i : true) !== false
236
+ };
237
+ const url = `${this.baseUrl}events/track_partial`;
238
+ const p = postJson(
239
+ url,
240
+ payload,
241
+ { Authorization: `Bearer ${this.writeKey}` },
242
+ { maxAttempts: 3, debug: this.debug }
243
+ );
244
+ this.inFlight.add(p);
245
+ try {
246
+ try {
247
+ await p;
248
+ if (this.debug) {
249
+ console.log(`[raindrop-ai/ai-sdk] sent track_partial ${eventId} (${eventName})`);
250
+ }
251
+ } catch (err) {
252
+ if (this.debug) {
253
+ const msg = err instanceof Error ? err.message : String(err);
254
+ console.warn(`[raindrop-ai/ai-sdk] failed to send track_partial (dropping): ${msg}`);
255
+ }
256
+ }
257
+ } finally {
258
+ this.inFlight.delete(p);
259
+ }
260
+ const isPending = payload.is_pending;
261
+ if (!isPending) {
262
+ this.sticky.delete(eventId);
263
+ }
264
+ }
265
+ };
266
+
267
+ // src/internal/ids.ts
268
+ function getCrypto() {
269
+ const c = globalThis.crypto;
270
+ return c;
271
+ }
272
+ function randomBytes(length) {
273
+ const cryptoObj = getCrypto();
274
+ const out = new Uint8Array(length);
275
+ if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
276
+ cryptoObj.getRandomValues(out);
277
+ return out;
278
+ }
279
+ for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
280
+ return out;
281
+ }
282
+ function randomUUID() {
283
+ const cryptoObj = getCrypto();
284
+ if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
285
+ return cryptoObj.randomUUID();
286
+ }
287
+ const b = randomBytes(16);
288
+ b[6] = b[6] & 15 | 64;
289
+ b[8] = b[8] & 63 | 128;
290
+ const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
291
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
292
+ }
293
+ function base64Encode(bytes) {
294
+ const maybeBuffer = globalThis.Buffer;
295
+ if (maybeBuffer) {
296
+ return maybeBuffer.from(bytes).toString("base64");
297
+ }
298
+ let binary = "";
299
+ for (let i2 = 0; i2 < bytes.length; i2++) {
300
+ binary += String.fromCharCode(bytes[i2]);
301
+ }
302
+ const btoaFn = globalThis.btoa;
303
+ if (typeof btoaFn === "function") return btoaFn(binary);
304
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
305
+ let out = "";
306
+ let i = 0;
307
+ while (i < binary.length) {
308
+ const c1 = binary.charCodeAt(i++) & 255;
309
+ const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
310
+ const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
311
+ const e1 = c1 >> 2;
312
+ const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
313
+ const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
314
+ const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
315
+ out += alphabet.charAt(e1);
316
+ out += alphabet.charAt(e2);
317
+ out += e3 === 64 ? "=" : alphabet.charAt(e3);
318
+ out += e4 === 64 ? "=" : alphabet.charAt(e4);
319
+ }
320
+ return out;
321
+ }
322
+
323
+ // src/internal/otlp.ts
324
+ function createSpanIds(parent) {
325
+ const traceId = parent ? parent.traceIdB64 : base64Encode(randomBytes(16));
326
+ const spanId = base64Encode(randomBytes(8));
327
+ return {
328
+ traceIdB64: traceId,
329
+ spanIdB64: spanId,
330
+ parentSpanIdB64: parent ? parent.spanIdB64 : void 0
331
+ };
332
+ }
333
+ function nowUnixNanoString() {
334
+ return String(Date.now() * 1e6);
335
+ }
336
+ function attrString(key, value) {
337
+ if (value === void 0) return void 0;
338
+ return { key, value: { stringValue: value } };
339
+ }
340
+ function attrInt(key, value) {
341
+ if (value === void 0) return void 0;
342
+ if (!Number.isFinite(value)) return void 0;
343
+ return { key, value: { intValue: String(Math.trunc(value)) } };
344
+ }
345
+ function attrDouble(key, value) {
346
+ if (value === void 0) return void 0;
347
+ if (!Number.isFinite(value)) return void 0;
348
+ return { key, value: { doubleValue: value } };
349
+ }
350
+ function attrBool(key, value) {
351
+ if (value === void 0) return void 0;
352
+ return { key, value: { boolValue: value } };
353
+ }
354
+ function attrStringArray(key, values) {
355
+ if (!values || values.length === 0) return void 0;
356
+ return {
357
+ key,
358
+ value: {
359
+ arrayValue: {
360
+ values: values.filter((v) => typeof v === "string").map((v) => ({ stringValue: v }))
361
+ }
362
+ }
363
+ };
364
+ }
365
+ function buildOtlpSpan(args) {
366
+ const attrs = args.attributes.filter((x) => x !== void 0);
367
+ const span = {
368
+ traceId: args.ids.traceIdB64,
369
+ spanId: args.ids.spanIdB64,
370
+ name: args.name,
371
+ startTimeUnixNano: args.startTimeUnixNano,
372
+ endTimeUnixNano: args.endTimeUnixNano
373
+ };
374
+ if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
375
+ if (attrs.length) span.attributes = attrs;
376
+ return span;
377
+ }
378
+ function buildExportTraceServiceRequest(spans) {
379
+ return {
380
+ resourceSpans: [
381
+ {
382
+ resource: {
383
+ attributes: [
384
+ { key: "service.name", value: { stringValue: "raindrop.ai-sdk" } }
385
+ ]
386
+ },
387
+ scopeSpans: [
388
+ {
389
+ scope: { name: "raindrop.ai-sdk", version: "0.0.1" },
390
+ spans
391
+ }
392
+ ]
393
+ }
394
+ ]
395
+ };
396
+ }
397
+
398
+ // src/internal/traces.ts
399
+ var TraceShipper = class {
400
+ constructor(opts) {
401
+ this.queue = [];
402
+ this.inFlight = /* @__PURE__ */ new Set();
403
+ var _a, _b, _c, _d;
404
+ if (!opts.writeKey) throw new Error("[raindrop-ai/ai-sdk] writeKey is required");
405
+ this.writeKey = opts.writeKey;
406
+ this.baseUrl = (_a = formatEndpoint(opts.endpoint)) != null ? _a : "https://api.raindrop.ai/v1/";
407
+ this.enabled = opts.enabled;
408
+ this.debug = opts.debug;
409
+ this.debugSpans = opts.debugSpans === true;
410
+ this.flushIntervalMs = (_b = opts.flushIntervalMs) != null ? _b : 1e3;
411
+ this.maxBatchSize = (_c = opts.maxBatchSize) != null ? _c : 50;
412
+ this.maxQueueSize = (_d = opts.maxQueueSize) != null ? _d : 5e3;
413
+ }
414
+ isDebugEnabled() {
415
+ return this.debug;
416
+ }
417
+ startSpan(args) {
418
+ var _a;
419
+ const ids = createSpanIds(args.parent);
420
+ const started = nowUnixNanoString();
421
+ const attrs = [
422
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
423
+ // Important: omit userId to avoid backend spans->events duplication
424
+ attrString("ai.operationId", args.operationId)
425
+ ];
426
+ if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
427
+ return { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
428
+ }
429
+ endSpan(span, extra) {
430
+ var _a;
431
+ if (span.endTimeUnixNano) return;
432
+ span.endTimeUnixNano = nowUnixNanoString();
433
+ if ((_a = extra == null ? void 0 : extra.attributes) == null ? void 0 : _a.length) {
434
+ span.attributes.push(...extra.attributes);
435
+ }
436
+ const otlp = buildOtlpSpan({
437
+ ids: span.ids,
438
+ name: span.name,
439
+ startTimeUnixNano: span.startTimeUnixNano,
440
+ endTimeUnixNano: span.endTimeUnixNano,
441
+ attributes: span.attributes
442
+ });
443
+ this.enqueue(otlp);
444
+ }
445
+ enqueue(span) {
446
+ if (!this.enabled) return;
447
+ if (this.debugSpans) {
448
+ const short = (s) => s ? s.slice(-8) : "none";
449
+ console.log(
450
+ `[raindrop-ai/ai-sdk][span] name=${span.name} trace=${short(span.traceId)} span=${short(span.spanId)} parent=${short(
451
+ span.parentSpanId
452
+ )}`
453
+ );
454
+ }
455
+ if (this.queue.length >= this.maxQueueSize) {
456
+ this.queue.shift();
457
+ }
458
+ this.queue.push(span);
459
+ if (this.queue.length >= this.maxBatchSize) {
460
+ void this.flush().catch(() => {
461
+ });
462
+ return;
463
+ }
464
+ if (!this.timer) {
465
+ this.timer = setTimeout(() => {
466
+ this.timer = void 0;
467
+ void this.flush().catch(() => {
468
+ });
469
+ }, this.flushIntervalMs);
470
+ }
471
+ }
472
+ async flush() {
473
+ if (!this.enabled) return;
474
+ if (this.timer) {
475
+ clearTimeout(this.timer);
476
+ this.timer = void 0;
477
+ }
478
+ while (this.queue.length > 0) {
479
+ const batch = this.queue.splice(0, this.maxBatchSize);
480
+ const body = buildExportTraceServiceRequest(batch);
481
+ const url = `${this.baseUrl}traces`;
482
+ const p = postJson(
483
+ url,
484
+ body,
485
+ { Authorization: `Bearer ${this.writeKey}` },
486
+ { maxAttempts: 3, debug: this.debug }
487
+ );
488
+ this.inFlight.add(p);
489
+ try {
490
+ try {
491
+ await p;
492
+ if (this.debug) console.log(`[raindrop-ai/ai-sdk] sent ${batch.length} spans`);
493
+ } catch (err) {
494
+ if (this.debug) {
495
+ const msg = err instanceof Error ? err.message : String(err);
496
+ console.warn(`[raindrop-ai/ai-sdk] failed to send spans (dropping): ${msg}`);
497
+ }
498
+ }
499
+ } finally {
500
+ this.inFlight.delete(p);
501
+ }
502
+ }
503
+ }
504
+ async shutdown() {
505
+ if (this.timer) {
506
+ clearTimeout(this.timer);
507
+ this.timer = void 0;
508
+ }
509
+ await this.flush();
510
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
511
+ })));
512
+ }
513
+ };
514
+
515
+ // src/internal/spanContext.ts
516
+ var NOOP_SPAN = {
517
+ traceIdB64: "",
518
+ spanIdB64: "",
519
+ eventId: "",
520
+ log() {
521
+ }
522
+ };
523
+ function isPromiseLike(value) {
524
+ return value !== null && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function";
525
+ }
526
+ var PendingAsyncLocalStorage = class {
527
+ constructor() {
528
+ this._real = null;
529
+ this._stack = [];
530
+ }
531
+ setReal(real) {
532
+ const current = this._stack.length ? this._stack[this._stack.length - 1] : void 0;
533
+ this._real = real;
534
+ if (current !== void 0 && typeof this._real.enterWith === "function") {
535
+ this._real.enterWith(current);
536
+ }
537
+ }
538
+ getStore() {
539
+ var _a, _b;
540
+ return (_b = (_a = this._real) == null ? void 0 : _a.getStore()) != null ? _b : this._stack[this._stack.length - 1];
541
+ }
542
+ run(store, callback) {
543
+ if (this._real) {
544
+ return this._real.run(store, callback);
545
+ }
546
+ this._stack.push(store);
547
+ try {
548
+ const result = callback();
549
+ if (isPromiseLike(result)) {
550
+ return result.then(
551
+ (value) => {
552
+ this._stack.pop();
553
+ return value;
554
+ },
555
+ (err) => {
556
+ this._stack.pop();
557
+ throw err;
558
+ }
559
+ );
560
+ }
561
+ this._stack.pop();
562
+ return result;
563
+ } catch (err) {
564
+ this._stack.pop();
565
+ throw err;
566
+ }
567
+ }
568
+ };
569
+ var ContextManager = class {
570
+ };
571
+ var RaindropContextManager = class extends ContextManager {
572
+ constructor() {
573
+ var _a;
574
+ super();
575
+ this._storage = null;
576
+ this._pending = null;
577
+ this._initPromise = null;
578
+ const isNode = typeof process !== "undefined" && typeof ((_a = process == null ? void 0 : process.versions) == null ? void 0 : _a.node) === "string";
579
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
580
+ if (Ctor) {
581
+ this._storage = new Ctor();
582
+ this._pending = null;
583
+ this._initPromise = null;
584
+ return;
585
+ }
586
+ if (isNode) {
587
+ this._pending = new PendingAsyncLocalStorage();
588
+ this._storage = this._pending;
589
+ this._initPromise = this._initialize();
590
+ } else {
591
+ this._storage = null;
592
+ this._pending = null;
593
+ this._initPromise = null;
594
+ }
595
+ }
596
+ async _initialize() {
597
+ try {
598
+ const mod = await import('async_hooks');
599
+ const real = new mod.AsyncLocalStorage();
600
+ if (this._pending) {
601
+ this._pending.setReal(real);
602
+ }
603
+ this._storage = real;
604
+ } catch (e) {
605
+ this._storage = null;
606
+ }
607
+ }
608
+ async ensureReady() {
609
+ if (this._initPromise) {
610
+ await this._initPromise;
611
+ this._initPromise = null;
612
+ }
613
+ }
614
+ isReady() {
615
+ return this._initPromise === null;
616
+ }
617
+ getParentSpanIds() {
618
+ var _a;
619
+ const span = (_a = this._storage) == null ? void 0 : _a.getStore();
620
+ if (!span || span === NOOP_SPAN) return void 0;
621
+ return {
622
+ traceIdB64: span.traceIdB64,
623
+ spanIdB64: span.spanIdB64,
624
+ eventId: span.eventId
625
+ };
626
+ }
627
+ runInContext(span, callback) {
628
+ if (!this._storage) return callback();
629
+ return this._storage.run(span, callback);
630
+ }
631
+ getCurrentSpan() {
632
+ var _a;
633
+ return (_a = this._storage) == null ? void 0 : _a.getStore();
634
+ }
635
+ };
636
+ var _contextManager = null;
637
+ function getContextManager() {
638
+ if (!_contextManager) {
639
+ _contextManager = globalThis.RAINDROP_CONTEXT_MANAGER ? new globalThis.RAINDROP_CONTEXT_MANAGER() : new RaindropContextManager();
640
+ }
641
+ return _contextManager;
642
+ }
643
+ function currentSpan() {
644
+ var _a;
645
+ return (_a = getContextManager().getCurrentSpan()) != null ? _a : NOOP_SPAN;
646
+ }
647
+ function withCurrent(span, callback) {
648
+ return getContextManager().runInContext(span, callback);
649
+ }
650
+ async function getCurrentParentSpanContext() {
651
+ const cm = getContextManager();
652
+ if (cm instanceof RaindropContextManager) {
653
+ await cm.ensureReady();
654
+ }
655
+ return cm.getParentSpanIds();
656
+ }
657
+ async function runWithParentSpanContext(ctx, fn) {
658
+ const cm = getContextManager();
659
+ if (cm instanceof RaindropContextManager) {
660
+ await cm.ensureReady();
661
+ }
662
+ const span = {
663
+ traceIdB64: ctx.traceIdB64,
664
+ spanIdB64: ctx.spanIdB64,
665
+ eventId: ctx.eventId
666
+ };
667
+ return cm.runInContext(span, fn);
668
+ }
669
+ async function* asyncGeneratorWithCurrent(span, gen) {
670
+ let nextValue;
671
+ while (true) {
672
+ const result = await withCurrent(span, async () => {
673
+ try {
674
+ return await gen.next(nextValue);
675
+ } catch (e) {
676
+ return { value: void 0, done: true, error: e };
677
+ }
678
+ });
679
+ if ("error" in result && result.error !== void 0) {
680
+ throw result.error;
681
+ }
682
+ if (result.done) {
683
+ return result.value;
684
+ }
685
+ nextValue = yield result.value;
686
+ }
687
+ }
688
+ function isAsyncGenerator(value) {
689
+ return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value.next === "function";
690
+ }
691
+
692
+ // src/internal/wrap/helpers.ts
693
+ function isRecord(value) {
694
+ return typeof value === "object" && value !== null;
695
+ }
696
+ function isFunction(value) {
697
+ return typeof value === "function";
698
+ }
699
+ function isModuleNamespace(obj) {
700
+ var _a;
701
+ if (!obj || typeof obj !== "object") return false;
702
+ const asObject = obj;
703
+ if (((_a = asObject.constructor) == null ? void 0 : _a.name) === "Module") return true;
704
+ try {
705
+ const keys = Object.keys(obj);
706
+ if (keys.length === 0) return false;
707
+ const descriptor = Object.getOwnPropertyDescriptor(obj, keys[0]);
708
+ if (!descriptor) return false;
709
+ const isWritable = "writable" in descriptor ? descriptor.writable : true;
710
+ return !descriptor.configurable && !isWritable;
711
+ } catch (e) {
712
+ return false;
713
+ }
714
+ }
715
+ function safeJson(value) {
716
+ try {
717
+ return JSON.stringify(value);
718
+ } catch (e) {
719
+ return void 0;
720
+ }
721
+ }
722
+ function safeJsonWithUint8(value) {
723
+ try {
724
+ return JSON.stringify(value, (_key, v) => {
725
+ if (v instanceof Uint8Array) return base64Encode(v);
726
+ return v;
727
+ });
728
+ } catch (e) {
729
+ return void 0;
730
+ }
731
+ }
732
+ function extractModelInfo(model) {
733
+ if (typeof model === "string") {
734
+ const slashIndex2 = model.indexOf("/");
735
+ if (slashIndex2 > 0 && slashIndex2 < model.length - 1) {
736
+ return {
737
+ provider: model.slice(0, slashIndex2),
738
+ modelId: model.slice(slashIndex2 + 1)
739
+ };
740
+ }
741
+ return { modelId: model };
742
+ }
743
+ if (!isRecord(model)) return {};
744
+ const provider = typeof model["provider"] === "string" ? model["provider"] : void 0;
745
+ let modelIdRaw;
746
+ if (typeof model["modelId"] === "string") {
747
+ modelIdRaw = model["modelId"];
748
+ } else if (typeof model["model"] === "string") {
749
+ modelIdRaw = model["model"];
750
+ }
751
+ if (!modelIdRaw) {
752
+ return { provider };
753
+ }
754
+ const slashIndex = modelIdRaw.indexOf("/");
755
+ if (!provider && slashIndex > 0 && slashIndex < modelIdRaw.length - 1) {
756
+ return {
757
+ provider: modelIdRaw.slice(0, slashIndex),
758
+ modelId: modelIdRaw.slice(slashIndex + 1)
759
+ };
760
+ }
761
+ return { provider, modelId: modelIdRaw };
762
+ }
763
+ function extractTextOutput(result) {
764
+ if (!isRecord(result)) return void 0;
765
+ const text = result["text"];
766
+ return typeof text === "string" ? text : void 0;
767
+ }
768
+ function extractObjectOutput(result) {
769
+ var _a;
770
+ if (!isRecord(result)) return void 0;
771
+ const obj = result["object"];
772
+ if (obj === void 0) return void 0;
773
+ return (_a = safeJson(obj)) != null ? _a : String(obj);
774
+ }
775
+ function extractUsage(result) {
776
+ if (!isRecord(result)) return void 0;
777
+ const usage = isRecord(result["totalUsage"]) ? result["totalUsage"] : result["usage"];
778
+ if (!isRecord(usage)) return void 0;
779
+ let inputTokens;
780
+ const inputVal = usage["inputTokens"];
781
+ if (typeof inputVal === "number") {
782
+ inputTokens = inputVal;
783
+ } else if (isRecord(inputVal) && typeof inputVal["total"] === "number") {
784
+ inputTokens = inputVal["total"];
785
+ } else if (typeof usage["promptTokens"] === "number") {
786
+ inputTokens = usage["promptTokens"];
787
+ }
788
+ let outputTokens;
789
+ const outputVal = usage["outputTokens"];
790
+ if (typeof outputVal === "number") {
791
+ outputTokens = outputVal;
792
+ } else if (isRecord(outputVal) && typeof outputVal["total"] === "number") {
793
+ outputTokens = outputVal["total"];
794
+ } else if (typeof usage["completionTokens"] === "number") {
795
+ outputTokens = usage["completionTokens"];
796
+ }
797
+ if (inputTokens === void 0 && outputTokens === void 0) return void 0;
798
+ return { inputTokens, outputTokens };
799
+ }
800
+ function isAgentClass(value) {
801
+ if (typeof value !== "function") return false;
802
+ const proto = value.prototype;
803
+ if (!isRecord(proto)) return false;
804
+ return typeof proto["generate"] === "function" && typeof proto["stream"] === "function";
805
+ }
806
+ function extractModel(result) {
807
+ if (!isRecord(result)) return void 0;
808
+ const model = result["model"];
809
+ return typeof model === "string" && model.length ? model : void 0;
810
+ }
811
+ function extractFinishReason(result) {
812
+ if (!isRecord(result)) return void 0;
813
+ if (typeof result["finishReason"] === "string") return result["finishReason"];
814
+ if (isRecord(result["finishReason"]) && typeof result["finishReason"]["unified"] === "string") {
815
+ return result["finishReason"]["unified"];
816
+ }
817
+ return void 0;
818
+ }
819
+ function lastUserMessageTextFromArgs(args) {
820
+ var _a;
821
+ if (!isRecord(args)) return void 0;
822
+ const messages = args["messages"];
823
+ if (!Array.isArray(messages)) return void 0;
824
+ for (let i = messages.length - 1; i >= 0; i--) {
825
+ const message = messages[i];
826
+ if (!isRecord(message) || message["role"] !== "user") continue;
827
+ const content = message["content"];
828
+ if (typeof content === "string") return content;
829
+ return (_a = safeJsonWithUint8(content)) != null ? _a : String(content);
830
+ }
831
+ return void 0;
832
+ }
833
+ function extractInputFromArgs(args) {
834
+ var _a;
835
+ if (!isRecord(args)) return void 0;
836
+ const prompt = args["prompt"];
837
+ if (typeof prompt === "string") return prompt;
838
+ const messages = args["messages"];
839
+ if (Array.isArray(messages) && messages.length > 0) {
840
+ const last = messages[messages.length - 1];
841
+ if (isRecord(last)) {
842
+ const content = last["content"];
843
+ if (typeof content === "string") return content;
844
+ const asJson = safeJson(content);
845
+ if (asJson) return asJson;
846
+ }
847
+ return (_a = safeJson(messages)) != null ? _a : void 0;
848
+ }
849
+ const input = args["input"];
850
+ if (typeof input === "string") return input;
851
+ return safeJson(args);
852
+ }
853
+ function coerceMessagesFromArgs(args) {
854
+ if (!isRecord(args)) return [];
855
+ const result = [];
856
+ if (typeof args["system"] === "string" && args["system"]) {
857
+ result.push({ role: "system", content: args["system"] });
858
+ }
859
+ const messages = args["messages"];
860
+ if (Array.isArray(messages)) {
861
+ for (const message of messages) {
862
+ if (isRecord(message) && typeof message["role"] === "string") {
863
+ result.push(message);
864
+ }
865
+ }
866
+ return result;
867
+ }
868
+ if (typeof args["prompt"] === "string" && args["prompt"]) {
869
+ result.push({ role: "user", content: args["prompt"] });
870
+ }
871
+ return result;
872
+ }
873
+ function extractResponseMessages(result) {
874
+ if (!isRecord(result)) return [];
875
+ const response = result["response"];
876
+ if (isRecord(response) && Array.isArray(response["messages"])) {
877
+ return response["messages"].filter((message) => isRecord(message) && typeof message["role"] === "string" && "content" in message).map((message) => message);
878
+ }
879
+ const steps = result["steps"];
880
+ if (Array.isArray(steps) && steps.length > 0) {
881
+ const lastStep = steps[steps.length - 1];
882
+ if (isRecord(lastStep) && isRecord(lastStep["response"])) {
883
+ const responseMessages = lastStep["response"]["messages"];
884
+ if (Array.isArray(responseMessages)) {
885
+ return responseMessages.filter((message) => isRecord(message) && typeof message["role"] === "string" && "content" in message).map((message) => message);
886
+ }
887
+ }
888
+ }
889
+ return [];
890
+ }
891
+ function extractTextFromLmContent(content) {
892
+ if (!Array.isArray(content)) return void 0;
893
+ let result = "";
894
+ for (const part of content) {
895
+ if (isRecord(part) && part["type"] === "text" && typeof part["text"] === "string") {
896
+ result += part["text"];
897
+ }
898
+ }
899
+ return result.length ? result : void 0;
900
+ }
901
+ function extractToolCallsFromLmContent(content) {
902
+ if (!Array.isArray(content)) return void 0;
903
+ const calls = [];
904
+ for (const part of content) {
905
+ if (!isRecord(part) || part["type"] !== "tool-call") continue;
906
+ const toolCallId = typeof part["toolCallId"] === "string" ? part["toolCallId"] : void 0;
907
+ const toolName = typeof part["toolName"] === "string" ? part["toolName"] : void 0;
908
+ if (toolCallId || toolName) {
909
+ calls.push({ toolCallId, toolName, input: part["input"] });
910
+ }
911
+ }
912
+ return calls.length ? calls : void 0;
913
+ }
914
+ function extractExperimentalTelemetry(args) {
915
+ if (!isRecord(args)) return void 0;
916
+ const telemetryConfig = args["experimental_telemetry"];
917
+ if (!isRecord(telemetryConfig)) return void 0;
918
+ return {
919
+ functionId: typeof telemetryConfig["functionId"] === "string" ? telemetryConfig["functionId"] : void 0,
920
+ isEnabled: typeof telemetryConfig["isEnabled"] === "boolean" ? telemetryConfig["isEnabled"] : void 0,
921
+ recordInputs: typeof telemetryConfig["recordInputs"] === "boolean" ? telemetryConfig["recordInputs"] : void 0,
922
+ recordOutputs: typeof telemetryConfig["recordOutputs"] === "boolean" ? telemetryConfig["recordOutputs"] : void 0,
923
+ metadata: isRecord(telemetryConfig["metadata"]) ? telemetryConfig["metadata"] : void 0
924
+ };
925
+ }
926
+ function opName(operationId, functionId) {
927
+ return {
928
+ operationName: `${operationId}${functionId ? ` ${functionId}` : ""}`,
929
+ resourceName: functionId
930
+ };
931
+ }
932
+ function toOtlpAttr(key, value) {
933
+ if (value === void 0 || value === null) return void 0;
934
+ if (typeof value === "string") return attrString(key, value);
935
+ if (typeof value === "number") return Number.isInteger(value) ? attrInt(key, value) : attrDouble(key, value);
936
+ if (typeof value === "boolean") return attrBool(key, value);
937
+ if (Array.isArray(value) && value.every((v) => typeof v === "string")) return attrStringArray(key, value);
938
+ const asJson = safeJsonWithUint8(value);
939
+ return asJson ? attrString(key, asJson) : void 0;
940
+ }
941
+ function attrsFromTelemetryMetadata(metadata) {
942
+ if (!metadata) return [];
943
+ return Object.entries(metadata).map(([k, v]) => {
944
+ const key = k === "raindrop.userId" ? "raindrop.ai.userId" : k;
945
+ return toOtlpAttr(`ai.telemetry.metadata.${key}`, v);
946
+ });
947
+ }
948
+ function attrsFromHeaders(headers) {
949
+ if (!isRecord(headers)) return [];
950
+ return Object.entries(headers).filter(([, v]) => typeof v === "string").map(([k, v]) => attrString(`ai.request.headers.${k}`, v));
951
+ }
952
+ function attrsFromSettings(args) {
953
+ if (!isRecord(args)) return [];
954
+ const result = [];
955
+ const settingKeys = [
956
+ "maxRetries",
957
+ "timeout",
958
+ "maxOutputTokens",
959
+ "temperature",
960
+ "topP",
961
+ "topK",
962
+ "presencePenalty",
963
+ "frequencyPenalty",
964
+ "seed",
965
+ "stopSequences"
966
+ ];
967
+ for (const key of settingKeys) {
968
+ if (!(key in args)) continue;
969
+ const value = args[key];
970
+ if (key === "stopSequences" && Array.isArray(value) && value.every((item) => typeof item === "string")) {
971
+ result.push(attrStringArray(`ai.settings.${key}`, value));
972
+ } else if (key === "timeout" && typeof value === "number") {
973
+ result.push(attrInt(`ai.settings.${key}`, value));
974
+ } else {
975
+ result.push(toOtlpAttr(`ai.settings.${key}`, value));
976
+ }
977
+ }
978
+ return result;
979
+ }
980
+ function attrsFromGenAiRequest(options) {
981
+ if (!isRecord(options)) return [];
982
+ return [
983
+ attrDouble("gen_ai.request.frequency_penalty", typeof options["frequencyPenalty"] === "number" ? options["frequencyPenalty"] : void 0),
984
+ attrInt("gen_ai.request.max_tokens", typeof options["maxOutputTokens"] === "number" ? options["maxOutputTokens"] : void 0),
985
+ attrDouble("gen_ai.request.presence_penalty", typeof options["presencePenalty"] === "number" ? options["presencePenalty"] : void 0),
986
+ ...Array.isArray(options["stopSequences"]) && options["stopSequences"].every((x) => typeof x === "string") ? [attrStringArray("gen_ai.request.stop_sequences", options["stopSequences"])] : [],
987
+ attrDouble("gen_ai.request.temperature", typeof options["temperature"] === "number" ? options["temperature"] : void 0),
988
+ attrInt("gen_ai.request.top_k", typeof options["topK"] === "number" ? options["topK"] : void 0),
989
+ attrDouble("gen_ai.request.top_p", typeof options["topP"] === "number" ? options["topP"] : void 0)
990
+ ];
991
+ }
992
+
993
+ // src/internal/wrap/wrapAISDK.ts
994
+ function extractRaindropMetadata(metadata) {
995
+ if (!metadata || typeof metadata !== "object") return {};
996
+ const result = {};
997
+ const userId = metadata["raindrop.userId"];
998
+ if (typeof userId === "string" && userId) result.userId = userId;
999
+ const eventId = metadata["raindrop.eventId"];
1000
+ if (typeof eventId === "string" && eventId) result.eventId = eventId;
1001
+ const convoId = metadata["raindrop.convoId"];
1002
+ if (typeof convoId === "string" && convoId) result.convoId = convoId;
1003
+ const eventName = metadata["raindrop.eventName"];
1004
+ if (typeof eventName === "string" && eventName) result.eventName = eventName;
1005
+ const properties = metadata["raindrop.properties"];
1006
+ if (typeof properties === "string") {
1007
+ try {
1008
+ result.properties = JSON.parse(properties);
1009
+ } catch (e) {
1010
+ }
1011
+ } else if (properties && typeof properties === "object") {
1012
+ result.properties = properties;
1013
+ }
1014
+ return result;
1015
+ }
1016
+ function mergeContexts(wrapTime, callTime) {
1017
+ const result = { ...wrapTime };
1018
+ if (callTime.userId) result.userId = callTime.userId;
1019
+ if (callTime.eventId) result.eventId = callTime.eventId;
1020
+ if (callTime.convoId) result.convoId = callTime.convoId;
1021
+ if (callTime.eventName) result.eventName = callTime.eventName;
1022
+ if (callTime.properties) {
1023
+ result.properties = {
1024
+ ...wrapTime.properties,
1025
+ ...callTime.properties
1026
+ };
1027
+ }
1028
+ return result;
1029
+ }
1030
+ function wrapAISDK(aiSDK, deps) {
1031
+ var _a, _b;
1032
+ const debug = deps.eventShipper.isDebugEnabled() || deps.traceShipper.isDebugEnabled();
1033
+ const instrumentedOps = /* @__PURE__ */ new Set(["generateText", "streamText", "generateObject", "streamObject"]);
1034
+ const agentClasses = /* @__PURE__ */ new Set(["ToolLoopAgent"]);
1035
+ const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
1036
+ const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
1037
+ const proxyTarget = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
1038
+ return new Proxy(proxyTarget, {
1039
+ get(target, prop, receiver) {
1040
+ const original = Reflect.get(target, prop, receiver);
1041
+ if (typeof prop === "string" && agentClasses.has(prop) && isAgentClass(original)) {
1042
+ if (debug) console.log(`[raindrop-ai/ai-sdk] Wrapping Agent class: ${prop}`);
1043
+ return wrapAgentClass(original, aiSDK, deps, debug);
1044
+ }
1045
+ if (typeof prop !== "string" || !instrumentedOps.has(prop) || !isFunction(original)) {
1046
+ return original;
1047
+ }
1048
+ return async (...callArgs) => {
1049
+ var _a2, _b2, _c;
1050
+ const arg = callArgs[0];
1051
+ const operation = prop;
1052
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation, args: arg });
1053
+ const telemetry = extractExperimentalTelemetry(arg);
1054
+ const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1055
+ const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1056
+ const inherited = await getCurrentParentSpanContext();
1057
+ const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1058
+ const ctx = { ...mergedCtx};
1059
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1060
+ const outerOperationId = `ai.${operation}`;
1061
+ const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
1062
+ const modelInfoFromArgs = isRecord(arg) ? extractModelInfo(arg["model"]) : {};
1063
+ const rootSpan = sendTraces ? deps.traceShipper.startSpan({
1064
+ name: outerOperationId,
1065
+ parent: inheritedParent,
1066
+ eventId,
1067
+ operationId: outerOperationId,
1068
+ attributes: [
1069
+ attrString("operation.name", operationName),
1070
+ attrString("resource.name", resourceName),
1071
+ attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1072
+ attrString("ai.model.provider", modelInfoFromArgs.provider),
1073
+ attrString("ai.model.id", modelInfoFromArgs.modelId),
1074
+ ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1075
+ ...attrsFromHeaders(isRecord(arg) ? arg["headers"] : void 0),
1076
+ ...attrsFromSettings(arg),
1077
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1078
+ attrString(
1079
+ "ai.prompt",
1080
+ safeJsonWithUint8({
1081
+ system: isRecord(arg) ? arg["system"] : void 0,
1082
+ prompt: isRecord(arg) ? arg["prompt"] : void 0,
1083
+ messages: isRecord(arg) ? arg["messages"] : void 0
1084
+ })
1085
+ )
1086
+ ]
1087
+ ]
1088
+ }) : void 0;
1089
+ const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1090
+ const wrapCtx = { eventId, telemetry, sendTraces, traceShipper: deps.traceShipper, rootParentForChildren };
1091
+ const toolCalls = [];
1092
+ const argWithWrappedTools = wrapTools(arg, wrapCtx, toolCalls);
1093
+ const argWithWrappedModel = wrapModel(argWithWrappedTools, aiSDK, outerOperationId, wrapCtx);
1094
+ const finalize = async (result, error) => {
1095
+ var _a3, _b3, _c2;
1096
+ const usage = extractUsage(result);
1097
+ const model = extractModel(result);
1098
+ const baseMessages = coerceMessagesFromArgs(arg);
1099
+ const responseMessages = extractResponseMessages(result);
1100
+ const allMessages = [...baseMessages, ...responseMessages];
1101
+ const outputText = extractTextOutput(result);
1102
+ const outputObjectJson = extractObjectOutput(result);
1103
+ const defaultOutput = operation === "generateObject" || operation === "streamObject" ? outputObjectJson : outputText;
1104
+ const defaultPatch = {
1105
+ eventName: (_a3 = ctx.eventName) != null ? _a3 : operation,
1106
+ input: (_b3 = lastUserMessageTextFromArgs(arg)) != null ? _b3 : extractInputFromArgs(arg),
1107
+ output: defaultOutput,
1108
+ model,
1109
+ properties: ctx.properties,
1110
+ attachments: ctx.attachments
1111
+ };
1112
+ const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
1113
+ const patch = mergeBuildEventPatch(defaultPatch, built);
1114
+ const output = patch.output;
1115
+ const finalModel = (_c2 = patch.model) != null ? _c2 : model;
1116
+ if (rootSpan) {
1117
+ const finishReason = extractFinishReason(result);
1118
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1119
+ const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1120
+ const usageRec = isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1121
+ const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1122
+ const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1123
+ const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1124
+ deps.traceShipper.endSpan(rootSpan, {
1125
+ attributes: [
1126
+ ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
1127
+ attrString("ai.response.finishReason", finishReason),
1128
+ operation === "generateObject" || operation === "streamObject" ? attrString("ai.response.object", output) : attrString("ai.response.text", output),
1129
+ attrString("ai.response.toolCalls", resultToolCalls),
1130
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1131
+ ],
1132
+ attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1133
+ attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1134
+ attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1135
+ attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1136
+ attrInt("ai.usage.totalTokens", totalTokens),
1137
+ attrInt("ai.usage.reasoningTokens", reasoningTokens),
1138
+ attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1139
+ attrInt("ai.toolCall.count", toolCalls.length),
1140
+ ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
1141
+ ]
1142
+ });
1143
+ }
1144
+ if (sendEvents) {
1145
+ void deps.eventShipper.patch(eventId, {
1146
+ eventName: patch.eventName,
1147
+ userId: ctx.userId,
1148
+ convoId: ctx.convoId,
1149
+ input: patch.input,
1150
+ output,
1151
+ model: finalModel,
1152
+ properties: patch.properties,
1153
+ attachments: patch.attachments,
1154
+ isPending: false
1155
+ }).catch((err) => {
1156
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`);
1157
+ });
1158
+ }
1159
+ };
1160
+ const callOriginal = async (...args) => {
1161
+ return await original.call(aiSDK, ...args);
1162
+ };
1163
+ const runWithContext = async (fn) => {
1164
+ if (!rootSpan) return await fn();
1165
+ return await runWithParentSpanContext(
1166
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1167
+ fn
1168
+ );
1169
+ };
1170
+ if (operation === "streamText" || operation === "streamObject") {
1171
+ const argWithOnFinish = wrapOnFinish(argWithWrappedModel, async (result) => {
1172
+ try {
1173
+ await finalize(result);
1174
+ } catch (err) {
1175
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1176
+ }
1177
+ });
1178
+ try {
1179
+ const result = await runWithContext(async () => {
1180
+ const nextArgs = [...callArgs];
1181
+ nextArgs[0] = argWithOnFinish;
1182
+ return await callOriginal(...nextArgs);
1183
+ });
1184
+ if (operation === "streamObject" && result && isRecord(result)) {
1185
+ const baseStream = result["baseStream"];
1186
+ if (baseStream && typeof baseStream === "object" && "tee" in baseStream) {
1187
+ try {
1188
+ const [consumeStream, userStream] = baseStream.tee();
1189
+ result["baseStream"] = userStream;
1190
+ consumeStream.pipeTo(new WritableStream({ write() {
1191
+ } })).catch(() => {
1192
+ });
1193
+ } catch (e) {
1194
+ }
1195
+ }
1196
+ }
1197
+ return result;
1198
+ } catch (error) {
1199
+ try {
1200
+ await finalize(void 0, error);
1201
+ } catch (err) {
1202
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1203
+ }
1204
+ throw error;
1205
+ }
1206
+ }
1207
+ try {
1208
+ const result = await runWithContext(async () => {
1209
+ const nextArgs = [...callArgs];
1210
+ nextArgs[0] = argWithWrappedModel;
1211
+ return await callOriginal(...nextArgs);
1212
+ });
1213
+ try {
1214
+ await finalize(result);
1215
+ } catch (err) {
1216
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1217
+ }
1218
+ return result;
1219
+ } catch (error) {
1220
+ try {
1221
+ await finalize(void 0, error);
1222
+ } catch (err) {
1223
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1224
+ }
1225
+ throw error;
1226
+ }
1227
+ };
1228
+ }
1229
+ });
1230
+ }
1231
+ function wrapAgentClass(AgentClass, aiSDK, deps, debug) {
1232
+ return new Proxy(AgentClass, {
1233
+ construct(target, args, newTarget) {
1234
+ const instance = Reflect.construct(target, args, newTarget);
1235
+ const agentSettings = args[0];
1236
+ const className = (newTarget == null ? void 0 : newTarget.name) || target.name || "Agent";
1237
+ if (debug) console.log(`[raindrop-ai/ai-sdk] Creating wrapped ${className} instance`);
1238
+ return new Proxy(instance, {
1239
+ get(instanceTarget, prop, instanceReceiver) {
1240
+ const original = Reflect.get(instanceTarget, prop, instanceReceiver);
1241
+ if (prop === "generate" && isFunction(original)) {
1242
+ if (debug) console.log(`[raindrop-ai/ai-sdk] Wrapping ${className}.generate method`);
1243
+ return wrapAgentGenerate(
1244
+ original,
1245
+ instanceTarget,
1246
+ agentSettings,
1247
+ className,
1248
+ aiSDK,
1249
+ deps,
1250
+ debug
1251
+ );
1252
+ }
1253
+ if (prop === "stream" && isFunction(original)) {
1254
+ if (debug) console.log(`[raindrop-ai/ai-sdk] Wrapping ${className}.stream method`);
1255
+ return wrapAgentStream(
1256
+ original,
1257
+ instanceTarget,
1258
+ agentSettings,
1259
+ className,
1260
+ aiSDK,
1261
+ deps,
1262
+ debug
1263
+ );
1264
+ }
1265
+ return original;
1266
+ }
1267
+ });
1268
+ }
1269
+ });
1270
+ }
1271
+ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK, deps, debug) {
1272
+ var _a, _b;
1273
+ const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
1274
+ const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
1275
+ return async (...callArgs) => {
1276
+ var _a2, _b2, _c, _d;
1277
+ const callParams = callArgs[0];
1278
+ const mergedArgs = { ...agentSettings, ...callParams };
1279
+ const operation = `${className}.generate`;
1280
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation, args: mergedArgs });
1281
+ const telemetry = extractExperimentalTelemetry(mergedArgs);
1282
+ const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1283
+ const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1284
+ const inherited = await getCurrentParentSpanContext();
1285
+ const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1286
+ const ctx = { ...mergedCtx};
1287
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1288
+ const outerOperationId = `ai.${operation}`;
1289
+ const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
1290
+ const modelInfoFromArgs = extractModelInfo(mergedArgs["model"]);
1291
+ const rootSpan = sendTraces ? deps.traceShipper.startSpan({
1292
+ name: outerOperationId,
1293
+ parent: inheritedParent,
1294
+ eventId,
1295
+ operationId: outerOperationId,
1296
+ attributes: [
1297
+ attrString("operation.name", operationName),
1298
+ attrString("resource.name", resourceName),
1299
+ attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1300
+ attrString("ai.model.provider", modelInfoFromArgs.provider),
1301
+ attrString("ai.model.id", modelInfoFromArgs.modelId),
1302
+ ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1303
+ ...attrsFromHeaders(mergedArgs["headers"]),
1304
+ ...attrsFromSettings(mergedArgs),
1305
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1306
+ attrString(
1307
+ "ai.prompt",
1308
+ safeJsonWithUint8({
1309
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
1310
+ prompt: mergedArgs["prompt"],
1311
+ messages: mergedArgs["messages"]
1312
+ })
1313
+ )
1314
+ ]
1315
+ ]
1316
+ }) : void 0;
1317
+ const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1318
+ const wrapCtx = { eventId, telemetry, sendTraces, traceShipper: deps.traceShipper, rootParentForChildren };
1319
+ const toolCalls = [];
1320
+ const callParamsWithWrappedTools = callParams ? wrapTools(callParams, wrapCtx, toolCalls) : callParams;
1321
+ const finalize = async (result, error) => {
1322
+ var _a3, _b3, _c2;
1323
+ const usage = extractUsage(result);
1324
+ const model = extractModel(result);
1325
+ const baseMessages = coerceMessagesFromArgs(mergedArgs);
1326
+ const responseMessages = extractResponseMessages(result);
1327
+ const allMessages = [...baseMessages, ...responseMessages];
1328
+ const outputText = extractTextOutput(result);
1329
+ const defaultPatch = {
1330
+ eventName: (_a3 = ctx.eventName) != null ? _a3 : operation,
1331
+ input: (_b3 = lastUserMessageTextFromArgs(mergedArgs)) != null ? _b3 : extractInputFromArgs(mergedArgs),
1332
+ output: outputText,
1333
+ model,
1334
+ properties: ctx.properties,
1335
+ attachments: ctx.attachments
1336
+ };
1337
+ const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
1338
+ const patch = mergeBuildEventPatch(defaultPatch, built);
1339
+ const output = patch.output;
1340
+ const finalModel = (_c2 = patch.model) != null ? _c2 : model;
1341
+ if (rootSpan) {
1342
+ const finishReason = extractFinishReason(result);
1343
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1344
+ const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1345
+ const usageRec = isRecord(result) && isRecord(result["totalUsage"]) ? result["totalUsage"] : isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1346
+ const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1347
+ const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1348
+ const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1349
+ deps.traceShipper.endSpan(rootSpan, {
1350
+ attributes: [
1351
+ ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
1352
+ attrString("ai.response.finishReason", finishReason),
1353
+ attrString("ai.response.text", output),
1354
+ attrString("ai.response.toolCalls", resultToolCalls),
1355
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1356
+ ],
1357
+ attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1358
+ attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1359
+ attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1360
+ attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1361
+ attrInt("ai.usage.totalTokens", totalTokens),
1362
+ attrInt("ai.usage.reasoningTokens", reasoningTokens),
1363
+ attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1364
+ attrInt("ai.toolCall.count", toolCalls.length),
1365
+ ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
1366
+ ]
1367
+ });
1368
+ }
1369
+ if (sendEvents) {
1370
+ if (debug) {
1371
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} shipping event:`, {
1372
+ eventId,
1373
+ eventName: patch.eventName,
1374
+ userId: ctx.userId,
1375
+ hasOutput: !!output
1376
+ });
1377
+ }
1378
+ void deps.eventShipper.patch(eventId, {
1379
+ eventName: patch.eventName,
1380
+ userId: ctx.userId,
1381
+ convoId: ctx.convoId,
1382
+ input: patch.input,
1383
+ output,
1384
+ model: finalModel,
1385
+ properties: patch.properties,
1386
+ attachments: patch.attachments,
1387
+ isPending: false
1388
+ }).catch((err) => {
1389
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`);
1390
+ });
1391
+ } else if (debug) {
1392
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} sendEvents=false, skipping event`);
1393
+ }
1394
+ };
1395
+ const runWithContext = async (fn) => {
1396
+ if (!rootSpan) return await fn();
1397
+ return await runWithParentSpanContext(
1398
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1399
+ fn
1400
+ );
1401
+ };
1402
+ if (debug) {
1403
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} starting with context:`, {
1404
+ userId: ctx.userId,
1405
+ eventId,
1406
+ eventName: ctx.eventName
1407
+ });
1408
+ }
1409
+ try {
1410
+ const result = await runWithContext(async () => {
1411
+ return await generate.call(instance, callParamsWithWrappedTools);
1412
+ });
1413
+ if (debug) {
1414
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} completed, finalizing...`);
1415
+ }
1416
+ try {
1417
+ await finalize(result);
1418
+ } catch (err) {
1419
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1420
+ }
1421
+ return result;
1422
+ } catch (error) {
1423
+ try {
1424
+ await finalize(void 0, error);
1425
+ } catch (err) {
1426
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1427
+ }
1428
+ throw error;
1429
+ }
1430
+ };
1431
+ }
1432
+ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps, debug) {
1433
+ var _a, _b;
1434
+ const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
1435
+ const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
1436
+ return async (...callArgs) => {
1437
+ var _a2, _b2, _c, _d;
1438
+ const callParams = callArgs[0];
1439
+ const mergedArgs = { ...agentSettings, ...callParams };
1440
+ const operation = `${className}.stream`;
1441
+ const wrapTimeCtx = resolveContext(deps.options.context, { operation, args: mergedArgs });
1442
+ const telemetry = extractExperimentalTelemetry(mergedArgs);
1443
+ const callTimeCtx = extractRaindropMetadata(telemetry == null ? void 0 : telemetry.metadata);
1444
+ const mergedCtx = mergeContexts(wrapTimeCtx, callTimeCtx);
1445
+ const inherited = await getCurrentParentSpanContext();
1446
+ const eventId = (_c = (_b2 = (_a2 = callTimeCtx.eventId) != null ? _a2 : mergedCtx.eventId) != null ? _b2 : inherited == null ? void 0 : inherited.eventId) != null ? _c : randomUUID();
1447
+ const ctx = { ...mergedCtx};
1448
+ const inheritedParent = inherited && inherited.eventId === eventId ? { traceIdB64: inherited.traceIdB64, spanIdB64: inherited.spanIdB64 } : void 0;
1449
+ const outerOperationId = `ai.${operation}`;
1450
+ const { operationName, resourceName } = opName(outerOperationId, telemetry == null ? void 0 : telemetry.functionId);
1451
+ const modelInfoFromArgs = extractModelInfo(mergedArgs["model"]);
1452
+ const rootSpan = sendTraces ? deps.traceShipper.startSpan({
1453
+ name: outerOperationId,
1454
+ parent: inheritedParent,
1455
+ eventId,
1456
+ operationId: outerOperationId,
1457
+ attributes: [
1458
+ attrString("operation.name", operationName),
1459
+ attrString("resource.name", resourceName),
1460
+ attrString("ai.telemetry.functionId", telemetry == null ? void 0 : telemetry.functionId),
1461
+ attrString("ai.model.provider", modelInfoFromArgs.provider),
1462
+ attrString("ai.model.id", modelInfoFromArgs.modelId),
1463
+ ...attrsFromTelemetryMetadata(telemetry == null ? void 0 : telemetry.metadata),
1464
+ ...attrsFromHeaders(mergedArgs["headers"]),
1465
+ ...attrsFromSettings(mergedArgs),
1466
+ ...(telemetry == null ? void 0 : telemetry.recordInputs) === false ? [] : [
1467
+ attrString(
1468
+ "ai.prompt",
1469
+ safeJsonWithUint8({
1470
+ system: (_d = mergedArgs["system"]) != null ? _d : mergedArgs["instructions"],
1471
+ prompt: mergedArgs["prompt"],
1472
+ messages: mergedArgs["messages"]
1473
+ })
1474
+ )
1475
+ ]
1476
+ ]
1477
+ }) : void 0;
1478
+ const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1479
+ const wrapCtx = { eventId, telemetry, sendTraces, traceShipper: deps.traceShipper, rootParentForChildren };
1480
+ const toolCalls = [];
1481
+ const callParamsWithWrappedTools = callParams ? wrapTools(callParams, wrapCtx, toolCalls) : callParams;
1482
+ const finalize = async (result, error) => {
1483
+ var _a3, _b3, _c2;
1484
+ const usage = extractUsage(result);
1485
+ const model = extractModel(result);
1486
+ const baseMessages = coerceMessagesFromArgs(mergedArgs);
1487
+ const responseMessages = extractResponseMessages(result);
1488
+ const allMessages = [...baseMessages, ...responseMessages];
1489
+ const outputText = extractTextOutput(result);
1490
+ const defaultPatch = {
1491
+ eventName: (_a3 = ctx.eventName) != null ? _a3 : operation,
1492
+ input: (_b3 = lastUserMessageTextFromArgs(mergedArgs)) != null ? _b3 : extractInputFromArgs(mergedArgs),
1493
+ output: outputText,
1494
+ model,
1495
+ properties: ctx.properties,
1496
+ attachments: ctx.attachments
1497
+ };
1498
+ const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
1499
+ const patch = mergeBuildEventPatch(defaultPatch, built);
1500
+ const output = patch.output;
1501
+ const finalModel = (_c2 = patch.model) != null ? _c2 : model;
1502
+ if (rootSpan) {
1503
+ const finishReason = extractFinishReason(result);
1504
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1505
+ const resultToolCalls = isRecord(result) && Array.isArray(result["toolCalls"]) ? safeJsonWithUint8(result["toolCalls"]) : toolCalls.length ? safeJsonWithUint8(toolCalls) : void 0;
1506
+ const usageRec = isRecord(result) && isRecord(result["totalUsage"]) ? result["totalUsage"] : isRecord(result) && isRecord(result["usage"]) ? result["usage"] : void 0;
1507
+ const totalTokens = typeof (usageRec == null ? void 0 : usageRec["totalTokens"]) === "number" ? usageRec["totalTokens"] : void 0;
1508
+ const reasoningTokens = typeof (usageRec == null ? void 0 : usageRec["reasoningTokens"]) === "number" ? usageRec["reasoningTokens"] : void 0;
1509
+ const cachedInputTokens = typeof (usageRec == null ? void 0 : usageRec["cachedInputTokens"]) === "number" ? usageRec["cachedInputTokens"] : void 0;
1510
+ deps.traceShipper.endSpan(rootSpan, {
1511
+ attributes: [
1512
+ ...(telemetry == null ? void 0 : telemetry.recordOutputs) === false ? [] : [
1513
+ attrString("ai.response.finishReason", finishReason),
1514
+ attrString("ai.response.text", output),
1515
+ attrString("ai.response.toolCalls", resultToolCalls),
1516
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1517
+ ],
1518
+ attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1519
+ attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
1520
+ attrInt("ai.usage.inputTokens", usage == null ? void 0 : usage.inputTokens),
1521
+ attrInt("ai.usage.outputTokens", usage == null ? void 0 : usage.outputTokens),
1522
+ attrInt("ai.usage.totalTokens", totalTokens),
1523
+ attrInt("ai.usage.reasoningTokens", reasoningTokens),
1524
+ attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1525
+ attrInt("ai.toolCall.count", toolCalls.length),
1526
+ ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
1527
+ ]
1528
+ });
1529
+ }
1530
+ if (sendEvents) {
1531
+ if (debug) {
1532
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} shipping event:`, {
1533
+ eventId,
1534
+ eventName: patch.eventName,
1535
+ userId: ctx.userId,
1536
+ hasOutput: !!output
1537
+ });
1538
+ }
1539
+ void deps.eventShipper.patch(eventId, {
1540
+ eventName: patch.eventName,
1541
+ userId: ctx.userId,
1542
+ convoId: ctx.convoId,
1543
+ input: patch.input,
1544
+ output,
1545
+ model: finalModel,
1546
+ properties: patch.properties,
1547
+ attachments: patch.attachments,
1548
+ isPending: false
1549
+ }).catch((err) => {
1550
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`);
1551
+ });
1552
+ } else if (debug) {
1553
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} sendEvents=false, skipping event`);
1554
+ }
1555
+ };
1556
+ const runWithContext = async (fn) => {
1557
+ if (!rootSpan) return await fn();
1558
+ return await runWithParentSpanContext(
1559
+ { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64, eventId },
1560
+ fn
1561
+ );
1562
+ };
1563
+ if (debug) {
1564
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} starting with context:`, {
1565
+ userId: ctx.userId,
1566
+ eventId,
1567
+ eventName: ctx.eventName
1568
+ });
1569
+ }
1570
+ const callParamsWithOnFinish = wrapOnFinish(callParamsWithWrappedTools != null ? callParamsWithWrappedTools : {}, async (result) => {
1571
+ if (debug) {
1572
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} onFinish callback, finalizing...`);
1573
+ }
1574
+ try {
1575
+ await finalize(result);
1576
+ } catch (err) {
1577
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1578
+ }
1579
+ });
1580
+ try {
1581
+ const result = await runWithContext(async () => {
1582
+ return await stream.call(instance, callParamsWithOnFinish);
1583
+ });
1584
+ return result;
1585
+ } catch (error) {
1586
+ try {
1587
+ await finalize(void 0, error);
1588
+ } catch (err) {
1589
+ if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1590
+ }
1591
+ throw error;
1592
+ }
1593
+ };
1594
+ }
1595
+ function wrapTools(args, ctx, toolCalls) {
1596
+ if (!isRecord(args) || !("tools" in args) || !isRecord(args["tools"])) return args;
1597
+ const tools = args["tools"];
1598
+ const wrapped = {};
1599
+ for (const [name, tool] of Object.entries(tools)) {
1600
+ wrapped[name] = wrapToolExecute(name, tool, ctx, toolCalls);
1601
+ }
1602
+ return { ...args, tools: wrapped };
1603
+ }
1604
+ function wrapToolExecute(name, tool, ctx, toolCalls) {
1605
+ var _a;
1606
+ if (!isRecord(tool) || !isFunction(tool["execute"])) return tool;
1607
+ const originalExecute = tool["execute"];
1608
+ const { operationName, resourceName } = opName("ai.toolCall", (_a = ctx.telemetry) == null ? void 0 : _a.functionId);
1609
+ const createToolSpan = (toolCallId, toolArgs, parent) => {
1610
+ var _a2, _b;
1611
+ if (!ctx.sendTraces || !parent) return void 0;
1612
+ return ctx.traceShipper.startSpan({
1613
+ name: "ai.toolCall",
1614
+ parent,
1615
+ eventId: ctx.eventId,
1616
+ operationId: "ai.toolCall",
1617
+ attributes: [
1618
+ attrString("operation.name", operationName),
1619
+ attrString("resource.name", resourceName),
1620
+ attrString("ai.telemetry.functionId", (_a2 = ctx.telemetry) == null ? void 0 : _a2.functionId),
1621
+ attrString("ai.toolCall.name", name),
1622
+ attrString("ai.toolCall.id", toolCallId),
1623
+ ...((_b = ctx.telemetry) == null ? void 0 : _b.recordInputs) === false ? [] : [attrString("ai.toolCall.args", safeJsonWithUint8(toolArgs))]
1624
+ ]
1625
+ });
1626
+ };
1627
+ const endToolSpan = (span, result, error) => {
1628
+ var _a2;
1629
+ if (!span) return;
1630
+ if (error) {
1631
+ ctx.traceShipper.endSpan(span, {
1632
+ attributes: [attrString("error.message", error instanceof Error ? error.message : String(error))]
1633
+ });
1634
+ } else {
1635
+ ctx.traceShipper.endSpan(span, {
1636
+ attributes: ((_a2 = ctx.telemetry) == null ? void 0 : _a2.recordOutputs) === false ? [] : [attrString("ai.toolCall.result", safeJsonWithUint8(result))]
1637
+ });
1638
+ }
1639
+ };
1640
+ const createContextSpan = (span) => ({
1641
+ traceIdB64: span.ids.traceIdB64,
1642
+ spanIdB64: span.ids.spanIdB64,
1643
+ eventId: ctx.eventId
1644
+ });
1645
+ const wrappedExecute = (...execArgs) => {
1646
+ const toolArgs = execArgs[0];
1647
+ const execOptions = execArgs.length > 1 ? execArgs[1] : void 0;
1648
+ const toolCallId = isRecord(execOptions) && typeof execOptions["toolCallId"] === "string" ? execOptions["toolCallId"] : randomUUID();
1649
+ const result = originalExecute(...execArgs);
1650
+ if (isAsyncGenerator(result)) {
1651
+ return (async function* () {
1652
+ const parentCtx = await getCurrentParentSpanContext();
1653
+ const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
1654
+ const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
1655
+ try {
1656
+ let lastValue;
1657
+ const wrappedGen = toolSpan ? asyncGeneratorWithCurrent(createContextSpan(toolSpan), result) : result;
1658
+ for await (const value of wrappedGen) {
1659
+ lastValue = value;
1660
+ yield value;
1661
+ }
1662
+ toolCalls.push({ name, args: toolArgs, result: lastValue, status: "OK" });
1663
+ endToolSpan(toolSpan, lastValue);
1664
+ } catch (error) {
1665
+ toolCalls.push({ name, args: toolArgs, status: "ERROR" });
1666
+ endToolSpan(toolSpan, void 0, error);
1667
+ throw error;
1668
+ }
1669
+ })();
1670
+ }
1671
+ return (async () => {
1672
+ const parentCtx = await getCurrentParentSpanContext();
1673
+ const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
1674
+ const toolSpan = createToolSpan(toolCallId, toolArgs, parent);
1675
+ const run = async () => {
1676
+ try {
1677
+ const awaitedResult = await result;
1678
+ toolCalls.push({ name, args: toolArgs, result: awaitedResult, status: "OK" });
1679
+ endToolSpan(toolSpan, awaitedResult);
1680
+ return awaitedResult;
1681
+ } catch (error) {
1682
+ toolCalls.push({ name, args: toolArgs, status: "ERROR" });
1683
+ endToolSpan(toolSpan, void 0, error);
1684
+ throw error;
1685
+ }
1686
+ };
1687
+ if (!toolSpan) return await run();
1688
+ return await runWithParentSpanContext(
1689
+ { traceIdB64: toolSpan.ids.traceIdB64, spanIdB64: toolSpan.ids.spanIdB64, eventId: ctx.eventId },
1690
+ run
1691
+ );
1692
+ })();
1693
+ };
1694
+ return { ...tool, execute: wrappedExecute };
1695
+ }
1696
+ function wrapModel(args, aiSDK, outerOperationId, ctx) {
1697
+ if (!isRecord(args) || !("model" in args)) return args;
1698
+ let model = args["model"];
1699
+ if (typeof model === "string") {
1700
+ const maybeProvider = globalThis.AI_SDK_DEFAULT_PROVIDER;
1701
+ const gateway = isRecord(aiSDK) ? aiSDK["gateway"] : void 0;
1702
+ const provider = maybeProvider != null ? maybeProvider : gateway;
1703
+ if (isRecord(provider) && isFunction(provider["languageModel"])) {
1704
+ try {
1705
+ model = provider["languageModel"](model);
1706
+ } catch (e) {
1707
+ }
1708
+ }
1709
+ }
1710
+ if (!isRecord(model)) return args;
1711
+ const modelInfo = extractModelInfo(model);
1712
+ const doGenerateOpId = `${outerOperationId}.doGenerate`;
1713
+ const doStreamOpId = `${outerOperationId}.doStream`;
1714
+ const wrappedModel = new Proxy(model, {
1715
+ get(target, prop, receiver) {
1716
+ const original = Reflect.get(target, prop, receiver);
1717
+ if (prop === "doGenerate" && isFunction(original)) {
1718
+ return async (...callArgs) => {
1719
+ const options = callArgs[0];
1720
+ const parentCtx = await getCurrentParentSpanContext();
1721
+ const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
1722
+ const span = ctx.sendTraces && parent ? startDoGenerateSpan(doGenerateOpId, options, modelInfo, parent, ctx) : void 0;
1723
+ try {
1724
+ const result = await original.apply(target, callArgs);
1725
+ if (span) endDoGenerateSpan(span, result, modelInfo, ctx);
1726
+ return result;
1727
+ } catch (error) {
1728
+ if (span) ctx.traceShipper.endSpan(span, { attributes: [attrString("error.message", error instanceof Error ? error.message : String(error))] });
1729
+ throw error;
1730
+ }
1731
+ };
1732
+ }
1733
+ if (prop === "doStream" && isFunction(original)) {
1734
+ return async (...callArgs) => {
1735
+ const options = callArgs[0];
1736
+ const parentCtx = await getCurrentParentSpanContext();
1737
+ const parent = parentCtx && parentCtx.eventId === ctx.eventId ? { traceIdB64: parentCtx.traceIdB64, spanIdB64: parentCtx.spanIdB64 } : ctx.rootParentForChildren;
1738
+ const span = ctx.sendTraces && parent ? startDoStreamSpan(doStreamOpId, options, modelInfo, parent, ctx) : void 0;
1739
+ const startMs = Date.now();
1740
+ let firstChunkMs;
1741
+ let finishMs;
1742
+ let finishReason;
1743
+ let responseId;
1744
+ let responseModelId;
1745
+ let responseTimestampIso;
1746
+ let providerMetadata;
1747
+ let usage;
1748
+ let activeText = "";
1749
+ const toolCallsLocal = [];
1750
+ let result;
1751
+ try {
1752
+ result = await original.apply(target, callArgs);
1753
+ } catch (error) {
1754
+ if (span)
1755
+ ctx.traceShipper.endSpan(span, {
1756
+ attributes: [attrString("error.message", error instanceof Error ? error.message : String(error))]
1757
+ });
1758
+ throw error;
1759
+ }
1760
+ const stream = isRecord(result) ? result["stream"] : void 0;
1761
+ const RS = globalThis.ReadableStream;
1762
+ if (!RS || !(stream instanceof RS)) {
1763
+ if (span) ctx.traceShipper.endSpan(span);
1764
+ return result;
1765
+ }
1766
+ const reader = stream.getReader();
1767
+ let ended = false;
1768
+ const endSpan = (error) => {
1769
+ var _a;
1770
+ if (ended || !span) return;
1771
+ ended = true;
1772
+ const msToFirstChunk = firstChunkMs !== void 0 ? firstChunkMs - startMs : void 0;
1773
+ const msToFinish = finishMs !== void 0 ? finishMs - startMs : void 0;
1774
+ const inputTokens = extractNestedTokens(usage, "inputTokens");
1775
+ const outputTokens = extractNestedTokens(usage, "outputTokens");
1776
+ const avgOutTokensPerSecond = msToFinish && outputTokens !== void 0 && msToFinish > 0 ? 1e3 * outputTokens / msToFinish : void 0;
1777
+ ctx.traceShipper.endSpan(span, {
1778
+ attributes: [
1779
+ ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
1780
+ attrString("ai.response.finishReason", finishReason),
1781
+ attrString("ai.response.text", activeText.length ? activeText : void 0),
1782
+ attrString("ai.response.toolCalls", safeJsonWithUint8(toolCallsLocal.length ? toolCallsLocal : void 0)),
1783
+ attrString("ai.response.id", responseId),
1784
+ attrString("ai.response.model", responseModelId),
1785
+ attrString("ai.response.timestamp", responseTimestampIso),
1786
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1787
+ ],
1788
+ attrInt("ai.usage.inputTokens", inputTokens),
1789
+ attrInt("ai.usage.outputTokens", outputTokens),
1790
+ ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
1791
+ attrString("gen_ai.response.id", responseId),
1792
+ attrString("gen_ai.response.model", responseModelId),
1793
+ attrInt("gen_ai.usage.input_tokens", inputTokens),
1794
+ attrInt("gen_ai.usage.output_tokens", outputTokens),
1795
+ ...msToFirstChunk !== void 0 ? [attrInt("ai.stream.msToFirstChunk", msToFirstChunk)] : [],
1796
+ ...msToFinish !== void 0 ? [attrInt("ai.stream.msToFinish", msToFinish)] : [],
1797
+ ...avgOutTokensPerSecond !== void 0 ? [attrDouble("ai.stream.avgOutputTokensPerSecond", avgOutTokensPerSecond)] : [],
1798
+ ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
1799
+ ]
1800
+ });
1801
+ };
1802
+ const wrappedStream = new RS({
1803
+ async pull(controller) {
1804
+ try {
1805
+ const { done, value } = await reader.read();
1806
+ if (done) {
1807
+ finishMs = Date.now();
1808
+ endSpan();
1809
+ controller.close();
1810
+ return;
1811
+ }
1812
+ if (firstChunkMs === void 0) firstChunkMs = Date.now();
1813
+ if (isRecord(value)) {
1814
+ const type = value["type"];
1815
+ if (type === "text-delta" && typeof value["textDelta"] === "string") activeText += value["textDelta"];
1816
+ if (type === "finish" && typeof value["finishReason"] === "string") finishReason = value["finishReason"];
1817
+ if (type === "tool-call") toolCallsLocal.push(value);
1818
+ if ("response" in value && isRecord(value["response"])) {
1819
+ const response = value["response"];
1820
+ if (typeof response["id"] === "string") responseId = response["id"];
1821
+ if (typeof response["modelId"] === "string") responseModelId = response["modelId"];
1822
+ if (response["timestamp"] instanceof Date) responseTimestampIso = response["timestamp"].toISOString();
1823
+ else if (typeof response["timestamp"] === "string") responseTimestampIso = response["timestamp"];
1824
+ }
1825
+ if ("usage" in value) usage = value["usage"];
1826
+ if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
1827
+ }
1828
+ controller.enqueue(value);
1829
+ } catch (error) {
1830
+ endSpan(error);
1831
+ controller.error(error);
1832
+ }
1833
+ },
1834
+ cancel(reason) {
1835
+ void reader.cancel(reason);
1836
+ endSpan(reason);
1837
+ }
1838
+ });
1839
+ return { ...result, stream: wrappedStream };
1840
+ };
1841
+ }
1842
+ return original;
1843
+ }
1844
+ });
1845
+ return { ...args, model: wrappedModel };
1846
+ }
1847
+ function startDoGenerateSpan(operationId, options, modelInfo, parent, ctx) {
1848
+ var _a, _b, _c;
1849
+ const { operationName, resourceName } = opName(operationId, (_a = ctx.telemetry) == null ? void 0 : _a.functionId);
1850
+ const tools = isRecord(options) ? options["tools"] : void 0;
1851
+ const toolsJson = Array.isArray(tools) && tools.length ? tools.map((tool) => safeJsonWithUint8(tool)).filter((json) => typeof json === "string" && json.length > 0) : void 0;
1852
+ const toolChoiceJson = isRecord(options) ? safeJsonWithUint8(options["toolChoice"]) : void 0;
1853
+ const promptJson = isRecord(options) ? safeJsonWithUint8(options["prompt"]) : safeJsonWithUint8(options);
1854
+ return ctx.traceShipper.startSpan({
1855
+ name: operationId,
1856
+ parent,
1857
+ eventId: ctx.eventId,
1858
+ operationId,
1859
+ attributes: [
1860
+ attrString("operation.name", operationName),
1861
+ attrString("resource.name", resourceName),
1862
+ attrString("ai.telemetry.functionId", (_b = ctx.telemetry) == null ? void 0 : _b.functionId),
1863
+ attrString("ai.model.provider", modelInfo.provider),
1864
+ attrString("ai.model.id", modelInfo.modelId),
1865
+ ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [attrString("ai.prompt.messages", promptJson), attrStringArray("ai.prompt.tools", toolsJson), attrString("ai.prompt.toolChoice", toolChoiceJson)],
1866
+ attrString("gen_ai.system", modelInfo.provider),
1867
+ attrString("gen_ai.request.model", modelInfo.modelId),
1868
+ ...attrsFromGenAiRequest(options)
1869
+ ]
1870
+ });
1871
+ }
1872
+ function endDoGenerateSpan(span, result, modelInfo, ctx) {
1873
+ var _a;
1874
+ const finishReason = extractFinishReason(result);
1875
+ const content = isRecord(result) ? result["content"] : void 0;
1876
+ const response = isRecord(result) ? result["response"] : void 0;
1877
+ const usage = isRecord(result) ? result["usage"] : void 0;
1878
+ const providerMetadata = isRecord(result) ? result["providerMetadata"] : void 0;
1879
+ let responseId;
1880
+ if (isRecord(response) && typeof response["id"] === "string") {
1881
+ responseId = response["id"];
1882
+ } else {
1883
+ responseId = randomUUID();
1884
+ }
1885
+ let responseModelId;
1886
+ if (isRecord(response) && typeof response["modelId"] === "string") {
1887
+ responseModelId = response["modelId"];
1888
+ } else {
1889
+ responseModelId = modelInfo.modelId;
1890
+ }
1891
+ let responseTimestampIso;
1892
+ if (isRecord(response) && response["timestamp"] instanceof Date) {
1893
+ responseTimestampIso = response["timestamp"].toISOString();
1894
+ } else if (isRecord(response) && typeof response["timestamp"] === "string") {
1895
+ responseTimestampIso = response["timestamp"];
1896
+ } else {
1897
+ responseTimestampIso = (/* @__PURE__ */ new Date()).toISOString();
1898
+ }
1899
+ const inputTokens = extractNestedTokens(usage, "inputTokens");
1900
+ const outputTokens = extractNestedTokens(usage, "outputTokens");
1901
+ ctx.traceShipper.endSpan(span, {
1902
+ attributes: [
1903
+ ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
1904
+ attrString("ai.response.finishReason", finishReason),
1905
+ attrString("ai.response.text", extractTextFromLmContent(content)),
1906
+ attrString("ai.response.toolCalls", safeJsonWithUint8(extractToolCallsFromLmContent(content))),
1907
+ attrString("ai.response.id", responseId),
1908
+ attrString("ai.response.model", responseModelId),
1909
+ attrString("ai.response.timestamp", responseTimestampIso),
1910
+ attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1911
+ ],
1912
+ attrInt("ai.usage.promptTokens", inputTokens),
1913
+ attrInt("ai.usage.completionTokens", outputTokens),
1914
+ ...finishReason ? [attrStringArray("gen_ai.response.finish_reasons", [finishReason])] : [],
1915
+ attrString("gen_ai.response.id", responseId),
1916
+ attrString("gen_ai.response.model", responseModelId),
1917
+ attrInt("gen_ai.usage.input_tokens", inputTokens),
1918
+ attrInt("gen_ai.usage.output_tokens", outputTokens)
1919
+ ]
1920
+ });
1921
+ }
1922
+ function startDoStreamSpan(operationId, options, modelInfo, parent, ctx) {
1923
+ var _a, _b, _c;
1924
+ const { operationName, resourceName } = opName(operationId, (_a = ctx.telemetry) == null ? void 0 : _a.functionId);
1925
+ const tools = isRecord(options) ? options["tools"] : void 0;
1926
+ const toolsJson = Array.isArray(tools) && tools.length ? tools.map((tool) => safeJsonWithUint8(tool)).filter((json) => typeof json === "string" && json.length > 0) : void 0;
1927
+ const toolChoiceJson = isRecord(options) ? safeJsonWithUint8(options["toolChoice"]) : void 0;
1928
+ const promptJson = isRecord(options) ? safeJsonWithUint8(options["prompt"]) : safeJsonWithUint8(options);
1929
+ return ctx.traceShipper.startSpan({
1930
+ name: operationId,
1931
+ parent,
1932
+ eventId: ctx.eventId,
1933
+ operationId,
1934
+ attributes: [
1935
+ attrString("operation.name", operationName),
1936
+ attrString("resource.name", resourceName),
1937
+ attrString("ai.telemetry.functionId", (_b = ctx.telemetry) == null ? void 0 : _b.functionId),
1938
+ attrString("ai.model.provider", modelInfo.provider),
1939
+ attrString("ai.model.id", modelInfo.modelId),
1940
+ ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [attrString("ai.prompt.messages", promptJson), attrStringArray("ai.prompt.tools", toolsJson), attrString("ai.prompt.toolChoice", toolChoiceJson)],
1941
+ attrString("gen_ai.system", modelInfo.provider),
1942
+ attrString("gen_ai.request.model", modelInfo.modelId),
1943
+ ...attrsFromGenAiRequest(options)
1944
+ ]
1945
+ });
1946
+ }
1947
+ function resolveContext(context, info) {
1948
+ return typeof context === "function" ? context(info) : context;
1949
+ }
1950
+ function wrapOnFinish(args, onFinish) {
1951
+ if (!isRecord(args)) return args;
1952
+ const existing = args["onFinish"];
1953
+ if (existing === void 0) {
1954
+ return { ...args, onFinish: async (result) => onFinish(result) };
1955
+ }
1956
+ if (!isFunction(existing)) return args;
1957
+ return {
1958
+ ...args,
1959
+ onFinish: async (result) => {
1960
+ try {
1961
+ const maybePromise = existing(result);
1962
+ if (maybePromise && typeof maybePromise.then === "function") {
1963
+ await maybePromise;
1964
+ }
1965
+ } catch (e) {
1966
+ }
1967
+ await onFinish(result);
1968
+ }
1969
+ };
1970
+ }
1971
+ async function maybeBuildEvent(buildEvent, messages) {
1972
+ if (!buildEvent) return void 0;
1973
+ try {
1974
+ const r = buildEvent(messages);
1975
+ return r && typeof r === "object" ? r : void 0;
1976
+ } catch (e) {
1977
+ return void 0;
1978
+ }
1979
+ }
1980
+ function mergeBuildEventPatch(defaults, override) {
1981
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1982
+ if (!override) return defaults;
1983
+ return {
1984
+ eventName: (_a = override.eventName) != null ? _a : defaults.eventName,
1985
+ input: (_b = override.input) != null ? _b : defaults.input,
1986
+ output: (_c = override.output) != null ? _c : defaults.output,
1987
+ model: (_d = override.model) != null ? _d : defaults.model,
1988
+ properties: override.properties !== void 0 ? { ...(_e = defaults.properties) != null ? _e : {}, ...(_f = override.properties) != null ? _f : {} } : defaults.properties,
1989
+ attachments: override.attachments !== void 0 ? [...(_g = defaults.attachments) != null ? _g : [], ...(_h = override.attachments) != null ? _h : []] : defaults.attachments
1990
+ };
1991
+ }
1992
+ function extractNestedTokens(usage, key) {
1993
+ if (!isRecord(usage)) return void 0;
1994
+ const val = usage[key];
1995
+ if (typeof val === "number") return val;
1996
+ if (isRecord(val) && typeof val["total"] === "number") return val["total"];
1997
+ return void 0;
1998
+ }
1999
+
2000
+ // src/index.ts
2001
+ function eventMetadata(options) {
2002
+ var _a;
2003
+ const result = {};
2004
+ result["raindrop.eventId"] = (_a = options.eventId) != null ? _a : randomUUID();
2005
+ if (options.userId) result["raindrop.userId"] = options.userId;
2006
+ if (options.convoId) result["raindrop.convoId"] = options.convoId;
2007
+ if (options.eventName) result["raindrop.eventName"] = options.eventName;
2008
+ if (options.properties) result["raindrop.properties"] = JSON.stringify(options.properties);
2009
+ return result;
2010
+ }
2011
+ function createRaindropAISDK(opts) {
2012
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2013
+ const eventsEnabled = ((_a = opts.events) == null ? void 0 : _a.enabled) !== false;
2014
+ const tracesEnabled = ((_b = opts.traces) == null ? void 0 : _b.enabled) !== false;
2015
+ const eventShipper = new EventShipper({
2016
+ writeKey: opts.writeKey,
2017
+ endpoint: opts.endpoint,
2018
+ enabled: eventsEnabled,
2019
+ debug: ((_c = opts.events) == null ? void 0 : _c.debug) === true,
2020
+ partialFlushMs: (_d = opts.events) == null ? void 0 : _d.partialFlushMs
2021
+ });
2022
+ const traceShipper = new TraceShipper({
2023
+ writeKey: opts.writeKey,
2024
+ endpoint: opts.endpoint,
2025
+ enabled: tracesEnabled,
2026
+ debug: ((_e = opts.traces) == null ? void 0 : _e.debug) === true,
2027
+ debugSpans: ((_f = opts.traces) == null ? void 0 : _f.debugSpans) === true,
2028
+ flushIntervalMs: (_g = opts.traces) == null ? void 0 : _g.flushIntervalMs,
2029
+ maxBatchSize: (_h = opts.traces) == null ? void 0 : _h.maxBatchSize,
2030
+ maxQueueSize: (_i = opts.traces) == null ? void 0 : _i.maxQueueSize
2031
+ });
2032
+ return {
2033
+ wrap(aiSDK, options) {
2034
+ return wrapAISDK(aiSDK, {
2035
+ options,
2036
+ eventShipper,
2037
+ traceShipper
2038
+ });
2039
+ },
2040
+ events: {
2041
+ async patch(eventId, patch) {
2042
+ await eventShipper.patch(eventId, patch);
2043
+ },
2044
+ async addAttachments(eventId, attachments) {
2045
+ await eventShipper.patch(eventId, { attachments });
2046
+ },
2047
+ async setProperties(eventId, properties) {
2048
+ await eventShipper.patch(eventId, { properties });
2049
+ },
2050
+ async finish(eventId, patch) {
2051
+ await eventShipper.finish(eventId, patch);
2052
+ }
2053
+ },
2054
+ signals: {
2055
+ async track(signal) {
2056
+ await eventShipper.trackSignal(signal);
2057
+ }
2058
+ },
2059
+ async flush() {
2060
+ await Promise.all([eventShipper.flush(), traceShipper.flush()]);
2061
+ },
2062
+ async shutdown() {
2063
+ await Promise.all([eventShipper.shutdown(), traceShipper.shutdown()]);
2064
+ }
2065
+ };
2066
+ }
2067
+
2068
+ export { createRaindropAISDK, currentSpan, eventMetadata, getContextManager, withCurrent };