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