@raindrop-ai/langchain 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,1119 @@
1
+ // src/callback-handler.ts
2
+ import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
3
+
4
+ // ../core/dist/chunk-FOHDGBT5.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 asNumber = Number(value);
71
+ if (value.trim() !== "" && !Number.isNaN(asNumber)) return asNumber * 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 TraceShipper = class {
452
+ constructor(opts) {
453
+ this.queue = [];
454
+ this.inFlight = /* @__PURE__ */ new Set();
455
+ var _a, _b, _c, _d, _e, _f, _g, _h;
456
+ this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
457
+ this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
458
+ this.enabled = opts.enabled !== false;
459
+ this.debug = opts.debug;
460
+ this.debugSpans = opts.debugSpans === true;
461
+ this.flushIntervalMs = (_c = opts.flushIntervalMs) != null ? _c : 1e3;
462
+ this.maxBatchSize = (_d = opts.maxBatchSize) != null ? _d : 50;
463
+ this.maxQueueSize = (_e = opts.maxQueueSize) != null ? _e : 5e3;
464
+ this.sdkName = (_f = opts.sdkName) != null ? _f : "core";
465
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
466
+ this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
467
+ this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
468
+ }
469
+ isDebugEnabled() {
470
+ return this.debug;
471
+ }
472
+ authHeaders() {
473
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
474
+ }
475
+ startSpan(args) {
476
+ var _a, _b;
477
+ const ids = createSpanIds(args.parent);
478
+ const started = (_a = args.startTimeUnixNano) != null ? _a : nowUnixNanoString();
479
+ const attrs = [
480
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
481
+ attrString("ai.operationId", args.operationId)
482
+ ];
483
+ if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
484
+ return { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
485
+ }
486
+ endSpan(span, extra) {
487
+ var _a, _b;
488
+ if (span.endTimeUnixNano) return;
489
+ span.endTimeUnixNano = (_a = extra == null ? void 0 : extra.endTimeUnixNano) != null ? _a : nowUnixNanoString();
490
+ if ((_b = extra == null ? void 0 : extra.attributes) == null ? void 0 : _b.length) {
491
+ span.attributes.push(...extra.attributes);
492
+ }
493
+ let status = extra == null ? void 0 : extra.status;
494
+ if (!status && (extra == null ? void 0 : extra.error) !== void 0) {
495
+ const message = extra.error instanceof Error ? extra.error.message : String(extra.error);
496
+ status = { code: SpanStatusCode.ERROR, message };
497
+ }
498
+ const otlp = buildOtlpSpan({
499
+ ids: span.ids,
500
+ name: span.name,
501
+ startTimeUnixNano: span.startTimeUnixNano,
502
+ endTimeUnixNano: span.endTimeUnixNano,
503
+ attributes: span.attributes,
504
+ status
505
+ });
506
+ this.enqueue(otlp);
507
+ }
508
+ createSpan(args) {
509
+ var _a;
510
+ const ids = createSpanIds(args.parent);
511
+ const attrs = [
512
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId)
513
+ ];
514
+ if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
515
+ const otlp = buildOtlpSpan({
516
+ ids,
517
+ name: args.name,
518
+ startTimeUnixNano: args.startTimeUnixNano,
519
+ endTimeUnixNano: args.endTimeUnixNano,
520
+ attributes: attrs,
521
+ status: args.status
522
+ });
523
+ this.enqueue(otlp);
524
+ }
525
+ enqueue(span) {
526
+ if (!this.enabled) return;
527
+ if (this.debugSpans) {
528
+ const short = (s) => s ? s.slice(-8) : "none";
529
+ console.log(
530
+ `${this.prefix}[span] name=${span.name} trace=${short(span.traceId)} span=${short(span.spanId)} parent=${short(
531
+ span.parentSpanId
532
+ )}`
533
+ );
534
+ }
535
+ if (this.queue.length >= this.maxQueueSize) {
536
+ this.queue.shift();
537
+ }
538
+ this.queue.push(span);
539
+ if (this.queue.length >= this.maxBatchSize) {
540
+ void this.flush().catch(() => {
541
+ });
542
+ return;
543
+ }
544
+ if (!this.timer) {
545
+ this.timer = setTimeout(() => {
546
+ this.timer = void 0;
547
+ void this.flush().catch(() => {
548
+ });
549
+ }, this.flushIntervalMs);
550
+ }
551
+ }
552
+ async flush() {
553
+ if (!this.enabled) return;
554
+ if (this.timer) {
555
+ clearTimeout(this.timer);
556
+ this.timer = void 0;
557
+ }
558
+ while (this.queue.length > 0) {
559
+ const batch = this.queue.splice(0, this.maxBatchSize);
560
+ const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
561
+ const url = `${this.baseUrl}traces`;
562
+ if (this.debug) {
563
+ console.log(`${this.prefix} sending traces batch`, {
564
+ spans: batch.length,
565
+ endpoint: url
566
+ });
567
+ }
568
+ const p = postJson(url, body, this.authHeaders(), {
569
+ maxAttempts: 3,
570
+ debug: this.debug,
571
+ sdkName: this.sdkName
572
+ });
573
+ this.inFlight.add(p);
574
+ try {
575
+ try {
576
+ await p;
577
+ if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
578
+ } catch (err) {
579
+ const msg = err instanceof Error ? err.message : String(err);
580
+ console.warn(`${this.prefix} failed to send ${batch.length} spans: ${msg}`);
581
+ }
582
+ } finally {
583
+ this.inFlight.delete(p);
584
+ }
585
+ }
586
+ }
587
+ async shutdown() {
588
+ if (this.timer) {
589
+ clearTimeout(this.timer);
590
+ this.timer = void 0;
591
+ }
592
+ await this.flush();
593
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
594
+ })));
595
+ }
596
+ };
597
+
598
+ // src/callback-handler.ts
599
+ var LANGGRAPH_INTERNAL_NAMES = /* @__PURE__ */ new Set([
600
+ "LangGraph",
601
+ "__start__",
602
+ "__end__",
603
+ "ChannelWrite",
604
+ "ChannelRead"
605
+ ]);
606
+ var RaindropCallbackHandler = class extends BaseCallbackHandler {
607
+ constructor(opts) {
608
+ var _a, _b, _c;
609
+ super();
610
+ this.name = "RaindropCallbackHandler";
611
+ this.spans = /* @__PURE__ */ new Map();
612
+ this.rootRunIds = /* @__PURE__ */ new Map();
613
+ this.eventIds = /* @__PURE__ */ new Map();
614
+ this.eventShipper = opts.eventShipper;
615
+ this.traceShipper = opts.traceShipper;
616
+ this.userId = opts.userId;
617
+ this.convoId = opts.convoId;
618
+ this.traceChains = (_a = opts.traceChains) != null ? _a : true;
619
+ this.traceRetrievers = (_b = opts.traceRetrievers) != null ? _b : true;
620
+ this.filterLangGraphInternals = (_c = opts.filterLangGraphInternals) != null ? _c : true;
621
+ }
622
+ getEventId(runId, parentRunId) {
623
+ var _a;
624
+ const rootId = parentRunId ? (_a = this.rootRunIds.get(parentRunId)) != null ? _a : parentRunId : runId;
625
+ this.rootRunIds.set(runId, rootId);
626
+ if (!this.eventIds.has(rootId)) {
627
+ this.eventIds.set(rootId, randomUUID());
628
+ }
629
+ return this.eventIds.get(rootId);
630
+ }
631
+ getParent(parentRunId) {
632
+ if (!parentRunId) return void 0;
633
+ const parentSpan = this.spans.get(parentRunId);
634
+ if (!parentSpan) return void 0;
635
+ return {
636
+ traceIdB64: parentSpan.ids.traceIdB64,
637
+ spanIdB64: parentSpan.ids.spanIdB64
638
+ };
639
+ }
640
+ cleanup(runId) {
641
+ var _a;
642
+ this.spans.delete(runId);
643
+ this.spans.delete(`${runId}:agent_action`);
644
+ const rootId = (_a = this.rootRunIds.get(runId)) != null ? _a : runId;
645
+ this.rootRunIds.delete(runId);
646
+ if (rootId === runId) {
647
+ this.eventIds.delete(rootId);
648
+ }
649
+ }
650
+ async finalizeEventIfRoot(runId, patch) {
651
+ var _a;
652
+ const rootId = (_a = this.rootRunIds.get(runId)) != null ? _a : runId;
653
+ const isRoot = rootId === runId;
654
+ const eventId = this.eventIds.get(rootId);
655
+ if (!eventId) return;
656
+ if (isRoot) {
657
+ if (this.convoId) {
658
+ await this.eventShipper.patch(eventId, { userId: this.userId, convoId: this.convoId, isPending: true });
659
+ }
660
+ await this.eventShipper.finish(eventId, { userId: this.userId, ...patch });
661
+ } else if (patch) {
662
+ await this.eventShipper.patch(eventId, { userId: this.userId, convoId: this.convoId, ...patch, isPending: true });
663
+ }
664
+ }
665
+ // ---------------------------------------------------------------------------
666
+ // LLM events
667
+ // ---------------------------------------------------------------------------
668
+ /** Called at the start of an LLM run with string prompts. */
669
+ async handleLLMStart(llm, prompts, runId, parentRunId, _extraParams, tags, metadata, runName) {
670
+ try {
671
+ if (this.filterLangGraphInternals && this.spans.has(runId)) return;
672
+ const eventId = this.getEventId(runId, parentRunId);
673
+ const modelId = getName(llm, runName);
674
+ const span = this.traceShipper.startSpan({
675
+ name: "llm",
676
+ parent: this.getParent(parentRunId),
677
+ eventId,
678
+ attributes: [
679
+ attrString("ai.model.provider", modelId),
680
+ attrString("ai.operationId", "llm")
681
+ ]
682
+ });
683
+ this.spans.set(runId, span);
684
+ await this.eventShipper.patch(eventId, {
685
+ userId: this.userId,
686
+ convoId: this.convoId,
687
+ input: prompts.join("\n"),
688
+ properties: buildProperties(tags, metadata),
689
+ isPending: true
690
+ });
691
+ } catch (e) {
692
+ }
693
+ }
694
+ /** Called at the start of a chat model run with structured messages. */
695
+ async handleChatModelStart(llm, messages, runId, parentRunId, _extraParams, tags, metadata, runName) {
696
+ try {
697
+ if (this.filterLangGraphInternals && this.spans.has(runId)) return;
698
+ const eventId = this.getEventId(runId, parentRunId);
699
+ const modelId = getName(llm, runName);
700
+ const span = this.traceShipper.startSpan({
701
+ name: "llm",
702
+ parent: this.getParent(parentRunId),
703
+ eventId,
704
+ attributes: [
705
+ attrString("ai.model.provider", modelId),
706
+ attrString("ai.operationId", "chat")
707
+ ]
708
+ });
709
+ this.spans.set(runId, span);
710
+ const allMessages = messages.flat();
711
+ const userMessages = allMessages.filter((m) => {
712
+ var _a, _b;
713
+ const role = (_b = (_a = m._getType) == null ? void 0 : _a.call(m)) != null ? _b : "unknown";
714
+ return role === "human";
715
+ });
716
+ const toExtract = userMessages.length > 0 ? userMessages : allMessages.slice(-1);
717
+ const inputText = toExtract.map((m) => typeof m.content === "string" ? m.content : safeStringify(m.content)).join("\n");
718
+ await this.eventShipper.patch(eventId, {
719
+ userId: this.userId,
720
+ convoId: this.convoId,
721
+ input: inputText,
722
+ properties: buildProperties(tags, metadata),
723
+ isPending: true
724
+ });
725
+ } catch (e) {
726
+ }
727
+ }
728
+ async handleLLMEnd(output, runId, _parentRunId) {
729
+ try {
730
+ const span = this.spans.get(runId);
731
+ if (!span) {
732
+ await this.finalizeEventIfRoot(runId);
733
+ return;
734
+ }
735
+ const { model, promptTokens, completionTokens, outputText } = extractLLMMetadata(output);
736
+ this.traceShipper.endSpan(span, {
737
+ attributes: [
738
+ attrString("ai.response.model", model),
739
+ attrInt("ai.usage.prompt_tokens", promptTokens),
740
+ attrInt("ai.usage.completion_tokens", completionTokens)
741
+ ]
742
+ });
743
+ const properties = {};
744
+ if (promptTokens != null) properties["ai.usage.prompt_tokens"] = promptTokens;
745
+ if (completionTokens != null) properties["ai.usage.completion_tokens"] = completionTokens;
746
+ await this.finalizeEventIfRoot(runId, {
747
+ output: outputText,
748
+ model,
749
+ properties: Object.keys(properties).length > 0 ? properties : void 0
750
+ });
751
+ } catch (e) {
752
+ } finally {
753
+ this.cleanup(runId);
754
+ }
755
+ }
756
+ /** Called when an LLM run encounters an error. */
757
+ async handleLLMError(err, runId) {
758
+ try {
759
+ const span = this.spans.get(runId);
760
+ if (span) {
761
+ this.traceShipper.endSpan(span, { error: err });
762
+ }
763
+ await this.finalizeEventIfRoot(runId);
764
+ } catch (e) {
765
+ } finally {
766
+ this.cleanup(runId);
767
+ }
768
+ }
769
+ // ---------------------------------------------------------------------------
770
+ // Chain events
771
+ // ---------------------------------------------------------------------------
772
+ async handleChainStart(chain, _inputs, runId, parentRunId, _tags, _metadata, _runType, runName) {
773
+ var _a;
774
+ try {
775
+ const chainName = getName(chain, runName);
776
+ if (this.filterLangGraphInternals && isLangGraphInternal(chainName)) return;
777
+ this.getEventId(runId, parentRunId);
778
+ if (!this.traceChains) return;
779
+ const eventId = this.eventIds.get((_a = this.rootRunIds.get(runId)) != null ? _a : runId);
780
+ const span = this.traceShipper.startSpan({
781
+ name: "chain",
782
+ parent: this.getParent(parentRunId),
783
+ eventId,
784
+ attributes: [
785
+ attrString("chain.name", chainName),
786
+ attrString("ai.operationId", "chain")
787
+ ]
788
+ });
789
+ this.spans.set(runId, span);
790
+ } catch (e) {
791
+ }
792
+ }
793
+ async handleChainEnd(_outputs, runId) {
794
+ try {
795
+ if (this.traceChains) {
796
+ const span = this.spans.get(runId);
797
+ if (span) this.traceShipper.endSpan(span);
798
+ }
799
+ await this.finalizeEventIfRoot(runId);
800
+ } catch (e) {
801
+ } finally {
802
+ this.cleanup(runId);
803
+ }
804
+ }
805
+ async handleChainError(err, runId) {
806
+ try {
807
+ const span = this.spans.get(runId);
808
+ if (span) this.traceShipper.endSpan(span, { error: err });
809
+ await this.finalizeEventIfRoot(runId);
810
+ } catch (e) {
811
+ } finally {
812
+ this.cleanup(runId);
813
+ }
814
+ }
815
+ // ---------------------------------------------------------------------------
816
+ // Tool events
817
+ // ---------------------------------------------------------------------------
818
+ async handleToolStart(tool, input, runId, parentRunId, _tags, _metadata, runName) {
819
+ try {
820
+ const eventId = this.getEventId(runId, parentRunId);
821
+ const toolName = getName(tool, runName);
822
+ const span = this.traceShipper.startSpan({
823
+ name: "tool",
824
+ parent: this.getParent(parentRunId),
825
+ eventId,
826
+ attributes: [
827
+ attrString("tool.name", toolName),
828
+ attrString("tool.input", truncate(input, 4096))
829
+ ]
830
+ });
831
+ this.spans.set(runId, span);
832
+ } catch (e) {
833
+ }
834
+ }
835
+ /** Called at the end of a tool run. */
836
+ async handleToolEnd(output, runId) {
837
+ try {
838
+ const span = this.spans.get(runId);
839
+ if (span) {
840
+ const outputStr = typeof output === "string" ? output : safeStringify(output);
841
+ this.traceShipper.endSpan(span, {
842
+ attributes: [attrString("tool.output", truncate(outputStr, 4096))]
843
+ });
844
+ }
845
+ await this.finalizeEventIfRoot(runId);
846
+ } catch (e) {
847
+ } finally {
848
+ this.cleanup(runId);
849
+ }
850
+ }
851
+ /** Called when a tool run encounters an error. */
852
+ async handleToolError(err, runId) {
853
+ try {
854
+ const span = this.spans.get(runId);
855
+ if (span) this.traceShipper.endSpan(span, { error: err });
856
+ await this.finalizeEventIfRoot(runId);
857
+ } catch (e) {
858
+ } finally {
859
+ this.cleanup(runId);
860
+ }
861
+ }
862
+ // ---------------------------------------------------------------------------
863
+ // Retriever events
864
+ // ---------------------------------------------------------------------------
865
+ /** Called at the start of a retriever run. */
866
+ async handleRetrieverStart(retriever, query, runId, parentRunId, _tags, _metadata, name) {
867
+ try {
868
+ const eventId = this.getEventId(runId, parentRunId);
869
+ if (!this.traceRetrievers) return;
870
+ const retrieverName = getName(retriever, name);
871
+ const span = this.traceShipper.startSpan({
872
+ name: "retriever",
873
+ parent: this.getParent(parentRunId),
874
+ eventId,
875
+ attributes: [
876
+ attrString("retriever.name", retrieverName),
877
+ attrString("retriever.query", truncate(query, 2048))
878
+ ]
879
+ });
880
+ this.spans.set(runId, span);
881
+ } catch (e) {
882
+ }
883
+ }
884
+ /** Called at the end of a retriever run. */
885
+ async handleRetrieverEnd(documents, runId) {
886
+ try {
887
+ if (this.traceRetrievers) {
888
+ const span = this.spans.get(runId);
889
+ if (span) {
890
+ this.traceShipper.endSpan(span, {
891
+ attributes: [attrInt("retriever.document_count", documents.length)]
892
+ });
893
+ }
894
+ }
895
+ await this.finalizeEventIfRoot(runId);
896
+ } catch (e) {
897
+ } finally {
898
+ this.cleanup(runId);
899
+ }
900
+ }
901
+ /** Called when a retriever run encounters an error. */
902
+ async handleRetrieverError(err, runId) {
903
+ try {
904
+ const span = this.spans.get(runId);
905
+ if (span) this.traceShipper.endSpan(span, { error: err });
906
+ await this.finalizeEventIfRoot(runId);
907
+ } catch (e) {
908
+ } finally {
909
+ this.cleanup(runId);
910
+ }
911
+ }
912
+ // ---------------------------------------------------------------------------
913
+ // Agent events
914
+ // ---------------------------------------------------------------------------
915
+ async handleAgentAction(action, runId, parentRunId) {
916
+ try {
917
+ const eventId = this.getEventId(runId, parentRunId);
918
+ const span = this.traceShipper.startSpan({
919
+ name: "agent_action",
920
+ parent: this.getParent(parentRunId),
921
+ eventId,
922
+ attributes: [
923
+ attrString("agent.tool", action.tool),
924
+ attrString("agent.tool_input", truncate(
925
+ typeof action.toolInput === "string" ? action.toolInput : safeStringify(action.toolInput),
926
+ 4096
927
+ ))
928
+ ]
929
+ });
930
+ this.spans.set(`${runId}:agent_action`, span);
931
+ } catch (e) {
932
+ }
933
+ }
934
+ async handleAgentEnd(_action, runId) {
935
+ try {
936
+ const spanKey = `${runId}:agent_action`;
937
+ const span = this.spans.get(spanKey);
938
+ if (span) {
939
+ this.traceShipper.endSpan(span);
940
+ this.spans.delete(spanKey);
941
+ }
942
+ } catch (e) {
943
+ }
944
+ }
945
+ };
946
+ function getName(serialized, runName) {
947
+ var _a;
948
+ if (runName) return runName;
949
+ if ((_a = serialized == null ? void 0 : serialized.id) == null ? void 0 : _a.length) return serialized.id[serialized.id.length - 1];
950
+ if ("name" in serialized && typeof serialized.name === "string") return serialized.name;
951
+ return "unknown";
952
+ }
953
+ function isLangGraphInternal(name) {
954
+ if (LANGGRAPH_INTERNAL_NAMES.has(name)) return true;
955
+ if (name.startsWith("Branch")) return true;
956
+ if (name.startsWith("ChannelWrite")) return true;
957
+ if (name.startsWith("__") && name.endsWith("__")) return true;
958
+ return false;
959
+ }
960
+ function buildProperties(tags, metadata) {
961
+ if (!(tags == null ? void 0 : tags.length) && !metadata) return void 0;
962
+ const props = {};
963
+ if (tags == null ? void 0 : tags.length) props["langchain.tags"] = tags;
964
+ if (metadata) Object.assign(props, metadata);
965
+ return props;
966
+ }
967
+ function safeStringify(value) {
968
+ var _a;
969
+ try {
970
+ return (_a = JSON.stringify(value)) != null ? _a : "";
971
+ } catch (e) {
972
+ return String(value);
973
+ }
974
+ }
975
+ function truncate(str, maxLen) {
976
+ if (str.length <= maxLen) return str;
977
+ return str.slice(0, maxLen - 3) + "...";
978
+ }
979
+ function extractLLMMetadata(output) {
980
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
981
+ const gen = (_b = (_a = output.generations) == null ? void 0 : _a[0]) == null ? void 0 : _b[0];
982
+ const message = gen == null ? void 0 : gen.message;
983
+ const responseMeta = message == null ? void 0 : message.response_metadata;
984
+ const usageMeta = message == null ? void 0 : message.usage_metadata;
985
+ const llmOutput = output.llmOutput;
986
+ const tokenUsage = (_c = llmOutput == null ? void 0 : llmOutput.token_usage) != null ? _c : llmOutput == null ? void 0 : llmOutput.tokenUsage;
987
+ const estimatedTokens = llmOutput == null ? void 0 : llmOutput.estimatedTokens;
988
+ const model = (_f = (_e = (_d = responseMeta == null ? void 0 : responseMeta.model_name) != null ? _d : responseMeta == null ? void 0 : responseMeta.model) != null ? _e : llmOutput == null ? void 0 : llmOutput.model_name) != null ? _f : llmOutput == null ? void 0 : llmOutput.model;
989
+ const usage = (_g = usageMeta != null ? usageMeta : tokenUsage) != null ? _g : estimatedTokens;
990
+ const promptTokens = (_i = (_h = usage == null ? void 0 : usage.input_tokens) != null ? _h : usage == null ? void 0 : usage.prompt_tokens) != null ? _i : usage == null ? void 0 : usage.promptTokens;
991
+ const completionTokens = (_k = (_j = usage == null ? void 0 : usage.output_tokens) != null ? _j : usage == null ? void 0 : usage.completion_tokens) != null ? _k : usage == null ? void 0 : usage.completionTokens;
992
+ const outputText = (_m = (_l = gen == null ? void 0 : gen.text) != null ? _l : typeof (message == null ? void 0 : message.content) === "string" ? message.content : void 0) != null ? _m : (message == null ? void 0 : message.content) ? JSON.stringify(message.content) : void 0;
993
+ return { model, promptTokens, completionTokens, outputText };
994
+ }
995
+
996
+ // package.json
997
+ var package_default = {
998
+ name: "@raindrop-ai/langchain",
999
+ version: "0.0.1",
1000
+ description: "Raindrop integration for LangChain",
1001
+ main: "dist/index.js",
1002
+ module: "dist/index.mjs",
1003
+ types: "dist/index.d.ts",
1004
+ exports: {
1005
+ ".": {
1006
+ types: "./dist/index.d.ts",
1007
+ import: "./dist/index.mjs",
1008
+ require: "./dist/index.js"
1009
+ }
1010
+ },
1011
+ sideEffects: false,
1012
+ files: ["dist/**"],
1013
+ scripts: {
1014
+ build: "tsup",
1015
+ dev: "tsup --watch",
1016
+ clean: "rm -rf dist",
1017
+ test: "vitest run"
1018
+ },
1019
+ peerDependencies: {
1020
+ "@langchain/core": ">=0.3.0 <1.0.0"
1021
+ },
1022
+ devDependencies: {
1023
+ "@raindrop-ai/core": "workspace:*",
1024
+ "@langchain/core": ">=0.3.0",
1025
+ "@types/node": "^20.11.17",
1026
+ msw: "^2.12.7",
1027
+ tsup: "^8.4.0",
1028
+ typescript: "^5.3.3",
1029
+ vitest: "^2.1.9"
1030
+ },
1031
+ tsup: {
1032
+ entry: ["src/index.ts"],
1033
+ format: ["cjs", "esm"],
1034
+ dts: { resolve: true },
1035
+ clean: true,
1036
+ noExternal: ["@raindrop-ai/core"]
1037
+ },
1038
+ publishConfig: {
1039
+ access: "public"
1040
+ }
1041
+ };
1042
+
1043
+ // src/version.ts
1044
+ var libraryName = package_default.name;
1045
+ var libraryVersion = package_default.version;
1046
+
1047
+ // src/index.ts
1048
+ function createRaindropLangChain(opts) {
1049
+ var _a, _b;
1050
+ const writeKey = opts.writeKey;
1051
+ const enabled = !!writeKey;
1052
+ if (!writeKey) {
1053
+ console.warn("[raindrop-ai/langchain] writeKey not provided; telemetry shipping is disabled");
1054
+ }
1055
+ const eventShipper = new EventShipper({
1056
+ writeKey,
1057
+ endpoint: opts.endpoint,
1058
+ enabled,
1059
+ debug: (_a = opts.debug) != null ? _a : false,
1060
+ sdkName: "langchain",
1061
+ libraryName,
1062
+ libraryVersion
1063
+ });
1064
+ const traceShipper = new TraceShipper({
1065
+ writeKey,
1066
+ endpoint: opts.endpoint,
1067
+ enabled,
1068
+ debug: (_b = opts.debug) != null ? _b : false,
1069
+ sdkName: "langchain",
1070
+ serviceName: "raindrop.langchain",
1071
+ serviceVersion: libraryVersion
1072
+ });
1073
+ const handler = new RaindropCallbackHandler({
1074
+ eventShipper,
1075
+ traceShipper,
1076
+ userId: opts.userId,
1077
+ convoId: opts.convoId,
1078
+ traceChains: opts.traceChains,
1079
+ traceRetrievers: opts.traceRetrievers,
1080
+ filterLangGraphInternals: opts.filterLangGraphInternals
1081
+ });
1082
+ return {
1083
+ handler,
1084
+ async flush() {
1085
+ await Promise.all([eventShipper.flush(), traceShipper.flush()]);
1086
+ },
1087
+ async shutdown() {
1088
+ await Promise.all([eventShipper.shutdown(), traceShipper.shutdown()]);
1089
+ },
1090
+ events: {
1091
+ async patch(eventId, patch) {
1092
+ await eventShipper.patch(eventId, patch);
1093
+ },
1094
+ async finish(eventId, patch) {
1095
+ await eventShipper.finish(eventId, patch);
1096
+ },
1097
+ async addAttachments(eventId, attachments) {
1098
+ await eventShipper.patch(eventId, { attachments });
1099
+ },
1100
+ async setProperties(eventId, properties) {
1101
+ await eventShipper.patch(eventId, { properties });
1102
+ }
1103
+ },
1104
+ users: {
1105
+ async identify(users) {
1106
+ await eventShipper.identify(users);
1107
+ }
1108
+ },
1109
+ signals: {
1110
+ async track(signal) {
1111
+ await eventShipper.trackSignal(signal);
1112
+ }
1113
+ }
1114
+ };
1115
+ }
1116
+ export {
1117
+ RaindropCallbackHandler,
1118
+ createRaindropLangChain
1119
+ };