@raindrop-ai/deep-agents 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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1217 @@
1
+ // src/callback-handler.ts
2
+ import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
3
+
4
+ // ../core/dist/chunk-4UCYIEH4.js
5
+ function getCrypto() {
6
+ const c = globalThis.crypto;
7
+ return c;
8
+ }
9
+ function randomBytes(length) {
10
+ const cryptoObj = getCrypto();
11
+ const out = new Uint8Array(length);
12
+ if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
13
+ cryptoObj.getRandomValues(out);
14
+ return out;
15
+ }
16
+ for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
17
+ return out;
18
+ }
19
+ function randomUUID() {
20
+ const cryptoObj = getCrypto();
21
+ if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
22
+ return cryptoObj.randomUUID();
23
+ }
24
+ const b = randomBytes(16);
25
+ b[6] = b[6] & 15 | 64;
26
+ b[8] = b[8] & 63 | 128;
27
+ const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
28
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
29
+ }
30
+ function base64Encode(bytes) {
31
+ const maybeBuffer = globalThis.Buffer;
32
+ if (maybeBuffer) {
33
+ return maybeBuffer.from(bytes).toString("base64");
34
+ }
35
+ let binary = "";
36
+ for (let i2 = 0; i2 < bytes.length; i2++) {
37
+ binary += String.fromCharCode(bytes[i2]);
38
+ }
39
+ const btoaFn = globalThis.btoa;
40
+ if (typeof btoaFn === "function") return btoaFn(binary);
41
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
42
+ let out = "";
43
+ let i = 0;
44
+ while (i < binary.length) {
45
+ const c1 = binary.charCodeAt(i++) & 255;
46
+ const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
47
+ const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
48
+ const e1 = c1 >> 2;
49
+ const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
50
+ const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
51
+ const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
52
+ out += alphabet.charAt(e1);
53
+ out += alphabet.charAt(e2);
54
+ out += e3 === 64 ? "=" : alphabet.charAt(e3);
55
+ out += e4 === 64 ? "=" : alphabet.charAt(e4);
56
+ }
57
+ return out;
58
+ }
59
+ function wait(ms) {
60
+ return new Promise((resolve) => setTimeout(resolve, ms));
61
+ }
62
+ function formatEndpoint(endpoint) {
63
+ if (!endpoint) return void 0;
64
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
65
+ }
66
+ function parseRetryAfter(headers) {
67
+ var _a;
68
+ const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
69
+ if (!value) return void 0;
70
+ const asNumber2 = Number(value);
71
+ if (value.trim() !== "" && !Number.isNaN(asNumber2)) return asNumber2 * 1e3;
72
+ const asDate = new Date(value).getTime();
73
+ if (!Number.isNaN(asDate)) {
74
+ const delta = asDate - Date.now();
75
+ return delta > 0 ? delta : 0;
76
+ }
77
+ return void 0;
78
+ }
79
+ function getRetryDelayMs(attemptNumber, previousError) {
80
+ if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
81
+ const v = previousError.retryAfterMs;
82
+ if (typeof v === "number") return Math.max(0, v);
83
+ }
84
+ if (attemptNumber <= 1) return 0;
85
+ const base = 500;
86
+ const factor = Math.pow(2, attemptNumber - 2);
87
+ return base * factor;
88
+ }
89
+ async function withRetry(operation, opName, opts) {
90
+ const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
91
+ let lastError = void 0;
92
+ for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
93
+ if (attemptNumber > 1) {
94
+ const delay = getRetryDelayMs(attemptNumber, lastError);
95
+ if (opts.debug) {
96
+ console.warn(
97
+ `${prefix} ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
98
+ );
99
+ }
100
+ if (delay > 0) await wait(delay);
101
+ } else if (opts.debug) {
102
+ console.log(`${prefix} ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
103
+ }
104
+ try {
105
+ return await operation();
106
+ } catch (err) {
107
+ lastError = err;
108
+ if (opts.debug) {
109
+ const msg = err instanceof Error ? err.message : String(err);
110
+ console.warn(
111
+ `${prefix} ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
112
+ );
113
+ }
114
+ if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
115
+ break;
116
+ if (attemptNumber === opts.maxAttempts) break;
117
+ }
118
+ }
119
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
120
+ }
121
+ async function postJson(url, body, headers, opts) {
122
+ const opName = `POST ${url}`;
123
+ await withRetry(
124
+ async () => {
125
+ const resp = await fetch(url, {
126
+ method: "POST",
127
+ headers: {
128
+ "Content-Type": "application/json",
129
+ ...headers
130
+ },
131
+ body: JSON.stringify(body)
132
+ });
133
+ if (!resp.ok) {
134
+ const text = await resp.text().catch(() => "");
135
+ const err = new Error(
136
+ `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
137
+ );
138
+ const retryAfterMs = parseRetryAfter(resp.headers);
139
+ if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
140
+ err.retryable = resp.status === 429 || resp.status >= 500;
141
+ throw err;
142
+ }
143
+ },
144
+ opName,
145
+ opts
146
+ );
147
+ }
148
+ var SpanStatusCode = {
149
+ UNSET: 0,
150
+ OK: 1,
151
+ ERROR: 2
152
+ };
153
+ function createSpanIds(parent) {
154
+ const traceId = parent ? parent.traceIdB64 : base64Encode(randomBytes(16));
155
+ const spanId = base64Encode(randomBytes(8));
156
+ return {
157
+ traceIdB64: traceId,
158
+ spanIdB64: spanId,
159
+ parentSpanIdB64: parent ? parent.spanIdB64 : void 0
160
+ };
161
+ }
162
+ function nowUnixNanoString() {
163
+ return Date.now().toString() + "000000";
164
+ }
165
+ function attrString(key, value) {
166
+ if (value === void 0) return void 0;
167
+ return { key, value: { stringValue: value } };
168
+ }
169
+ function attrInt(key, value) {
170
+ if (value === void 0) return void 0;
171
+ if (!Number.isFinite(value)) return void 0;
172
+ return { key, value: { intValue: String(Math.trunc(value)) } };
173
+ }
174
+ function buildOtlpSpan(args) {
175
+ const attrs = args.attributes.filter((x) => x !== void 0);
176
+ const span = {
177
+ traceId: args.ids.traceIdB64,
178
+ spanId: args.ids.spanIdB64,
179
+ name: args.name,
180
+ startTimeUnixNano: args.startTimeUnixNano,
181
+ endTimeUnixNano: args.endTimeUnixNano
182
+ };
183
+ if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
184
+ if (attrs.length) span.attributes = attrs;
185
+ if (args.status) span.status = args.status;
186
+ return span;
187
+ }
188
+ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", serviceVersion = "0.0.0") {
189
+ return {
190
+ resourceSpans: [
191
+ {
192
+ resource: {
193
+ attributes: [{ key: "service.name", value: { stringValue: serviceName } }]
194
+ },
195
+ scopeSpans: [
196
+ {
197
+ scope: { name: serviceName, version: serviceVersion },
198
+ spans
199
+ }
200
+ ]
201
+ }
202
+ ]
203
+ };
204
+ }
205
+ function mergePatches(target, source) {
206
+ var _a, _b, _c, _d;
207
+ const out = { ...target, ...source };
208
+ if (target.properties || source.properties) {
209
+ out.properties = { ...(_a = target.properties) != null ? _a : {}, ...(_b = source.properties) != null ? _b : {} };
210
+ }
211
+ if (target.attachments || source.attachments) {
212
+ out.attachments = [...(_c = target.attachments) != null ? _c : [], ...(_d = source.attachments) != null ? _d : []];
213
+ }
214
+ return out;
215
+ }
216
+ var EventShipper = class {
217
+ constructor(opts) {
218
+ this.buffers = /* @__PURE__ */ new Map();
219
+ this.sticky = /* @__PURE__ */ new Map();
220
+ this.timers = /* @__PURE__ */ new Map();
221
+ this.inFlight = /* @__PURE__ */ new Set();
222
+ var _a, _b, _c, _d, _e, _f, _g;
223
+ this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
224
+ this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
225
+ this.enabled = opts.enabled !== false;
226
+ this.debug = opts.debug;
227
+ this.partialFlushMs = (_c = opts.partialFlushMs) != null ? _c : 1e3;
228
+ this.sdkName = (_d = opts.sdkName) != null ? _d : "core";
229
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
230
+ this.defaultEventName = (_e = opts.defaultEventName) != null ? _e : "ai_generation";
231
+ const isNode = typeof process !== "undefined" && typeof process.version === "string";
232
+ this.context = {
233
+ library: {
234
+ name: (_f = opts.libraryName) != null ? _f : "@raindrop-ai/core",
235
+ version: (_g = opts.libraryVersion) != null ? _g : "0.0.0"
236
+ },
237
+ metadata: {
238
+ jsRuntime: isNode ? "node" : "web",
239
+ ...isNode ? { nodeVersion: process.version } : {}
240
+ }
241
+ };
242
+ }
243
+ isDebugEnabled() {
244
+ return this.debug;
245
+ }
246
+ authHeaders() {
247
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
248
+ }
249
+ async patch(eventId, patch) {
250
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
251
+ if (!this.enabled) return;
252
+ if (!eventId || !eventId.trim()) return;
253
+ if (this.debug) {
254
+ console.log(`${this.prefix} queue patch`, {
255
+ eventId,
256
+ userId: patch.userId,
257
+ convoId: patch.convoId,
258
+ eventName: patch.eventName,
259
+ hasInput: typeof patch.input === "string" && patch.input.length > 0,
260
+ hasOutput: typeof patch.output === "string" && patch.output.length > 0,
261
+ attachments: (_b = (_a = patch.attachments) == null ? void 0 : _a.length) != null ? _b : 0,
262
+ isPending: patch.isPending
263
+ });
264
+ }
265
+ const sticky = (_c = this.sticky.get(eventId)) != null ? _c : {};
266
+ const existing = (_d = this.buffers.get(eventId)) != null ? _d : {};
267
+ const merged = mergePatches(existing, patch);
268
+ merged.isPending = (_g = (_f = (_e = patch.isPending) != null ? _e : existing.isPending) != null ? _f : sticky.isPending) != null ? _g : true;
269
+ this.buffers.set(eventId, merged);
270
+ this.sticky.set(eventId, {
271
+ userId: (_h = merged.userId) != null ? _h : sticky.userId,
272
+ convoId: (_i = merged.convoId) != null ? _i : sticky.convoId,
273
+ eventName: (_j = merged.eventName) != null ? _j : sticky.eventName,
274
+ isPending: (_k = merged.isPending) != null ? _k : sticky.isPending
275
+ });
276
+ const t = this.timers.get(eventId);
277
+ if (t) clearTimeout(t);
278
+ if (merged.isPending === false) {
279
+ await this.flushOne(eventId);
280
+ return;
281
+ }
282
+ const timeout = setTimeout(() => {
283
+ void this.flushOne(eventId).catch(() => {
284
+ });
285
+ }, this.partialFlushMs);
286
+ this.timers.set(eventId, timeout);
287
+ }
288
+ async finish(eventId, patch) {
289
+ await this.patch(eventId, { ...patch, isPending: false });
290
+ }
291
+ async flush() {
292
+ if (!this.enabled) return;
293
+ const ids = [...this.buffers.keys()];
294
+ await Promise.all(ids.map((id) => this.flushOne(id)));
295
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
296
+ })));
297
+ }
298
+ async shutdown() {
299
+ for (const t of this.timers.values()) clearTimeout(t);
300
+ this.timers.clear();
301
+ await this.flush();
302
+ }
303
+ async trackSignal(signal) {
304
+ var _a, _b;
305
+ if (!this.enabled) return;
306
+ const body = [
307
+ {
308
+ event_id: signal.eventId,
309
+ signal_name: signal.name,
310
+ signal_type: (_a = signal.type) != null ? _a : "default",
311
+ timestamp: signal.timestamp,
312
+ sentiment: signal.sentiment,
313
+ attachment_id: signal.attachmentId,
314
+ properties: {
315
+ ...(_b = signal.properties) != null ? _b : {},
316
+ ...signal.comment ? { comment: signal.comment } : {},
317
+ ...signal.after ? { after: signal.after } : {}
318
+ }
319
+ }
320
+ ];
321
+ const url = `${this.baseUrl}signals/track`;
322
+ try {
323
+ await postJson(url, body, this.authHeaders(), {
324
+ maxAttempts: 3,
325
+ debug: this.debug,
326
+ sdkName: this.sdkName
327
+ });
328
+ } catch (err) {
329
+ const msg = err instanceof Error ? err.message : String(err);
330
+ console.warn(`${this.prefix} failed to send signal (dropping): ${msg}`);
331
+ }
332
+ }
333
+ async identify(users) {
334
+ if (!this.enabled) return;
335
+ const list = Array.isArray(users) ? users : [users];
336
+ const body = list.filter((user) => {
337
+ if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
338
+ if (this.debug) {
339
+ console.warn(`${this.prefix} skipping identify: missing userId`);
340
+ }
341
+ return false;
342
+ }
343
+ return true;
344
+ }).map((user) => {
345
+ var _a;
346
+ return {
347
+ user_id: user.userId,
348
+ traits: (_a = user.traits) != null ? _a : {}
349
+ };
350
+ });
351
+ if (body.length === 0) return;
352
+ const url = `${this.baseUrl}users/identify`;
353
+ try {
354
+ await postJson(url, body, this.authHeaders(), {
355
+ maxAttempts: 3,
356
+ debug: this.debug,
357
+ sdkName: this.sdkName
358
+ });
359
+ } catch (err) {
360
+ const msg = err instanceof Error ? err.message : String(err);
361
+ console.warn(`${this.prefix} failed to send identify (dropping): ${msg}`);
362
+ }
363
+ }
364
+ async flushOne(eventId) {
365
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
366
+ if (!this.enabled) return;
367
+ const timer = this.timers.get(eventId);
368
+ if (timer) {
369
+ clearTimeout(timer);
370
+ this.timers.delete(eventId);
371
+ }
372
+ const accumulated = this.buffers.get(eventId);
373
+ this.buffers.delete(eventId);
374
+ if (!accumulated) return;
375
+ const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
376
+ const eventName = (_c = (_b = accumulated.eventName) != null ? _b : sticky.eventName) != null ? _c : this.defaultEventName;
377
+ const userId = (_d = accumulated.userId) != null ? _d : sticky.userId;
378
+ if (!userId) {
379
+ if (this.debug) {
380
+ console.warn(`${this.prefix} skipping track_partial for ${eventId}: missing userId`);
381
+ }
382
+ this.sticky.delete(eventId);
383
+ return;
384
+ }
385
+ const { wizardSession, ...restProperties } = (_e = accumulated.properties) != null ? _e : {};
386
+ const convoId = (_f = accumulated.convoId) != null ? _f : sticky.convoId;
387
+ const isPending = (_h = (_g = accumulated.isPending) != null ? _g : sticky.isPending) != null ? _h : true;
388
+ const payload = {
389
+ event_id: eventId,
390
+ user_id: userId,
391
+ event: eventName,
392
+ timestamp: (_i = accumulated.timestamp) != null ? _i : (/* @__PURE__ */ new Date()).toISOString(),
393
+ ai_data: {
394
+ input: accumulated.input,
395
+ output: accumulated.output,
396
+ model: accumulated.model,
397
+ convo_id: convoId
398
+ },
399
+ properties: {
400
+ ...restProperties,
401
+ ...wizardSession ? { "raindrop.wizardSession": wizardSession } : {},
402
+ $context: this.context
403
+ },
404
+ attachments: accumulated.attachments,
405
+ is_pending: isPending
406
+ };
407
+ const url = `${this.baseUrl}events/track_partial`;
408
+ if (this.debug) {
409
+ console.log(`${this.prefix} sending track_partial`, {
410
+ eventId,
411
+ eventName,
412
+ userId,
413
+ convoId,
414
+ isPending,
415
+ inputPreview: typeof accumulated.input === "string" ? accumulated.input.slice(0, 120) : void 0,
416
+ outputPreview: typeof accumulated.output === "string" ? accumulated.output.slice(0, 120) : void 0,
417
+ attachments: (_k = (_j = accumulated.attachments) == null ? void 0 : _j.length) != null ? _k : 0,
418
+ attachmentKinds: (_m = (_l = accumulated.attachments) == null ? void 0 : _l.map((a) => ({
419
+ type: a.type,
420
+ role: a.role,
421
+ name: a.name,
422
+ valuePreview: a.value.slice(0, 60)
423
+ }))) != null ? _m : [],
424
+ endpoint: url
425
+ });
426
+ }
427
+ const p = postJson(url, payload, this.authHeaders(), {
428
+ maxAttempts: 3,
429
+ debug: this.debug,
430
+ sdkName: this.sdkName
431
+ });
432
+ this.inFlight.add(p);
433
+ try {
434
+ try {
435
+ await p;
436
+ if (this.debug) {
437
+ console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
438
+ }
439
+ } catch (err) {
440
+ const msg = err instanceof Error ? err.message : String(err);
441
+ console.warn(`${this.prefix} failed to send track_partial (dropping): ${msg}`);
442
+ }
443
+ } finally {
444
+ this.inFlight.delete(p);
445
+ }
446
+ if (!isPending) {
447
+ this.sticky.delete(eventId);
448
+ }
449
+ }
450
+ };
451
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
452
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
453
+ var _a, _b, _c;
454
+ const resolved = (_b = baseUrl != null ? baseUrl : typeof process !== "undefined" ? (_a = process.env) == null ? void 0 : _a[LOCAL_DEBUGGER_ENV_VAR] : void 0) != null ? _b : null;
455
+ return resolved ? (_c = formatEndpoint(resolved)) != null ? _c : null : null;
456
+ }
457
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
458
+ var _a;
459
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
460
+ if (!baseUrl) return;
461
+ void postJson(`${baseUrl}traces`, body, {}, {
462
+ maxAttempts: 1,
463
+ debug: (_a = options.debug) != null ? _a : false,
464
+ sdkName: options.sdkName
465
+ }).catch(() => {
466
+ });
467
+ }
468
+ var TraceShipper = class {
469
+ constructor(opts) {
470
+ this.queue = [];
471
+ this.inFlight = /* @__PURE__ */ new Set();
472
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
473
+ this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
474
+ this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
475
+ this.enabled = opts.enabled !== false;
476
+ this.debug = opts.debug;
477
+ this.debugSpans = opts.debugSpans === true;
478
+ this.flushIntervalMs = (_c = opts.flushIntervalMs) != null ? _c : 1e3;
479
+ this.maxBatchSize = (_d = opts.maxBatchSize) != null ? _d : 50;
480
+ this.maxQueueSize = (_e = opts.maxQueueSize) != null ? _e : 5e3;
481
+ this.sdkName = (_f = opts.sdkName) != null ? _f : "core";
482
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
483
+ this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
484
+ this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
485
+ const localDebugger = typeof process !== "undefined" ? (_i = process.env) == null ? void 0 : _i.RAINDROP_LOCAL_DEBUGGER : void 0;
486
+ if (localDebugger) {
487
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(localDebugger)) != null ? _j : void 0;
488
+ if (this.debug) {
489
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
490
+ }
491
+ }
492
+ }
493
+ isDebugEnabled() {
494
+ return this.debug;
495
+ }
496
+ authHeaders() {
497
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
498
+ }
499
+ startSpan(args) {
500
+ var _a, _b;
501
+ const ids = createSpanIds(args.parent);
502
+ const started = (_a = args.startTimeUnixNano) != null ? _a : nowUnixNanoString();
503
+ const attrs = [
504
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
505
+ attrString("ai.operationId", args.operationId)
506
+ ];
507
+ if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
508
+ const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
509
+ if (this.localDebuggerUrl) {
510
+ const openSpan = buildOtlpSpan({
511
+ ids: span.ids,
512
+ name: span.name,
513
+ startTimeUnixNano: span.startTimeUnixNano,
514
+ endTimeUnixNano: span.startTimeUnixNano,
515
+ // placeholder — will be updated on endSpan
516
+ attributes: span.attributes,
517
+ status: { code: SpanStatusCode.UNSET }
518
+ });
519
+ const body = buildExportTraceServiceRequest([openSpan], this.serviceName, this.serviceVersion);
520
+ mirrorTraceExportToLocalDebugger(body, {
521
+ baseUrl: this.localDebuggerUrl,
522
+ debug: false,
523
+ sdkName: this.sdkName
524
+ });
525
+ }
526
+ return span;
527
+ }
528
+ endSpan(span, extra) {
529
+ var _a, _b;
530
+ if (span.endTimeUnixNano) return;
531
+ span.endTimeUnixNano = (_a = extra == null ? void 0 : extra.endTimeUnixNano) != null ? _a : nowUnixNanoString();
532
+ if ((_b = extra == null ? void 0 : extra.attributes) == null ? void 0 : _b.length) {
533
+ span.attributes.push(...extra.attributes);
534
+ }
535
+ let status = extra == null ? void 0 : extra.status;
536
+ if (!status && (extra == null ? void 0 : extra.error) !== void 0) {
537
+ const message = extra.error instanceof Error ? extra.error.message : String(extra.error);
538
+ status = { code: SpanStatusCode.ERROR, message };
539
+ }
540
+ const otlp = buildOtlpSpan({
541
+ ids: span.ids,
542
+ name: span.name,
543
+ startTimeUnixNano: span.startTimeUnixNano,
544
+ endTimeUnixNano: span.endTimeUnixNano,
545
+ attributes: span.attributes,
546
+ status
547
+ });
548
+ this.enqueue(otlp);
549
+ if (this.localDebuggerUrl) {
550
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
551
+ mirrorTraceExportToLocalDebugger(body, {
552
+ baseUrl: this.localDebuggerUrl,
553
+ debug: false,
554
+ sdkName: this.sdkName
555
+ });
556
+ }
557
+ }
558
+ createSpan(args) {
559
+ var _a;
560
+ const ids = createSpanIds(args.parent);
561
+ const attrs = [
562
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId)
563
+ ];
564
+ if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
565
+ const otlp = buildOtlpSpan({
566
+ ids,
567
+ name: args.name,
568
+ startTimeUnixNano: args.startTimeUnixNano,
569
+ endTimeUnixNano: args.endTimeUnixNano,
570
+ attributes: attrs,
571
+ status: args.status
572
+ });
573
+ this.enqueue(otlp);
574
+ if (this.localDebuggerUrl) {
575
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
576
+ mirrorTraceExportToLocalDebugger(body, {
577
+ baseUrl: this.localDebuggerUrl,
578
+ debug: false,
579
+ sdkName: this.sdkName
580
+ });
581
+ }
582
+ }
583
+ enqueue(span) {
584
+ if (!this.enabled) return;
585
+ if (this.debugSpans) {
586
+ const short = (s) => s ? s.slice(-8) : "none";
587
+ console.log(
588
+ `${this.prefix}[span] name=${span.name} trace=${short(span.traceId)} span=${short(span.spanId)} parent=${short(
589
+ span.parentSpanId
590
+ )}`
591
+ );
592
+ }
593
+ if (this.queue.length >= this.maxQueueSize) {
594
+ this.queue.shift();
595
+ }
596
+ this.queue.push(span);
597
+ if (this.queue.length >= this.maxBatchSize) {
598
+ void this.flush().catch(() => {
599
+ });
600
+ return;
601
+ }
602
+ if (!this.timer) {
603
+ this.timer = setTimeout(() => {
604
+ this.timer = void 0;
605
+ void this.flush().catch(() => {
606
+ });
607
+ }, this.flushIntervalMs);
608
+ }
609
+ }
610
+ async flush() {
611
+ if (!this.enabled) return;
612
+ if (this.timer) {
613
+ clearTimeout(this.timer);
614
+ this.timer = void 0;
615
+ }
616
+ while (this.queue.length > 0) {
617
+ const batch = this.queue.splice(0, this.maxBatchSize);
618
+ const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
619
+ const url = `${this.baseUrl}traces`;
620
+ if (this.debug) {
621
+ console.log(`${this.prefix} sending traces batch`, {
622
+ spans: batch.length,
623
+ endpoint: url
624
+ });
625
+ }
626
+ const p = postJson(url, body, this.authHeaders(), {
627
+ maxAttempts: 3,
628
+ debug: this.debug,
629
+ sdkName: this.sdkName
630
+ });
631
+ this.inFlight.add(p);
632
+ try {
633
+ try {
634
+ await p;
635
+ if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
636
+ } catch (err) {
637
+ const msg = err instanceof Error ? err.message : String(err);
638
+ console.warn(`${this.prefix} failed to send ${batch.length} spans: ${msg}`);
639
+ }
640
+ } finally {
641
+ this.inFlight.delete(p);
642
+ }
643
+ }
644
+ }
645
+ async shutdown() {
646
+ if (this.timer) {
647
+ clearTimeout(this.timer);
648
+ this.timer = void 0;
649
+ }
650
+ await this.flush();
651
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
652
+ })));
653
+ }
654
+ };
655
+
656
+ // ../core/dist/index.node.js
657
+ import { AsyncLocalStorage } from "async_hooks";
658
+ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
659
+
660
+ // src/callback-handler.ts
661
+ function isInternalName(name) {
662
+ if (name.startsWith("Branch:")) return true;
663
+ if (name.startsWith("ChannelWrite")) return true;
664
+ if (name.startsWith("ChannelRead")) return true;
665
+ if (name.startsWith("__") && name.endsWith("__")) return true;
666
+ return false;
667
+ }
668
+ var CHAIN_TEXT_MAX_LEN = 8192;
669
+ function extractTextFromContent(content) {
670
+ if (content == null) return void 0;
671
+ if (typeof content === "string") return content;
672
+ if (Array.isArray(content)) {
673
+ const parts = [];
674
+ for (const part of content) {
675
+ if (typeof part === "string") {
676
+ parts.push(part);
677
+ } else if (part && typeof part === "object") {
678
+ const p = part;
679
+ if (typeof p.text === "string") {
680
+ parts.push(p.text);
681
+ } else if (p.type === "text" && typeof p.content === "string") {
682
+ parts.push(p.content);
683
+ }
684
+ }
685
+ }
686
+ if (parts.length > 0) return parts.join("\n");
687
+ return safeStringify(content);
688
+ }
689
+ if (typeof content === "object") {
690
+ const c = content;
691
+ if (typeof c.text === "string") return c.text;
692
+ if (typeof c.content === "string") return c.content;
693
+ return safeStringify(content);
694
+ }
695
+ return String(content);
696
+ }
697
+ var RaindropDeepAgentsHandler = class extends BaseCallbackHandler {
698
+ constructor(opts) {
699
+ super();
700
+ this.name = "RaindropDeepAgentsHandler";
701
+ this.spans = /* @__PURE__ */ new Map();
702
+ this.rootRunIds = /* @__PURE__ */ new Map();
703
+ this.eventIds = /* @__PURE__ */ new Map();
704
+ this.forwardedSpans = /* @__PURE__ */ new Set();
705
+ this.eventShipper = opts.eventShipper;
706
+ this.traceShipper = opts.traceShipper;
707
+ this.userId = opts.userId;
708
+ this.convoId = opts.convoId;
709
+ this.traceChains = opts.traceChains ?? true;
710
+ }
711
+ getEventId(runId, parentRunId) {
712
+ const rootId = parentRunId ? this.rootRunIds.get(parentRunId) ?? parentRunId : runId;
713
+ this.rootRunIds.set(runId, rootId);
714
+ if (!this.eventIds.has(rootId)) {
715
+ this.eventIds.set(rootId, randomUUID());
716
+ }
717
+ return this.eventIds.get(rootId);
718
+ }
719
+ getParent(parentRunId) {
720
+ if (!parentRunId) return void 0;
721
+ const parentSpan = this.spans.get(parentRunId);
722
+ if (!parentSpan) return void 0;
723
+ return {
724
+ traceIdB64: parentSpan.ids.traceIdB64,
725
+ spanIdB64: parentSpan.ids.spanIdB64
726
+ };
727
+ }
728
+ cleanup(runId) {
729
+ this.spans.delete(runId);
730
+ this.spans.delete(`${runId}:agent_action`);
731
+ this.forwardedSpans.delete(runId);
732
+ const rootId = this.rootRunIds.get(runId) ?? runId;
733
+ this.rootRunIds.delete(runId);
734
+ if (rootId === runId) {
735
+ this.eventIds.delete(rootId);
736
+ }
737
+ }
738
+ async finalizeEventIfRoot(runId, patch) {
739
+ const rootId = this.rootRunIds.get(runId) ?? runId;
740
+ const isRoot = rootId === runId;
741
+ const eventId = this.eventIds.get(rootId);
742
+ if (!eventId) return;
743
+ if (isRoot) {
744
+ if (this.convoId) {
745
+ await this.eventShipper.patch(eventId, {
746
+ userId: this.userId,
747
+ convoId: this.convoId,
748
+ isPending: true
749
+ });
750
+ }
751
+ await this.eventShipper.finish(eventId, { userId: this.userId, ...patch });
752
+ } else if (patch) {
753
+ await this.eventShipper.patch(eventId, {
754
+ userId: this.userId,
755
+ convoId: this.convoId,
756
+ ...patch,
757
+ isPending: true
758
+ });
759
+ }
760
+ }
761
+ // ---------------------------------------------------------------------------
762
+ // LLM events
763
+ // ---------------------------------------------------------------------------
764
+ async handleLLMStart(llm, prompts, runId, parentRunId, _extraParams, tags, metadata, runName) {
765
+ try {
766
+ if (this.spans.has(runId)) return;
767
+ const eventId = this.getEventId(runId, parentRunId);
768
+ const modelId = getName(llm, runName);
769
+ const span = this.traceShipper.startSpan({
770
+ name: "llm",
771
+ parent: this.getParent(parentRunId),
772
+ eventId,
773
+ attributes: [
774
+ attrString("ai.model.provider", modelId),
775
+ attrString("ai.operationId", "llm")
776
+ ]
777
+ });
778
+ this.spans.set(runId, span);
779
+ await this.eventShipper.patch(eventId, {
780
+ userId: this.userId,
781
+ convoId: this.convoId,
782
+ input: truncate(prompts.join("\n"), CHAIN_TEXT_MAX_LEN),
783
+ properties: buildProperties(tags, metadata),
784
+ isPending: true
785
+ });
786
+ } catch {
787
+ }
788
+ }
789
+ async handleChatModelStart(llm, messages, runId, parentRunId, _extraParams, tags, metadata, runName) {
790
+ try {
791
+ if (this.spans.has(runId)) return;
792
+ const eventId = this.getEventId(runId, parentRunId);
793
+ const modelId = getName(llm, runName);
794
+ const span = this.traceShipper.startSpan({
795
+ name: "llm",
796
+ parent: this.getParent(parentRunId),
797
+ eventId,
798
+ attributes: [
799
+ attrString("ai.model.provider", modelId),
800
+ attrString("ai.operationId", "chat")
801
+ ]
802
+ });
803
+ this.spans.set(runId, span);
804
+ const allMessages = messages.flat();
805
+ const userMessages = allMessages.filter((m) => {
806
+ const role = m._getType?.() ?? "unknown";
807
+ return role === "human";
808
+ });
809
+ const lastMsg = userMessages.length > 0 ? userMessages[userMessages.length - 1] : allMessages[allMessages.length - 1];
810
+ const extracted = lastMsg ? extractTextFromContent(lastMsg.content) : void 0;
811
+ const inputText = extracted !== void 0 ? truncate(extracted, CHAIN_TEXT_MAX_LEN) : void 0;
812
+ await this.eventShipper.patch(eventId, {
813
+ userId: this.userId,
814
+ convoId: this.convoId,
815
+ input: inputText,
816
+ properties: buildProperties(tags, metadata),
817
+ isPending: true
818
+ });
819
+ } catch {
820
+ }
821
+ }
822
+ async handleLLMEnd(output, runId, _parentRunId) {
823
+ const earlyRootId = this.rootRunIds.get(runId) ?? runId;
824
+ if (earlyRootId === runId) {
825
+ this._lastRootEventId = this.eventIds.get(earlyRootId) ?? this._lastRootEventId;
826
+ }
827
+ try {
828
+ const span = this.spans.get(runId);
829
+ if (!span) {
830
+ await this.finalizeEventIfRoot(runId);
831
+ return;
832
+ }
833
+ const meta = extractLLMMetadata(output);
834
+ const {
835
+ model,
836
+ promptTokens,
837
+ completionTokens,
838
+ cachedTokens,
839
+ reasoningTokens,
840
+ finishReason,
841
+ outputText
842
+ } = meta;
843
+ this.traceShipper.endSpan(span, {
844
+ attributes: [
845
+ attrString("ai.response.model", model),
846
+ attrInt("ai.usage.prompt_tokens", promptTokens),
847
+ attrInt("ai.usage.completion_tokens", completionTokens),
848
+ attrInt("ai.usage.cached_tokens", cachedTokens),
849
+ attrInt("ai.usage.thoughts_tokens", reasoningTokens),
850
+ attrString("ai.finish_reason", finishReason)
851
+ ]
852
+ });
853
+ const properties = {};
854
+ if (promptTokens != null) properties["ai.usage.prompt_tokens"] = promptTokens;
855
+ if (completionTokens != null) properties["ai.usage.completion_tokens"] = completionTokens;
856
+ if (cachedTokens != null) properties["ai.usage.cached_tokens"] = cachedTokens;
857
+ if (reasoningTokens != null) properties["ai.usage.thoughts_tokens"] = reasoningTokens;
858
+ if (finishReason != null) properties["ai.finish_reason"] = finishReason;
859
+ const cappedOutput = outputText !== void 0 ? truncate(outputText, CHAIN_TEXT_MAX_LEN) : void 0;
860
+ await this.finalizeEventIfRoot(runId, {
861
+ output: cappedOutput,
862
+ model,
863
+ properties: Object.keys(properties).length > 0 ? properties : void 0
864
+ });
865
+ } catch {
866
+ } finally {
867
+ this.cleanup(runId);
868
+ }
869
+ }
870
+ async handleLLMError(err, runId) {
871
+ const earlyRootId = this.rootRunIds.get(runId) ?? runId;
872
+ if (earlyRootId === runId) {
873
+ this._lastRootEventId = this.eventIds.get(earlyRootId) ?? this._lastRootEventId;
874
+ }
875
+ try {
876
+ const span = this.spans.get(runId);
877
+ if (span) {
878
+ this.traceShipper.endSpan(span, { error: err });
879
+ }
880
+ const errorInfo = extractErrorInfo(err);
881
+ await this.finalizeEventIfRoot(runId, {
882
+ output: `[Error] ${errorInfo.type}: ${errorInfo.message}`,
883
+ properties: {
884
+ "error.type": errorInfo.type,
885
+ "error.message": errorInfo.message
886
+ }
887
+ });
888
+ } catch {
889
+ } finally {
890
+ this.cleanup(runId);
891
+ }
892
+ }
893
+ // ---------------------------------------------------------------------------
894
+ // Chain events
895
+ // ---------------------------------------------------------------------------
896
+ async handleChainStart(chain, _inputs, runId, parentRunId, _tags, _metadata, _runType, runName) {
897
+ try {
898
+ const chainName = getName(chain, runName);
899
+ this.getEventId(runId, parentRunId);
900
+ if (isInternalName(chainName)) {
901
+ const parentSpan = parentRunId ? this.spans.get(parentRunId) : void 0;
902
+ if (parentSpan) {
903
+ this.spans.set(runId, parentSpan);
904
+ this.forwardedSpans.add(runId);
905
+ }
906
+ return;
907
+ }
908
+ if (!this.traceChains) return;
909
+ const eventId = this.eventIds.get(this.rootRunIds.get(runId) ?? runId);
910
+ const span = this.traceShipper.startSpan({
911
+ name: "chain",
912
+ parent: this.getParent(parentRunId),
913
+ eventId,
914
+ attributes: [
915
+ attrString("chain.name", chainName),
916
+ attrString("ai.operationId", "chain")
917
+ ]
918
+ });
919
+ this.spans.set(runId, span);
920
+ } catch {
921
+ }
922
+ }
923
+ async handleChainEnd(_outputs, runId) {
924
+ const earlyRootId = this.rootRunIds.get(runId) ?? runId;
925
+ if (earlyRootId === runId) {
926
+ this._lastRootEventId = this.eventIds.get(earlyRootId) ?? this._lastRootEventId;
927
+ }
928
+ try {
929
+ if (this.traceChains && !this.forwardedSpans.has(runId)) {
930
+ const span = this.spans.get(runId);
931
+ if (span) this.traceShipper.endSpan(span);
932
+ }
933
+ await this.finalizeEventIfRoot(runId);
934
+ } catch {
935
+ } finally {
936
+ this.cleanup(runId);
937
+ }
938
+ }
939
+ async handleChainError(err, runId) {
940
+ const earlyRootId = this.rootRunIds.get(runId) ?? runId;
941
+ if (earlyRootId === runId) {
942
+ this._lastRootEventId = this.eventIds.get(earlyRootId) ?? this._lastRootEventId;
943
+ }
944
+ try {
945
+ if (this.traceChains && !this.forwardedSpans.has(runId)) {
946
+ const span = this.spans.get(runId);
947
+ if (span) this.traceShipper.endSpan(span, { error: err });
948
+ }
949
+ const errorInfo = extractErrorInfo(err);
950
+ await this.finalizeEventIfRoot(runId, {
951
+ output: `[Error] ${errorInfo.type}: ${errorInfo.message}`,
952
+ properties: {
953
+ "error.type": errorInfo.type,
954
+ "error.message": errorInfo.message
955
+ }
956
+ });
957
+ } catch {
958
+ } finally {
959
+ this.cleanup(runId);
960
+ }
961
+ }
962
+ // ---------------------------------------------------------------------------
963
+ // Tool events -- Deep Agents uses tools heavily (write_todos, read_file,
964
+ // write_file, edit_file, ls, execute, task, etc.)
965
+ // ---------------------------------------------------------------------------
966
+ async handleToolStart(tool, input, runId, parentRunId, _tags, _metadata, runName) {
967
+ try {
968
+ const eventId = this.getEventId(runId, parentRunId);
969
+ const toolName = getName(tool, runName);
970
+ const span = this.traceShipper.startSpan({
971
+ name: "tool",
972
+ parent: this.getParent(parentRunId),
973
+ eventId,
974
+ operationId: "ai.toolCall",
975
+ attributes: [
976
+ attrString("ai.toolCall.name", toolName),
977
+ attrString("tool.input", truncate(input, 4096))
978
+ ]
979
+ });
980
+ this.spans.set(runId, span);
981
+ } catch {
982
+ }
983
+ }
984
+ async handleToolEnd(output, runId) {
985
+ const earlyRootId = this.rootRunIds.get(runId) ?? runId;
986
+ if (earlyRootId === runId) {
987
+ this._lastRootEventId = this.eventIds.get(earlyRootId) ?? this._lastRootEventId;
988
+ }
989
+ try {
990
+ const span = this.spans.get(runId);
991
+ if (span) {
992
+ const outputStr = typeof output === "string" ? output : safeStringify(output);
993
+ this.traceShipper.endSpan(span, {
994
+ attributes: [attrString("tool.output", truncate(outputStr, 4096))]
995
+ });
996
+ }
997
+ await this.finalizeEventIfRoot(runId);
998
+ } catch {
999
+ } finally {
1000
+ this.cleanup(runId);
1001
+ }
1002
+ }
1003
+ async handleToolError(err, runId) {
1004
+ const earlyRootId = this.rootRunIds.get(runId) ?? runId;
1005
+ if (earlyRootId === runId) {
1006
+ this._lastRootEventId = this.eventIds.get(earlyRootId) ?? this._lastRootEventId;
1007
+ }
1008
+ try {
1009
+ const span = this.spans.get(runId);
1010
+ if (span) this.traceShipper.endSpan(span, { error: err });
1011
+ const errorInfo = extractErrorInfo(err);
1012
+ await this.finalizeEventIfRoot(runId, {
1013
+ output: `[Error] ${errorInfo.type}: ${errorInfo.message}`,
1014
+ properties: {
1015
+ "error.type": errorInfo.type,
1016
+ "error.message": errorInfo.message
1017
+ }
1018
+ });
1019
+ } catch {
1020
+ } finally {
1021
+ this.cleanup(runId);
1022
+ }
1023
+ }
1024
+ // ---------------------------------------------------------------------------
1025
+ // Agent events
1026
+ // ---------------------------------------------------------------------------
1027
+ async handleAgentAction(action, runId, parentRunId) {
1028
+ try {
1029
+ const eventId = this.getEventId(runId, parentRunId);
1030
+ const span = this.traceShipper.startSpan({
1031
+ name: "agent_action",
1032
+ parent: this.getParent(parentRunId),
1033
+ eventId,
1034
+ operationId: "ai.toolCall",
1035
+ attributes: [
1036
+ attrString("ai.toolCall.name", action.tool),
1037
+ attrString("agent.tool_input", truncate(
1038
+ typeof action.toolInput === "string" ? action.toolInput : safeStringify(action.toolInput),
1039
+ 4096
1040
+ ))
1041
+ ]
1042
+ });
1043
+ this.spans.set(`${runId}:agent_action`, span);
1044
+ } catch {
1045
+ }
1046
+ }
1047
+ async handleAgentEnd(_action, runId) {
1048
+ try {
1049
+ const spanKey = `${runId}:agent_action`;
1050
+ const span = this.spans.get(spanKey);
1051
+ if (span) {
1052
+ this.traceShipper.endSpan(span);
1053
+ this.spans.delete(spanKey);
1054
+ }
1055
+ } catch {
1056
+ }
1057
+ }
1058
+ };
1059
+ function getName(serialized, runName) {
1060
+ if (runName) return runName;
1061
+ if (serialized?.id?.length) return serialized.id[serialized.id.length - 1];
1062
+ if ("name" in serialized && typeof serialized.name === "string")
1063
+ return serialized.name;
1064
+ return "unknown";
1065
+ }
1066
+ function buildProperties(tags, metadata) {
1067
+ if (!tags?.length && !metadata) return void 0;
1068
+ const props = {};
1069
+ if (tags?.length) props["deep_agents.tags"] = tags;
1070
+ if (metadata) Object.assign(props, metadata);
1071
+ return props;
1072
+ }
1073
+ function safeStringify(value) {
1074
+ try {
1075
+ return JSON.stringify(value) ?? "";
1076
+ } catch {
1077
+ return String(value);
1078
+ }
1079
+ }
1080
+ function truncate(str, maxLen) {
1081
+ if (str.length <= maxLen) return str;
1082
+ return str.slice(0, maxLen - 3) + "...";
1083
+ }
1084
+ function extractLLMMetadata(output) {
1085
+ const gen = output.generations?.[0]?.[0];
1086
+ const message = gen?.message;
1087
+ const responseMeta = message?.response_metadata;
1088
+ const usageMeta = message?.usage_metadata;
1089
+ const generationInfo = gen?.generationInfo;
1090
+ const llmOutput = output.llmOutput;
1091
+ const tokenUsage = llmOutput?.token_usage ?? llmOutput?.tokenUsage;
1092
+ const estimatedTokens = llmOutput?.estimatedTokens;
1093
+ const model = responseMeta?.model_name ?? responseMeta?.model ?? llmOutput?.model_name ?? llmOutput?.model;
1094
+ const usage = usageMeta ?? tokenUsage ?? estimatedTokens;
1095
+ const promptTokens = asNumber(
1096
+ usage?.input_tokens ?? usage?.prompt_tokens ?? usage?.promptTokens
1097
+ );
1098
+ const completionTokens = asNumber(
1099
+ usage?.output_tokens ?? usage?.completion_tokens ?? usage?.completionTokens
1100
+ );
1101
+ const inputDetails = usage?.input_token_details;
1102
+ const outputDetails = usage?.output_token_details;
1103
+ const cachedTokens = asNumber(
1104
+ inputDetails?.cache_read ?? usage?.cache_read_input_tokens ?? usage?.cached_tokens
1105
+ );
1106
+ const reasoningTokens = asNumber(
1107
+ outputDetails?.reasoning ?? usage?.reasoning_tokens ?? usage?.thoughts_tokens
1108
+ );
1109
+ const finishReason = generationInfo?.finish_reason ?? responseMeta?.finish_reason ?? responseMeta?.stop_reason;
1110
+ const outputText = gen?.text ?? (typeof message?.content === "string" ? message.content : void 0) ?? (message?.content ? extractTextFromContent(message.content) : void 0);
1111
+ return {
1112
+ model,
1113
+ promptTokens,
1114
+ completionTokens,
1115
+ cachedTokens,
1116
+ reasoningTokens,
1117
+ finishReason,
1118
+ outputText
1119
+ };
1120
+ }
1121
+ function asNumber(val) {
1122
+ if (val == null) return void 0;
1123
+ const n = typeof val === "number" ? val : Number(val);
1124
+ return Number.isFinite(n) ? n : void 0;
1125
+ }
1126
+ function extractErrorInfo(err) {
1127
+ if (err instanceof Error) {
1128
+ return { type: err.name || err.constructor.name, message: err.message };
1129
+ }
1130
+ if (typeof err === "object" && err !== null) {
1131
+ const e = err;
1132
+ const type = e.name ?? e.constructor?.name ?? "Error";
1133
+ const message = e.message ?? safeStringify(err);
1134
+ return { type, message };
1135
+ }
1136
+ return { type: "Error", message: String(err) };
1137
+ }
1138
+
1139
+ // src/version.ts
1140
+ var libraryName = "@raindrop-ai/deep-agents";
1141
+ var libraryVersion = "0.0.1";
1142
+
1143
+ // src/index.ts
1144
+ function createRaindropDeepAgents(opts) {
1145
+ const writeKey = opts.writeKey;
1146
+ const enabled = !!writeKey;
1147
+ if (!writeKey) {
1148
+ console.warn(
1149
+ "[raindrop-ai/deep-agents] writeKey not provided; telemetry shipping is disabled"
1150
+ );
1151
+ }
1152
+ const eventShipper = new EventShipper({
1153
+ writeKey,
1154
+ endpoint: opts.endpoint,
1155
+ enabled,
1156
+ debug: opts.debug ?? false,
1157
+ sdkName: "deep-agents",
1158
+ libraryName,
1159
+ libraryVersion
1160
+ });
1161
+ const traceShipper = new TraceShipper({
1162
+ writeKey,
1163
+ endpoint: opts.endpoint,
1164
+ enabled,
1165
+ debug: opts.debug ?? false,
1166
+ sdkName: "deep-agents",
1167
+ serviceName: "raindrop.deep-agents",
1168
+ serviceVersion: libraryVersion
1169
+ });
1170
+ const handler = new RaindropDeepAgentsHandler({
1171
+ eventShipper,
1172
+ traceShipper,
1173
+ userId: opts.userId,
1174
+ convoId: opts.convoId,
1175
+ traceChains: opts.traceChains
1176
+ });
1177
+ return {
1178
+ handler,
1179
+ get lastEventId() {
1180
+ return handler._lastRootEventId;
1181
+ },
1182
+ async flush() {
1183
+ await Promise.all([eventShipper.flush(), traceShipper.flush()]);
1184
+ },
1185
+ async shutdown() {
1186
+ await Promise.all([eventShipper.shutdown(), traceShipper.shutdown()]);
1187
+ },
1188
+ events: {
1189
+ async patch(eventId, patch) {
1190
+ await eventShipper.patch(eventId, patch);
1191
+ },
1192
+ async finish(eventId, patch) {
1193
+ await eventShipper.finish(eventId, patch);
1194
+ },
1195
+ async addAttachments(eventId, attachments) {
1196
+ await eventShipper.patch(eventId, { attachments });
1197
+ },
1198
+ async setProperties(eventId, properties) {
1199
+ await eventShipper.patch(eventId, { properties });
1200
+ }
1201
+ },
1202
+ users: {
1203
+ async identify(users) {
1204
+ await eventShipper.identify(users);
1205
+ }
1206
+ },
1207
+ signals: {
1208
+ async track(signal) {
1209
+ await eventShipper.trackSignal(signal);
1210
+ }
1211
+ }
1212
+ };
1213
+ }
1214
+ export {
1215
+ RaindropDeepAgentsHandler,
1216
+ createRaindropDeepAgents
1217
+ };