@raindrop-ai/opencode-plugin 0.1.4 → 0.2.0

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/v2.cjs ADDED
@@ -0,0 +1,3327 @@
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/v2.ts
21
+ var v2_exports = {};
22
+ __export(v2_exports, {
23
+ default: () => raindrop
24
+ });
25
+ module.exports = __toCommonJS(v2_exports);
26
+ var import_plugin = require("@opencode/plugin");
27
+
28
+ // ../core/dist/chunk-BYBMRLZM.js
29
+ var EVAL_CORRELATION_ID_ATTRIBUTE = "raindrop.eval_correlation_id";
30
+ var PROBE_SCOPE = { correlationId: "" };
31
+ var EvalScopeStorage = class {
32
+ constructor() {
33
+ this._als = null;
34
+ this._probed = false;
35
+ }
36
+ maybeAdoptAsyncLocalStorage() {
37
+ if (this._probed) return;
38
+ this._probed = true;
39
+ try {
40
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
41
+ if (!Ctor) return;
42
+ const als = new Ctor();
43
+ als.run(PROBE_SCOPE, () => {
44
+ });
45
+ this._als = als;
46
+ } catch (e) {
47
+ this._als = null;
48
+ }
49
+ }
50
+ run(scope, callback) {
51
+ this.maybeAdoptAsyncLocalStorage();
52
+ if (this._als) return this._als.run(scope, callback);
53
+ const previous = this._syncScope;
54
+ this._syncScope = scope;
55
+ try {
56
+ return callback();
57
+ } finally {
58
+ this._syncScope = previous;
59
+ }
60
+ }
61
+ current() {
62
+ this.maybeAdoptAsyncLocalStorage();
63
+ if (this._als) return this._als.getStore();
64
+ return this._syncScope;
65
+ }
66
+ };
67
+ var EVAL_SCOPE_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.evalScopeStorage");
68
+ function evalScopeStorage() {
69
+ const holder = globalThis;
70
+ let storage = holder[EVAL_SCOPE_STORAGE_KEY];
71
+ if (!storage) {
72
+ storage = new EvalScopeStorage();
73
+ holder[EVAL_SCOPE_STORAGE_KEY] = storage;
74
+ }
75
+ return storage;
76
+ }
77
+ function currentEvalScope() {
78
+ try {
79
+ return evalScopeStorage().current();
80
+ } catch (e) {
81
+ return void 0;
82
+ }
83
+ }
84
+ function evalScopeAttributes() {
85
+ const scope = currentEvalScope();
86
+ if (!scope) return {};
87
+ return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
88
+ }
89
+
90
+ // ../core/dist/chunk-WJOR6M7H.js
91
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
92
+ function state() {
93
+ const holder = globalThis;
94
+ let current = holder[STATE_KEY];
95
+ if (!current) {
96
+ let storage = null;
97
+ try {
98
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
99
+ if (Ctor) storage = new Ctor();
100
+ } catch (e) {
101
+ storage = null;
102
+ }
103
+ current = {
104
+ storage,
105
+ syncDestination: void 0,
106
+ spanDestinations: /* @__PURE__ */ new WeakMap()
107
+ };
108
+ holder[STATE_KEY] = current;
109
+ }
110
+ return current;
111
+ }
112
+ function currentReplayTraceDestination() {
113
+ var _a, _b;
114
+ const routing = state();
115
+ return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
116
+ }
117
+ function rememberReplayTraceDestination(span) {
118
+ const destination = currentReplayTraceDestination();
119
+ if (destination) state().spanDestinations.set(span, destination);
120
+ }
121
+ function copyReplayTraceDestination(source, target) {
122
+ const destination = state().spanDestinations.get(source);
123
+ if (destination) state().spanDestinations.set(target, destination);
124
+ }
125
+ function replayTraceDestinationFor(value) {
126
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
127
+ return void 0;
128
+ }
129
+ return state().spanDestinations.get(value);
130
+ }
131
+ function recordReplayExportedSpan(destination, spanId, traceId) {
132
+ var _a, _b;
133
+ if (!destination || !spanId || !traceId) return;
134
+ (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
135
+ (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
136
+ }
137
+ function replayTraceUrl(baseUrl) {
138
+ return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
139
+ }
140
+ function getAsyncLocalStorageCtor() {
141
+ return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
142
+ }
143
+ var MAX_BINDING_STACK = 128;
144
+ var EMPTY_STACK = [];
145
+ var ContextStackStorage = class {
146
+ /** Emitted once when this runtime cannot support an ambient push. */
147
+ constructor(noAmbientBindWarning) {
148
+ this.noAmbientBindWarning = noAmbientBindWarning;
149
+ this._als = null;
150
+ this._enterWithUsable = false;
151
+ this._syncStack = EMPTY_STACK;
152
+ this._adoptionChecked = false;
153
+ this._warnedNoAmbientBind = false;
154
+ }
155
+ maybeAdoptAsyncLocalStorage() {
156
+ if (this._adoptionChecked) return;
157
+ this._adoptionChecked = true;
158
+ const Ctor = getAsyncLocalStorageCtor();
159
+ if (!Ctor) return;
160
+ const als = new Ctor();
161
+ try {
162
+ als.run(EMPTY_STACK, () => {
163
+ });
164
+ } catch (e) {
165
+ return;
166
+ }
167
+ this._als = als;
168
+ if (typeof als.enterWith === "function") {
169
+ try {
170
+ als.enterWith(EMPTY_STACK);
171
+ this._enterWithUsable = true;
172
+ } catch (e) {
173
+ this._enterWithUsable = false;
174
+ }
175
+ }
176
+ }
177
+ getStack() {
178
+ var _a;
179
+ this.maybeAdoptAsyncLocalStorage();
180
+ if (this._als) return (_a = this._als.getStore()) != null ? _a : this._syncStack;
181
+ return this._syncStack;
182
+ }
183
+ /**
184
+ * Persist an ambient stack mutation. Returns false when an ALS is adopted but
185
+ * `enterWith` is unusable (workerd): callers must NOT fall back to the
186
+ * process-shared sync stack, since concurrent isolates would cross-stamp.
187
+ */
188
+ setAmbientStack(stack) {
189
+ if (this._als) {
190
+ if (!this._enterWithUsable) return false;
191
+ this._als.enterWith(stack);
192
+ return true;
193
+ }
194
+ this._syncStack = stack;
195
+ return true;
196
+ }
197
+ push(binding) {
198
+ this.maybeAdoptAsyncLocalStorage();
199
+ if (this._als && !this._enterWithUsable) {
200
+ this.warnNoAmbientBindOnce();
201
+ return;
202
+ }
203
+ let stack = this.getStack();
204
+ if (stack.length >= MAX_BINDING_STACK) {
205
+ stack = stack.filter((b) => b.isLive());
206
+ if (stack.length >= MAX_BINDING_STACK) {
207
+ stack = stack.slice(stack.length - (MAX_BINDING_STACK - 1));
208
+ }
209
+ }
210
+ this.setAmbientStack([...stack, binding]);
211
+ }
212
+ remove(binding) {
213
+ binding.markDead();
214
+ const stack = this.getStack();
215
+ const pruned = stack.filter((b) => b !== binding && b.isLive());
216
+ if (pruned.length !== stack.length) {
217
+ this.setAmbientStack(pruned);
218
+ }
219
+ }
220
+ runWith(binding, callback) {
221
+ this.maybeAdoptAsyncLocalStorage();
222
+ if (this._als) {
223
+ return this._als.run([...this.getStack(), binding], callback);
224
+ }
225
+ const previous = this._syncStack;
226
+ this._syncStack = [...previous, binding];
227
+ try {
228
+ return callback();
229
+ } finally {
230
+ this._syncStack = previous;
231
+ }
232
+ }
233
+ current() {
234
+ const stack = this.getStack();
235
+ if (stack.length === 0) return void 0;
236
+ const top = stack[stack.length - 1];
237
+ if (top.isLive()) return top;
238
+ const pruned = stack.filter((b) => b.isLive());
239
+ this.setAmbientStack(pruned);
240
+ return pruned.length > 0 ? pruned[pruned.length - 1] : void 0;
241
+ }
242
+ warnNoAmbientBindOnce() {
243
+ if (this._warnedNoAmbientBind) return;
244
+ this._warnedNoAmbientBind = true;
245
+ console.warn(this.noAmbientBindWarning);
246
+ }
247
+ };
248
+ var NO_AMBIENT_ROUTING_BIND_WARNING = "[raindrop] This runtime's AsyncLocalStorage does not implement enterWith (e.g. Cloudflare Workers), so begin()/finish() cannot scope auto-instrumented spans to a project without cross-contaminating concurrent requests. Manual events and explicit span routing are unaffected; use asCurrent()/withSpan (run-based) to route auto-instrumented spans on this runtime.";
249
+ var ROUTING_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.routingContextStorage");
250
+ function routingStorage() {
251
+ const holder = globalThis;
252
+ let storage = holder[ROUTING_STORAGE_KEY];
253
+ if (!storage) {
254
+ storage = new ContextStackStorage(NO_AMBIENT_ROUTING_BIND_WARNING);
255
+ holder[ROUTING_STORAGE_KEY] = storage;
256
+ }
257
+ return storage;
258
+ }
259
+ function currentRoutingBinding() {
260
+ const bound = routingStorage().current();
261
+ if (!bound) return void 0;
262
+ return {
263
+ projectId: bound.projectId,
264
+ authHint: bound.authHint,
265
+ ...bound.appGit ? { appGit: bound.appGit } : {},
266
+ ...bound.appGitSource ? { appGitSource: bound.appGitSource } : {}
267
+ };
268
+ }
269
+ var APP_COMMIT_SHA = "raindrop.app.commit_sha";
270
+ var APP_COMMIT_DIRTY = "raindrop.app.commit_dirty";
271
+ var APP_BRANCH = "raindrop.app.branch";
272
+ var APP_GIT_KEYS = [APP_COMMIT_SHA, APP_COMMIT_DIRTY, APP_BRANCH];
273
+ var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
274
+ function appGitExplicitKeys(properties) {
275
+ const keys = /* @__PURE__ */ new Set();
276
+ if (!properties) return keys;
277
+ for (const key of APP_GIT_KEYS) {
278
+ if (own(properties, key)) keys.add(key);
279
+ }
280
+ return keys;
281
+ }
282
+ function mergeAppGitSnapshot(base, properties, explicitKeys = /* @__PURE__ */ new Set()) {
283
+ try {
284
+ const result = { ...base };
285
+ if (properties && own(properties, APP_COMMIT_SHA) && properties[APP_COMMIT_SHA] !== result[APP_COMMIT_SHA]) {
286
+ if (!explicitKeys.has(APP_COMMIT_DIRTY) && !own(properties, APP_COMMIT_DIRTY)) {
287
+ delete result[APP_COMMIT_DIRTY];
288
+ }
289
+ if (!explicitKeys.has(APP_BRANCH) && !own(properties, APP_BRANCH)) {
290
+ delete result[APP_BRANCH];
291
+ }
292
+ }
293
+ for (const key of APP_GIT_KEYS) {
294
+ if (properties && own(properties, key)) result[key] = properties[key];
295
+ }
296
+ return Object.freeze(result);
297
+ } catch (e) {
298
+ return Object.freeze({});
299
+ }
300
+ }
301
+ function validAppCommitSha(value) {
302
+ if (typeof value !== "string" || value.length > 128) return void 0;
303
+ const cleaned = value.trim();
304
+ return /^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(cleaned) ? cleaned.toLowerCase() : void 0;
305
+ }
306
+ function shortString(value) {
307
+ if (typeof value !== "string" || value.length > 1024) return void 0;
308
+ const cleaned = value.trim();
309
+ return cleaned.length > 0 ? cleaned : void 0;
310
+ }
311
+ function flag(value) {
312
+ if (value === true || value === "true" || value === "1") return true;
313
+ if (value === false || value === "false" || value === "0") return false;
314
+ return void 0;
315
+ }
316
+ function environment() {
317
+ try {
318
+ return typeof process === "undefined" ? {} : process.env;
319
+ } catch (e) {
320
+ return {};
321
+ }
322
+ }
323
+ var DEPLOYMENTS = [
324
+ ["VERCEL", "VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
325
+ ["NETLIFY", "COMMIT_REF", "BRANCH"],
326
+ ["RAILWAY_ENVIRONMENT_NAME", "RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH"],
327
+ ["RAILWAY_ENVIRONMENT", "RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH"],
328
+ ["RENDER", "RENDER_GIT_COMMIT", "RENDER_GIT_BRANCH"],
329
+ ["DYNO", "HEROKU_BUILD_COMMIT", ""],
330
+ ["DYNO", "HEROKU_SLUG_COMMIT", ""],
331
+ ["AWS_APP_ID", "AWS_COMMIT_ID", "AWS_BRANCH"],
332
+ ["WORKERS_CI", "WORKERS_CI_COMMIT_SHA", "WORKERS_CI_BRANCH"]
333
+ ];
334
+ var CI_SOURCES = [
335
+ ["GITHUB_ACTIONS", "GITHUB_SHA", "GITHUB_REF_NAME"],
336
+ ["GITLAB_CI", "CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
337
+ ["CIRCLECI", "CIRCLE_SHA1", "CIRCLE_BRANCH"]
338
+ ];
339
+ function detectedSource(env, table, detectBranch) {
340
+ for (const row of table) {
341
+ const [marker, shaKey, branchKey] = row;
342
+ if (!marker || !shaKey || !shortString(env[marker]) || flag(env[marker]) === false) continue;
343
+ const commitSha = validAppCommitSha(env[shaKey]);
344
+ if (commitSha)
345
+ return {
346
+ commitSha,
347
+ ...detectBranch && branchKey ? { branch: shortString(env[branchKey]) } : {}
348
+ };
349
+ }
350
+ return {};
351
+ }
352
+ var AppGitContextImpl = class {
353
+ constructor(options, runtime = {}) {
354
+ this.defaults = {};
355
+ this.explicit = {};
356
+ this.explicitKeys = /* @__PURE__ */ new Set();
357
+ this.disposed = false;
358
+ this.operations = /* @__PURE__ */ new Map();
359
+ this.operationOverflow = false;
360
+ this.detectBranch = false;
361
+ this.disabled = false;
362
+ var _a, _b, _c, _d, _e, _f;
363
+ try {
364
+ if (options === false) {
365
+ this.disabled = true;
366
+ return;
367
+ }
368
+ const opts = options != null ? options : {};
369
+ const env = (_a = runtime.env) != null ? _a : environment();
370
+ const detectBranch = (_c = (_b = flag(opts.detectBranch)) != null ? _b : flag(env.RAINDROP_GIT_DETECT_BRANCH)) != null ? _c : false;
371
+ this.detectBranch = detectBranch;
372
+ const collectBranch = detectBranch || runtime.captureLegacyReplayBranch === true;
373
+ const autoDetect = runtime.allowDiscovery === false ? false : (_e = (_d = flag(opts.autoDetect)) != null ? _d : flag(env.RAINDROP_GIT_AUTO_DETECT)) != null ? _e : true;
374
+ const configuredSha = opts.commitSha;
375
+ const explicitSha = configuredSha === void 0 ? env.RAINDROP_COMMIT_SHA : configuredSha;
376
+ if (explicitSha === null) this.explicit[APP_COMMIT_SHA] = null;
377
+ else if (typeof explicitSha === "string" && validAppCommitSha(explicitSha))
378
+ this.explicit[APP_COMMIT_SHA] = explicitSha;
379
+ const configuredDirty = opts.commitDirty;
380
+ const explicitDirty = configuredDirty === void 0 ? flag(env.RAINDROP_COMMIT_DIRTY) : configuredDirty;
381
+ if (explicitDirty === null || typeof explicitDirty === "boolean")
382
+ this.explicit[APP_COMMIT_DIRTY] = explicitDirty;
383
+ const configuredBranch = opts.branch;
384
+ const explicitBranch = configuredBranch === void 0 ? env.RAINDROP_BRANCH : configuredBranch;
385
+ if (explicitBranch === null) this.explicit[APP_BRANCH] = null;
386
+ else if (typeof explicitBranch === "string" && explicitBranch.length <= 1024)
387
+ this.explicit[APP_BRANCH] = explicitBranch;
388
+ this.explicitKeys = appGitExplicitKeys(this.explicit);
389
+ this.defaults = { ...this.explicit };
390
+ if (!autoDetect || explicitSha !== void 0) return;
391
+ const sourceDirectory = (_f = shortString(opts.sourceDirectory)) != null ? _f : shortString(env.RAINDROP_GIT_SOURCE_DIRECTORY);
392
+ if (runtime.allowLocalGit === false && !sourceDirectory) return;
393
+ const deploy = sourceDirectory ? {} : detectedSource(env, DEPLOYMENTS, collectBranch);
394
+ if (deploy.commitSha) {
395
+ this.accept(deploy);
396
+ return;
397
+ }
398
+ const fallback = sourceDirectory ? {} : detectedSource(env, CI_SOURCES, collectBranch);
399
+ if (runtime.resolveLocal && (runtime.allowLocalGit !== false || sourceDirectory)) {
400
+ this.cancel = runtime.resolveLocal(sourceDirectory, collectBranch, (result) => {
401
+ try {
402
+ if (!this.disposed) this.accept(result.commitSha ? result : fallback);
403
+ } catch (e) {
404
+ }
405
+ });
406
+ } else this.accept(fallback);
407
+ } catch (e) {
408
+ }
409
+ }
410
+ accept(result) {
411
+ const sha = validAppCommitSha(result.commitSha);
412
+ if (!sha) return;
413
+ this.replayBranch = shortString(result.branch);
414
+ this.defaults = {
415
+ [APP_COMMIT_SHA]: sha,
416
+ ...typeof result.commitDirty === "boolean" ? { [APP_COMMIT_DIRTY]: result.commitDirty } : {},
417
+ ...this.detectBranch && this.replayBranch ? { [APP_BRANCH]: this.replayBranch } : {},
418
+ ...this.explicit
419
+ };
420
+ }
421
+ snapshot(properties) {
422
+ var _a;
423
+ try {
424
+ const binding = currentRoutingBinding();
425
+ const base = this.disabled && (binding == null ? void 0 : binding.appGitSource) !== "replay-override" ? {} : (_a = binding == null ? void 0 : binding.appGit) != null ? _a : this.defaults;
426
+ return this.mergeSnapshot(base, properties);
427
+ } catch (e) {
428
+ return Object.freeze({});
429
+ }
430
+ }
431
+ /** Safe defaults when no operation/span start was observed; never infer identity. */
432
+ snapshotExplicit(properties, eventId) {
433
+ try {
434
+ const base = { ...this.explicit };
435
+ const operation = eventId ? this.operations.get(eventId) : void 0;
436
+ if (operation) {
437
+ for (const key of operation.explicitKeys) base[key] = operation.snapshot[key];
438
+ }
439
+ return this.mergeSnapshot(base, properties, new Set(Object.keys(base)));
440
+ } catch (e) {
441
+ return mergeAppGitSnapshot({}, properties);
442
+ }
443
+ }
444
+ /** Existing replay branch reporting stays separate from opt-in event properties. */
445
+ snapshotForReplay() {
446
+ const snapshot = this.snapshot();
447
+ if (this.replayBranch && !own(snapshot, APP_BRANCH) && snapshot[APP_COMMIT_SHA] === this.defaults[APP_COMMIT_SHA]) {
448
+ return Object.freeze({ ...snapshot, [APP_BRANCH]: this.replayBranch });
449
+ }
450
+ return snapshot;
451
+ }
452
+ /** Merge a frozen span snapshot without losing client-authored provenance. */
453
+ mergeSnapshot(base, properties, explicitKeys = this.explicitKeys) {
454
+ return mergeAppGitSnapshot(base, properties, /* @__PURE__ */ new Set([...this.explicitKeys, ...explicitKeys]));
455
+ }
456
+ /** Shippers belonging to one client share this bounded operation registry. */
457
+ forOperation(eventId, properties, owner) {
458
+ if (!eventId) return this.snapshot(properties);
459
+ let operation = this.operations.get(eventId);
460
+ if (!operation) {
461
+ if (this.operations.size >= 1e4) this.operationOverflow = true;
462
+ if (this.operationOverflow) return this.mergeSnapshot({}, properties);
463
+ operation = {
464
+ snapshot: this.snapshot(properties),
465
+ owners: /* @__PURE__ */ new Set(),
466
+ unowned: owner === void 0,
467
+ explicitKeys: appGitExplicitKeys(properties)
468
+ };
469
+ this.operations.set(eventId, operation);
470
+ } else if (properties && APP_GIT_KEYS.some((key) => own(properties, key))) {
471
+ const explicitKeys = /* @__PURE__ */ new Set([...this.explicitKeys, ...operation.explicitKeys]);
472
+ operation.snapshot = this.mergeSnapshot(operation.snapshot, properties, explicitKeys);
473
+ for (const key of appGitExplicitKeys(properties)) operation.explicitKeys.add(key);
474
+ }
475
+ if (!owner) operation.unowned = true;
476
+ if (owner) operation.owners.add(owner);
477
+ return operation.snapshot;
478
+ }
479
+ releaseOperation(eventId, owner) {
480
+ const operation = this.operations.get(eventId);
481
+ if (!operation) return;
482
+ operation.owners.delete(owner);
483
+ if (operation.owners.size === 0 && !operation.unowned) this.operations.delete(eventId);
484
+ }
485
+ finishOperation(eventId) {
486
+ this.operations.delete(eventId);
487
+ }
488
+ dispose() {
489
+ var _a;
490
+ this.disposed = true;
491
+ try {
492
+ (_a = this.cancel) == null ? void 0 : _a.call(this);
493
+ } catch (e) {
494
+ }
495
+ }
496
+ };
497
+ var AppGitContext = AppGitContextImpl;
498
+ function createAppGitContext(options, runtime = {}) {
499
+ return new AppGitContext(options, runtime);
500
+ }
501
+ function withAppGitProperties(properties, snapshot) {
502
+ try {
503
+ const merged = { ...properties };
504
+ for (const key of APP_GIT_KEYS)
505
+ if (!own(merged, key) && own(snapshot, key)) merged[key] = snapshot[key];
506
+ return merged;
507
+ } catch (e) {
508
+ return properties != null ? properties : {};
509
+ }
510
+ }
511
+ function withAppGitAttributes(attributes, snapshot) {
512
+ try {
513
+ const present = new Set(attributes.flatMap((attr) => attr ? [attr.key] : []));
514
+ const added = [];
515
+ for (const key of APP_GIT_KEYS) {
516
+ if (present.has(key) || present.has(`ai.telemetry.metadata.${key}`) || present.has(`traceloop.association.properties.${key}`))
517
+ continue;
518
+ const value = snapshot[key];
519
+ if (typeof value === "string") added.push({ key, value: { stringValue: value } });
520
+ else if (typeof value === "boolean") added.push({ key, value: { boolValue: value } });
521
+ }
522
+ return added.length ? [...attributes, ...added] : attributes;
523
+ } catch (e) {
524
+ return attributes;
525
+ }
526
+ }
527
+ function appGitPropertiesFromAttributes(attributes) {
528
+ var _a, _b, _c;
529
+ const properties = {};
530
+ try {
531
+ for (const attr of attributes) {
532
+ if (!attr) continue;
533
+ for (const key of APP_GIT_KEYS) {
534
+ if (attr.key === key || attr.key === `ai.telemetry.metadata.${key}` || attr.key === `traceloop.association.properties.${key}`) {
535
+ properties[key] = (_c = (_b = (_a = attr.value.stringValue) != null ? _a : attr.value.boolValue) != null ? _b : attr.value.intValue) != null ? _c : null;
536
+ }
537
+ }
538
+ }
539
+ } catch (e) {
540
+ }
541
+ return properties;
542
+ }
543
+ function getCrypto() {
544
+ const c = globalThis.crypto;
545
+ return c;
546
+ }
547
+ function randomBytes(length) {
548
+ const cryptoObj = getCrypto();
549
+ const out = new Uint8Array(length);
550
+ if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
551
+ cryptoObj.getRandomValues(out);
552
+ return out;
553
+ }
554
+ for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
555
+ return out;
556
+ }
557
+ function randomUUID() {
558
+ const cryptoObj = getCrypto();
559
+ if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
560
+ return cryptoObj.randomUUID();
561
+ }
562
+ const b = randomBytes(16);
563
+ b[6] = b[6] & 15 | 64;
564
+ b[8] = b[8] & 63 | 128;
565
+ const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
566
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
567
+ }
568
+ function base64Encode(bytes) {
569
+ const maybeBuffer = globalThis.Buffer;
570
+ if (maybeBuffer) {
571
+ return maybeBuffer.from(bytes).toString("base64");
572
+ }
573
+ let binary = "";
574
+ for (let i2 = 0; i2 < bytes.length; i2++) {
575
+ binary += String.fromCharCode(bytes[i2]);
576
+ }
577
+ const btoaFn = globalThis.btoa;
578
+ if (typeof btoaFn === "function") return btoaFn(binary);
579
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
580
+ let out = "";
581
+ let i = 0;
582
+ while (i < binary.length) {
583
+ const c1 = binary.charCodeAt(i++) & 255;
584
+ const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
585
+ const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
586
+ const e1 = c1 >> 2;
587
+ const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
588
+ const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
589
+ const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
590
+ out += alphabet.charAt(e1);
591
+ out += alphabet.charAt(e2);
592
+ out += e3 === 64 ? "=" : alphabet.charAt(e3);
593
+ out += e4 === 64 ? "=" : alphabet.charAt(e4);
594
+ }
595
+ return out;
596
+ }
597
+ function base64ToHex(value) {
598
+ if (!value) return "";
599
+ const maybeBuffer = globalThis.Buffer;
600
+ if (maybeBuffer) {
601
+ return maybeBuffer.from(value, "base64").toString("hex");
602
+ }
603
+ const atobFn = globalThis.atob;
604
+ if (typeof atobFn !== "function") return "";
605
+ try {
606
+ const binary = atobFn(value);
607
+ let hex = "";
608
+ for (let i = 0; i < binary.length; i++) {
609
+ hex += (binary.charCodeAt(i) & 255).toString(16).padStart(2, "0");
610
+ }
611
+ return hex;
612
+ } catch (e) {
613
+ return "";
614
+ }
615
+ }
616
+ function generateId() {
617
+ return randomUUID();
618
+ }
619
+ var HANDOFF_ATTRIBUTE_SUFFIXES = {
620
+ mode: "raindrop.handoff.mode",
621
+ childEventId: "raindrop.handoff.childEventId",
622
+ parentEventId: "raindrop.handoff.parentEventId",
623
+ parentSpanId: "raindrop.handoff.parentSpanId",
624
+ name: "raindrop.handoff.name",
625
+ terminal: "raindrop.handoff.terminal",
626
+ agentRole: "raindrop.agent.role"
627
+ };
628
+ var HANDOFF_TERMINAL_PROPERTY_KEY = HANDOFF_ATTRIBUTE_SUFFIXES.terminal;
629
+ var TRACEPARENT_HEADER = "traceparent";
630
+ var BAGGAGE_HEADER = "baggage";
631
+ var HANDOFF_HEADER = "x-raindrop-handoff";
632
+ var UNRESOLVED_CARRIER_WARNING = `[raindrop] resume: headers were supplied but no hand-off carrier was found on them (searched ${HANDOFF_HEADER}, ${TRACEPARENT_HEADER}, ${BAGGAGE_HEADER}). This run reports as an UNLINKED event, and the launcher that dispatched it will stay on "queued" forever because nothing ever references its child. Passing headers means a parent handed off, so no carrier on them is almost certainly a defect: a gateway or proxy stripping ${HANDOFF_HEADER}, a middleware overwriting ${BAGGAGE_HEADER}, a request forwarded without its headers, or a hand-built carrier whose field names do not match. Send every header the launcher's dispatch returned. Logged once per process; pass no headers for a directly-invoked sub-agent to silence it.`;
633
+ function runWithTracingSuppressed(fn) {
634
+ const hook = globalThis.RAINDROP_SUPPRESS_TRACING;
635
+ if (typeof hook !== "function") return fn();
636
+ let started = false;
637
+ try {
638
+ return hook(() => {
639
+ started = true;
640
+ return fn();
641
+ });
642
+ } catch (err) {
643
+ if (started) throw err;
644
+ return fn();
645
+ }
646
+ }
647
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
648
+ var MAX_RETRY_DELAY_MS = 3e4;
649
+ function wait(ms) {
650
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
651
+ }
652
+ function formatEndpoint(endpoint) {
653
+ if (!endpoint) return void 0;
654
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
655
+ }
656
+ function redactUrlForLog(url) {
657
+ try {
658
+ const parsed = new URL(url);
659
+ parsed.username = "";
660
+ parsed.password = "";
661
+ parsed.search = "";
662
+ parsed.hash = "";
663
+ return parsed.toString();
664
+ } catch (e) {
665
+ return "<unparseable-url>";
666
+ }
667
+ }
668
+ var RATE_LIMITED_LOG_INTERVAL_MS = 3e4;
669
+ var rateLimitedLogLast = /* @__PURE__ */ new Map();
670
+ function rateLimitedLog(key, log) {
671
+ const now = Date.now();
672
+ const last = rateLimitedLogLast.get(key);
673
+ if (last !== void 0 && now - last < RATE_LIMITED_LOG_INTERVAL_MS) {
674
+ return false;
675
+ }
676
+ rateLimitedLogLast.set(key, now);
677
+ log();
678
+ return true;
679
+ }
680
+ async function raceWithTimeout(promise, timeoutMs) {
681
+ let timer;
682
+ const settledInTime = await Promise.race([
683
+ promise.then(
684
+ () => true,
685
+ () => true
686
+ ),
687
+ new Promise((resolve2) => {
688
+ var _a;
689
+ timer = setTimeout(() => resolve2(false), Math.max(0, timeoutMs));
690
+ (_a = timer.unref) == null ? void 0 : _a.call(timer);
691
+ })
692
+ ]);
693
+ if (timer) clearTimeout(timer);
694
+ return settledInTime;
695
+ }
696
+ function parseRetryAfter(headers) {
697
+ var _a;
698
+ const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
699
+ if (!value) return void 0;
700
+ const asNumber = Number(value);
701
+ if (value.trim() !== "" && !Number.isNaN(asNumber)) return asNumber * 1e3;
702
+ const asDate = new Date(value).getTime();
703
+ if (!Number.isNaN(asDate)) {
704
+ const delta = asDate - Date.now();
705
+ return delta > 0 ? delta : 0;
706
+ }
707
+ return void 0;
708
+ }
709
+ function getRetryDelayMs(attemptNumber, previousError) {
710
+ if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
711
+ const v = previousError.retryAfterMs;
712
+ if (typeof v === "number") return Math.min(Math.max(0, v), MAX_RETRY_DELAY_MS);
713
+ }
714
+ if (attemptNumber <= 1) return 0;
715
+ const base = 500;
716
+ const factor = Math.pow(2, attemptNumber - 2);
717
+ return Math.min(base * factor, MAX_RETRY_DELAY_MS);
718
+ }
719
+ async function withRetry(operation, opName, opts) {
720
+ const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
721
+ let lastError = void 0;
722
+ for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
723
+ if (attemptNumber > 1) {
724
+ const delay = getRetryDelayMs(attemptNumber, lastError);
725
+ if (opts.debug) {
726
+ console.warn(
727
+ `${prefix} ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
728
+ );
729
+ }
730
+ if (delay > 0) await wait(delay);
731
+ } else if (opts.debug) {
732
+ console.log(`${prefix} ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
733
+ }
734
+ try {
735
+ return await operation();
736
+ } catch (err) {
737
+ lastError = err;
738
+ if (opts.debug) {
739
+ const msg = err instanceof Error ? err.message : String(err);
740
+ console.warn(
741
+ `${prefix} ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
742
+ );
743
+ }
744
+ if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
745
+ break;
746
+ if (attemptNumber === opts.maxAttempts) break;
747
+ }
748
+ }
749
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
750
+ }
751
+ async function postJson(url, body, headers, opts) {
752
+ var _a;
753
+ const opName = `POST ${redactUrlForLog(url)}`;
754
+ const timeoutMs = (_a = opts.timeoutMs) != null ? _a : DEFAULT_REQUEST_TIMEOUT_MS;
755
+ await withRetry(
756
+ async () => {
757
+ const resp = await runWithTracingSuppressed(
758
+ () => fetch(url, {
759
+ method: "POST",
760
+ redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
761
+ headers: {
762
+ "Content-Type": "application/json",
763
+ ...headers
764
+ },
765
+ body: JSON.stringify(body),
766
+ signal: AbortSignal.timeout(timeoutMs)
767
+ })
768
+ );
769
+ if (!resp.ok) {
770
+ const text = await resp.text().catch(() => "");
771
+ const err = new Error(
772
+ `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
773
+ );
774
+ const retryAfterMs = parseRetryAfter(resp.headers);
775
+ if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
776
+ err.retryable = resp.status === 429 || resp.status >= 500;
777
+ throw err;
778
+ }
779
+ },
780
+ opName,
781
+ opts
782
+ );
783
+ }
784
+ var DEFAULT_MAX_TEXT_FIELD_CHARS = 1e6;
785
+ var TRUNCATION_MARKER = "...[truncated by raindrop]";
786
+ var currentDefaultMaxTextFieldChars = DEFAULT_MAX_TEXT_FIELD_CHARS;
787
+ function resolveMaxTextFieldChars(value) {
788
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
789
+ return Math.floor(value);
790
+ }
791
+ return currentDefaultMaxTextFieldChars;
792
+ }
793
+ function truncateToLimit(text, limit) {
794
+ if (limit > TRUNCATION_MARKER.length) {
795
+ return text.slice(0, limit - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
796
+ }
797
+ return text.slice(0, Math.max(0, limit));
798
+ }
799
+ function capText(value, limit) {
800
+ if (typeof value !== "string") return value;
801
+ const max = limit != null ? limit : currentDefaultMaxTextFieldChars;
802
+ if (value.length <= max) return value;
803
+ return truncateToLimit(value, max);
804
+ }
805
+ var SpanStatusCode = {
806
+ UNSET: 0,
807
+ OK: 1,
808
+ ERROR: 2
809
+ };
810
+ function createSpanIds(parent) {
811
+ const traceId = parent ? parent.traceIdB64 : base64Encode(randomBytes(16));
812
+ const spanId = base64Encode(randomBytes(8));
813
+ return {
814
+ traceIdB64: traceId,
815
+ spanIdB64: spanId,
816
+ parentSpanIdB64: parent ? parent.spanIdB64 : void 0
817
+ };
818
+ }
819
+ function nowUnixNanoString() {
820
+ return Date.now().toString() + "000000";
821
+ }
822
+ function attrString(key, value) {
823
+ if (value === void 0) return void 0;
824
+ return { key, value: { stringValue: value } };
825
+ }
826
+ function attrInt(key, value) {
827
+ if (value === void 0) return void 0;
828
+ if (!Number.isFinite(value)) return void 0;
829
+ return { key, value: { intValue: String(Math.trunc(value)) } };
830
+ }
831
+ function attrDouble(key, value) {
832
+ if (value === void 0) return void 0;
833
+ if (!Number.isFinite(value)) return void 0;
834
+ return { key, value: { doubleValue: value } };
835
+ }
836
+ function buildOtlpSpan(args) {
837
+ const attrs = args.attributes.filter((x) => x !== void 0);
838
+ const span = {
839
+ traceId: args.ids.traceIdB64,
840
+ spanId: args.ids.spanIdB64,
841
+ name: args.name,
842
+ startTimeUnixNano: args.startTimeUnixNano,
843
+ endTimeUnixNano: args.endTimeUnixNano
844
+ };
845
+ if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
846
+ if (attrs.length) span.attributes = attrs;
847
+ if (args.status) span.status = args.status;
848
+ return span;
849
+ }
850
+ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", serviceVersion = "0.0.0") {
851
+ return {
852
+ resourceSpans: [
853
+ {
854
+ resource: {
855
+ attributes: [{ key: "service.name", value: { stringValue: serviceName } }]
856
+ },
857
+ scopeSpans: [
858
+ {
859
+ scope: { name: serviceName, version: serviceVersion },
860
+ spans
861
+ }
862
+ ]
863
+ }
864
+ ]
865
+ };
866
+ }
867
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
868
+ var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
869
+ var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
870
+ function readEnvVar(name) {
871
+ var _a;
872
+ try {
873
+ const env = (_a = globalThis == null ? void 0 : globalThis.process) == null ? void 0 : _a.env;
874
+ if (env && typeof env[name] === "string" && env[name].length > 0) {
875
+ return env[name];
876
+ }
877
+ } catch (e) {
878
+ }
879
+ return void 0;
880
+ }
881
+ function readWorkshopEnv() {
882
+ const raw = readEnvVar(WORKSHOP_ENV_VAR);
883
+ if (raw === void 0) return void 0;
884
+ const trimmed = raw.trim();
885
+ if (trimmed.length === 0) return void 0;
886
+ if (/^https?:\/\//i.test(trimmed)) return { url: trimmed };
887
+ if (/^(1|true|yes|on)$/i.test(trimmed)) return "enable";
888
+ if (/^(0|false|no|off)$/i.test(trimmed)) return "disable";
889
+ return void 0;
890
+ }
891
+ function isLocalDevHost(hostname) {
892
+ if (!hostname) return false;
893
+ if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0" || hostname === "::1") {
894
+ return true;
895
+ }
896
+ if (hostname.endsWith(".localhost")) return true;
897
+ return false;
898
+ }
899
+ function readRuntimeHostname() {
900
+ try {
901
+ const loc = globalThis == null ? void 0 : globalThis.location;
902
+ if (loc && typeof loc.hostname === "string" && loc.hostname.length > 0) {
903
+ return loc.hostname;
904
+ }
905
+ } catch (e) {
906
+ }
907
+ return void 0;
908
+ }
909
+ function shouldAutoEnableLocalWorkshop() {
910
+ if (isLocalDevHost(readRuntimeHostname())) return true;
911
+ if (readEnvVar("NODE_ENV") === "development") return true;
912
+ return false;
913
+ }
914
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
915
+ var _a, _b, _c;
916
+ if (baseUrl === null) return null;
917
+ if (typeof baseUrl === "string" && baseUrl.length > 0) {
918
+ return (_a = formatEndpoint(baseUrl)) != null ? _a : null;
919
+ }
920
+ const explicitUrlEnv = readEnvVar(LOCAL_DEBUGGER_ENV_VAR);
921
+ if (explicitUrlEnv) return (_b = formatEndpoint(explicitUrlEnv)) != null ? _b : null;
922
+ const workshopEnv = readWorkshopEnv();
923
+ if (workshopEnv === "disable") return null;
924
+ if (workshopEnv === "enable") return DEFAULT_LOCAL_WORKSHOP_URL;
925
+ if (workshopEnv && "url" in workshopEnv) return (_c = formatEndpoint(workshopEnv.url)) != null ? _c : null;
926
+ if (shouldAutoEnableLocalWorkshop()) return DEFAULT_LOCAL_WORKSHOP_URL;
927
+ return null;
928
+ }
929
+ var LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS = 2e3;
930
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
931
+ var _a;
932
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
933
+ if (!baseUrl) return Promise.resolve();
934
+ return postJson(`${baseUrl}traces`, body, {}, {
935
+ maxAttempts: 1,
936
+ debug: (_a = options.debug) != null ? _a : false,
937
+ sdkName: options.sdkName,
938
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
939
+ }).catch(() => {
940
+ });
941
+ }
942
+ function mirrorPartialEventToLocalDebugger(event, options = {}) {
943
+ var _a;
944
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
945
+ if (!baseUrl) return Promise.resolve();
946
+ const headers = options.writeKey ? { Authorization: `Bearer ${options.writeKey}` } : {};
947
+ return postJson(`${baseUrl}events/track_partial`, event, headers, {
948
+ maxAttempts: 1,
949
+ debug: (_a = options.debug) != null ? _a : false,
950
+ sdkName: options.sdkName,
951
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
952
+ }).catch(() => {
953
+ });
954
+ }
955
+ var PROJECT_ID_HEADER = "X-Raindrop-Project-Id";
956
+ var PROJECT_ID_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
957
+ function isValidProjectIdSlug(value) {
958
+ return PROJECT_ID_SLUG_PATTERN.test(value);
959
+ }
960
+ function normalizeProjectId(raw, opts) {
961
+ if (typeof raw !== "string") return void 0;
962
+ const trimmed = raw.trim();
963
+ if (!trimmed) return void 0;
964
+ if (!isValidProjectIdSlug(trimmed) && opts.debug) {
965
+ console.warn(
966
+ `${opts.prefix} projectId "${trimmed}" does not match slug ${PROJECT_ID_SLUG_PATTERN.source}; sending anyway \u2014 backend may reject with HTTP 400`
967
+ );
968
+ }
969
+ return trimmed;
970
+ }
971
+ function projectIdHeaders(projectId) {
972
+ return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
973
+ }
974
+ var SHUTDOWN_DEADLINE_MS = 1e4;
975
+ var POST_SHUTDOWN_TIMEOUT_MS = 5e3;
976
+ function appGitOwnerId(prefix) {
977
+ try {
978
+ return `${prefix}:${randomUUID()}`;
979
+ } catch (e) {
980
+ return `${prefix}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
981
+ }
982
+ }
983
+ function mergePatches(target, source) {
984
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
985
+ const out = { ...target, ...source };
986
+ if (target.properties || source.properties) {
987
+ out.properties = { ...(_a = target.properties) != null ? _a : {}, ...(_b = source.properties) != null ? _b : {} };
988
+ }
989
+ if (target.usage || source.usage) {
990
+ out.usage = { ...(_c = target.usage) != null ? _c : {} };
991
+ if (((_d = source.usage) == null ? void 0 : _d.promptTokens) !== void 0) {
992
+ out.usage.promptTokens = source.usage.promptTokens;
993
+ }
994
+ if (((_e = source.usage) == null ? void 0 : _e.completionTokens) !== void 0) {
995
+ out.usage.completionTokens = source.usage.completionTokens;
996
+ }
997
+ }
998
+ if (source.error === void 0) {
999
+ out.error = target.error;
1000
+ }
1001
+ if (target.featureFlags || source.featureFlags) {
1002
+ out.featureFlags = { ...(_f = target.featureFlags) != null ? _f : {}, ...(_g = source.featureFlags) != null ? _g : {} };
1003
+ }
1004
+ if (target.attachments || source.attachments) {
1005
+ out.attachments = [...(_h = target.attachments) != null ? _h : [], ...(_i = source.attachments) != null ? _i : []];
1006
+ }
1007
+ return out;
1008
+ }
1009
+ function isErrorLike(value) {
1010
+ return value !== null && typeof value === "object";
1011
+ }
1012
+ function eventTelemetryProperties(patch) {
1013
+ var _a, _b;
1014
+ const properties = {};
1015
+ if (((_a = patch.usage) == null ? void 0 : _a.promptTokens) !== void 0 && Number.isFinite(patch.usage.promptTokens)) {
1016
+ properties["ai.usage.prompt_tokens"] = patch.usage.promptTokens;
1017
+ }
1018
+ if (((_b = patch.usage) == null ? void 0 : _b.completionTokens) !== void 0 && Number.isFinite(patch.usage.completionTokens)) {
1019
+ properties["ai.usage.completion_tokens"] = patch.usage.completionTokens;
1020
+ }
1021
+ if (patch.error !== void 0 && patch.error !== null) {
1022
+ const constructorName = patch.error instanceof Error && patch.error.constructor !== Error ? patch.error.constructor.name : void 0;
1023
+ const errorType = patch.error instanceof Error ? patch.error.name && patch.error.name !== "Error" ? patch.error.name : constructorName || patch.error.name || "Error" : isErrorLike(patch.error) && typeof patch.error.name === "string" && patch.error.name.length > 0 ? patch.error.name : "Error";
1024
+ const errorMessage2 = patch.error instanceof Error ? patch.error.message : isErrorLike(patch.error) && typeof patch.error.message === "string" ? patch.error.message : String(patch.error);
1025
+ properties["error.type"] = errorType;
1026
+ properties["error.message"] = errorMessage2;
1027
+ }
1028
+ return properties;
1029
+ }
1030
+ var EventShipper = class {
1031
+ constructor(opts) {
1032
+ this.appGitOwner = appGitOwnerId("event");
1033
+ this.buffers = /* @__PURE__ */ new Map();
1034
+ this.sticky = /* @__PURE__ */ new Map();
1035
+ this.timers = /* @__PURE__ */ new Map();
1036
+ this.inFlight = /* @__PURE__ */ new Set();
1037
+ this.hasShutdown = false;
1038
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1039
+ this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
1040
+ this.ownsAppGitContext = opts.appGitContext === void 0;
1041
+ this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
1042
+ this.baseUrl = (_c = formatEndpoint(opts.endpoint)) != null ? _c : "https://api.raindrop.ai/v1/";
1043
+ this.enabled = opts.enabled !== false;
1044
+ this.debug = opts.debug;
1045
+ this.partialFlushMs = (_d = opts.partialFlushMs) != null ? _d : 1e3;
1046
+ this.sdkName = (_e = opts.sdkName) != null ? _e : "core";
1047
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
1048
+ this.defaultEventName = (_f = opts.defaultEventName) != null ? _f : "ai_generation";
1049
+ this.maxTextFieldCharsOpt = opts.maxTextFieldChars;
1050
+ this.localDebuggerUrl = (_g = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _g : void 0;
1051
+ if (this.debug && this.localDebuggerUrl) {
1052
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
1053
+ }
1054
+ this.projectId = normalizeProjectId(opts.projectId, {
1055
+ debug: this.debug,
1056
+ prefix: this.prefix
1057
+ });
1058
+ const isNode = typeof process !== "undefined" && typeof process.version === "string";
1059
+ this.context = {
1060
+ library: {
1061
+ name: (_h = opts.libraryName) != null ? _h : "@raindrop-ai/core",
1062
+ version: (_i = opts.libraryVersion) != null ? _i : "0.0.0"
1063
+ },
1064
+ metadata: {
1065
+ jsRuntime: isNode ? "node" : "web",
1066
+ ...isNode ? { nodeVersion: process.version } : {}
1067
+ }
1068
+ };
1069
+ }
1070
+ ownAppGitContextForShutdown() {
1071
+ this.ownsAppGitContext = true;
1072
+ }
1073
+ isDebugEnabled() {
1074
+ return this.debug;
1075
+ }
1076
+ authHeaders() {
1077
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
1078
+ }
1079
+ requestHeaders() {
1080
+ return { ...this.authHeaders(), ...projectIdHeaders(this.projectId) };
1081
+ }
1082
+ /**
1083
+ * Build the retry/timeout options for one POST, honoring the shutdown
1084
+ * deadline. Returns `null` when the shutdown drain window is exhausted —
1085
+ * the caller must drop the payload (with a rate-limited warning) instead
1086
+ * of issuing a request that could outlive process exit.
1087
+ *
1088
+ * Checked fresh on EVERY send, so a shutdown that begins while the flush
1089
+ * path is mid-drain takes effect immediately: no further retries, and the
1090
+ * per-attempt timeout is clamped to the remaining window. After
1091
+ * `shutdown()` returns (deadline cleared, `hasShutdown` still set),
1092
+ * sends — late callers, or flush work the deadline abandoned mid-drain —
1093
+ * run as a single short attempt rather than regaining the full retry
1094
+ * schedule.
1095
+ */
1096
+ requestOpts() {
1097
+ if (this.shutdownDeadlineAt !== void 0) {
1098
+ const remainingMs = this.shutdownDeadlineAt - Date.now();
1099
+ if (remainingMs <= 0) return null;
1100
+ return {
1101
+ maxAttempts: 1,
1102
+ debug: this.debug,
1103
+ sdkName: this.sdkName,
1104
+ timeoutMs: Math.min(DEFAULT_REQUEST_TIMEOUT_MS, remainingMs)
1105
+ };
1106
+ }
1107
+ if (this.hasShutdown) {
1108
+ return {
1109
+ maxAttempts: 1,
1110
+ debug: this.debug,
1111
+ sdkName: this.sdkName,
1112
+ timeoutMs: POST_SHUTDOWN_TIMEOUT_MS
1113
+ };
1114
+ }
1115
+ return { maxAttempts: 3, debug: this.debug, sdkName: this.sdkName };
1116
+ }
1117
+ async patch(eventId, patch) {
1118
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
1119
+ if (!this.enabled) return;
1120
+ if (!eventId || !eventId.trim()) return;
1121
+ const capturedSticky = this.sticky.get(eventId);
1122
+ const eventAlreadyKnown = capturedSticky !== void 0 || this.buffers.has(eventId);
1123
+ const destination = currentReplayTraceDestination();
1124
+ const cloudReplay = destination !== void 0 && destination.kind !== "workshop";
1125
+ if ((capturedSticky == null ? void 0 : capturedSticky.replayOnly) === true || !eventAlreadyKnown && cloudReplay) {
1126
+ if (patch.isPending === false) this.sticky.delete(eventId);
1127
+ else this.sticky.set(eventId, { ...capturedSticky, replayOnly: true });
1128
+ return;
1129
+ }
1130
+ const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
1131
+ if (typeof patch.input === "string" && patch.input.length > maxChars) {
1132
+ patch = { ...patch, input: capText(patch.input, maxChars) };
1133
+ }
1134
+ if (typeof patch.output === "string" && patch.output.length > maxChars) {
1135
+ patch = { ...patch, output: capText(patch.output, maxChars) };
1136
+ }
1137
+ if (this.debug) {
1138
+ console.log(`${this.prefix} queue patch`, {
1139
+ eventId,
1140
+ userId: patch.userId,
1141
+ convoId: patch.convoId,
1142
+ eventName: patch.eventName,
1143
+ hasInput: typeof patch.input === "string" && patch.input.length > 0,
1144
+ hasOutput: typeof patch.output === "string" && patch.output.length > 0,
1145
+ attachments: (_b = (_a = patch.attachments) == null ? void 0 : _a.length) != null ? _b : 0,
1146
+ isPending: patch.isPending
1147
+ });
1148
+ }
1149
+ const sticky = (_c = this.sticky.get(eventId)) != null ? _c : {};
1150
+ const existing = (_d = this.buffers.get(eventId)) != null ? _d : {};
1151
+ patch = {
1152
+ ...patch,
1153
+ properties: withAppGitProperties(
1154
+ patch.properties,
1155
+ this.appGitContext.forOperation(eventId, patch.properties, this.appGitOwner)
1156
+ )
1157
+ };
1158
+ const merged = mergePatches(existing, patch);
1159
+ merged.isPending = (_g = (_f = (_e = patch.isPending) != null ? _e : existing.isPending) != null ? _f : sticky.isPending) != null ? _g : true;
1160
+ this.buffers.set(eventId, merged);
1161
+ this.sticky.set(eventId, {
1162
+ userId: (_h = merged.userId) != null ? _h : sticky.userId,
1163
+ convoId: (_i = merged.convoId) != null ? _i : sticky.convoId,
1164
+ eventName: (_j = merged.eventName) != null ? _j : sticky.eventName,
1165
+ isPending: (_k = merged.isPending) != null ? _k : sticky.isPending
1166
+ });
1167
+ const t = this.timers.get(eventId);
1168
+ if (t) clearTimeout(t);
1169
+ if (merged.isPending === false) {
1170
+ await this.flushOne(eventId);
1171
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(eventId, this.appGitOwner);
1172
+ else this.appGitContext.finishOperation(eventId);
1173
+ return;
1174
+ }
1175
+ const timeout = setTimeout(() => {
1176
+ void this.flushOne(eventId).catch(() => {
1177
+ });
1178
+ }, this.partialFlushMs);
1179
+ this.timers.set(eventId, timeout);
1180
+ }
1181
+ async finish(eventId, patch) {
1182
+ await this.patch(eventId, { ...patch, isPending: false });
1183
+ }
1184
+ async flush() {
1185
+ if (!this.enabled) return;
1186
+ const ids = [...this.buffers.keys()];
1187
+ await Promise.all(ids.map((id) => this.flushOne(id)));
1188
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
1189
+ })));
1190
+ }
1191
+ async shutdown() {
1192
+ this.hasShutdown = true;
1193
+ this.shutdownDeadlineAt = Date.now() + SHUTDOWN_DEADLINE_MS;
1194
+ try {
1195
+ for (const t of this.timers.values()) clearTimeout(t);
1196
+ this.timers.clear();
1197
+ for (const [eventId, sticky] of this.sticky) {
1198
+ if (sticky.replayOnly) this.sticky.delete(eventId);
1199
+ }
1200
+ const settled = await raceWithTimeout(this.flush(), SHUTDOWN_DEADLINE_MS);
1201
+ if (!settled) this.warnShutdownDrop("in-flight request(s) at shutdown");
1202
+ } finally {
1203
+ this.shutdownDeadlineAt = void 0;
1204
+ if (this.ownsAppGitContext) this.appGitContext.dispose();
1205
+ }
1206
+ }
1207
+ async trackSignal(signal) {
1208
+ var _a, _b;
1209
+ if (!this.enabled) return;
1210
+ const destination = currentReplayTraceDestination();
1211
+ if (destination && destination.kind !== "workshop") return;
1212
+ const body = [
1213
+ {
1214
+ event_id: signal.eventId,
1215
+ signal_name: signal.name,
1216
+ signal_type: (_a = signal.type) != null ? _a : "default",
1217
+ timestamp: signal.timestamp,
1218
+ sentiment: signal.sentiment,
1219
+ attachment_id: signal.attachmentId,
1220
+ properties: {
1221
+ ...(_b = signal.properties) != null ? _b : {},
1222
+ ...signal.comment ? { comment: signal.comment } : {},
1223
+ ...signal.after ? { after: signal.after } : {}
1224
+ }
1225
+ }
1226
+ ];
1227
+ if (!this.writeKey) return;
1228
+ const url = `${this.baseUrl}signals/track`;
1229
+ const opts = this.requestOpts();
1230
+ if (!opts) {
1231
+ this.warnShutdownDrop("signal");
1232
+ return;
1233
+ }
1234
+ try {
1235
+ await postJson(url, body, this.requestHeaders(), opts);
1236
+ } catch (err) {
1237
+ const msg = err instanceof Error ? err.message : String(err);
1238
+ rateLimitedLog(
1239
+ `${this.prefix}.send_signal_failed`,
1240
+ () => console.warn(`${this.prefix} failed to send signal (dropping): ${msg}`)
1241
+ );
1242
+ }
1243
+ }
1244
+ async identify(users) {
1245
+ if (!this.enabled) return;
1246
+ const destination = currentReplayTraceDestination();
1247
+ if (destination && destination.kind !== "workshop") return;
1248
+ const list = Array.isArray(users) ? users : [users];
1249
+ const body = list.filter((user) => {
1250
+ if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
1251
+ if (this.debug) {
1252
+ console.warn(`${this.prefix} skipping identify: missing userId`);
1253
+ }
1254
+ return false;
1255
+ }
1256
+ return true;
1257
+ }).map((user) => {
1258
+ var _a;
1259
+ return {
1260
+ user_id: user.userId,
1261
+ traits: (_a = user.traits) != null ? _a : {}
1262
+ };
1263
+ });
1264
+ if (!this.writeKey) return;
1265
+ if (body.length === 0) return;
1266
+ const url = `${this.baseUrl}users/identify`;
1267
+ const opts = this.requestOpts();
1268
+ if (!opts) {
1269
+ this.warnShutdownDrop("identify");
1270
+ return;
1271
+ }
1272
+ try {
1273
+ await postJson(url, body, this.requestHeaders(), opts);
1274
+ } catch (err) {
1275
+ const msg = err instanceof Error ? err.message : String(err);
1276
+ rateLimitedLog(
1277
+ `${this.prefix}.send_identify_failed`,
1278
+ () => console.warn(`${this.prefix} failed to send identify (dropping): ${msg}`)
1279
+ );
1280
+ }
1281
+ }
1282
+ warnShutdownDrop(what) {
1283
+ rateLimitedLog(
1284
+ `${this.prefix}.shutdown_deadline`,
1285
+ () => console.warn(`${this.prefix} shutdown flush deadline exceeded; dropping ${what}`)
1286
+ );
1287
+ }
1288
+ async flushOne(eventId) {
1289
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1290
+ if (!this.enabled) return;
1291
+ const timer = this.timers.get(eventId);
1292
+ if (timer) {
1293
+ clearTimeout(timer);
1294
+ this.timers.delete(eventId);
1295
+ }
1296
+ const accumulated = this.buffers.get(eventId);
1297
+ this.buffers.delete(eventId);
1298
+ if (!accumulated) return;
1299
+ const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
1300
+ const isPending = (_c = (_b = accumulated.isPending) != null ? _b : sticky.isPending) != null ? _c : true;
1301
+ const eventName = (_e = (_d = accumulated.eventName) != null ? _d : sticky.eventName) != null ? _e : this.defaultEventName;
1302
+ const userId = (_f = accumulated.userId) != null ? _f : sticky.userId;
1303
+ if (!userId) {
1304
+ if (this.debug) {
1305
+ console.warn(`${this.prefix} skipping track_partial for ${eventId}: missing userId`);
1306
+ }
1307
+ this.sticky.delete(eventId);
1308
+ return;
1309
+ }
1310
+ const { wizardSession, ...restProperties } = (_g = accumulated.properties) != null ? _g : {};
1311
+ let telemetryProperties = {};
1312
+ try {
1313
+ telemetryProperties = eventTelemetryProperties(accumulated);
1314
+ } catch (e) {
1315
+ }
1316
+ const convoId = (_h = accumulated.convoId) != null ? _h : sticky.convoId;
1317
+ const payload = {
1318
+ event_id: eventId,
1319
+ user_id: userId,
1320
+ event: eventName,
1321
+ timestamp: (_i = accumulated.timestamp) != null ? _i : (/* @__PURE__ */ new Date()).toISOString(),
1322
+ ai_data: {
1323
+ input: accumulated.input,
1324
+ output: accumulated.error !== void 0 && accumulated.error !== null ? void 0 : accumulated.output,
1325
+ model: accumulated.model,
1326
+ convo_id: convoId
1327
+ },
1328
+ properties: {
1329
+ ...restProperties,
1330
+ ...telemetryProperties,
1331
+ ...wizardSession ? { "raindrop.wizardSession": wizardSession } : {},
1332
+ $context: this.context
1333
+ },
1334
+ ...accumulated.featureFlags && Object.keys(accumulated.featureFlags).length > 0 ? { feature_flags: accumulated.featureFlags } : {},
1335
+ attachments: accumulated.attachments,
1336
+ is_pending: isPending
1337
+ };
1338
+ const url = `${this.baseUrl}events/track_partial`;
1339
+ if (this.debug) {
1340
+ console.log(`${this.prefix} sending track_partial`, {
1341
+ eventId,
1342
+ eventName,
1343
+ userId,
1344
+ convoId,
1345
+ isPending,
1346
+ inputPreview: typeof accumulated.input === "string" ? accumulated.input.slice(0, 120) : void 0,
1347
+ outputPreview: typeof accumulated.output === "string" ? accumulated.output.slice(0, 120) : void 0,
1348
+ attachments: (_k = (_j = accumulated.attachments) == null ? void 0 : _j.length) != null ? _k : 0,
1349
+ attachmentKinds: (_m = (_l = accumulated.attachments) == null ? void 0 : _l.map((a) => ({
1350
+ type: a.type,
1351
+ role: a.role,
1352
+ name: a.name,
1353
+ valuePreview: a.value.slice(0, 60)
1354
+ }))) != null ? _m : [],
1355
+ endpoint: url
1356
+ });
1357
+ }
1358
+ const mirror = this.localDebuggerUrl ? mirrorPartialEventToLocalDebugger(payload, {
1359
+ baseUrl: this.localDebuggerUrl,
1360
+ writeKey: this.writeKey,
1361
+ debug: this.debug,
1362
+ sdkName: this.sdkName
1363
+ }) : void 0;
1364
+ if (!this.writeKey) {
1365
+ if (!isPending) this.sticky.delete(eventId);
1366
+ if (mirror) await mirror;
1367
+ return;
1368
+ }
1369
+ const opts = this.requestOpts();
1370
+ if (!opts) {
1371
+ this.warnShutdownDrop(`track_partial ${eventId}`);
1372
+ if (!isPending) this.sticky.delete(eventId);
1373
+ if (mirror) await mirror;
1374
+ return;
1375
+ }
1376
+ const p = postJson(url, payload, this.requestHeaders(), opts);
1377
+ const combined = mirror ? Promise.all([mirror, p]).then(() => void 0) : p;
1378
+ this.inFlight.add(combined);
1379
+ try {
1380
+ try {
1381
+ await combined;
1382
+ if (this.debug) {
1383
+ console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
1384
+ }
1385
+ } catch (err) {
1386
+ const msg = err instanceof Error ? err.message : String(err);
1387
+ rateLimitedLog(
1388
+ `${this.prefix}.send_track_partial_failed`,
1389
+ () => console.warn(`${this.prefix} failed to send track_partial (dropping): ${msg}`)
1390
+ );
1391
+ }
1392
+ } finally {
1393
+ this.inFlight.delete(combined);
1394
+ }
1395
+ if (!isPending) {
1396
+ this.sticky.delete(eventId);
1397
+ }
1398
+ }
1399
+ };
1400
+ var MODEL_USAGE_ATTRIBUTES = {
1401
+ usageSource: "raindrop.usage.source",
1402
+ providerName: "gen_ai.provider.name",
1403
+ requestModel: "gen_ai.request.model",
1404
+ responseModel: "gen_ai.response.model",
1405
+ inputTokens: "gen_ai.usage.input_tokens",
1406
+ outputTokens: "gen_ai.usage.output_tokens",
1407
+ reasoningTokens: "gen_ai.usage.reasoning_tokens",
1408
+ cacheReadInputTokens: "gen_ai.usage.cache_read_input_tokens",
1409
+ cacheWriteInputTokens: "gen_ai.usage.cache_write_input_tokens",
1410
+ providerReportedCost: "gen_ai.usage.provider_reported_cost",
1411
+ nonCachedInputTokens: "raindrop.usage.input_tokens.non_cached",
1412
+ nonReasoningOutputTokens: "raindrop.usage.output_tokens.non_reasoning",
1413
+ totalOutputTokens: "raindrop.usage.output_tokens.total",
1414
+ reasoningOutputTokens: "raindrop.usage.output_tokens.reasoning",
1415
+ cacheReadTokens: "raindrop.usage.input_tokens.cache_read",
1416
+ cacheWriteTokens: "raindrop.usage.input_tokens.cache_write"
1417
+ };
1418
+ var MODEL_PROVIDER_NAMES = [
1419
+ ["google.vertex.anthropic", "google-vertex"],
1420
+ ["google.vertex_ai", "google-vertex"],
1421
+ ["google.vertex", "google-vertex"],
1422
+ ["gcp.vertex_ai", "google-vertex"],
1423
+ ["gcp.gemini", "google"],
1424
+ ["google_vertexai", "google-vertex"],
1425
+ ["vertex.anthropic", "google-vertex"],
1426
+ ["amazon-bedrock", "amazon-bedrock"],
1427
+ ["aws.bedrock", "amazon-bedrock"],
1428
+ ["bedrock", "amazon-bedrock"],
1429
+ ["anthropic", "anthropic"],
1430
+ ["openai", "openai"],
1431
+ ["google", "google"],
1432
+ ["az.ai.openai", "azure"],
1433
+ ["azure", "azure"],
1434
+ ["openrouter", "openrouter"]
1435
+ ];
1436
+ function canonicalModelProvider(provider) {
1437
+ var _a;
1438
+ const normalizedProvider = provider.trim().toLowerCase();
1439
+ if (normalizedProvider === "gateway") return "vercel";
1440
+ const match = MODEL_PROVIDER_NAMES.find(
1441
+ ([family]) => normalizedProvider === family || normalizedProvider.startsWith(`${family}.`)
1442
+ );
1443
+ return (_a = match == null ? void 0 : match[1]) != null ? _a : normalizedProvider;
1444
+ }
1445
+ function tokenCount(value) {
1446
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1447
+ }
1448
+ function buildRawModelUsageAttributes(usage) {
1449
+ const providerReportedCost = typeof usage.providerReportedCost === "number" && Number.isFinite(usage.providerReportedCost) && usage.providerReportedCost >= 0 ? usage.providerReportedCost : void 0;
1450
+ return [
1451
+ attrInt(MODEL_USAGE_ATTRIBUTES.inputTokens, tokenCount(usage.inputTokens)),
1452
+ attrInt(MODEL_USAGE_ATTRIBUTES.outputTokens, tokenCount(usage.outputTokens)),
1453
+ attrInt(MODEL_USAGE_ATTRIBUTES.reasoningTokens, tokenCount(usage.reasoningTokens)),
1454
+ attrInt(MODEL_USAGE_ATTRIBUTES.cacheReadInputTokens, tokenCount(usage.cacheReadInputTokens)),
1455
+ attrInt(MODEL_USAGE_ATTRIBUTES.cacheWriteInputTokens, tokenCount(usage.cacheWriteInputTokens)),
1456
+ attrDouble(MODEL_USAGE_ATTRIBUTES.providerReportedCost, providerReportedCost)
1457
+ ].filter((attribute) => attribute !== void 0);
1458
+ }
1459
+ var STRING_ALIASES = {
1460
+ [MODEL_USAGE_ATTRIBUTES.requestModel]: ["ai.model.id", "ai.model"]
1461
+ };
1462
+ var NUMBER_ALIASES = {
1463
+ [MODEL_USAGE_ATTRIBUTES.inputTokens]: [
1464
+ "gen_ai.usage.prompt_tokens",
1465
+ "ai.usage.prompt_tokens",
1466
+ "ai.usage.promptTokens",
1467
+ "ai.usage.input_tokens",
1468
+ "ai.usage.inputTokens"
1469
+ ],
1470
+ [MODEL_USAGE_ATTRIBUTES.outputTokens]: [
1471
+ "gen_ai.usage.completion_tokens",
1472
+ "ai.usage.completion_tokens",
1473
+ "ai.usage.completionTokens",
1474
+ "ai.usage.output_tokens",
1475
+ "ai.usage.outputTokens"
1476
+ ],
1477
+ [MODEL_USAGE_ATTRIBUTES.reasoningTokens]: [
1478
+ "gen_ai.usage.reasoning.output_tokens",
1479
+ "ai.usage.reasoningTokens",
1480
+ "ai.usage.thoughts_tokens"
1481
+ ],
1482
+ [MODEL_USAGE_ATTRIBUTES.cacheReadInputTokens]: [
1483
+ "gen_ai.usage.cache_read_tokens",
1484
+ "gen_ai.usage.cache_read.input_tokens",
1485
+ "ai.usage.cachedInputTokens",
1486
+ "ai.usage.cached_tokens",
1487
+ "ai.usage.cache_read_tokens",
1488
+ "ai.usage.cache_read_input_tokens",
1489
+ "ai.usage.cacheReadInputTokens"
1490
+ ],
1491
+ [MODEL_USAGE_ATTRIBUTES.cacheWriteInputTokens]: [
1492
+ "gen_ai.usage.cache_creation_input_tokens",
1493
+ "gen_ai.usage.cache_creation.input_tokens",
1494
+ "ai.usage.cacheWriteInputTokens",
1495
+ "ai.usage.cache_creation_input_tokens",
1496
+ "ai.usage.cacheCreationInputTokens"
1497
+ ]
1498
+ };
1499
+ function hasAttribute(attributes, key) {
1500
+ return attributes.some((attribute) => attribute.key === key);
1501
+ }
1502
+ function findStringAttribute(attributes, keys) {
1503
+ return attributes.find(
1504
+ (attribute) => keys.includes(attribute.key) && typeof attribute.value.stringValue === "string" && attribute.value.stringValue.length > 0
1505
+ );
1506
+ }
1507
+ function findNumberAttribute(attributes, keys) {
1508
+ return attributes.find((attribute) => {
1509
+ if (!keys.includes(attribute.key)) return false;
1510
+ if (typeof attribute.value.doubleValue === "number" && Number.isSafeInteger(attribute.value.doubleValue) && attribute.value.doubleValue >= 0) {
1511
+ return true;
1512
+ }
1513
+ const intValue = attribute.value.intValue;
1514
+ return integerValue(intValue) !== void 0;
1515
+ });
1516
+ }
1517
+ function integerValue(value) {
1518
+ if (typeof value === "number") {
1519
+ return Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1520
+ }
1521
+ if (typeof value !== "string") return void 0;
1522
+ const parsed = Number(value);
1523
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
1524
+ }
1525
+ function appendAlias(attributes, target, source) {
1526
+ if (!source || hasAttribute(attributes, target)) return attributes;
1527
+ return [...attributes, { key: target, value: { ...source.value } }];
1528
+ }
1529
+ function appendProviderAlias(attributes) {
1530
+ if (hasAttribute(attributes, MODEL_USAGE_ATTRIBUTES.providerName)) return attributes;
1531
+ const source = findStringAttribute(attributes, ["gen_ai.system", "ai.model.provider"]);
1532
+ if (!(source == null ? void 0 : source.value.stringValue)) return attributes;
1533
+ const attribute = attrString(
1534
+ MODEL_USAGE_ATTRIBUTES.providerName,
1535
+ canonicalModelProvider(source.value.stringValue)
1536
+ );
1537
+ return attribute ? [...attributes, attribute] : attributes;
1538
+ }
1539
+ function normalizeModelUsageSpan(span) {
1540
+ const original = span.attributes;
1541
+ if (!original || original.length === 0) return span;
1542
+ const responseModel = findStringAttribute(original, [
1543
+ MODEL_USAGE_ATTRIBUTES.responseModel,
1544
+ "ai.response.model"
1545
+ ]);
1546
+ if (!responseModel) return span;
1547
+ let attributes = appendAlias(original, MODEL_USAGE_ATTRIBUTES.responseModel, responseModel);
1548
+ attributes = appendProviderAlias(attributes);
1549
+ for (const [target, aliases] of Object.entries(STRING_ALIASES)) {
1550
+ attributes = appendAlias(attributes, target, findStringAttribute(attributes, aliases));
1551
+ }
1552
+ for (const [target, aliases] of Object.entries(NUMBER_ALIASES)) {
1553
+ attributes = appendAlias(attributes, target, findNumberAttribute(attributes, aliases));
1554
+ }
1555
+ return attributes === original ? span : { ...span, attributes };
1556
+ }
1557
+ var DEFAULT_SECRET_KEY_NAMES = [
1558
+ "apikey",
1559
+ "apisecret",
1560
+ "apitoken",
1561
+ "secretaccesskey",
1562
+ "sessiontoken",
1563
+ "privatekey",
1564
+ "privatekeyid",
1565
+ "clientsecret",
1566
+ "accesstoken",
1567
+ "refreshtoken",
1568
+ "oauthtoken",
1569
+ "bearertoken",
1570
+ "authorization",
1571
+ "password",
1572
+ "passphrase"
1573
+ ];
1574
+ var REDACTED_PLACEHOLDER = "[REDACTED]";
1575
+ function normalizeKeyName(name) {
1576
+ return name.toLowerCase().replace(/[-_.]/g, "");
1577
+ }
1578
+ function redactSecretsInObject(value, options) {
1579
+ var _a, _b;
1580
+ const normalizedSecretSet = buildSecretSet((_a = options == null ? void 0 : options.secretKeyNames) != null ? _a : DEFAULT_SECRET_KEY_NAMES);
1581
+ const placeholder = (_b = options == null ? void 0 : options.placeholder) != null ? _b : REDACTED_PLACEHOLDER;
1582
+ const seen = /* @__PURE__ */ new WeakSet();
1583
+ const walk = (node) => {
1584
+ if (node === null || typeof node !== "object") return node;
1585
+ if (seen.has(node)) return "[CIRCULAR]";
1586
+ seen.add(node);
1587
+ if (Array.isArray(node)) {
1588
+ return node.map((item) => walk(item));
1589
+ }
1590
+ const out = {};
1591
+ for (const [k, v] of Object.entries(node)) {
1592
+ if (normalizedSecretSet.has(normalizeKeyName(k))) {
1593
+ out[k] = placeholder;
1594
+ } else {
1595
+ out[k] = walk(v);
1596
+ }
1597
+ }
1598
+ return out;
1599
+ };
1600
+ return walk(value);
1601
+ }
1602
+ function buildSecretSet(names) {
1603
+ const set = /* @__PURE__ */ new Set();
1604
+ for (const name of names) set.add(normalizeKeyName(name));
1605
+ return set;
1606
+ }
1607
+ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
1608
+ "ai.request.providerOptions",
1609
+ "ai.response.providerMetadata"
1610
+ ];
1611
+ function defaultTransformSpan(span) {
1612
+ const attrs = span.attributes;
1613
+ if (!attrs || attrs.length === 0) return span;
1614
+ let nextAttrs;
1615
+ for (let i = 0; i < attrs.length; i++) {
1616
+ const attr = attrs[i];
1617
+ const redacted = redactJsonAttributeValue(attr.key, attr.value);
1618
+ if (redacted === void 0) continue;
1619
+ if (!nextAttrs) nextAttrs = attrs.slice();
1620
+ nextAttrs[i] = { key: attr.key, value: redacted };
1621
+ }
1622
+ if (!nextAttrs) return span;
1623
+ return { ...span, attributes: nextAttrs };
1624
+ }
1625
+ var REDACT_JSON_ATTRIBUTE_KEYS = new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
1626
+ function redactJsonAttributeValue(key, value) {
1627
+ if (!REDACT_JSON_ATTRIBUTE_KEYS.has(key)) return void 0;
1628
+ const json = value.stringValue;
1629
+ if (typeof json !== "string" || json.length === 0) return void 0;
1630
+ let parsed;
1631
+ try {
1632
+ parsed = JSON.parse(json);
1633
+ } catch (e) {
1634
+ return void 0;
1635
+ }
1636
+ const scrubbed = redactSecretsInObject(parsed);
1637
+ let scrubbedJson;
1638
+ try {
1639
+ scrubbedJson = JSON.stringify(scrubbed);
1640
+ } catch (e) {
1641
+ return void 0;
1642
+ }
1643
+ if (scrubbedJson === json) return void 0;
1644
+ return { stringValue: scrubbedJson };
1645
+ }
1646
+ function appGitOwnerId2(prefix) {
1647
+ try {
1648
+ return `${prefix}:${randomUUID()}`;
1649
+ } catch (e) {
1650
+ return `${prefix}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
1651
+ }
1652
+ }
1653
+ function identityAttrs(args) {
1654
+ return [
1655
+ attrString("ai.telemetry.metadata.raindrop.ai.userId", args.userId),
1656
+ attrString("ai.telemetry.metadata.raindrop.convoId", args.convoId),
1657
+ attrString("ai.telemetry.metadata.raindrop.eventName", args.eventName)
1658
+ ];
1659
+ }
1660
+ function applyOtelSpanAttributeLimit(limit) {
1661
+ var _a, _b;
1662
+ try {
1663
+ const raw = (_b = (_a = globalThis == null ? void 0 : globalThis.process) == null ? void 0 : _a.env) == null ? void 0 : _b.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT;
1664
+ if (!raw) return limit;
1665
+ const parsed = Number.parseInt(raw, 10);
1666
+ if (Number.isFinite(parsed) && parsed > 0) {
1667
+ return Math.min(limit, parsed);
1668
+ }
1669
+ } catch (e) {
1670
+ }
1671
+ return limit;
1672
+ }
1673
+ var TraceShipper = class {
1674
+ constructor(opts) {
1675
+ this.appGitOwner = appGitOwnerId2("trace");
1676
+ this.appGitEventIds = /* @__PURE__ */ new WeakMap();
1677
+ this.appGitActiveSpans = /* @__PURE__ */ new Map();
1678
+ this.appGitCaptured = /* @__PURE__ */ new WeakSet();
1679
+ this.appGitAdded = /* @__PURE__ */ new WeakMap();
1680
+ this.queue = [];
1681
+ this.inFlight = /* @__PURE__ */ new Set();
1682
+ this.hasShutdown = false;
1683
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1684
+ this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
1685
+ this.ownsAppGitContext = opts.appGitContext === void 0;
1686
+ this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
1687
+ this.baseUrl = (_c = formatEndpoint(opts.endpoint)) != null ? _c : "https://api.raindrop.ai/v1/";
1688
+ this.enabled = opts.enabled !== false;
1689
+ this.debug = opts.debug;
1690
+ this.debugSpans = opts.debugSpans === true;
1691
+ this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
1692
+ this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
1693
+ this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
1694
+ this.sdkName = (_g = opts.sdkName) != null ? _g : "core";
1695
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
1696
+ this.serviceName = (_h = opts.serviceName) != null ? _h : "raindrop.core";
1697
+ this.serviceVersion = (_i = opts.serviceVersion) != null ? _i : "0.0.0";
1698
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _j : void 0;
1699
+ if (this.debug && this.localDebuggerUrl) {
1700
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
1701
+ }
1702
+ this.projectId = normalizeProjectId(opts.projectId, {
1703
+ debug: this.debug,
1704
+ prefix: this.prefix
1705
+ });
1706
+ this.transformSpanHook = opts.transformSpan;
1707
+ this.disableDefaultRedaction = opts.disableDefaultRedaction === true;
1708
+ this.maxTextFieldCharsOpt = opts.maxTextFieldChars;
1709
+ }
1710
+ /**
1711
+ * Cap every string attribute value on the span. O(#attributes) length
1712
+ * checks; only oversized values pay a slice. Runs AFTER the redaction
1713
+ * pipeline so the default secret-scrub still sees parseable JSON in
1714
+ * `ai.request.providerOptions` / `ai.response.providerMetadata` (capping
1715
+ * first could cut a JSON blob mid-way, fail the parse, and ship secrets
1716
+ * in the surviving prefix).
1717
+ *
1718
+ * A stricter `OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT` env var is honored
1719
+ * for span content, matching the Python SDK and the OTel SDK convention.
1720
+ */
1721
+ capSpanAttributes(span) {
1722
+ var _a;
1723
+ const maxChars = applyOtelSpanAttributeLimit(
1724
+ resolveMaxTextFieldChars(this.maxTextFieldCharsOpt)
1725
+ );
1726
+ const attrs = span.attributes;
1727
+ if (!attrs || attrs.length === 0) return span;
1728
+ let nextAttrs;
1729
+ for (let i = 0; i < attrs.length; i++) {
1730
+ const attr = attrs[i];
1731
+ const value = (_a = attr.value) == null ? void 0 : _a.stringValue;
1732
+ if (typeof value !== "string" || value.length <= maxChars) continue;
1733
+ if (!nextAttrs) nextAttrs = attrs.slice();
1734
+ nextAttrs[i] = {
1735
+ key: attr.key,
1736
+ value: { ...attr.value, stringValue: capText(value, maxChars) }
1737
+ };
1738
+ }
1739
+ if (!nextAttrs) return span;
1740
+ return { ...span, attributes: nextAttrs };
1741
+ }
1742
+ /**
1743
+ * Apply the user `transformSpan` hook (if any) followed by the default
1744
+ * redactor (unless disabled). Returns either the (possibly new) span to
1745
+ * ship, or `null` to drop the span entirely.
1746
+ *
1747
+ * Ordering: user hook runs first so callers can rewrite the span freely
1748
+ * (rename attrs, add new ones, scrub things the default doesn't know
1749
+ * about). The default redactor then runs on whatever the user produced,
1750
+ * acting as the always-on floor for documented BYOK secrets. If the user
1751
+ * sets `disableDefaultRedaction: true`, the floor is skipped.
1752
+ *
1753
+ * Fail-closed: if the user hook throws, the span is dropped — a buggy
1754
+ * hook can never accidentally ship raw, un-redacted spans.
1755
+ */
1756
+ redactSpan(span) {
1757
+ let current = span;
1758
+ if (this.transformSpanHook) {
1759
+ try {
1760
+ const result = this.transformSpanHook(current);
1761
+ if (result === null) return null;
1762
+ if (result !== void 0) {
1763
+ copyReplayTraceDestination(current, result);
1764
+ current = result;
1765
+ }
1766
+ } catch (err) {
1767
+ if (this.debug) {
1768
+ const msg = err instanceof Error ? err.message : String(err);
1769
+ console.warn(`${this.prefix} transformSpan hook threw: ${msg}`);
1770
+ }
1771
+ return null;
1772
+ }
1773
+ }
1774
+ try {
1775
+ const normalized = normalizeModelUsageSpan(current);
1776
+ copyReplayTraceDestination(current, normalized);
1777
+ current = normalized;
1778
+ } catch (e) {
1779
+ }
1780
+ if (!this.disableDefaultRedaction) {
1781
+ const redacted = defaultTransformSpan(current);
1782
+ copyReplayTraceDestination(current, redacted);
1783
+ current = redacted;
1784
+ }
1785
+ const capped = this.capSpanAttributes(current);
1786
+ copyReplayTraceDestination(current, capped);
1787
+ return capped;
1788
+ }
1789
+ isDebugEnabled() {
1790
+ return this.debug;
1791
+ }
1792
+ authHeaders() {
1793
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
1794
+ }
1795
+ requestHeaders() {
1796
+ return { ...this.authHeaders(), ...projectIdHeaders(this.projectId) };
1797
+ }
1798
+ startSpan(args) {
1799
+ var _a, _b, _c;
1800
+ const ids = createSpanIds(args.parent);
1801
+ const started = (_a = args.startTimeUnixNano) != null ? _a : nowUnixNanoString();
1802
+ const attrs = [
1803
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1804
+ ...identityAttrs(args),
1805
+ attrString("ai.operationId", args.operationId),
1806
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1807
+ ];
1808
+ if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
1809
+ const tracksAppGit = this.appGitActiveSpans.has(args.eventId) || this.appGitActiveSpans.size < 1e4;
1810
+ const appGitOverrides = appGitPropertiesFromAttributes(attrs);
1811
+ const span = {
1812
+ ids,
1813
+ name: args.name,
1814
+ startTimeUnixNano: started,
1815
+ attributes: withAppGitAttributes(
1816
+ attrs,
1817
+ this.appGitContext.forOperation(args.eventId, appGitOverrides, this.appGitOwner)
1818
+ )
1819
+ };
1820
+ rememberReplayTraceDestination(span);
1821
+ this.appGitCaptured.add(span);
1822
+ this.appGitEventIds.set(span, args.eventId);
1823
+ if (tracksAppGit) {
1824
+ this.appGitActiveSpans.set(args.eventId, ((_c = this.appGitActiveSpans.get(args.eventId)) != null ? _c : 0) + 1);
1825
+ }
1826
+ this.appGitAdded.set(span, new Set(span.attributes.filter((attr) => !attrs.includes(attr))));
1827
+ const openSpan = buildOtlpSpan({
1828
+ ids: span.ids,
1829
+ name: span.name,
1830
+ startTimeUnixNano: span.startTimeUnixNano,
1831
+ endTimeUnixNano: span.startTimeUnixNano,
1832
+ // placeholder — will be updated on endSpan
1833
+ attributes: span.attributes,
1834
+ status: { code: SpanStatusCode.UNSET }
1835
+ });
1836
+ copyReplayTraceDestination(span, openSpan);
1837
+ this.mirrorToLocalDebugger(openSpan);
1838
+ return span;
1839
+ }
1840
+ mirrorToLocalDebugger(span, completed = false) {
1841
+ const destination = replayTraceDestinationFor(span);
1842
+ if (destination && destination.kind !== "workshop") return;
1843
+ const localDebuggerUrl = (destination == null ? void 0 : destination.kind) === "workshop" ? destination.url : this.localDebuggerUrl;
1844
+ if (!localDebuggerUrl) return;
1845
+ const redacted = this.redactSpan(span);
1846
+ if (redacted === null) return;
1847
+ if (completed && (destination == null ? void 0 : destination.kind) === "workshop") {
1848
+ recordReplayExportedSpan(
1849
+ destination,
1850
+ base64ToHex(redacted.spanId),
1851
+ base64ToHex(redacted.traceId)
1852
+ );
1853
+ }
1854
+ const body = buildExportTraceServiceRequest([redacted], this.serviceName, this.serviceVersion);
1855
+ const p = mirrorTraceExportToLocalDebugger(body, {
1856
+ baseUrl: localDebuggerUrl,
1857
+ debug: false,
1858
+ sdkName: this.sdkName
1859
+ });
1860
+ this.inFlight.add(p);
1861
+ void p.finally(() => {
1862
+ this.inFlight.delete(p);
1863
+ });
1864
+ }
1865
+ endSpan(span, extra) {
1866
+ var _a, _b, _c;
1867
+ if (span.endTimeUnixNano) return;
1868
+ span.endTimeUnixNano = (_a = extra == null ? void 0 : extra.endTimeUnixNano) != null ? _a : nowUnixNanoString();
1869
+ if ((_b = extra == null ? void 0 : extra.attributes) == null ? void 0 : _b.length) {
1870
+ const overrides = appGitPropertiesFromAttributes(extra.attributes);
1871
+ const eventId2 = this.appGitEventIds.get(span);
1872
+ const snapshot = eventId2 ? this.appGitContext.forOperation(eventId2, overrides, this.appGitOwner) : overrides;
1873
+ const added = this.appGitAdded.get(span);
1874
+ span.attributes = span.attributes.filter((attr) => !(added == null ? void 0 : added.has(attr)) || !attr || !Object.prototype.hasOwnProperty.call(overrides, APP_COMMIT_SHA) && !Object.prototype.hasOwnProperty.call(overrides, attr.key));
1875
+ span.attributes.push(...extra.attributes);
1876
+ span.attributes = withAppGitAttributes(span.attributes, snapshot);
1877
+ }
1878
+ let status = extra == null ? void 0 : extra.status;
1879
+ if (!status && (extra == null ? void 0 : extra.error) !== void 0) {
1880
+ const message = extra.error instanceof Error ? extra.error.message : String(extra.error);
1881
+ status = { code: SpanStatusCode.ERROR, message };
1882
+ }
1883
+ const otlp = buildOtlpSpan({
1884
+ ids: span.ids,
1885
+ name: span.name,
1886
+ startTimeUnixNano: span.startTimeUnixNano,
1887
+ endTimeUnixNano: span.endTimeUnixNano,
1888
+ attributes: span.attributes,
1889
+ status
1890
+ });
1891
+ copyReplayTraceDestination(span, otlp);
1892
+ this.appGitCaptured.add(otlp);
1893
+ this.enqueue(otlp);
1894
+ this.mirrorToLocalDebugger(otlp, true);
1895
+ const eventId = this.appGitEventIds.get(span);
1896
+ if (eventId && this.appGitActiveSpans.has(eventId)) {
1897
+ const remaining = ((_c = this.appGitActiveSpans.get(eventId)) != null ? _c : 1) - 1;
1898
+ if (remaining > 0) this.appGitActiveSpans.set(eventId, remaining);
1899
+ else {
1900
+ this.appGitActiveSpans.delete(eventId);
1901
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(eventId, this.appGitOwner);
1902
+ else if (this.ownsAppGitContext) this.appGitContext.finishOperation(eventId);
1903
+ }
1904
+ }
1905
+ }
1906
+ createSpan(args) {
1907
+ var _a;
1908
+ const ids = createSpanIds(args.parent);
1909
+ const attrs = [
1910
+ attrString("ai.telemetry.metadata.raindrop.eventId", args.eventId),
1911
+ ...identityAttrs(args),
1912
+ ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1913
+ ];
1914
+ if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
1915
+ const tracksAppGit = !this.appGitActiveSpans.has(args.eventId);
1916
+ const otlp = buildOtlpSpan({
1917
+ ids,
1918
+ name: args.name,
1919
+ startTimeUnixNano: args.startTimeUnixNano,
1920
+ endTimeUnixNano: args.endTimeUnixNano,
1921
+ attributes: withAppGitAttributes(
1922
+ attrs,
1923
+ this.appGitContext.forOperation(
1924
+ args.eventId,
1925
+ appGitPropertiesFromAttributes(attrs),
1926
+ this.appGitOwner
1927
+ )
1928
+ ),
1929
+ status: args.status
1930
+ });
1931
+ rememberReplayTraceDestination(otlp);
1932
+ this.appGitCaptured.add(otlp);
1933
+ if (tracksAppGit) {
1934
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(args.eventId, this.appGitOwner);
1935
+ else if (this.ownsAppGitContext) this.appGitContext.finishOperation(args.eventId);
1936
+ }
1937
+ this.enqueue(otlp);
1938
+ this.mirrorToLocalDebugger(otlp, true);
1939
+ }
1940
+ enqueue(span) {
1941
+ var _a;
1942
+ if (!this.enabled) return;
1943
+ const attributes = (_a = span.attributes) != null ? _a : [];
1944
+ const enriched = this.appGitCaptured.has(span) ? attributes : withAppGitAttributes(attributes, this.appGitContext.snapshot(appGitPropertiesFromAttributes(attributes)));
1945
+ if (enriched !== attributes) {
1946
+ const original = span;
1947
+ span = { ...span, attributes: enriched.filter((attr) => attr !== void 0) };
1948
+ copyReplayTraceDestination(original, span);
1949
+ }
1950
+ if (this.debugSpans) {
1951
+ const short = (s) => s ? s.slice(-8) : "none";
1952
+ console.log(
1953
+ `${this.prefix}[span] name=${span.name} trace=${short(span.traceId)} span=${short(span.spanId)} parent=${short(
1954
+ span.parentSpanId
1955
+ )}`
1956
+ );
1957
+ }
1958
+ const redacted = this.redactSpan(span);
1959
+ if (redacted === null) return;
1960
+ const destination = replayTraceDestinationFor(redacted);
1961
+ recordReplayExportedSpan(
1962
+ destination,
1963
+ base64ToHex(redacted.spanId),
1964
+ base64ToHex(redacted.traceId)
1965
+ );
1966
+ if ((destination == null ? void 0 : destination.kind) === "workshop") return;
1967
+ if (this.queue.length >= this.maxQueueSize) {
1968
+ this.queue.shift();
1969
+ }
1970
+ this.queue.push(redacted);
1971
+ if (this.queue.length >= this.maxBatchSize) {
1972
+ void this.flush().catch(() => {
1973
+ });
1974
+ return;
1975
+ }
1976
+ if (!this.timer) {
1977
+ this.timer = setTimeout(() => {
1978
+ this.timer = void 0;
1979
+ void this.flush().catch(() => {
1980
+ });
1981
+ }, this.flushIntervalMs);
1982
+ }
1983
+ }
1984
+ async flush() {
1985
+ var _a;
1986
+ if (!this.enabled) {
1987
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
1988
+ })));
1989
+ return;
1990
+ }
1991
+ if (this.timer) {
1992
+ clearTimeout(this.timer);
1993
+ this.timer = void 0;
1994
+ }
1995
+ while (this.queue.length > 0) {
1996
+ const batch = this.queue.splice(0, this.maxBatchSize);
1997
+ const groups = /* @__PURE__ */ new Map();
1998
+ for (const span of batch) {
1999
+ const destination = replayTraceDestinationFor(span);
2000
+ const spans = groups.get(destination);
2001
+ if (spans) spans.push(span);
2002
+ else groups.set(destination, [span]);
2003
+ }
2004
+ for (const [destination, spans] of groups) {
2005
+ if (!destination && !this.writeKey) continue;
2006
+ if ((destination == null ? void 0 : destination.kind) === "workshop") continue;
2007
+ const opts = this.requestOpts();
2008
+ if (!opts) {
2009
+ rateLimitedLog(
2010
+ `${this.prefix}.shutdown_deadline`,
2011
+ () => console.warn(
2012
+ `${this.prefix} shutdown flush deadline exceeded; dropping ${spans.length} spans`
2013
+ )
2014
+ );
2015
+ continue;
2016
+ }
2017
+ const body = buildExportTraceServiceRequest(spans, this.serviceName, this.serviceVersion);
2018
+ const url = destination ? replayTraceUrl(destination.url) : `${this.baseUrl}traces`;
2019
+ const headers = destination ? {
2020
+ Authorization: `Bearer ${destination.apiKey}`,
2021
+ "X-Raindrop-Replay-Id": destination.replayId,
2022
+ "X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
2023
+ } : this.requestHeaders();
2024
+ if (this.debug) {
2025
+ console.log(`${this.prefix} sending traces batch`, {
2026
+ spans: spans.length,
2027
+ endpoint: url
2028
+ });
2029
+ }
2030
+ const p = postJson(url, body, headers, opts);
2031
+ this.inFlight.add(p);
2032
+ try {
2033
+ try {
2034
+ await p;
2035
+ if (this.debug) console.log(`${this.prefix} sent ${spans.length} spans`);
2036
+ } catch (err) {
2037
+ const msg = err instanceof Error ? err.message : String(err);
2038
+ rateLimitedLog(
2039
+ `${this.prefix}.send_spans_failed`,
2040
+ () => console.warn(`${this.prefix} failed to send ${spans.length} spans: ${msg}`)
2041
+ );
2042
+ }
2043
+ } finally {
2044
+ this.inFlight.delete(p);
2045
+ }
2046
+ }
2047
+ }
2048
+ }
2049
+ /** See EventShipper.requestOpts — same shutdown-budget semantics. */
2050
+ requestOpts() {
2051
+ if (this.shutdownDeadlineAt !== void 0) {
2052
+ const remainingMs = this.shutdownDeadlineAt - Date.now();
2053
+ if (remainingMs <= 0) return null;
2054
+ return {
2055
+ maxAttempts: 1,
2056
+ debug: this.debug,
2057
+ sdkName: this.sdkName,
2058
+ timeoutMs: Math.min(DEFAULT_REQUEST_TIMEOUT_MS, remainingMs)
2059
+ };
2060
+ }
2061
+ if (this.hasShutdown) {
2062
+ return {
2063
+ maxAttempts: 1,
2064
+ debug: this.debug,
2065
+ sdkName: this.sdkName,
2066
+ timeoutMs: POST_SHUTDOWN_TIMEOUT_MS
2067
+ };
2068
+ }
2069
+ return { maxAttempts: 3, debug: this.debug, sdkName: this.sdkName };
2070
+ }
2071
+ async shutdown() {
2072
+ this.hasShutdown = true;
2073
+ this.shutdownDeadlineAt = Date.now() + SHUTDOWN_DEADLINE_MS;
2074
+ try {
2075
+ if (this.timer) {
2076
+ clearTimeout(this.timer);
2077
+ this.timer = void 0;
2078
+ }
2079
+ const drain = async () => {
2080
+ await this.flush();
2081
+ await Promise.all([...this.inFlight].map((p) => p.catch(() => {
2082
+ })));
2083
+ };
2084
+ const settled = await raceWithTimeout(drain(), SHUTDOWN_DEADLINE_MS);
2085
+ if (!settled) {
2086
+ rateLimitedLog(
2087
+ `${this.prefix}.shutdown_deadline`,
2088
+ () => console.warn(
2089
+ `${this.prefix} shutdown flush deadline exceeded; abandoning in-flight spans`
2090
+ )
2091
+ );
2092
+ }
2093
+ } finally {
2094
+ this.shutdownDeadlineAt = void 0;
2095
+ if (this.ownsAppGitContext) this.appGitContext.dispose();
2096
+ }
2097
+ }
2098
+ };
2099
+
2100
+ // ../core/dist/index.node.js
2101
+ var import_async_hooks = require("async_hooks");
2102
+ var import_child_process = require("child_process");
2103
+ var import_path = require("path");
2104
+ var resolveLocal = (sourceDirectory, detectBranch, completed) => {
2105
+ const cwd = sourceDirectory ? (0, import_path.resolve)(sourceDirectory) : process.cwd();
2106
+ let cancelled = false;
2107
+ let active;
2108
+ let deadlineTimer;
2109
+ const deadline = Date.now() + 1e3;
2110
+ const run = (args, done) => {
2111
+ if (cancelled) return;
2112
+ const remaining = deadline - Date.now();
2113
+ if (remaining <= 0) {
2114
+ done(void 0);
2115
+ return;
2116
+ }
2117
+ try {
2118
+ active = (0, import_child_process.execFile)(
2119
+ "git",
2120
+ args,
2121
+ {
2122
+ cwd,
2123
+ encoding: "utf8",
2124
+ maxBuffer: 4096,
2125
+ windowsHide: true,
2126
+ env: {
2127
+ ...process.env,
2128
+ // The selected application cwd, not the invoking shell's Git plumbing, owns identity.
2129
+ GIT_DIR: void 0,
2130
+ GIT_WORK_TREE: void 0,
2131
+ GIT_COMMON_DIR: void 0,
2132
+ GIT_NAMESPACE: void 0,
2133
+ GIT_INDEX_FILE: void 0,
2134
+ GIT_OBJECT_DIRECTORY: void 0,
2135
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: void 0,
2136
+ GIT_CONFIG_PARAMETERS: void 0,
2137
+ GIT_CONFIG_COUNT: "0",
2138
+ GIT_TERMINAL_PROMPT: "0",
2139
+ GIT_OPTIONAL_LOCKS: "0"
2140
+ }
2141
+ },
2142
+ (error, stdout) => {
2143
+ clearTimeout(deadlineTimer);
2144
+ deadlineTimer = void 0;
2145
+ active = void 0;
2146
+ if (!cancelled) {
2147
+ try {
2148
+ done(error ? void 0 : stdout.trim());
2149
+ } catch (e) {
2150
+ }
2151
+ }
2152
+ }
2153
+ );
2154
+ active.unref();
2155
+ if (active.stdout && "unref" in active.stdout && typeof active.stdout.unref === "function")
2156
+ active.stdout.unref();
2157
+ if (active.stderr && "unref" in active.stderr && typeof active.stderr.unref === "function")
2158
+ active.stderr.unref();
2159
+ deadlineTimer = setTimeout(() => {
2160
+ try {
2161
+ active == null ? void 0 : active.kill("SIGKILL");
2162
+ } catch (e) {
2163
+ }
2164
+ }, remaining);
2165
+ deadlineTimer.unref();
2166
+ } catch (e) {
2167
+ try {
2168
+ done(void 0);
2169
+ } catch (e2) {
2170
+ }
2171
+ }
2172
+ };
2173
+ const scheduled = setTimeout(() => {
2174
+ try {
2175
+ run(["rev-parse", "HEAD"], (rawSha) => {
2176
+ const commitSha = validAppCommitSha(rawSha);
2177
+ if (!commitSha) {
2178
+ completed({});
2179
+ return;
2180
+ }
2181
+ run(["-c", "core.fsmonitor=false", "status", "--porcelain"], (status) => {
2182
+ const finish = (branch) => {
2183
+ run(["rev-parse", "HEAD"], (finalSha) => {
2184
+ const coherent = validAppCommitSha(finalSha) === commitSha;
2185
+ completed({
2186
+ commitSha,
2187
+ ...coherent && status !== void 0 ? { commitDirty: status !== "" } : {},
2188
+ ...coherent && branch && branch !== "HEAD" ? { branch } : {}
2189
+ });
2190
+ });
2191
+ };
2192
+ if (detectBranch) run(["symbolic-ref", "--quiet", "--short", "HEAD"], finish);
2193
+ else finish();
2194
+ });
2195
+ });
2196
+ } catch (e) {
2197
+ completed({});
2198
+ }
2199
+ }, 0);
2200
+ scheduled.unref();
2201
+ return () => {
2202
+ cancelled = true;
2203
+ clearTimeout(scheduled);
2204
+ clearTimeout(deadlineTimer);
2205
+ try {
2206
+ active == null ? void 0 : active.kill("SIGKILL");
2207
+ } catch (e) {
2208
+ }
2209
+ };
2210
+ };
2211
+ function createAppGitContext2(options, runtime = {}) {
2212
+ return new AppGitContext(options, { ...runtime, resolveLocal });
2213
+ }
2214
+ function hasDestination(options) {
2215
+ var _a;
2216
+ if (options.enabled === false) return false;
2217
+ return Boolean(((_a = options.writeKey) == null ? void 0 : _a.trim()) || resolveLocalDebuggerBaseUrl(options.localDebuggerUrl));
2218
+ }
2219
+ var EventShipper2 = class extends EventShipper {
2220
+ constructor(options) {
2221
+ var _a;
2222
+ const ownsAppGitContext = options.appGitContext === void 0;
2223
+ const appGitContext = (_a = options.appGitContext) != null ? _a : createAppGitContext2(options.appGit, { allowDiscovery: hasDestination(options) });
2224
+ try {
2225
+ super({ ...options, appGitContext });
2226
+ } catch (error) {
2227
+ if (ownsAppGitContext) appGitContext.dispose();
2228
+ throw error;
2229
+ }
2230
+ if (ownsAppGitContext) this.ownAppGitContextForShutdown();
2231
+ }
2232
+ };
2233
+ var TraceShipper2 = class extends TraceShipper {
2234
+ constructor(options) {
2235
+ var _a;
2236
+ const ownsAppGitContext = options.appGitContext === void 0;
2237
+ const appGitContext = (_a = options.appGitContext) != null ? _a : createAppGitContext2(options.appGit, { allowDiscovery: hasDestination(options) });
2238
+ try {
2239
+ super({ ...options, appGitContext });
2240
+ } catch (error) {
2241
+ if (ownsAppGitContext) appGitContext.dispose();
2242
+ throw error;
2243
+ }
2244
+ this.ownsAppGitContext = ownsAppGitContext;
2245
+ }
2246
+ };
2247
+ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = import_async_hooks.AsyncLocalStorage;
2248
+ var SUPPRESS_TRACING_KEY = /* @__PURE__ */ Symbol.for(
2249
+ "OpenTelemetry SDK Context Key SUPPRESS_TRACING"
2250
+ );
2251
+ function findOtelContextManager() {
2252
+ var _a;
2253
+ for (const sym of Object.getOwnPropertySymbols(globalThis)) {
2254
+ if (!((_a = sym.description) == null ? void 0 : _a.startsWith("opentelemetry.js.api."))) continue;
2255
+ const api = globalThis[sym];
2256
+ const cm = api == null ? void 0 : api.context;
2257
+ if (cm && typeof cm.with === "function" && typeof cm.active === "function") {
2258
+ return cm;
2259
+ }
2260
+ }
2261
+ return void 0;
2262
+ }
2263
+ function installTracingSuppressionHook() {
2264
+ if (typeof globalThis.RAINDROP_SUPPRESS_TRACING === "function") return;
2265
+ const hook = (fn) => {
2266
+ const cm = findOtelContextManager();
2267
+ if (!cm) return fn();
2268
+ return cm.with(cm.active().setValue(SUPPRESS_TRACING_KEY, true), fn);
2269
+ };
2270
+ globalThis.RAINDROP_SUPPRESS_TRACING = hook;
2271
+ }
2272
+ installTracingSuppressionHook();
2273
+
2274
+ // src/config.ts
2275
+ var import_node_fs = require("fs");
2276
+ var import_node_os = require("os");
2277
+ var import_node_path = require("path");
2278
+ function loadConfig(projectDirectory) {
2279
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2280
+ let merged = {};
2281
+ const configPaths = [
2282
+ (0, import_node_path.join)((0, import_node_os.homedir)(), ".config", "opencode", "raindrop.json"),
2283
+ (0, import_node_path.join)(projectDirectory, ".opencode", "raindrop.json")
2284
+ ];
2285
+ for (const configPath of configPaths) {
2286
+ try {
2287
+ if ((0, import_node_fs.existsSync)(configPath)) {
2288
+ const content = (0, import_node_fs.readFileSync)(configPath, "utf-8");
2289
+ const parsed = JSON.parse(content);
2290
+ merged = { ...merged, ...parsed };
2291
+ }
2292
+ } catch (e) {
2293
+ }
2294
+ }
2295
+ let eventMetadata;
2296
+ const envMeta = process.env["RAINDROP_EVENT_METADATA"];
2297
+ if (envMeta) {
2298
+ try {
2299
+ eventMetadata = JSON.parse(envMeta);
2300
+ } catch (e) {
2301
+ }
2302
+ }
2303
+ return {
2304
+ writeKey: (_b = (_a = process.env["RAINDROP_WRITE_KEY"]) != null ? _a : merged.write_key) != null ? _b : "",
2305
+ endpoint: (_d = (_c = process.env["RAINDROP_API_URL"]) != null ? _c : merged.api_url) != null ? _d : "https://api.raindrop.ai/v1",
2306
+ projectId: (_e = process.env["RAINDROP_PROJECT_ID"]) != null ? _e : merged.project_id,
2307
+ eventName: (_f = merged.event_name) != null ? _f : "opencode_session",
2308
+ debug: process.env["RAINDROP_DEBUG"] === "true" ? true : (_g = merged.debug) != null ? _g : false,
2309
+ captureSystemPrompt: process.env["RAINDROP_CAPTURE_SYSTEM_PROMPT"] !== void 0 ? process.env["RAINDROP_CAPTURE_SYSTEM_PROMPT"] === "true" : (_h = merged.capture_system_prompt) != null ? _h : false,
2310
+ eventMetadata,
2311
+ localWorkshopUrl: resolveLocalWorkshopUrl(merged.local_workshop_url),
2312
+ appGit: mapAppGit(merged.app_git)
2313
+ };
2314
+ }
2315
+ function mapAppGit(value) {
2316
+ if (value === false) return false;
2317
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
2318
+ return {
2319
+ commitSha: "commit_sha" in value && (typeof value.commit_sha === "string" || value.commit_sha === null) ? value.commit_sha : void 0,
2320
+ commitDirty: "commit_dirty" in value && (typeof value.commit_dirty === "boolean" || value.commit_dirty === null) ? value.commit_dirty : void 0,
2321
+ branch: "branch" in value && (typeof value.branch === "string" || value.branch === null) ? value.branch : void 0,
2322
+ detectBranch: "detect_branch" in value && typeof value.detect_branch === "boolean" ? value.detect_branch : void 0,
2323
+ sourceDirectory: "source_directory" in value && typeof value.source_directory === "string" ? value.source_directory : void 0,
2324
+ autoDetect: "auto_detect" in value && typeof value.auto_detect === "boolean" ? value.auto_detect : void 0
2325
+ };
2326
+ }
2327
+ function resolveLocalWorkshopUrl(fileValue) {
2328
+ const envValue = process.env["RAINDROP_LOCAL_WORKSHOP_URL"];
2329
+ if (envValue !== void 0) {
2330
+ if (envValue === "" || envValue.toLowerCase() === "null" || envValue.toLowerCase() === "false") {
2331
+ return null;
2332
+ }
2333
+ return envValue;
2334
+ }
2335
+ return fileValue;
2336
+ }
2337
+
2338
+ // package.json
2339
+ var package_default = {
2340
+ name: "@raindrop-ai/opencode-plugin",
2341
+ version: "0.2.0",
2342
+ description: "Raindrop observability plugin for OpenCode \u2014 automatic session/event/span tracing",
2343
+ type: "module",
2344
+ main: "dist/index.js",
2345
+ module: "dist/index.js",
2346
+ types: "dist/index.d.ts",
2347
+ license: "MIT",
2348
+ homepage: "https://www.raindrop.ai/docs/integrations/opencode/",
2349
+ bugs: {
2350
+ url: "https://www.raindrop.ai/docs/support/"
2351
+ },
2352
+ exports: {
2353
+ ".": {
2354
+ types: "./dist/index.d.ts",
2355
+ import: "./dist/index.js",
2356
+ require: "./dist/index.cjs"
2357
+ },
2358
+ "./v2": {
2359
+ types: "./dist/v2.d.ts",
2360
+ import: "./dist/v2.js",
2361
+ require: "./dist/v2.cjs"
2362
+ }
2363
+ },
2364
+ sideEffects: false,
2365
+ files: [
2366
+ "dist/**"
2367
+ ],
2368
+ scripts: {
2369
+ build: "tsup",
2370
+ dev: "tsup --watch",
2371
+ clean: "rm -rf dist",
2372
+ test: "cd tests && pnpm test"
2373
+ },
2374
+ peerDependencies: {
2375
+ "@opencode-ai/plugin": ">=1.3.0",
2376
+ "@opencode-ai/sdk": ">=1.3.0",
2377
+ "@opencode/plugin": ">=2.0.0",
2378
+ "@opencode/sdk": ">=2.0.0"
2379
+ },
2380
+ peerDependenciesMeta: {
2381
+ "@opencode-ai/plugin": {
2382
+ optional: true
2383
+ },
2384
+ "@opencode-ai/sdk": {
2385
+ optional: true
2386
+ },
2387
+ "@opencode/plugin": {
2388
+ optional: true
2389
+ },
2390
+ "@opencode/sdk": {
2391
+ optional: true
2392
+ }
2393
+ },
2394
+ devDependencies: {
2395
+ "@raindrop-ai/core": "workspace:*",
2396
+ "@opencode-ai/plugin": "^1.3.3",
2397
+ "@opencode-ai/sdk": "^1.3.3",
2398
+ "@opencode/plugin": "^2.0.10",
2399
+ "@opencode/sdk": "^2.0.10",
2400
+ "@types/node": "^20.11.17",
2401
+ tsup: "^8.4.0",
2402
+ typescript: "^5.3.3"
2403
+ },
2404
+ tsup: {
2405
+ entry: [
2406
+ "src/index.ts",
2407
+ "src/v2.ts"
2408
+ ],
2409
+ format: [
2410
+ "cjs",
2411
+ "esm"
2412
+ ],
2413
+ dts: {
2414
+ resolve: true
2415
+ },
2416
+ clean: true,
2417
+ noExternal: [
2418
+ "@raindrop-ai/core"
2419
+ ]
2420
+ },
2421
+ publishConfig: {
2422
+ access: "public"
2423
+ }
2424
+ };
2425
+
2426
+ // src/package-info.ts
2427
+ var PLUGIN_NAME = package_default.name;
2428
+ var PLUGIN_VERSION = package_default.version;
2429
+
2430
+ // src/shipper.ts
2431
+ var EventShipper3 = class extends EventShipper2 {
2432
+ constructor(opts) {
2433
+ var _a, _b, _c, _d;
2434
+ super({
2435
+ ...opts,
2436
+ sdkName: (_a = opts.sdkName) != null ? _a : "opencode-plugin",
2437
+ libraryName: (_b = opts.libraryName) != null ? _b : PLUGIN_NAME,
2438
+ libraryVersion: (_c = opts.libraryVersion) != null ? _c : PLUGIN_VERSION,
2439
+ defaultEventName: (_d = opts.defaultEventName) != null ? _d : "opencode_session"
2440
+ });
2441
+ }
2442
+ };
2443
+ var TraceShipper3 = class extends TraceShipper2 {
2444
+ constructor(opts) {
2445
+ var _a, _b, _c;
2446
+ super({
2447
+ ...opts,
2448
+ sdkName: (_a = opts.sdkName) != null ? _a : "opencode-plugin",
2449
+ serviceName: (_b = opts.serviceName) != null ? _b : "raindrop.opencode-plugin",
2450
+ serviceVersion: (_c = opts.serviceVersion) != null ? _c : PLUGIN_VERSION
2451
+ });
2452
+ }
2453
+ enqueue(span) {
2454
+ var _a;
2455
+ const attrs = (_a = span.attributes) != null ? _a : [];
2456
+ attrs.unshift(
2457
+ { key: "span.id", value: { stringValue: span.spanId } },
2458
+ ...span.parentSpanId ? [{ key: "span.parent.id", value: { stringValue: span.parentSpanId } }] : []
2459
+ );
2460
+ span.attributes = attrs;
2461
+ super.enqueue(span);
2462
+ }
2463
+ };
2464
+
2465
+ // src/tracing-v2.ts
2466
+ var import_node_os2 = require("os");
2467
+
2468
+ // src/bounded.ts
2469
+ var TRUNCATION_MARKER2 = "...[truncated by raindrop]";
2470
+ var MAX_TEXT_FIELD_CHARS = 1e6;
2471
+ var MAX_BOUNDED_DEPTH = 12;
2472
+ function truncateToLimit2(text, limit) {
2473
+ if (text.length <= limit) return text;
2474
+ if (limit > TRUNCATION_MARKER2.length) {
2475
+ return text.slice(0, limit - TRUNCATION_MARKER2.length) + TRUNCATION_MARKER2;
2476
+ }
2477
+ return text.slice(0, limit);
2478
+ }
2479
+ function capText2(value, limit = MAX_TEXT_FIELD_CHARS) {
2480
+ if (value.length <= limit) return value;
2481
+ return truncateToLimit2(value, limit);
2482
+ }
2483
+ function boundedClone2(value, budget, depth) {
2484
+ if (budget.remaining <= 0) return TRUNCATION_MARKER2;
2485
+ if (typeof value === "string") {
2486
+ if (value.length > budget.remaining) {
2487
+ const taken = value.slice(0, Math.max(0, budget.remaining)) + TRUNCATION_MARKER2;
2488
+ budget.remaining = 0;
2489
+ return taken;
2490
+ }
2491
+ budget.remaining -= Math.max(value.length, 1);
2492
+ return value;
2493
+ }
2494
+ if (value === null || typeof value === "number" || typeof value === "boolean") {
2495
+ budget.remaining -= 8;
2496
+ return value;
2497
+ }
2498
+ if (typeof value !== "object") {
2499
+ budget.remaining -= 8;
2500
+ return value;
2501
+ }
2502
+ if (depth >= MAX_BOUNDED_DEPTH) {
2503
+ budget.remaining -= 16;
2504
+ return `<max depth: ${TRUNCATION_MARKER2}>`;
2505
+ }
2506
+ const withToJson = value;
2507
+ if (typeof withToJson.toJSON === "function") {
2508
+ try {
2509
+ return boundedClone2(withToJson.toJSON(), budget, depth + 1);
2510
+ } catch (e) {
2511
+ }
2512
+ }
2513
+ if (Array.isArray(value)) {
2514
+ const out2 = [];
2515
+ for (const item of value) {
2516
+ if (budget.remaining <= 0) {
2517
+ out2.push(TRUNCATION_MARKER2);
2518
+ break;
2519
+ }
2520
+ out2.push(boundedClone2(item, budget, depth + 1));
2521
+ }
2522
+ return out2;
2523
+ }
2524
+ const out = {};
2525
+ for (const key of Object.keys(value)) {
2526
+ if (budget.remaining <= 0) {
2527
+ out["..."] = TRUNCATION_MARKER2;
2528
+ break;
2529
+ }
2530
+ budget.remaining -= Math.max(key.length, 1);
2531
+ out[key] = boundedClone2(value[key], budget, depth + 1);
2532
+ }
2533
+ return out;
2534
+ }
2535
+ function boundedStringify(value, limit = MAX_TEXT_FIELD_CHARS) {
2536
+ var _a;
2537
+ try {
2538
+ if (typeof value === "string") {
2539
+ return truncateToLimit2(JSON.stringify(capText2(value, limit)), limit);
2540
+ }
2541
+ const pruned = boundedClone2(value, { remaining: limit + TRUNCATION_MARKER2.length + 256 }, 0);
2542
+ return truncateToLimit2((_a = JSON.stringify(pruned)) != null ? _a : "", limit);
2543
+ } catch (e) {
2544
+ return capText2(String(value), limit);
2545
+ }
2546
+ }
2547
+
2548
+ // src/model-spend.ts
2549
+ function parseOpenCodeAssistantTokens(tokens) {
2550
+ const input = tokens["input"];
2551
+ const output = tokens["output"];
2552
+ if (typeof input !== "number" || typeof output !== "number") return void 0;
2553
+ const reasoning = tokens["reasoning"];
2554
+ const cache = tokens["cache"];
2555
+ const cacheObj = cache && typeof cache === "object" && cache !== null ? cache : void 0;
2556
+ return {
2557
+ input,
2558
+ output,
2559
+ reasoning: typeof reasoning === "number" ? reasoning : 0,
2560
+ cacheRead: typeof (cacheObj == null ? void 0 : cacheObj["read"]) === "number" ? cacheObj["read"] : 0,
2561
+ cacheWrite: typeof (cacheObj == null ? void 0 : cacheObj["write"]) === "number" ? cacheObj["write"] : 0
2562
+ };
2563
+ }
2564
+ function modelSpendSpanAttributes(input) {
2565
+ const providerAttr = attrString("gen_ai.provider.name", canonicalModelProvider(input.providerID));
2566
+ const usageAttrs = buildRawModelUsageAttributes({
2567
+ inputTokens: input.tokens.input,
2568
+ outputTokens: input.tokens.output,
2569
+ reasoningTokens: input.tokens.reasoning,
2570
+ cacheReadInputTokens: input.tokens.cacheRead,
2571
+ cacheWriteInputTokens: input.tokens.cacheWrite
2572
+ });
2573
+ return providerAttr ? [providerAttr, ...usageAttrs] : usageAttrs;
2574
+ }
2575
+ function buildLlmGenAiAttributes(input) {
2576
+ const parsed = parseOpenCodeAssistantTokens(input.tokens);
2577
+ if (!parsed) return [];
2578
+ return [
2579
+ // OpenCode has already normalized both token axes. Provenance lets Dawn
2580
+ // select that contract without the SDK or customer declaring semantics.
2581
+ attrString(MODEL_USAGE_ATTRIBUTES.usageSource, "opencode"),
2582
+ attrString("gen_ai.system", input.providerID),
2583
+ attrString("gen_ai.request.model", input.modelID),
2584
+ attrString("gen_ai.response.model", input.modelID),
2585
+ ...modelSpendSpanAttributes({ providerID: input.providerID, tokens: parsed })
2586
+ ].filter((attribute) => attribute !== void 0);
2587
+ }
2588
+
2589
+ // src/tracing-v2.ts
2590
+ var ERROR_LOG_INTERVAL_MS = 3e4;
2591
+ var lastErrorLogAt = /* @__PURE__ */ new Map();
2592
+ function rateLimitedErrorLog(key, message) {
2593
+ const now = Date.now();
2594
+ const last = lastErrorLogAt.get(key);
2595
+ if (last !== void 0 && now - last < ERROR_LOG_INTERVAL_MS) return;
2596
+ lastErrorLogAt.set(key, now);
2597
+ console.log(message);
2598
+ }
2599
+ function unwrapQuotes(s) {
2600
+ if (s.length < 2) return s;
2601
+ const first = s[0];
2602
+ const last = s[s.length - 1];
2603
+ if ((first === '"' || first === "'") && first === last) return s.slice(1, -1);
2604
+ return s;
2605
+ }
2606
+ function buildPromptMessages(systemPrompt, userInput) {
2607
+ const messages = [];
2608
+ if (systemPrompt) messages.push({ role: "system", content: systemPrompt });
2609
+ messages.push({ role: "user", content: unwrapQuotes(userInput) });
2610
+ return JSON.stringify(messages);
2611
+ }
2612
+ function getHostname() {
2613
+ var _a;
2614
+ try {
2615
+ const bunGlobal = globalThis;
2616
+ if ((_a = bunGlobal.Bun) == null ? void 0 : _a.hostname) return bunGlobal.Bun.hostname;
2617
+ return (0, import_node_os2.hostname)();
2618
+ } catch (e) {
2619
+ const h = process.env["HOSTNAME"];
2620
+ if (h === void 0 || h === "") throw new Error("HOSTNAME env is not set");
2621
+ return h;
2622
+ }
2623
+ }
2624
+ function msToNs(ms) {
2625
+ return `${String(Math.floor(ms))}000000`;
2626
+ }
2627
+ var IMAGE_NAME_RE = /\.(png|jpe?g|gif|webp|bmp|avif|svg)$/i;
2628
+ function isImageAttachment(file) {
2629
+ var _a;
2630
+ if (file.uri.startsWith("data:image/")) return true;
2631
+ return IMAGE_NAME_RE.test((_a = file.name) != null ? _a : "") || IMAGE_NAME_RE.test(file.uri);
2632
+ }
2633
+ function errorString(error) {
2634
+ return `${error.message}
2635
+
2636
+ type: ${error.type}`;
2637
+ }
2638
+ function createV2Tracing(config, eventShipper, traceShipper, sessionLookup) {
2639
+ const sessions = /* @__PURE__ */ new Map();
2640
+ const admittedPrompts = /* @__PURE__ */ new Map();
2641
+ const subagentLinks = /* @__PURE__ */ new Map();
2642
+ const hostname = getHostname();
2643
+ const os = process.platform;
2644
+ function getOrCreateState(sessionID) {
2645
+ let state2 = sessions.get(sessionID);
2646
+ if (!state2) {
2647
+ state2 = {
2648
+ sessionId: sessionID,
2649
+ input: "",
2650
+ outputParts: /* @__PURE__ */ new Map(),
2651
+ reasoningParts: /* @__PURE__ */ new Map(),
2652
+ turnOutputParts: [],
2653
+ turnOutputTokens: 0,
2654
+ turnInputTokens: 0,
2655
+ stepSpans: /* @__PURE__ */ new Map(),
2656
+ toolStarts: /* @__PURE__ */ new Map(),
2657
+ toolNames: /* @__PURE__ */ new Map()
2658
+ };
2659
+ sessions.set(sessionID, state2);
2660
+ }
2661
+ return state2;
2662
+ }
2663
+ function unlinkedSubagentParent(parent) {
2664
+ var _a, _b;
2665
+ const running = [...parent.toolStarts.values()].at(-1);
2666
+ return (_b = running == null ? void 0 : running.span.ids) != null ? _b : (_a = parent.rootSpan) == null ? void 0 : _a.ids;
2667
+ }
2668
+ function systemPromptAttrs(state2) {
2669
+ if (!state2.systemPrompt) return [];
2670
+ return [
2671
+ attrString("gen_ai.prompt.0.role", "system"),
2672
+ attrString("gen_ai.prompt.0.content", state2.systemPrompt)
2673
+ ];
2674
+ }
2675
+ async function finalizeTurn(state2, error) {
2676
+ var _a, _b, _c;
2677
+ for (const step of state2.stepSpans.values()) {
2678
+ traceShipper.endSpan(step.span);
2679
+ }
2680
+ state2.stepSpans.clear();
2681
+ if (state2.compactionSpan) {
2682
+ traceShipper.endSpan(state2.compactionSpan);
2683
+ state2.compactionSpan = void 0;
2684
+ }
2685
+ for (const start of state2.toolStarts.values()) {
2686
+ traceShipper.endSpan(start.span);
2687
+ }
2688
+ state2.toolStarts.clear();
2689
+ state2.outputParts.clear();
2690
+ state2.reasoningParts.clear();
2691
+ state2.toolNames.clear();
2692
+ if (state2.rootSpan) {
2693
+ const attrs = [];
2694
+ if (state2.parentId) {
2695
+ attrs.push(
2696
+ attrString("is_subagent", "true"),
2697
+ attrString("parent_session_id", state2.parentId)
2698
+ );
2699
+ }
2700
+ attrs.push(attrString("message_id", state2.lastAssistantMessageId));
2701
+ traceShipper.endSpan(state2.rootSpan, {
2702
+ attributes: attrs,
2703
+ error
2704
+ });
2705
+ state2.rootSpan = void 0;
2706
+ }
2707
+ const eventId = state2.eventId;
2708
+ state2.eventId = void 0;
2709
+ if (eventId && !state2.parentId) {
2710
+ const turnOutput = capText2(state2.turnOutputParts.join("\n\n"));
2711
+ await eventShipper.finish(eventId, {
2712
+ userId: (_b = (_a = state2.eventMetadata) == null ? void 0 : _a.userId) != null ? _b : state2.sessionId,
2713
+ model: (_c = state2.lastModel) == null ? void 0 : _c.modelID,
2714
+ output: turnOutput.length > 0 ? turnOutput : void 0,
2715
+ usage: {
2716
+ promptTokens: state2.turnInputTokens,
2717
+ completionTokens: state2.turnOutputTokens
2718
+ },
2719
+ error: error ? { message: error } : void 0,
2720
+ properties: {
2721
+ plugin_version: PLUGIN_VERSION,
2722
+ opencode_version: "v2",
2723
+ ...state2.lastModel ? { "ai.provider": state2.lastModel.providerID } : {},
2724
+ ...state2.lastAssistantMessageId ? { message_id: state2.lastAssistantMessageId } : {}
2725
+ }
2726
+ });
2727
+ }
2728
+ await Promise.all([eventShipper.flush(), traceShipper.flush()]);
2729
+ }
2730
+ return {
2731
+ currentEventId(sessionID) {
2732
+ var _a;
2733
+ return (_a = sessions.get(sessionID)) == null ? void 0 : _a.eventId;
2734
+ },
2735
+ // ------------------------------------------------------------------
2736
+ // prompt hook — record the admitted prompt; the turn opens on delivery
2737
+ // ------------------------------------------------------------------
2738
+ onPrompt(input, directory) {
2739
+ var _a, _b, _c;
2740
+ try {
2741
+ const textParts = [];
2742
+ const attachments = [];
2743
+ const prompt = input.prompt;
2744
+ if (typeof prompt.text === "string" && prompt.text.length > 0) {
2745
+ textParts.push(prompt.text);
2746
+ }
2747
+ for (const file of (_a = prompt.files) != null ? _a : []) {
2748
+ if (isImageAttachment(file)) {
2749
+ attachments.push({
2750
+ type: "image",
2751
+ role: "input",
2752
+ name: file.name,
2753
+ value: file.uri
2754
+ });
2755
+ }
2756
+ }
2757
+ const baseMeta = { ...config.eventMetadata };
2758
+ const promptMeta = {};
2759
+ const meta = input.metadata;
2760
+ if (meta != null && typeof meta === "object") {
2761
+ if (typeof meta["userId"] === "string") promptMeta.userId = meta["userId"];
2762
+ if (typeof meta["eventName"] === "string") promptMeta.eventName = meta["eventName"];
2763
+ if (meta["properties"] != null && typeof meta["properties"] === "object")
2764
+ promptMeta.properties = meta["properties"];
2765
+ }
2766
+ admittedPrompts.set(input.messageID, {
2767
+ sessionID: input.sessionID,
2768
+ directory,
2769
+ text: capText2(textParts.join("\n")),
2770
+ attachments,
2771
+ eventMetadata: {
2772
+ ...baseMeta,
2773
+ ...promptMeta,
2774
+ properties: baseMeta.properties || promptMeta.properties ? { ...(_b = baseMeta.properties) != null ? _b : {}, ...(_c = promptMeta.properties) != null ? _c : {} } : void 0
2775
+ }
2776
+ });
2777
+ } catch (err) {
2778
+ rateLimitedErrorLog(
2779
+ "prompt",
2780
+ `[raindrop-ai/opencode-plugin] [error] Error in prompt hook: ${err instanceof Error ? err.message : String(err)}`
2781
+ );
2782
+ }
2783
+ },
2784
+ onContext(input) {
2785
+ onContextImpl(input);
2786
+ },
2787
+ onEvent(event) {
2788
+ return onEventImpl(event);
2789
+ }
2790
+ };
2791
+ async function startTurn(prompt, deliveredAt) {
2792
+ var _a, _b, _c, _d, _e, _f, _g;
2793
+ const sessionID = prompt.sessionID;
2794
+ const directory = prompt.directory;
2795
+ const state2 = getOrCreateState(sessionID);
2796
+ const link = subagentLinks.get(sessionID);
2797
+ subagentLinks.delete(sessionID);
2798
+ if (link) state2.parentId = link.parentSessionId;
2799
+ if (state2.parentId === void 0 && sessionLookup) {
2800
+ try {
2801
+ const info = await sessionLookup(sessionID);
2802
+ if (info == null ? void 0 : info.parentID) state2.parentId = info.parentID;
2803
+ } catch (e) {
2804
+ }
2805
+ }
2806
+ if (state2.eventId || state2.rootSpan) {
2807
+ await finalizeTurn(state2);
2808
+ }
2809
+ state2.eventMetadata = prompt.eventMetadata;
2810
+ const userText = prompt.text;
2811
+ const newAttachments = prompt.attachments;
2812
+ state2.input = userText;
2813
+ state2.turnOutputParts = [];
2814
+ state2.turnOutputTokens = 0;
2815
+ state2.turnInputTokens = 0;
2816
+ state2.lastModel = void 0;
2817
+ state2.lastAssistantMessageId = void 0;
2818
+ state2.outputParts.clear();
2819
+ state2.reasoningParts.clear();
2820
+ state2.toolNames.clear();
2821
+ if (state2.parentId) {
2822
+ const parent = sessions.get(state2.parentId);
2823
+ const eventId = (_a = link == null ? void 0 : link.eventId) != null ? _a : parent == null ? void 0 : parent.eventId;
2824
+ const parentSpan = (_b = link == null ? void 0 : link.toolSpan) != null ? _b : parent ? unlinkedSubagentParent(parent) : void 0;
2825
+ if (!eventId || !parentSpan) return;
2826
+ state2.eventId = eventId;
2827
+ state2.rootSpan = traceShipper.startSpan({
2828
+ name: "Subagent",
2829
+ parent: parentSpan,
2830
+ eventId: state2.eventId,
2831
+ startTimeUnixNano: msToNs(deliveredAt),
2832
+ operationId: "ai.subagent",
2833
+ attributes: [
2834
+ attrString("workspace", directory),
2835
+ attrString("directory", directory),
2836
+ attrString("hostname", hostname),
2837
+ attrString("os", os),
2838
+ attrString("is_subagent", "true"),
2839
+ attrString("parent_session_id", state2.parentId)
2840
+ ]
2841
+ });
2842
+ return;
2843
+ }
2844
+ state2.eventId = generateId();
2845
+ state2.rootSpan = traceShipper.startSpan({
2846
+ name: "ai.event",
2847
+ eventId: state2.eventId,
2848
+ startTimeUnixNano: msToNs(deliveredAt),
2849
+ operationId: "ai.event",
2850
+ attributes: [
2851
+ attrString("workspace", directory),
2852
+ attrString("directory", directory),
2853
+ attrString("hostname", hostname),
2854
+ attrString("os", os)
2855
+ ]
2856
+ });
2857
+ await eventShipper.patch(state2.eventId, {
2858
+ isPending: true,
2859
+ userId: (_d = (_c = state2.eventMetadata) == null ? void 0 : _c.userId) != null ? _d : state2.sessionId,
2860
+ convoId: state2.sessionId,
2861
+ eventName: (_f = (_e = state2.eventMetadata) == null ? void 0 : _e.eventName) != null ? _f : config.eventName,
2862
+ input: userText,
2863
+ ...newAttachments.length > 0 ? { attachments: newAttachments } : {},
2864
+ properties: {
2865
+ workspace: directory,
2866
+ directory,
2867
+ hostname,
2868
+ os,
2869
+ plugin_version: PLUGIN_VERSION,
2870
+ opencode_version: "v2",
2871
+ ...(_g = state2.eventMetadata) == null ? void 0 : _g.properties
2872
+ }
2873
+ });
2874
+ }
2875
+ function onContextImpl(input) {
2876
+ try {
2877
+ if (!config.captureSystemPrompt) return;
2878
+ const state2 = getOrCreateState(input.sessionID);
2879
+ const MAX_SYSTEM_PROMPT_LENGTH = 32768;
2880
+ const TRUNCATION_MARKER3 = "\n...[truncated]";
2881
+ const joined = input.system.map((part) => part.text).join("\n\n");
2882
+ state2.systemPrompt = joined.length > MAX_SYSTEM_PROMPT_LENGTH ? joined.slice(0, MAX_SYSTEM_PROMPT_LENGTH - TRUNCATION_MARKER3.length) + TRUNCATION_MARKER3 : joined;
2883
+ } catch (err) {
2884
+ rateLimitedErrorLog(
2885
+ "context",
2886
+ `[raindrop-ai/opencode-plugin] [error] Error in context hook: ${err instanceof Error ? err.message : String(err)}`
2887
+ );
2888
+ }
2889
+ }
2890
+ async function onEventImpl(event) {
2891
+ var _a, _b, _c, _d, _e;
2892
+ switch (event.type) {
2893
+ case "session.created": {
2894
+ const data = event.data;
2895
+ const state2 = getOrCreateState(data.sessionID);
2896
+ state2.parentId = data.parentID;
2897
+ break;
2898
+ }
2899
+ case "session.inbox.delivered": {
2900
+ const prompt = admittedPrompts.get(event.data.inboxID);
2901
+ if (!prompt) return;
2902
+ admittedPrompts.delete(event.data.inboxID);
2903
+ await startTurn(prompt, event.created);
2904
+ break;
2905
+ }
2906
+ case "session.inbox.cancelled": {
2907
+ admittedPrompts.delete(event.data.inboxID);
2908
+ break;
2909
+ }
2910
+ case "session.step.started": {
2911
+ const data = event.data;
2912
+ const state2 = sessions.get(data.sessionID);
2913
+ if (!state2 || !state2.eventId) return;
2914
+ const parent = (_a = state2.rootSpan) == null ? void 0 : _a.ids;
2915
+ if (!parent) return;
2916
+ const span = traceShipper.startSpan({
2917
+ name: `${data.model.providerID}/${data.model.id}`,
2918
+ parent,
2919
+ eventId: state2.eventId,
2920
+ startTimeUnixNano: msToNs(data.started),
2921
+ attributes: [
2922
+ attrString("ai.operationId", "generateText"),
2923
+ attrString("ai.prompt", unwrapQuotes(state2.input)),
2924
+ attrString(
2925
+ "ai.prompt.messages",
2926
+ buildPromptMessages(state2.systemPrompt, state2.input)
2927
+ )
2928
+ ]
2929
+ });
2930
+ state2.stepSpans.set(data.assistantMessageID, {
2931
+ span,
2932
+ providerID: data.model.providerID,
2933
+ modelID: data.model.id
2934
+ });
2935
+ break;
2936
+ }
2937
+ case "session.step.ended": {
2938
+ const data = event.data;
2939
+ const state2 = sessions.get(data.sessionID);
2940
+ const step = state2 == null ? void 0 : state2.stepSpans.get(data.assistantMessageID);
2941
+ if (!state2 || !step) return;
2942
+ state2.stepSpans.delete(data.assistantMessageID);
2943
+ const text = state2.outputParts.get(data.assistantMessageID);
2944
+ if (text !== void 0 && text.trim().length > 0) {
2945
+ state2.turnOutputParts.push(text);
2946
+ }
2947
+ state2.turnOutputTokens += data.tokens.output;
2948
+ state2.turnInputTokens = data.tokens.input;
2949
+ state2.lastModel = { providerID: step.providerID, modelID: step.modelID };
2950
+ state2.lastAssistantMessageId = data.assistantMessageID;
2951
+ const attrs = [
2952
+ attrString("ai.response.text", text !== void 0 ? capText2(text) : void 0),
2953
+ ...systemPromptAttrs(state2),
2954
+ ...buildLlmGenAiAttributes({
2955
+ providerID: step.providerID,
2956
+ modelID: step.modelID,
2957
+ tokens: data.tokens
2958
+ })
2959
+ ];
2960
+ const reasoning = state2.reasoningParts.get(data.assistantMessageID);
2961
+ if (reasoning !== void 0) {
2962
+ attrs.push(attrString("ai.reasoning.text", reasoning));
2963
+ }
2964
+ traceShipper.endSpan(step.span, { attributes: attrs });
2965
+ break;
2966
+ }
2967
+ case "session.step.failed": {
2968
+ const data = event.data;
2969
+ const state2 = sessions.get(data.sessionID);
2970
+ const step = state2 == null ? void 0 : state2.stepSpans.get(data.assistantMessageID);
2971
+ if (!state2 || !step) return;
2972
+ state2.stepSpans.delete(data.assistantMessageID);
2973
+ traceShipper.endSpan(step.span, { error: errorString(data.error) });
2974
+ break;
2975
+ }
2976
+ case "session.text.ended": {
2977
+ const data = event.data;
2978
+ const state2 = sessions.get(data.sessionID);
2979
+ if (!state2) return;
2980
+ const prev = (_b = state2.outputParts.get(data.assistantMessageID)) != null ? _b : "";
2981
+ state2.outputParts.set(data.assistantMessageID, capText2(prev + data.text));
2982
+ break;
2983
+ }
2984
+ case "session.reasoning.ended": {
2985
+ const data = event.data;
2986
+ const state2 = sessions.get(data.sessionID);
2987
+ if (!state2) return;
2988
+ const prev = (_c = state2.reasoningParts.get(data.assistantMessageID)) != null ? _c : "";
2989
+ state2.reasoningParts.set(data.assistantMessageID, capText2(prev + data.text));
2990
+ break;
2991
+ }
2992
+ case "session.tool.input.started": {
2993
+ const data = event.data;
2994
+ const state2 = sessions.get(data.sessionID);
2995
+ if (!state2) return;
2996
+ state2.toolNames.set(data.id, data.name);
2997
+ break;
2998
+ }
2999
+ case "session.tool.called": {
3000
+ const data = event.data;
3001
+ const state2 = sessions.get(data.sessionID);
3002
+ if (!state2 || !state2.eventId) return;
3003
+ const parent = (_d = state2.rootSpan) == null ? void 0 : _d.ids;
3004
+ if (!parent) return;
3005
+ const name = (_e = state2.toolNames.get(data.id)) != null ? _e : "tool";
3006
+ const span = traceShipper.startSpan({
3007
+ name: "ai.toolCall",
3008
+ parent,
3009
+ eventId: state2.eventId,
3010
+ startTimeUnixNano: msToNs(event.created),
3011
+ attributes: [
3012
+ attrString("ai.operationId", "ai.toolCall"),
3013
+ attrString("ai.toolCall.name", name),
3014
+ attrString("ai.toolCall.id", data.id)
3015
+ ]
3016
+ });
3017
+ state2.toolStarts.set(data.id, {
3018
+ span,
3019
+ name,
3020
+ input: boundedStringify(data.input)
3021
+ });
3022
+ break;
3023
+ }
3024
+ case "session.tool.progress": {
3025
+ const data = event.data;
3026
+ const childSessionId = data.metadata["sessionID"];
3027
+ if (typeof childSessionId !== "string") return;
3028
+ const state2 = sessions.get(data.sessionID);
3029
+ const start = state2 == null ? void 0 : state2.toolStarts.get(data.id);
3030
+ if (!(state2 == null ? void 0 : state2.eventId) || !start) return;
3031
+ subagentLinks.set(childSessionId, {
3032
+ parentSessionId: data.sessionID,
3033
+ toolSpan: start.span.ids,
3034
+ eventId: state2.eventId
3035
+ });
3036
+ break;
3037
+ }
3038
+ case "session.tool.success": {
3039
+ const data = event.data;
3040
+ const state2 = sessions.get(data.sessionID);
3041
+ const start = state2 == null ? void 0 : state2.toolStarts.get(data.id);
3042
+ if (!state2 || !start) return;
3043
+ state2.toolStarts.delete(data.id);
3044
+ traceShipper.endSpan(start.span, {
3045
+ attributes: [
3046
+ attrString("ai.toolCall.args", start.input),
3047
+ attrString("ai.toolCall.result", boundedStringify(data.content))
3048
+ ]
3049
+ });
3050
+ break;
3051
+ }
3052
+ case "session.tool.failed": {
3053
+ const data = event.data;
3054
+ const state2 = sessions.get(data.sessionID);
3055
+ const start = state2 == null ? void 0 : state2.toolStarts.get(data.id);
3056
+ if (!state2 || !start) return;
3057
+ state2.toolStarts.delete(data.id);
3058
+ traceShipper.endSpan(start.span, {
3059
+ attributes: [
3060
+ attrString("ai.toolCall.args", start.input),
3061
+ attrString("error.message", data.error.message),
3062
+ ...data.content !== void 0 ? [attrString("ai.toolCall.result", boundedStringify(data.content))] : []
3063
+ ],
3064
+ error: errorString(data.error)
3065
+ });
3066
+ break;
3067
+ }
3068
+ case "session.compaction.started": {
3069
+ const data = event.data;
3070
+ const state2 = sessions.get(data.sessionID);
3071
+ if (!state2 || !state2.eventId || !state2.rootSpan) return;
3072
+ state2.compactionSpan = traceShipper.startSpan({
3073
+ name: "ai.compaction",
3074
+ parent: state2.rootSpan.ids,
3075
+ eventId: state2.eventId,
3076
+ attributes: [
3077
+ attrString("ai.operationId", "ai.compaction"),
3078
+ attrString("ai.compaction.reason", data.reason)
3079
+ ]
3080
+ });
3081
+ break;
3082
+ }
3083
+ case "session.compaction.ended": {
3084
+ const data = event.data;
3085
+ const state2 = sessions.get(data.sessionID);
3086
+ if (!state2 || !state2.compactionSpan) return;
3087
+ const span = state2.compactionSpan;
3088
+ state2.compactionSpan = void 0;
3089
+ const attrs = [
3090
+ attrString("ai.response.text", capText2(data.text))
3091
+ ];
3092
+ if (data.model && data.tokens) {
3093
+ attrs.push(
3094
+ ...buildLlmGenAiAttributes({
3095
+ providerID: data.model.providerID,
3096
+ modelID: data.model.id,
3097
+ tokens: data.tokens
3098
+ })
3099
+ );
3100
+ }
3101
+ if (data.cost !== void 0) {
3102
+ attrs.push(attrString("ai.compaction.cost", String(data.cost)));
3103
+ }
3104
+ traceShipper.endSpan(span, { attributes: attrs });
3105
+ break;
3106
+ }
3107
+ case "session.compaction.failed": {
3108
+ const data = event.data;
3109
+ const state2 = sessions.get(data.sessionID);
3110
+ if (!state2 || !state2.compactionSpan) return;
3111
+ traceShipper.endSpan(state2.compactionSpan, {
3112
+ error: errorString(data.error)
3113
+ });
3114
+ state2.compactionSpan = void 0;
3115
+ break;
3116
+ }
3117
+ case "session.execution.succeeded": {
3118
+ const state2 = sessions.get(event.data.sessionID);
3119
+ if (!state2) return;
3120
+ await finalizeTurn(state2);
3121
+ break;
3122
+ }
3123
+ case "session.execution.interrupted": {
3124
+ const state2 = sessions.get(event.data.sessionID);
3125
+ if (!state2) return;
3126
+ await finalizeTurn(state2);
3127
+ break;
3128
+ }
3129
+ case "session.execution.failed": {
3130
+ const state2 = sessions.get(event.data.sessionID);
3131
+ if (!state2) return;
3132
+ await finalizeTurn(state2, errorString(event.data.error));
3133
+ break;
3134
+ }
3135
+ case "session.deleted": {
3136
+ for (const [messageID, prompt] of admittedPrompts) {
3137
+ if (prompt.sessionID === event.data.sessionID) admittedPrompts.delete(messageID);
3138
+ }
3139
+ subagentLinks.delete(event.data.sessionID);
3140
+ const state2 = sessions.get(event.data.sessionID);
3141
+ if (!state2) return;
3142
+ if (state2.eventId || state2.rootSpan) {
3143
+ try {
3144
+ await finalizeTurn(state2);
3145
+ } catch (e) {
3146
+ }
3147
+ }
3148
+ sessions.delete(event.data.sessionID);
3149
+ break;
3150
+ }
3151
+ }
3152
+ }
3153
+ }
3154
+
3155
+ // src/v2.ts
3156
+ var RESUBSCRIBE_DELAY_MS = 1e3;
3157
+ function appLog(level, message) {
3158
+ console.log(`[raindrop-ai/opencode-plugin] [${level}] ${message}`);
3159
+ }
3160
+ function errorMessage(err) {
3161
+ return err instanceof Error ? err.message : String(err);
3162
+ }
3163
+ function firstInstance(s) {
3164
+ for (const instance of s.instances) return instance;
3165
+ return void 0;
3166
+ }
3167
+ async function disposeAll(disposables) {
3168
+ for (const disposable of [...disposables].reverse()) {
3169
+ try {
3170
+ await disposable.dispose();
3171
+ } catch (e) {
3172
+ }
3173
+ }
3174
+ disposables.length = 0;
3175
+ }
3176
+ function raindrop(opts = {}) {
3177
+ let shared;
3178
+ async function shutdownShared() {
3179
+ const s = shared;
3180
+ if (!s) return;
3181
+ shared = void 0;
3182
+ for (const instance of s.instances) await disposeAll(instance.disposables);
3183
+ s.instances.clear();
3184
+ s.abort.abort();
3185
+ try {
3186
+ await Promise.all([s.eventShipper.shutdown(), s.traceShipper.shutdown()]);
3187
+ } finally {
3188
+ try {
3189
+ s.appGitContext.dispose();
3190
+ } catch (e) {
3191
+ }
3192
+ }
3193
+ }
3194
+ async function removeInstance(s, instance) {
3195
+ await disposeAll(instance.disposables);
3196
+ s.instances.delete(instance);
3197
+ if (shared === s && s.instances.size === 0) await shutdownShared();
3198
+ }
3199
+ async function runEventLoop(s) {
3200
+ while (!s.abort.signal.aborted) {
3201
+ const instance = firstInstance(s);
3202
+ if (!instance) return;
3203
+ try {
3204
+ for await (const event of instance.ctx.event.subscribe({ signal: s.abort.signal })) {
3205
+ try {
3206
+ await s.runtime.onEvent(event);
3207
+ } catch (err) {
3208
+ rateLimitedErrorLog(
3209
+ "event",
3210
+ `[raindrop-ai/opencode-plugin] [error] Error in event dispatch: ${errorMessage(err)}`
3211
+ );
3212
+ }
3213
+ }
3214
+ } catch (err) {
3215
+ if (s.abort.signal.aborted) return;
3216
+ rateLimitedErrorLog(
3217
+ "subscribe",
3218
+ `[raindrop-ai/opencode-plugin] [error] Event subscription ended, resubscribing: ${errorMessage(err)}`
3219
+ );
3220
+ }
3221
+ if (s.abort.signal.aborted) return;
3222
+ await new Promise((resolve2) => setTimeout(resolve2, RESUBSCRIBE_DELAY_MS).unref());
3223
+ }
3224
+ }
3225
+ function createShared(ctx) {
3226
+ var _a, _b, _c;
3227
+ const config = loadConfig((_a = opts.directory) != null ? _a : ctx.location.directory);
3228
+ const resolvedLocalUrl = resolveLocalDebuggerBaseUrl(config.localWorkshopUrl);
3229
+ const hasLocalDestination = resolvedLocalUrl !== null;
3230
+ if (!config.writeKey && !hasLocalDestination) {
3231
+ appLog(
3232
+ "warn",
3233
+ "RAINDROP_WRITE_KEY not set and no local Workshop daemon detected \u2014 Raindrop tracing disabled. Set RAINDROP_WRITE_KEY for cloud, or RAINDROP_LOCAL_WORKSHOP_URL / RAINDROP_LOCAL_DEBUGGER for local-only mode."
3234
+ );
3235
+ return void 0;
3236
+ }
3237
+ if (config.debug) {
3238
+ const destinations = [
3239
+ config.writeKey ? `cloud (${config.endpoint})` : null,
3240
+ resolvedLocalUrl ? `local Workshop (${resolvedLocalUrl})` : null
3241
+ ].filter(Boolean);
3242
+ appLog("info", `Raindrop tracing enabled \u2014 destinations: ${destinations.join(", ")}`);
3243
+ }
3244
+ const configuredAppGit = (_b = opts.appGit) != null ? _b : config.appGit;
3245
+ const appGitContext = createAppGitContext2(
3246
+ ((_c = config.writeKey) == null ? void 0 : _c.trim()) || hasLocalDestination ? configuredAppGit : false,
3247
+ { allowLocalGit: false }
3248
+ );
3249
+ const shipperOptions = {
3250
+ writeKey: config.writeKey,
3251
+ endpoint: config.endpoint,
3252
+ debug: config.debug,
3253
+ projectId: config.projectId,
3254
+ localDebuggerUrl: config.localWorkshopUrl,
3255
+ appGitContext
3256
+ };
3257
+ const eventShipper = new EventShipper3(shipperOptions);
3258
+ const traceShipper = new TraceShipper3(shipperOptions);
3259
+ const s = {
3260
+ eventShipper,
3261
+ traceShipper,
3262
+ appGitContext,
3263
+ abort: new AbortController(),
3264
+ instances: /* @__PURE__ */ new Set(),
3265
+ runtime: createV2Tracing(config, eventShipper, traceShipper, async (sessionID) => {
3266
+ const instance = firstInstance(s);
3267
+ if (!instance) return void 0;
3268
+ const info = await instance.ctx.session.get({ sessionID });
3269
+ return { parentID: info.parentID };
3270
+ })
3271
+ };
3272
+ return s;
3273
+ }
3274
+ const handle = {
3275
+ users: {
3276
+ async identify(users) {
3277
+ await (shared == null ? void 0 : shared.eventShipper.identify(users));
3278
+ }
3279
+ },
3280
+ signals: {
3281
+ async track(signal) {
3282
+ await (shared == null ? void 0 : shared.eventShipper.trackSignal(signal));
3283
+ }
3284
+ },
3285
+ currentEventId(sessionID) {
3286
+ return shared == null ? void 0 : shared.runtime.currentEventId(sessionID);
3287
+ },
3288
+ async flush() {
3289
+ const s = shared;
3290
+ if (!s) return;
3291
+ await Promise.all([s.eventShipper.flush(), s.traceShipper.flush()]);
3292
+ },
3293
+ async shutdown() {
3294
+ await shutdownShared();
3295
+ }
3296
+ };
3297
+ const plugin = import_plugin.Plugin.define({
3298
+ id: "raindrop",
3299
+ async setup(ctx) {
3300
+ appLog("info", `Loading ${PLUGIN_NAME} v${PLUGIN_VERSION} (v2)`);
3301
+ let s;
3302
+ const instance = { ctx, disposables: [] };
3303
+ try {
3304
+ s = shared != null ? shared : createShared(ctx);
3305
+ if (!s) return;
3306
+ const isFirst = shared === void 0;
3307
+ shared = s;
3308
+ s.instances.add(instance);
3309
+ const runtime = s.runtime;
3310
+ const directory = ctx.location.directory;
3311
+ instance.disposables.push(await ctx.session.hook("prompt", (e) => runtime.onPrompt(e, directory)));
3312
+ instance.disposables.push(await ctx.session.hook("context", (e) => runtime.onContext(e)));
3313
+ if (isFirst) void runEventLoop(s);
3314
+ const owner = s;
3315
+ return async () => {
3316
+ await removeInstance(owner, instance);
3317
+ };
3318
+ } catch (err) {
3319
+ rateLimitedErrorLog("setup", `[raindrop-ai/opencode-plugin] [error] Setup failed: ${errorMessage(err)}`);
3320
+ if (s) await removeInstance(s, instance);
3321
+ return () => {
3322
+ };
3323
+ }
3324
+ }
3325
+ });
3326
+ return Object.assign(plugin, { raindrop: handle });
3327
+ }