@raindrop-ai/pi-agent 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,922 @@
1
+ // package.json
2
+ var package_default = {
3
+ name: "@raindrop-ai/pi-agent",
4
+ version: "0.0.2",
5
+ description: "Raindrop observability for Pi Agent \u2014 automatic tracing via subscriber or pi-coding-agent extension",
6
+ type: "module",
7
+ license: "MIT",
8
+ repository: {
9
+ type: "git",
10
+ url: "git+https://github.com/raindrop-ai/raindrop-js.git",
11
+ directory: "packages/pi-agent"
12
+ },
13
+ homepage: "https://github.com/raindrop-ai/raindrop-js/tree/main/packages/pi-agent#readme",
14
+ bugs: {
15
+ url: "https://github.com/raindrop-ai/raindrop-js/issues"
16
+ },
17
+ keywords: [
18
+ "pi-package",
19
+ "raindrop",
20
+ "pi-agent",
21
+ "observability",
22
+ "tracing"
23
+ ],
24
+ exports: {
25
+ ".": {
26
+ types: "./dist/index.d.ts",
27
+ import: "./dist/index.js",
28
+ require: "./dist/index.cjs"
29
+ },
30
+ "./extension": {
31
+ types: "./dist/extension.d.ts",
32
+ import: "./dist/extension.js",
33
+ require: "./dist/extension.cjs"
34
+ }
35
+ },
36
+ pi: {
37
+ extensions: [
38
+ "./dist/extension.js"
39
+ ]
40
+ },
41
+ sideEffects: false,
42
+ files: [
43
+ "dist/**",
44
+ "README.md"
45
+ ],
46
+ scripts: {
47
+ build: "tsup",
48
+ dev: "tsup --watch",
49
+ clean: "rm -rf dist",
50
+ test: "vitest run",
51
+ "test:watch": "vitest"
52
+ },
53
+ peerDependencies: {
54
+ "@mariozechner/pi-agent-core": ">=0.60.0",
55
+ "@mariozechner/pi-coding-agent": ">=0.65.2"
56
+ },
57
+ peerDependenciesMeta: {
58
+ "@mariozechner/pi-coding-agent": {
59
+ optional: true
60
+ }
61
+ },
62
+ devDependencies: {
63
+ "@raindrop-ai/core": "workspace:*",
64
+ "@mariozechner/pi-agent-core": "^0.66.0",
65
+ "@mariozechner/pi-coding-agent": "^0.66.0",
66
+ "@types/node": "^20.11.17",
67
+ msw: "^2.12.7",
68
+ tsup: "^8.5.1",
69
+ typescript: "^5.7.3",
70
+ vitest: "^2.1.9"
71
+ },
72
+ tsup: {
73
+ entry: [
74
+ "src/index.ts",
75
+ "src/extension.ts"
76
+ ],
77
+ format: [
78
+ "cjs",
79
+ "esm"
80
+ ],
81
+ dts: {
82
+ resolve: true
83
+ },
84
+ clean: true,
85
+ noExternal: [
86
+ "@raindrop-ai/core"
87
+ ]
88
+ },
89
+ publishConfig: {
90
+ access: "public"
91
+ }
92
+ };
93
+
94
+ // src/version.ts
95
+ var libraryName = package_default.name;
96
+ var libraryVersion = package_default.version;
97
+
98
+ // ../core/dist/chunk-4UCYIEH4.js
99
+ function getCrypto() {
100
+ const c = globalThis.crypto;
101
+ return c;
102
+ }
103
+ function randomBytes(length) {
104
+ const cryptoObj = getCrypto();
105
+ const out = new Uint8Array(length);
106
+ if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
107
+ cryptoObj.getRandomValues(out);
108
+ return out;
109
+ }
110
+ for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
111
+ return out;
112
+ }
113
+ function randomUUID() {
114
+ const cryptoObj = getCrypto();
115
+ if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
116
+ return cryptoObj.randomUUID();
117
+ }
118
+ const b = randomBytes(16);
119
+ b[6] = b[6] & 15 | 64;
120
+ b[8] = b[8] & 63 | 128;
121
+ const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
122
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
123
+ }
124
+ function base64Encode(bytes) {
125
+ const maybeBuffer = globalThis.Buffer;
126
+ if (maybeBuffer) {
127
+ return maybeBuffer.from(bytes).toString("base64");
128
+ }
129
+ let binary = "";
130
+ for (let i2 = 0; i2 < bytes.length; i2++) {
131
+ binary += String.fromCharCode(bytes[i2]);
132
+ }
133
+ const btoaFn = globalThis.btoa;
134
+ if (typeof btoaFn === "function") return btoaFn(binary);
135
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
136
+ let out = "";
137
+ let i = 0;
138
+ while (i < binary.length) {
139
+ const c1 = binary.charCodeAt(i++) & 255;
140
+ const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
141
+ const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
142
+ const e1 = c1 >> 2;
143
+ const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
144
+ const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
145
+ const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
146
+ out += alphabet.charAt(e1);
147
+ out += alphabet.charAt(e2);
148
+ out += e3 === 64 ? "=" : alphabet.charAt(e3);
149
+ out += e4 === 64 ? "=" : alphabet.charAt(e4);
150
+ }
151
+ return out;
152
+ }
153
+ function generateId() {
154
+ return base64Encode(randomBytes(12)).replace(/[+/=]/g, "").slice(0, 16);
155
+ }
156
+ function wait(ms) {
157
+ return new Promise((resolve) => setTimeout(resolve, ms));
158
+ }
159
+ function formatEndpoint(endpoint) {
160
+ if (!endpoint) return void 0;
161
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
162
+ }
163
+ function parseRetryAfter(headers) {
164
+ var _a;
165
+ const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
166
+ if (!value) return void 0;
167
+ const asNumber = Number(value);
168
+ if (value.trim() !== "" && !Number.isNaN(asNumber)) return asNumber * 1e3;
169
+ const asDate = new Date(value).getTime();
170
+ if (!Number.isNaN(asDate)) {
171
+ const delta = asDate - Date.now();
172
+ return delta > 0 ? delta : 0;
173
+ }
174
+ return void 0;
175
+ }
176
+ function getRetryDelayMs(attemptNumber, previousError) {
177
+ if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
178
+ const v = previousError.retryAfterMs;
179
+ if (typeof v === "number") return Math.max(0, v);
180
+ }
181
+ if (attemptNumber <= 1) return 0;
182
+ const base = 500;
183
+ const factor = Math.pow(2, attemptNumber - 2);
184
+ return base * factor;
185
+ }
186
+ async function withRetry(operation, opName, opts) {
187
+ const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
188
+ let lastError = void 0;
189
+ for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
190
+ if (attemptNumber > 1) {
191
+ const delay = getRetryDelayMs(attemptNumber, lastError);
192
+ if (opts.debug) {
193
+ console.warn(
194
+ `${prefix} ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
195
+ );
196
+ }
197
+ if (delay > 0) await wait(delay);
198
+ } else if (opts.debug) {
199
+ console.log(`${prefix} ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
200
+ }
201
+ try {
202
+ return await operation();
203
+ } catch (err) {
204
+ lastError = err;
205
+ if (opts.debug) {
206
+ const msg = err instanceof Error ? err.message : String(err);
207
+ console.warn(
208
+ `${prefix} ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
209
+ );
210
+ }
211
+ if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
212
+ break;
213
+ if (attemptNumber === opts.maxAttempts) break;
214
+ }
215
+ }
216
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
217
+ }
218
+ async function postJson(url, body, headers, opts) {
219
+ const opName = `POST ${url}`;
220
+ await withRetry(
221
+ async () => {
222
+ const resp = await fetch(url, {
223
+ method: "POST",
224
+ headers: {
225
+ "Content-Type": "application/json",
226
+ ...headers
227
+ },
228
+ body: JSON.stringify(body)
229
+ });
230
+ if (!resp.ok) {
231
+ const text = await resp.text().catch(() => "");
232
+ const err = new Error(
233
+ `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
234
+ );
235
+ const retryAfterMs = parseRetryAfter(resp.headers);
236
+ if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
237
+ err.retryable = resp.status === 429 || resp.status >= 500;
238
+ throw err;
239
+ }
240
+ },
241
+ opName,
242
+ opts
243
+ );
244
+ }
245
+ var SpanStatusCode = {
246
+ UNSET: 0,
247
+ OK: 1,
248
+ ERROR: 2
249
+ };
250
+ function createSpanIds(parent) {
251
+ const traceId = parent ? parent.traceIdB64 : base64Encode(randomBytes(16));
252
+ const spanId = base64Encode(randomBytes(8));
253
+ return {
254
+ traceIdB64: traceId,
255
+ spanIdB64: spanId,
256
+ parentSpanIdB64: parent ? parent.spanIdB64 : void 0
257
+ };
258
+ }
259
+ function nowUnixNanoString() {
260
+ return Date.now().toString() + "000000";
261
+ }
262
+ function attrString(key, value) {
263
+ if (value === void 0) return void 0;
264
+ return { key, value: { stringValue: value } };
265
+ }
266
+ function attrInt(key, value) {
267
+ if (value === void 0) return void 0;
268
+ if (!Number.isFinite(value)) return void 0;
269
+ return { key, value: { intValue: String(Math.trunc(value)) } };
270
+ }
271
+ function buildOtlpSpan(args) {
272
+ const attrs = args.attributes.filter((x) => x !== void 0);
273
+ const span = {
274
+ traceId: args.ids.traceIdB64,
275
+ spanId: args.ids.spanIdB64,
276
+ name: args.name,
277
+ startTimeUnixNano: args.startTimeUnixNano,
278
+ endTimeUnixNano: args.endTimeUnixNano
279
+ };
280
+ if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
281
+ if (attrs.length) span.attributes = attrs;
282
+ if (args.status) span.status = args.status;
283
+ return span;
284
+ }
285
+ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", serviceVersion = "0.0.0") {
286
+ return {
287
+ resourceSpans: [
288
+ {
289
+ resource: {
290
+ attributes: [{ key: "service.name", value: { stringValue: serviceName } }]
291
+ },
292
+ scopeSpans: [
293
+ {
294
+ scope: { name: serviceName, version: serviceVersion },
295
+ spans
296
+ }
297
+ ]
298
+ }
299
+ ]
300
+ };
301
+ }
302
+ function mergePatches(target, source) {
303
+ var _a, _b, _c, _d;
304
+ const out = { ...target, ...source };
305
+ if (target.properties || source.properties) {
306
+ out.properties = { ...(_a = target.properties) != null ? _a : {}, ...(_b = source.properties) != null ? _b : {} };
307
+ }
308
+ if (target.attachments || source.attachments) {
309
+ out.attachments = [...(_c = target.attachments) != null ? _c : [], ...(_d = source.attachments) != null ? _d : []];
310
+ }
311
+ return out;
312
+ }
313
+ var EventShipper = class {
314
+ constructor(opts) {
315
+ this.buffers = /* @__PURE__ */ new Map();
316
+ this.sticky = /* @__PURE__ */ new Map();
317
+ this.timers = /* @__PURE__ */ new Map();
318
+ this.inFlight = /* @__PURE__ */ new Set();
319
+ var _a, _b, _c, _d, _e, _f, _g;
320
+ this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
321
+ this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
322
+ this.enabled = opts.enabled !== false;
323
+ this.debug = opts.debug;
324
+ this.partialFlushMs = (_c = opts.partialFlushMs) != null ? _c : 1e3;
325
+ this.sdkName = (_d = opts.sdkName) != null ? _d : "core";
326
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
327
+ this.defaultEventName = (_e = opts.defaultEventName) != null ? _e : "ai_generation";
328
+ const isNode = typeof process !== "undefined" && typeof process.version === "string";
329
+ this.context = {
330
+ library: {
331
+ name: (_f = opts.libraryName) != null ? _f : "@raindrop-ai/core",
332
+ version: (_g = opts.libraryVersion) != null ? _g : "0.0.0"
333
+ },
334
+ metadata: {
335
+ jsRuntime: isNode ? "node" : "web",
336
+ ...isNode ? { nodeVersion: process.version } : {}
337
+ }
338
+ };
339
+ }
340
+ isDebugEnabled() {
341
+ return this.debug;
342
+ }
343
+ authHeaders() {
344
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
345
+ }
346
+ async patch(eventId, patch) {
347
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
348
+ if (!this.enabled) return;
349
+ if (!eventId || !eventId.trim()) return;
350
+ if (this.debug) {
351
+ console.log(`${this.prefix} queue patch`, {
352
+ eventId,
353
+ userId: patch.userId,
354
+ convoId: patch.convoId,
355
+ eventName: patch.eventName,
356
+ hasInput: typeof patch.input === "string" && patch.input.length > 0,
357
+ hasOutput: typeof patch.output === "string" && patch.output.length > 0,
358
+ attachments: (_b = (_a = patch.attachments) == null ? void 0 : _a.length) != null ? _b : 0,
359
+ isPending: patch.isPending
360
+ });
361
+ }
362
+ const sticky = (_c = this.sticky.get(eventId)) != null ? _c : {};
363
+ const existing = (_d = this.buffers.get(eventId)) != null ? _d : {};
364
+ const merged = mergePatches(existing, patch);
365
+ merged.isPending = (_g = (_f = (_e = patch.isPending) != null ? _e : existing.isPending) != null ? _f : sticky.isPending) != null ? _g : true;
366
+ this.buffers.set(eventId, merged);
367
+ this.sticky.set(eventId, {
368
+ userId: (_h = merged.userId) != null ? _h : sticky.userId,
369
+ convoId: (_i = merged.convoId) != null ? _i : sticky.convoId,
370
+ eventName: (_j = merged.eventName) != null ? _j : sticky.eventName,
371
+ isPending: (_k = merged.isPending) != null ? _k : sticky.isPending
372
+ });
373
+ const t = this.timers.get(eventId);
374
+ if (t) clearTimeout(t);
375
+ if (merged.isPending === false) {
376
+ await this.flushOne(eventId);
377
+ return;
378
+ }
379
+ const timeout = setTimeout(() => {
380
+ void this.flushOne(eventId).catch(() => {
381
+ });
382
+ }, this.partialFlushMs);
383
+ this.timers.set(eventId, timeout);
384
+ }
385
+ async finish(eventId, patch) {
386
+ await this.patch(eventId, { ...patch, isPending: false });
387
+ }
388
+ async flush() {
389
+ if (!this.enabled) return;
390
+ const ids = [...this.buffers.keys()];
391
+ await Promise.all(ids.map((id) => this.flushOne(id)));
392
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
393
+ })));
394
+ }
395
+ async shutdown() {
396
+ for (const t of this.timers.values()) clearTimeout(t);
397
+ this.timers.clear();
398
+ await this.flush();
399
+ }
400
+ async trackSignal(signal) {
401
+ var _a, _b;
402
+ if (!this.enabled) return;
403
+ const body = [
404
+ {
405
+ event_id: signal.eventId,
406
+ signal_name: signal.name,
407
+ signal_type: (_a = signal.type) != null ? _a : "default",
408
+ timestamp: signal.timestamp,
409
+ sentiment: signal.sentiment,
410
+ attachment_id: signal.attachmentId,
411
+ properties: {
412
+ ...(_b = signal.properties) != null ? _b : {},
413
+ ...signal.comment ? { comment: signal.comment } : {},
414
+ ...signal.after ? { after: signal.after } : {}
415
+ }
416
+ }
417
+ ];
418
+ const url = `${this.baseUrl}signals/track`;
419
+ try {
420
+ await postJson(url, body, this.authHeaders(), {
421
+ maxAttempts: 3,
422
+ debug: this.debug,
423
+ sdkName: this.sdkName
424
+ });
425
+ } catch (err) {
426
+ const msg = err instanceof Error ? err.message : String(err);
427
+ console.warn(`${this.prefix} failed to send signal (dropping): ${msg}`);
428
+ }
429
+ }
430
+ async identify(users) {
431
+ if (!this.enabled) return;
432
+ const list = Array.isArray(users) ? users : [users];
433
+ const body = list.filter((user) => {
434
+ if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
435
+ if (this.debug) {
436
+ console.warn(`${this.prefix} skipping identify: missing userId`);
437
+ }
438
+ return false;
439
+ }
440
+ return true;
441
+ }).map((user) => {
442
+ var _a;
443
+ return {
444
+ user_id: user.userId,
445
+ traits: (_a = user.traits) != null ? _a : {}
446
+ };
447
+ });
448
+ if (body.length === 0) return;
449
+ const url = `${this.baseUrl}users/identify`;
450
+ try {
451
+ await postJson(url, body, this.authHeaders(), {
452
+ maxAttempts: 3,
453
+ debug: this.debug,
454
+ sdkName: this.sdkName
455
+ });
456
+ } catch (err) {
457
+ const msg = err instanceof Error ? err.message : String(err);
458
+ console.warn(`${this.prefix} failed to send identify (dropping): ${msg}`);
459
+ }
460
+ }
461
+ async flushOne(eventId) {
462
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
463
+ if (!this.enabled) return;
464
+ const timer = this.timers.get(eventId);
465
+ if (timer) {
466
+ clearTimeout(timer);
467
+ this.timers.delete(eventId);
468
+ }
469
+ const accumulated = this.buffers.get(eventId);
470
+ this.buffers.delete(eventId);
471
+ if (!accumulated) return;
472
+ const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
473
+ const eventName = (_c = (_b = accumulated.eventName) != null ? _b : sticky.eventName) != null ? _c : this.defaultEventName;
474
+ const userId = (_d = accumulated.userId) != null ? _d : sticky.userId;
475
+ if (!userId) {
476
+ if (this.debug) {
477
+ console.warn(`${this.prefix} skipping track_partial for ${eventId}: missing userId`);
478
+ }
479
+ this.sticky.delete(eventId);
480
+ return;
481
+ }
482
+ const { wizardSession, ...restProperties } = (_e = accumulated.properties) != null ? _e : {};
483
+ const convoId = (_f = accumulated.convoId) != null ? _f : sticky.convoId;
484
+ const isPending = (_h = (_g = accumulated.isPending) != null ? _g : sticky.isPending) != null ? _h : true;
485
+ const payload = {
486
+ event_id: eventId,
487
+ user_id: userId,
488
+ event: eventName,
489
+ timestamp: (_i = accumulated.timestamp) != null ? _i : (/* @__PURE__ */ new Date()).toISOString(),
490
+ ai_data: {
491
+ input: accumulated.input,
492
+ output: accumulated.output,
493
+ model: accumulated.model,
494
+ convo_id: convoId
495
+ },
496
+ properties: {
497
+ ...restProperties,
498
+ ...wizardSession ? { "raindrop.wizardSession": wizardSession } : {},
499
+ $context: this.context
500
+ },
501
+ attachments: accumulated.attachments,
502
+ is_pending: isPending
503
+ };
504
+ const url = `${this.baseUrl}events/track_partial`;
505
+ if (this.debug) {
506
+ console.log(`${this.prefix} sending track_partial`, {
507
+ eventId,
508
+ eventName,
509
+ userId,
510
+ convoId,
511
+ isPending,
512
+ inputPreview: typeof accumulated.input === "string" ? accumulated.input.slice(0, 120) : void 0,
513
+ outputPreview: typeof accumulated.output === "string" ? accumulated.output.slice(0, 120) : void 0,
514
+ attachments: (_k = (_j = accumulated.attachments) == null ? void 0 : _j.length) != null ? _k : 0,
515
+ attachmentKinds: (_m = (_l = accumulated.attachments) == null ? void 0 : _l.map((a) => ({
516
+ type: a.type,
517
+ role: a.role,
518
+ name: a.name,
519
+ valuePreview: a.value.slice(0, 60)
520
+ }))) != null ? _m : [],
521
+ endpoint: url
522
+ });
523
+ }
524
+ const p = postJson(url, payload, this.authHeaders(), {
525
+ maxAttempts: 3,
526
+ debug: this.debug,
527
+ sdkName: this.sdkName
528
+ });
529
+ this.inFlight.add(p);
530
+ try {
531
+ try {
532
+ await p;
533
+ if (this.debug) {
534
+ console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
535
+ }
536
+ } catch (err) {
537
+ const msg = err instanceof Error ? err.message : String(err);
538
+ console.warn(`${this.prefix} failed to send track_partial (dropping): ${msg}`);
539
+ }
540
+ } finally {
541
+ this.inFlight.delete(p);
542
+ }
543
+ if (!isPending) {
544
+ this.sticky.delete(eventId);
545
+ }
546
+ }
547
+ };
548
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
549
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
550
+ var _a, _b, _c;
551
+ 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;
552
+ return resolved ? (_c = formatEndpoint(resolved)) != null ? _c : null : null;
553
+ }
554
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
555
+ var _a;
556
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
557
+ if (!baseUrl) return;
558
+ void postJson(`${baseUrl}traces`, body, {}, {
559
+ maxAttempts: 1,
560
+ debug: (_a = options.debug) != null ? _a : false,
561
+ sdkName: options.sdkName
562
+ }).catch(() => {
563
+ });
564
+ }
565
+ var TraceShipper = class {
566
+ constructor(opts) {
567
+ this.queue = [];
568
+ this.inFlight = /* @__PURE__ */ new Set();
569
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
570
+ this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
571
+ this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
572
+ this.enabled = opts.enabled !== false;
573
+ this.debug = opts.debug;
574
+ this.debugSpans = opts.debugSpans === true;
575
+ this.flushIntervalMs = (_c = opts.flushIntervalMs) != null ? _c : 1e3;
576
+ this.maxBatchSize = (_d = opts.maxBatchSize) != null ? _d : 50;
577
+ this.maxQueueSize = (_e = opts.maxQueueSize) != null ? _e : 5e3;
578
+ this.sdkName = (_f = opts.sdkName) != null ? _f : "core";
579
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
580
+ this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
581
+ this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
582
+ const localDebugger = typeof process !== "undefined" ? (_i = process.env) == null ? void 0 : _i.RAINDROP_LOCAL_DEBUGGER : void 0;
583
+ if (localDebugger) {
584
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(localDebugger)) != null ? _j : void 0;
585
+ if (this.debug) {
586
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
587
+ }
588
+ }
589
+ }
590
+ isDebugEnabled() {
591
+ return this.debug;
592
+ }
593
+ authHeaders() {
594
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
595
+ }
596
+ startSpan(args) {
597
+ var _a, _b;
598
+ const ids = createSpanIds(args.parent);
599
+ const started = (_a = args.startTimeUnixNano) != null ? _a : nowUnixNanoString();
600
+ const attrs = [
601
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
602
+ attrString("ai.operationId", args.operationId)
603
+ ];
604
+ if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
605
+ const span = { ids, name: args.name, startTimeUnixNano: started, attributes: attrs };
606
+ if (this.localDebuggerUrl) {
607
+ const openSpan = buildOtlpSpan({
608
+ ids: span.ids,
609
+ name: span.name,
610
+ startTimeUnixNano: span.startTimeUnixNano,
611
+ endTimeUnixNano: span.startTimeUnixNano,
612
+ // placeholder — will be updated on endSpan
613
+ attributes: span.attributes,
614
+ status: { code: SpanStatusCode.UNSET }
615
+ });
616
+ const body = buildExportTraceServiceRequest([openSpan], this.serviceName, this.serviceVersion);
617
+ mirrorTraceExportToLocalDebugger(body, {
618
+ baseUrl: this.localDebuggerUrl,
619
+ debug: false,
620
+ sdkName: this.sdkName
621
+ });
622
+ }
623
+ return span;
624
+ }
625
+ endSpan(span, extra) {
626
+ var _a, _b;
627
+ if (span.endTimeUnixNano) return;
628
+ span.endTimeUnixNano = (_a = extra == null ? void 0 : extra.endTimeUnixNano) != null ? _a : nowUnixNanoString();
629
+ if ((_b = extra == null ? void 0 : extra.attributes) == null ? void 0 : _b.length) {
630
+ span.attributes.push(...extra.attributes);
631
+ }
632
+ let status = extra == null ? void 0 : extra.status;
633
+ if (!status && (extra == null ? void 0 : extra.error) !== void 0) {
634
+ const message = extra.error instanceof Error ? extra.error.message : String(extra.error);
635
+ status = { code: SpanStatusCode.ERROR, message };
636
+ }
637
+ const otlp = buildOtlpSpan({
638
+ ids: span.ids,
639
+ name: span.name,
640
+ startTimeUnixNano: span.startTimeUnixNano,
641
+ endTimeUnixNano: span.endTimeUnixNano,
642
+ attributes: span.attributes,
643
+ status
644
+ });
645
+ this.enqueue(otlp);
646
+ if (this.localDebuggerUrl) {
647
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
648
+ mirrorTraceExportToLocalDebugger(body, {
649
+ baseUrl: this.localDebuggerUrl,
650
+ debug: false,
651
+ sdkName: this.sdkName
652
+ });
653
+ }
654
+ }
655
+ createSpan(args) {
656
+ var _a;
657
+ const ids = createSpanIds(args.parent);
658
+ const attrs = [
659
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId)
660
+ ];
661
+ if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
662
+ const otlp = buildOtlpSpan({
663
+ ids,
664
+ name: args.name,
665
+ startTimeUnixNano: args.startTimeUnixNano,
666
+ endTimeUnixNano: args.endTimeUnixNano,
667
+ attributes: attrs,
668
+ status: args.status
669
+ });
670
+ this.enqueue(otlp);
671
+ if (this.localDebuggerUrl) {
672
+ const body = buildExportTraceServiceRequest([otlp], this.serviceName, this.serviceVersion);
673
+ mirrorTraceExportToLocalDebugger(body, {
674
+ baseUrl: this.localDebuggerUrl,
675
+ debug: false,
676
+ sdkName: this.sdkName
677
+ });
678
+ }
679
+ }
680
+ enqueue(span) {
681
+ if (!this.enabled) return;
682
+ if (this.debugSpans) {
683
+ const short = (s) => s ? s.slice(-8) : "none";
684
+ console.log(
685
+ `${this.prefix}[span] name=${span.name} trace=${short(span.traceId)} span=${short(span.spanId)} parent=${short(
686
+ span.parentSpanId
687
+ )}`
688
+ );
689
+ }
690
+ if (this.queue.length >= this.maxQueueSize) {
691
+ this.queue.shift();
692
+ }
693
+ this.queue.push(span);
694
+ if (this.queue.length >= this.maxBatchSize) {
695
+ void this.flush().catch(() => {
696
+ });
697
+ return;
698
+ }
699
+ if (!this.timer) {
700
+ this.timer = setTimeout(() => {
701
+ this.timer = void 0;
702
+ void this.flush().catch(() => {
703
+ });
704
+ }, this.flushIntervalMs);
705
+ }
706
+ }
707
+ async flush() {
708
+ if (!this.enabled) return;
709
+ if (this.timer) {
710
+ clearTimeout(this.timer);
711
+ this.timer = void 0;
712
+ }
713
+ while (this.queue.length > 0) {
714
+ const batch = this.queue.splice(0, this.maxBatchSize);
715
+ const body = buildExportTraceServiceRequest(batch, this.serviceName, this.serviceVersion);
716
+ const url = `${this.baseUrl}traces`;
717
+ if (this.debug) {
718
+ console.log(`${this.prefix} sending traces batch`, {
719
+ spans: batch.length,
720
+ endpoint: url
721
+ });
722
+ }
723
+ const p = postJson(url, body, this.authHeaders(), {
724
+ maxAttempts: 3,
725
+ debug: this.debug,
726
+ sdkName: this.sdkName
727
+ });
728
+ this.inFlight.add(p);
729
+ try {
730
+ try {
731
+ await p;
732
+ if (this.debug) console.log(`${this.prefix} sent ${batch.length} spans`);
733
+ } catch (err) {
734
+ const msg = err instanceof Error ? err.message : String(err);
735
+ console.warn(`${this.prefix} failed to send ${batch.length} spans: ${msg}`);
736
+ }
737
+ } finally {
738
+ this.inFlight.delete(p);
739
+ }
740
+ }
741
+ }
742
+ async shutdown() {
743
+ if (this.timer) {
744
+ clearTimeout(this.timer);
745
+ this.timer = void 0;
746
+ }
747
+ await this.flush();
748
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
749
+ })));
750
+ }
751
+ };
752
+
753
+ // ../core/dist/index.node.js
754
+ import { AsyncLocalStorage } from "async_hooks";
755
+ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
756
+
757
+ // src/internal/shipper.ts
758
+ var EventShipper2 = class extends EventShipper {
759
+ constructor(opts) {
760
+ var _a, _b, _c, _d;
761
+ super({
762
+ ...opts,
763
+ sdkName: (_a = opts.sdkName) != null ? _a : "pi-agent",
764
+ libraryName: (_b = opts.libraryName) != null ? _b : libraryName,
765
+ libraryVersion: (_c = opts.libraryVersion) != null ? _c : libraryVersion,
766
+ defaultEventName: (_d = opts.defaultEventName) != null ? _d : "pi_agent_prompt"
767
+ });
768
+ }
769
+ };
770
+ var TraceShipper2 = class extends TraceShipper {
771
+ constructor(opts) {
772
+ var _a, _b, _c;
773
+ super({
774
+ ...opts,
775
+ sdkName: (_a = opts.sdkName) != null ? _a : "pi-agent",
776
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.pi-agent",
777
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : libraryVersion
778
+ });
779
+ }
780
+ enqueue(span) {
781
+ var _a;
782
+ const attrs = (_a = span.attributes) != null ? _a : [];
783
+ attrs.unshift(
784
+ { key: "span.id", value: { stringValue: span.spanId } },
785
+ ...span.parentSpanId ? [{ key: "span.parent.id", value: { stringValue: span.parentSpanId } }] : []
786
+ );
787
+ span.attributes = attrs;
788
+ super.enqueue(span);
789
+ }
790
+ };
791
+
792
+ // src/internal/helpers.ts
793
+ import { hostname, userInfo } from "os";
794
+ function extractUserText(message) {
795
+ if (!("role" in message) || message.role !== "user") return void 0;
796
+ const content = message.content;
797
+ if (typeof content === "string") return content;
798
+ if (!Array.isArray(content)) return void 0;
799
+ const textParts = [];
800
+ for (const block of content) {
801
+ if (block.type === "text" && typeof block.text === "string") {
802
+ textParts.push(block.text);
803
+ }
804
+ }
805
+ return textParts.length > 0 ? textParts.join("\n") : void 0;
806
+ }
807
+ function extractModelName(message) {
808
+ if (!("role" in message) || message.role !== "assistant") return void 0;
809
+ const provider = "provider" in message ? message.provider : void 0;
810
+ const model = typeof message.model === "string" ? message.model : void 0;
811
+ if (provider && model) return `${provider}/${model}`;
812
+ return model;
813
+ }
814
+ function extractTokenUsage(message) {
815
+ if (!("role" in message) || message.role !== "assistant") return void 0;
816
+ const usage = message.usage;
817
+ if (!usage || typeof usage.input !== "number" || typeof usage.output !== "number") {
818
+ return void 0;
819
+ }
820
+ return {
821
+ input: usage.input,
822
+ output: usage.output,
823
+ ...typeof usage.cacheRead === "number" && usage.cacheRead > 0 ? { cacheRead: usage.cacheRead } : {}
824
+ };
825
+ }
826
+ function extractAssistantText(message) {
827
+ if (!("role" in message) || message.role !== "assistant") return void 0;
828
+ if (!Array.isArray(message.content)) return void 0;
829
+ const textParts = [];
830
+ for (const block of message.content) {
831
+ if (block.type === "text" && typeof block.text === "string") {
832
+ textParts.push(block.text);
833
+ }
834
+ }
835
+ return textParts.length > 0 ? textParts.join("\n") : void 0;
836
+ }
837
+ function extractToolCallIds(message) {
838
+ if (!("role" in message) || message.role !== "assistant") return [];
839
+ if (!Array.isArray(message.content)) return [];
840
+ const ids = [];
841
+ for (const block of message.content) {
842
+ if (block.type === "toolCall" && typeof block.id === "string") {
843
+ ids.push(block.id);
844
+ }
845
+ }
846
+ return ids;
847
+ }
848
+ function formatToolSpanName(toolName, args) {
849
+ if (!args || typeof args !== "object") return toolName;
850
+ try {
851
+ const obj = args;
852
+ const firstValue = Object.values(obj)[0];
853
+ if (typeof firstValue === "string" && firstValue.length > 0) {
854
+ const preview = firstValue.length > 40 ? firstValue.slice(0, 37) + "..." : firstValue;
855
+ return `${toolName}: ${preview}`;
856
+ }
857
+ } catch (e) {
858
+ }
859
+ return toolName;
860
+ }
861
+ function safeStringify(value) {
862
+ if (value === void 0 || value === null) return void 0;
863
+ try {
864
+ return JSON.stringify(value);
865
+ } catch (e) {
866
+ try {
867
+ return String(value);
868
+ } catch (e2) {
869
+ return "[unserializable]";
870
+ }
871
+ }
872
+ }
873
+ var MAX_ATTR_LENGTH = 32768;
874
+ function truncate(value) {
875
+ if (value === void 0) return void 0;
876
+ if (value.length <= MAX_ATTR_LENGTH) return value;
877
+ const suffix = "\n...[truncated]";
878
+ return value.slice(0, MAX_ATTR_LENGTH - suffix.length) + suffix;
879
+ }
880
+ var _hostname;
881
+ function getHostname() {
882
+ var _a;
883
+ if (_hostname) return _hostname;
884
+ try {
885
+ _hostname = hostname();
886
+ } catch (e) {
887
+ _hostname = (_a = process.env.HOSTNAME) != null ? _a : "unknown";
888
+ }
889
+ return _hostname;
890
+ }
891
+ var _username;
892
+ function getUsername() {
893
+ var _a, _b;
894
+ if (_username) return _username;
895
+ try {
896
+ _username = userInfo().username;
897
+ } catch (e) {
898
+ _username = (_b = (_a = process.env.USER) != null ? _a : process.env.USERNAME) != null ? _b : "unknown";
899
+ }
900
+ return _username;
901
+ }
902
+
903
+ export {
904
+ libraryVersion,
905
+ randomUUID,
906
+ generateId,
907
+ nowUnixNanoString,
908
+ attrString,
909
+ attrInt,
910
+ EventShipper2 as EventShipper,
911
+ TraceShipper2 as TraceShipper,
912
+ extractUserText,
913
+ extractModelName,
914
+ extractTokenUsage,
915
+ extractAssistantText,
916
+ extractToolCallIds,
917
+ formatToolSpanName,
918
+ safeStringify,
919
+ truncate,
920
+ getHostname,
921
+ getUsername
922
+ };