@raindrop-ai/eve 0.0.22 → 0.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,9 +1,792 @@
1
1
  import { trace } from '@opentelemetry/api';
2
2
  import { createRaindropAISDK, getCurrentParentToolContext } from '@raindrop-ai/ai-sdk';
3
- import { createRequire } from 'module';
4
3
  import { AsyncLocalStorage } from 'async_hooks';
4
+ import { execFile } from 'child_process';
5
+ import { resolve } from 'path';
6
+ import { createRequire } from 'module';
5
7
 
6
8
  // src/index.ts
9
+
10
+ // ../core/dist/chunk-WJOR6M7H.js
11
+ function getAsyncLocalStorageCtor() {
12
+ return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
13
+ }
14
+ var MAX_BINDING_STACK = 128;
15
+ var EMPTY_STACK = [];
16
+ var ContextStackStorage = class {
17
+ /** Emitted once when this runtime cannot support an ambient push. */
18
+ constructor(noAmbientBindWarning) {
19
+ this.noAmbientBindWarning = noAmbientBindWarning;
20
+ this._als = null;
21
+ this._enterWithUsable = false;
22
+ this._syncStack = EMPTY_STACK;
23
+ this._adoptionChecked = false;
24
+ this._warnedNoAmbientBind = false;
25
+ }
26
+ maybeAdoptAsyncLocalStorage() {
27
+ if (this._adoptionChecked) return;
28
+ this._adoptionChecked = true;
29
+ const Ctor = getAsyncLocalStorageCtor();
30
+ if (!Ctor) return;
31
+ const als = new Ctor();
32
+ try {
33
+ als.run(EMPTY_STACK, () => {
34
+ });
35
+ } catch (e) {
36
+ return;
37
+ }
38
+ this._als = als;
39
+ if (typeof als.enterWith === "function") {
40
+ try {
41
+ als.enterWith(EMPTY_STACK);
42
+ this._enterWithUsable = true;
43
+ } catch (e) {
44
+ this._enterWithUsable = false;
45
+ }
46
+ }
47
+ }
48
+ getStack() {
49
+ var _a;
50
+ this.maybeAdoptAsyncLocalStorage();
51
+ if (this._als) return (_a = this._als.getStore()) != null ? _a : this._syncStack;
52
+ return this._syncStack;
53
+ }
54
+ /**
55
+ * Persist an ambient stack mutation. Returns false when an ALS is adopted but
56
+ * `enterWith` is unusable (workerd): callers must NOT fall back to the
57
+ * process-shared sync stack, since concurrent isolates would cross-stamp.
58
+ */
59
+ setAmbientStack(stack) {
60
+ if (this._als) {
61
+ if (!this._enterWithUsable) return false;
62
+ this._als.enterWith(stack);
63
+ return true;
64
+ }
65
+ this._syncStack = stack;
66
+ return true;
67
+ }
68
+ push(binding) {
69
+ this.maybeAdoptAsyncLocalStorage();
70
+ if (this._als && !this._enterWithUsable) {
71
+ this.warnNoAmbientBindOnce();
72
+ return;
73
+ }
74
+ let stack = this.getStack();
75
+ if (stack.length >= MAX_BINDING_STACK) {
76
+ stack = stack.filter((b) => b.isLive());
77
+ if (stack.length >= MAX_BINDING_STACK) {
78
+ stack = stack.slice(stack.length - (MAX_BINDING_STACK - 1));
79
+ }
80
+ }
81
+ this.setAmbientStack([...stack, binding]);
82
+ }
83
+ remove(binding) {
84
+ binding.markDead();
85
+ const stack = this.getStack();
86
+ const pruned = stack.filter((b) => b !== binding && b.isLive());
87
+ if (pruned.length !== stack.length) {
88
+ this.setAmbientStack(pruned);
89
+ }
90
+ }
91
+ runWith(binding, callback) {
92
+ this.maybeAdoptAsyncLocalStorage();
93
+ if (this._als) {
94
+ return this._als.run([...this.getStack(), binding], callback);
95
+ }
96
+ const previous = this._syncStack;
97
+ this._syncStack = [...previous, binding];
98
+ try {
99
+ return callback();
100
+ } finally {
101
+ this._syncStack = previous;
102
+ }
103
+ }
104
+ current() {
105
+ const stack = this.getStack();
106
+ if (stack.length === 0) return void 0;
107
+ const top = stack[stack.length - 1];
108
+ if (top.isLive()) return top;
109
+ const pruned = stack.filter((b) => b.isLive());
110
+ this.setAmbientStack(pruned);
111
+ return pruned.length > 0 ? pruned[pruned.length - 1] : void 0;
112
+ }
113
+ warnNoAmbientBindOnce() {
114
+ if (this._warnedNoAmbientBind) return;
115
+ this._warnedNoAmbientBind = true;
116
+ console.warn(this.noAmbientBindWarning);
117
+ }
118
+ };
119
+ 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.";
120
+ var ROUTING_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.routingContextStorage");
121
+ function routingStorage() {
122
+ const holder = globalThis;
123
+ let storage = holder[ROUTING_STORAGE_KEY];
124
+ if (!storage) {
125
+ storage = new ContextStackStorage(NO_AMBIENT_ROUTING_BIND_WARNING);
126
+ holder[ROUTING_STORAGE_KEY] = storage;
127
+ }
128
+ return storage;
129
+ }
130
+ function currentRoutingBinding() {
131
+ const bound = routingStorage().current();
132
+ if (!bound) return void 0;
133
+ return {
134
+ projectId: bound.projectId,
135
+ authHint: bound.authHint,
136
+ ...bound.appGit ? { appGit: bound.appGit } : {},
137
+ ...bound.appGitSource ? { appGitSource: bound.appGitSource } : {}
138
+ };
139
+ }
140
+ var APP_COMMIT_SHA = "raindrop.app.commit_sha";
141
+ var APP_COMMIT_DIRTY = "raindrop.app.commit_dirty";
142
+ var APP_BRANCH = "raindrop.app.branch";
143
+ var APP_GIT_KEYS = [APP_COMMIT_SHA, APP_COMMIT_DIRTY, APP_BRANCH];
144
+ var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
145
+ function appGitExplicitKeys(properties) {
146
+ const keys = /* @__PURE__ */ new Set();
147
+ if (!properties) return keys;
148
+ for (const key of APP_GIT_KEYS) {
149
+ if (own(properties, key)) keys.add(key);
150
+ }
151
+ return keys;
152
+ }
153
+ function mergeAppGitSnapshot(base, properties, explicitKeys = /* @__PURE__ */ new Set()) {
154
+ try {
155
+ const result = { ...base };
156
+ if (properties && own(properties, APP_COMMIT_SHA) && properties[APP_COMMIT_SHA] !== result[APP_COMMIT_SHA]) {
157
+ if (!explicitKeys.has(APP_COMMIT_DIRTY) && !own(properties, APP_COMMIT_DIRTY)) {
158
+ delete result[APP_COMMIT_DIRTY];
159
+ }
160
+ if (!explicitKeys.has(APP_BRANCH) && !own(properties, APP_BRANCH)) {
161
+ delete result[APP_BRANCH];
162
+ }
163
+ }
164
+ for (const key of APP_GIT_KEYS) {
165
+ if (properties && own(properties, key)) result[key] = properties[key];
166
+ }
167
+ return Object.freeze(result);
168
+ } catch (e) {
169
+ return Object.freeze({});
170
+ }
171
+ }
172
+ function validAppCommitSha(value) {
173
+ if (typeof value !== "string" || value.length > 128) return void 0;
174
+ const cleaned = value.trim();
175
+ return /^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(cleaned) ? cleaned.toLowerCase() : void 0;
176
+ }
177
+ function shortString(value) {
178
+ if (typeof value !== "string" || value.length > 1024) return void 0;
179
+ const cleaned = value.trim();
180
+ return cleaned.length > 0 ? cleaned : void 0;
181
+ }
182
+ function flag(value) {
183
+ if (value === true || value === "true" || value === "1") return true;
184
+ if (value === false || value === "false" || value === "0") return false;
185
+ return void 0;
186
+ }
187
+ function environment() {
188
+ try {
189
+ return typeof process === "undefined" ? {} : process.env;
190
+ } catch (e) {
191
+ return {};
192
+ }
193
+ }
194
+ var DEPLOYMENTS = [
195
+ ["VERCEL", "VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
196
+ ["NETLIFY", "COMMIT_REF", "BRANCH"],
197
+ ["RAILWAY_ENVIRONMENT_NAME", "RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH"],
198
+ ["RAILWAY_ENVIRONMENT", "RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH"],
199
+ ["RENDER", "RENDER_GIT_COMMIT", "RENDER_GIT_BRANCH"],
200
+ ["DYNO", "HEROKU_BUILD_COMMIT", ""],
201
+ ["DYNO", "HEROKU_SLUG_COMMIT", ""],
202
+ ["AWS_APP_ID", "AWS_COMMIT_ID", "AWS_BRANCH"],
203
+ ["WORKERS_CI", "WORKERS_CI_COMMIT_SHA", "WORKERS_CI_BRANCH"]
204
+ ];
205
+ var CI_SOURCES = [
206
+ ["GITHUB_ACTIONS", "GITHUB_SHA", "GITHUB_REF_NAME"],
207
+ ["GITLAB_CI", "CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
208
+ ["CIRCLECI", "CIRCLE_SHA1", "CIRCLE_BRANCH"]
209
+ ];
210
+ function detectedSource(env, table, detectBranch) {
211
+ for (const row of table) {
212
+ const [marker, shaKey, branchKey] = row;
213
+ if (!marker || !shaKey || !shortString(env[marker]) || flag(env[marker]) === false) continue;
214
+ const commitSha = validAppCommitSha(env[shaKey]);
215
+ if (commitSha)
216
+ return {
217
+ commitSha,
218
+ ...detectBranch && branchKey ? { branch: shortString(env[branchKey]) } : {}
219
+ };
220
+ }
221
+ return {};
222
+ }
223
+ var AppGitContextImpl = class {
224
+ constructor(options, runtime = {}) {
225
+ this.defaults = {};
226
+ this.explicit = {};
227
+ this.explicitKeys = /* @__PURE__ */ new Set();
228
+ this.disposed = false;
229
+ this.operations = /* @__PURE__ */ new Map();
230
+ this.operationOverflow = false;
231
+ this.detectBranch = false;
232
+ this.disabled = false;
233
+ var _a, _b, _c, _d, _e, _f;
234
+ try {
235
+ if (options === false) {
236
+ this.disabled = true;
237
+ return;
238
+ }
239
+ const opts = options != null ? options : {};
240
+ const env = (_a = runtime.env) != null ? _a : environment();
241
+ const detectBranch = (_c = (_b = flag(opts.detectBranch)) != null ? _b : flag(env.RAINDROP_GIT_DETECT_BRANCH)) != null ? _c : false;
242
+ this.detectBranch = detectBranch;
243
+ const collectBranch = detectBranch || runtime.captureLegacyReplayBranch === true;
244
+ const autoDetect = runtime.allowDiscovery === false ? false : (_e = (_d = flag(opts.autoDetect)) != null ? _d : flag(env.RAINDROP_GIT_AUTO_DETECT)) != null ? _e : true;
245
+ const configuredSha = opts.commitSha;
246
+ const explicitSha = configuredSha === void 0 ? env.RAINDROP_COMMIT_SHA : configuredSha;
247
+ if (explicitSha === null) this.explicit[APP_COMMIT_SHA] = null;
248
+ else if (typeof explicitSha === "string" && validAppCommitSha(explicitSha))
249
+ this.explicit[APP_COMMIT_SHA] = explicitSha;
250
+ const configuredDirty = opts.commitDirty;
251
+ const explicitDirty = configuredDirty === void 0 ? flag(env.RAINDROP_COMMIT_DIRTY) : configuredDirty;
252
+ if (explicitDirty === null || typeof explicitDirty === "boolean")
253
+ this.explicit[APP_COMMIT_DIRTY] = explicitDirty;
254
+ const configuredBranch = opts.branch;
255
+ const explicitBranch = configuredBranch === void 0 ? env.RAINDROP_BRANCH : configuredBranch;
256
+ if (explicitBranch === null) this.explicit[APP_BRANCH] = null;
257
+ else if (typeof explicitBranch === "string" && explicitBranch.length <= 1024)
258
+ this.explicit[APP_BRANCH] = explicitBranch;
259
+ this.explicitKeys = appGitExplicitKeys(this.explicit);
260
+ this.defaults = { ...this.explicit };
261
+ if (!autoDetect || explicitSha !== void 0) return;
262
+ const sourceDirectory = (_f = shortString(opts.sourceDirectory)) != null ? _f : shortString(env.RAINDROP_GIT_SOURCE_DIRECTORY);
263
+ if (runtime.allowLocalGit === false && !sourceDirectory) return;
264
+ const deploy = sourceDirectory ? {} : detectedSource(env, DEPLOYMENTS, collectBranch);
265
+ if (deploy.commitSha) {
266
+ this.accept(deploy);
267
+ return;
268
+ }
269
+ const fallback = sourceDirectory ? {} : detectedSource(env, CI_SOURCES, collectBranch);
270
+ if (runtime.resolveLocal && (runtime.allowLocalGit !== false || sourceDirectory)) {
271
+ this.cancel = runtime.resolveLocal(sourceDirectory, collectBranch, (result) => {
272
+ try {
273
+ if (!this.disposed) this.accept(result.commitSha ? result : fallback);
274
+ } catch (e) {
275
+ }
276
+ });
277
+ } else this.accept(fallback);
278
+ } catch (e) {
279
+ }
280
+ }
281
+ accept(result) {
282
+ const sha = validAppCommitSha(result.commitSha);
283
+ if (!sha) return;
284
+ this.replayBranch = shortString(result.branch);
285
+ this.defaults = {
286
+ [APP_COMMIT_SHA]: sha,
287
+ ...typeof result.commitDirty === "boolean" ? { [APP_COMMIT_DIRTY]: result.commitDirty } : {},
288
+ ...this.detectBranch && this.replayBranch ? { [APP_BRANCH]: this.replayBranch } : {},
289
+ ...this.explicit
290
+ };
291
+ }
292
+ snapshot(properties) {
293
+ var _a;
294
+ try {
295
+ const binding = currentRoutingBinding();
296
+ const base = this.disabled && (binding == null ? void 0 : binding.appGitSource) !== "replay-override" ? {} : (_a = binding == null ? void 0 : binding.appGit) != null ? _a : this.defaults;
297
+ return this.mergeSnapshot(base, properties);
298
+ } catch (e) {
299
+ return Object.freeze({});
300
+ }
301
+ }
302
+ /** Safe defaults when no operation/span start was observed; never infer identity. */
303
+ snapshotExplicit(properties, eventId) {
304
+ try {
305
+ const base = { ...this.explicit };
306
+ const operation = eventId ? this.operations.get(eventId) : void 0;
307
+ if (operation) {
308
+ for (const key of operation.explicitKeys) base[key] = operation.snapshot[key];
309
+ }
310
+ return this.mergeSnapshot(base, properties, new Set(Object.keys(base)));
311
+ } catch (e) {
312
+ return mergeAppGitSnapshot({}, properties);
313
+ }
314
+ }
315
+ /** Existing replay branch reporting stays separate from opt-in event properties. */
316
+ snapshotForReplay() {
317
+ const snapshot = this.snapshot();
318
+ if (this.replayBranch && !own(snapshot, APP_BRANCH) && snapshot[APP_COMMIT_SHA] === this.defaults[APP_COMMIT_SHA]) {
319
+ return Object.freeze({ ...snapshot, [APP_BRANCH]: this.replayBranch });
320
+ }
321
+ return snapshot;
322
+ }
323
+ /** Merge a frozen span snapshot without losing client-authored provenance. */
324
+ mergeSnapshot(base, properties, explicitKeys = this.explicitKeys) {
325
+ return mergeAppGitSnapshot(base, properties, /* @__PURE__ */ new Set([...this.explicitKeys, ...explicitKeys]));
326
+ }
327
+ /** Shippers belonging to one client share this bounded operation registry. */
328
+ forOperation(eventId, properties, owner) {
329
+ if (!eventId) return this.snapshot(properties);
330
+ let operation = this.operations.get(eventId);
331
+ if (!operation) {
332
+ if (this.operations.size >= 1e4) this.operationOverflow = true;
333
+ if (this.operationOverflow) return this.mergeSnapshot({}, properties);
334
+ operation = {
335
+ snapshot: this.snapshot(properties),
336
+ owners: /* @__PURE__ */ new Set(),
337
+ unowned: owner === void 0,
338
+ explicitKeys: appGitExplicitKeys(properties)
339
+ };
340
+ this.operations.set(eventId, operation);
341
+ } else if (properties && APP_GIT_KEYS.some((key) => own(properties, key))) {
342
+ const explicitKeys = /* @__PURE__ */ new Set([...this.explicitKeys, ...operation.explicitKeys]);
343
+ operation.snapshot = this.mergeSnapshot(operation.snapshot, properties, explicitKeys);
344
+ for (const key of appGitExplicitKeys(properties)) operation.explicitKeys.add(key);
345
+ }
346
+ if (!owner) operation.unowned = true;
347
+ if (owner) operation.owners.add(owner);
348
+ return operation.snapshot;
349
+ }
350
+ releaseOperation(eventId, owner) {
351
+ const operation = this.operations.get(eventId);
352
+ if (!operation) return;
353
+ operation.owners.delete(owner);
354
+ if (operation.owners.size === 0 && !operation.unowned) this.operations.delete(eventId);
355
+ }
356
+ finishOperation(eventId) {
357
+ this.operations.delete(eventId);
358
+ }
359
+ dispose() {
360
+ var _a;
361
+ this.disposed = true;
362
+ try {
363
+ (_a = this.cancel) == null ? void 0 : _a.call(this);
364
+ } catch (e) {
365
+ }
366
+ }
367
+ };
368
+ var AppGitContext = AppGitContextImpl;
369
+ function withAppGitAttributes(attributes, snapshot) {
370
+ try {
371
+ const present = new Set(attributes.flatMap((attr) => attr ? [attr.key] : []));
372
+ const added = [];
373
+ for (const key of APP_GIT_KEYS) {
374
+ if (present.has(key) || present.has(`ai.telemetry.metadata.${key}`) || present.has(`traceloop.association.properties.${key}`))
375
+ continue;
376
+ const value = snapshot[key];
377
+ if (typeof value === "string") added.push({ key, value: { stringValue: value } });
378
+ else if (typeof value === "boolean") added.push({ key, value: { boolValue: value } });
379
+ }
380
+ return added.length ? [...attributes, ...added] : attributes;
381
+ } catch (e) {
382
+ return attributes;
383
+ }
384
+ }
385
+ function getCrypto() {
386
+ const c = globalThis.crypto;
387
+ return c;
388
+ }
389
+ function randomBytes(length) {
390
+ const cryptoObj = getCrypto();
391
+ const out = new Uint8Array(length);
392
+ if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
393
+ cryptoObj.getRandomValues(out);
394
+ return out;
395
+ }
396
+ for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
397
+ return out;
398
+ }
399
+ function randomUUID() {
400
+ const cryptoObj = getCrypto();
401
+ if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
402
+ return cryptoObj.randomUUID();
403
+ }
404
+ const b = randomBytes(16);
405
+ b[6] = b[6] & 15 | 64;
406
+ b[8] = b[8] & 63 | 128;
407
+ const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
408
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
409
+ }
410
+ function runWithTracingSuppressed(fn) {
411
+ const hook = globalThis.RAINDROP_SUPPRESS_TRACING;
412
+ if (typeof hook !== "function") return fn();
413
+ let started = false;
414
+ try {
415
+ return hook(() => {
416
+ started = true;
417
+ return fn();
418
+ });
419
+ } catch (err) {
420
+ if (started) throw err;
421
+ return fn();
422
+ }
423
+ }
424
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
425
+ var MAX_RETRY_DELAY_MS = 3e4;
426
+ function wait(ms) {
427
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
428
+ }
429
+ function formatEndpoint(endpoint) {
430
+ if (!endpoint) return void 0;
431
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
432
+ }
433
+ function redactUrlForLog(url) {
434
+ try {
435
+ const parsed = new URL(url);
436
+ parsed.username = "";
437
+ parsed.password = "";
438
+ parsed.search = "";
439
+ parsed.hash = "";
440
+ return parsed.toString();
441
+ } catch (e) {
442
+ return "<unparseable-url>";
443
+ }
444
+ }
445
+ function parseRetryAfter(headers) {
446
+ var _a;
447
+ const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
448
+ if (!value) return void 0;
449
+ const asNumber = Number(value);
450
+ if (value.trim() !== "" && !Number.isNaN(asNumber)) return asNumber * 1e3;
451
+ const asDate = new Date(value).getTime();
452
+ if (!Number.isNaN(asDate)) {
453
+ const delta = asDate - Date.now();
454
+ return delta > 0 ? delta : 0;
455
+ }
456
+ return void 0;
457
+ }
458
+ function getRetryDelayMs(attemptNumber, previousError) {
459
+ if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
460
+ const v = previousError.retryAfterMs;
461
+ if (typeof v === "number") return Math.min(Math.max(0, v), MAX_RETRY_DELAY_MS);
462
+ }
463
+ if (attemptNumber <= 1) return 0;
464
+ const base = 500;
465
+ const factor = Math.pow(2, attemptNumber - 2);
466
+ return Math.min(base * factor, MAX_RETRY_DELAY_MS);
467
+ }
468
+ async function withRetry(operation, opName, opts) {
469
+ const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
470
+ let lastError = void 0;
471
+ for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
472
+ if (attemptNumber > 1) {
473
+ const delay = getRetryDelayMs(attemptNumber, lastError);
474
+ if (opts.debug) {
475
+ console.warn(
476
+ `${prefix} ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
477
+ );
478
+ }
479
+ if (delay > 0) await wait(delay);
480
+ } else if (opts.debug) {
481
+ console.log(`${prefix} ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
482
+ }
483
+ try {
484
+ return await operation();
485
+ } catch (err) {
486
+ lastError = err;
487
+ if (opts.debug) {
488
+ const msg = err instanceof Error ? err.message : String(err);
489
+ console.warn(
490
+ `${prefix} ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
491
+ );
492
+ }
493
+ if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
494
+ break;
495
+ if (attemptNumber === opts.maxAttempts) break;
496
+ }
497
+ }
498
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
499
+ }
500
+ async function postJson(url, body, headers, opts) {
501
+ var _a;
502
+ const opName = `POST ${redactUrlForLog(url)}`;
503
+ const timeoutMs = (_a = opts.timeoutMs) != null ? _a : DEFAULT_REQUEST_TIMEOUT_MS;
504
+ await withRetry(
505
+ async () => {
506
+ const resp = await runWithTracingSuppressed(
507
+ () => fetch(url, {
508
+ method: "POST",
509
+ redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
510
+ headers: {
511
+ "Content-Type": "application/json",
512
+ ...headers
513
+ },
514
+ body: JSON.stringify(body),
515
+ signal: AbortSignal.timeout(timeoutMs)
516
+ })
517
+ );
518
+ if (!resp.ok) {
519
+ const text = await resp.text().catch(() => "");
520
+ const err = new Error(
521
+ `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
522
+ );
523
+ const retryAfterMs = parseRetryAfter(resp.headers);
524
+ if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
525
+ err.retryable = resp.status === 429 || resp.status >= 500;
526
+ throw err;
527
+ }
528
+ },
529
+ opName,
530
+ opts
531
+ );
532
+ }
533
+ var SpanStatusCode = {
534
+ UNSET: 0,
535
+ OK: 1,
536
+ ERROR: 2
537
+ };
538
+ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", serviceVersion = "0.0.0") {
539
+ return {
540
+ resourceSpans: [
541
+ {
542
+ resource: {
543
+ attributes: [{ key: "service.name", value: { stringValue: serviceName } }]
544
+ },
545
+ scopeSpans: [
546
+ {
547
+ scope: { name: serviceName, version: serviceVersion },
548
+ spans
549
+ }
550
+ ]
551
+ }
552
+ ]
553
+ };
554
+ }
555
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
556
+ var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
557
+ var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
558
+ function readEnvVar(name) {
559
+ var _a;
560
+ try {
561
+ const env = (_a = globalThis == null ? void 0 : globalThis.process) == null ? void 0 : _a.env;
562
+ if (env && typeof env[name] === "string" && env[name].length > 0) {
563
+ return env[name];
564
+ }
565
+ } catch (e) {
566
+ }
567
+ return void 0;
568
+ }
569
+ function readWorkshopEnv() {
570
+ const raw = readEnvVar(WORKSHOP_ENV_VAR);
571
+ if (raw === void 0) return void 0;
572
+ const trimmed = raw.trim();
573
+ if (trimmed.length === 0) return void 0;
574
+ if (/^https?:\/\//i.test(trimmed)) return { url: trimmed };
575
+ if (/^(1|true|yes|on)$/i.test(trimmed)) return "enable";
576
+ if (/^(0|false|no|off)$/i.test(trimmed)) return "disable";
577
+ return void 0;
578
+ }
579
+ function isLocalDevHost(hostname) {
580
+ if (!hostname) return false;
581
+ if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0" || hostname === "::1") {
582
+ return true;
583
+ }
584
+ if (hostname.endsWith(".localhost")) return true;
585
+ return false;
586
+ }
587
+ function readRuntimeHostname() {
588
+ try {
589
+ const loc = globalThis == null ? void 0 : globalThis.location;
590
+ if (loc && typeof loc.hostname === "string" && loc.hostname.length > 0) {
591
+ return loc.hostname;
592
+ }
593
+ } catch (e) {
594
+ }
595
+ return void 0;
596
+ }
597
+ function shouldAutoEnableLocalWorkshop() {
598
+ if (isLocalDevHost(readRuntimeHostname())) return true;
599
+ if (readEnvVar("NODE_ENV") === "development") return true;
600
+ return false;
601
+ }
602
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
603
+ var _a, _b, _c;
604
+ if (baseUrl === null) return null;
605
+ if (typeof baseUrl === "string" && baseUrl.length > 0) {
606
+ return (_a = formatEndpoint(baseUrl)) != null ? _a : null;
607
+ }
608
+ const explicitUrlEnv = readEnvVar(LOCAL_DEBUGGER_ENV_VAR);
609
+ if (explicitUrlEnv) return (_b = formatEndpoint(explicitUrlEnv)) != null ? _b : null;
610
+ const workshopEnv = readWorkshopEnv();
611
+ if (workshopEnv === "disable") return null;
612
+ if (workshopEnv === "enable") return DEFAULT_LOCAL_WORKSHOP_URL;
613
+ if (workshopEnv && "url" in workshopEnv) return (_c = formatEndpoint(workshopEnv.url)) != null ? _c : null;
614
+ if (shouldAutoEnableLocalWorkshop()) return DEFAULT_LOCAL_WORKSHOP_URL;
615
+ return null;
616
+ }
617
+ var LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS = 2e3;
618
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
619
+ var _a;
620
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
621
+ if (!baseUrl) return Promise.resolve();
622
+ return postJson(`${baseUrl}traces`, body, {}, {
623
+ maxAttempts: 1,
624
+ debug: (_a = options.debug) != null ? _a : false,
625
+ sdkName: options.sdkName,
626
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
627
+ }).catch(() => {
628
+ });
629
+ }
630
+ var PROJECT_ID_HEADER = "X-Raindrop-Project-Id";
631
+ var PROJECT_ID_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
632
+ function isValidProjectIdSlug(value) {
633
+ return PROJECT_ID_SLUG_PATTERN.test(value);
634
+ }
635
+ function normalizeProjectId(raw, opts) {
636
+ if (typeof raw !== "string") return void 0;
637
+ const trimmed = raw.trim();
638
+ if (!trimmed) return void 0;
639
+ if (!isValidProjectIdSlug(trimmed) && opts.debug) {
640
+ console.warn(
641
+ `${opts.prefix} projectId "${trimmed}" does not match slug ${PROJECT_ID_SLUG_PATTERN.source}; sending anyway \u2014 backend may reject with HTTP 400`
642
+ );
643
+ }
644
+ return trimmed;
645
+ }
646
+ function projectIdHeaders(projectId) {
647
+ return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
648
+ }
649
+ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
650
+ "ai.request.providerOptions",
651
+ "ai.response.providerMetadata"
652
+ ];
653
+ new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
654
+ var resolveLocal = (sourceDirectory, detectBranch, completed) => {
655
+ const cwd = sourceDirectory ? resolve(sourceDirectory) : process.cwd();
656
+ let cancelled = false;
657
+ let active;
658
+ let deadlineTimer;
659
+ const deadline = Date.now() + 1e3;
660
+ const run = (args, done) => {
661
+ if (cancelled) return;
662
+ const remaining = deadline - Date.now();
663
+ if (remaining <= 0) {
664
+ done(void 0);
665
+ return;
666
+ }
667
+ try {
668
+ active = execFile(
669
+ "git",
670
+ args,
671
+ {
672
+ cwd,
673
+ encoding: "utf8",
674
+ maxBuffer: 4096,
675
+ windowsHide: true,
676
+ env: {
677
+ ...process.env,
678
+ // The selected application cwd, not the invoking shell's Git plumbing, owns identity.
679
+ GIT_DIR: void 0,
680
+ GIT_WORK_TREE: void 0,
681
+ GIT_COMMON_DIR: void 0,
682
+ GIT_NAMESPACE: void 0,
683
+ GIT_INDEX_FILE: void 0,
684
+ GIT_OBJECT_DIRECTORY: void 0,
685
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: void 0,
686
+ GIT_CONFIG_PARAMETERS: void 0,
687
+ GIT_CONFIG_COUNT: "0",
688
+ GIT_TERMINAL_PROMPT: "0",
689
+ GIT_OPTIONAL_LOCKS: "0"
690
+ }
691
+ },
692
+ (error, stdout) => {
693
+ clearTimeout(deadlineTimer);
694
+ deadlineTimer = void 0;
695
+ active = void 0;
696
+ if (!cancelled) {
697
+ try {
698
+ done(error ? void 0 : stdout.trim());
699
+ } catch (e) {
700
+ }
701
+ }
702
+ }
703
+ );
704
+ active.unref();
705
+ if (active.stdout && "unref" in active.stdout && typeof active.stdout.unref === "function")
706
+ active.stdout.unref();
707
+ if (active.stderr && "unref" in active.stderr && typeof active.stderr.unref === "function")
708
+ active.stderr.unref();
709
+ deadlineTimer = setTimeout(() => {
710
+ try {
711
+ active == null ? void 0 : active.kill("SIGKILL");
712
+ } catch (e) {
713
+ }
714
+ }, remaining);
715
+ deadlineTimer.unref();
716
+ } catch (e) {
717
+ try {
718
+ done(void 0);
719
+ } catch (e2) {
720
+ }
721
+ }
722
+ };
723
+ const scheduled = setTimeout(() => {
724
+ try {
725
+ run(["rev-parse", "HEAD"], (rawSha) => {
726
+ const commitSha = validAppCommitSha(rawSha);
727
+ if (!commitSha) {
728
+ completed({});
729
+ return;
730
+ }
731
+ run(["-c", "core.fsmonitor=false", "status", "--porcelain"], (status) => {
732
+ const finish = (branch) => {
733
+ run(["rev-parse", "HEAD"], (finalSha) => {
734
+ const coherent = validAppCommitSha(finalSha) === commitSha;
735
+ completed({
736
+ commitSha,
737
+ ...coherent && status !== void 0 ? { commitDirty: status !== "" } : {},
738
+ ...coherent && branch && branch !== "HEAD" ? { branch } : {}
739
+ });
740
+ });
741
+ };
742
+ if (detectBranch) run(["symbolic-ref", "--quiet", "--short", "HEAD"], finish);
743
+ else finish();
744
+ });
745
+ });
746
+ } catch (e) {
747
+ completed({});
748
+ }
749
+ }, 0);
750
+ scheduled.unref();
751
+ return () => {
752
+ cancelled = true;
753
+ clearTimeout(scheduled);
754
+ clearTimeout(deadlineTimer);
755
+ try {
756
+ active == null ? void 0 : active.kill("SIGKILL");
757
+ } catch (e) {
758
+ }
759
+ };
760
+ };
761
+ function createAppGitContext(options, runtime = {}) {
762
+ return new AppGitContext(options, { ...runtime, resolveLocal });
763
+ }
764
+ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
765
+ var SUPPRESS_TRACING_KEY = /* @__PURE__ */ Symbol.for(
766
+ "OpenTelemetry SDK Context Key SUPPRESS_TRACING"
767
+ );
768
+ function findOtelContextManager() {
769
+ var _a;
770
+ for (const sym of Object.getOwnPropertySymbols(globalThis)) {
771
+ if (!((_a = sym.description) == null ? void 0 : _a.startsWith("opentelemetry.js.api."))) continue;
772
+ const api = globalThis[sym];
773
+ const cm = api == null ? void 0 : api.context;
774
+ if (cm && typeof cm.with === "function" && typeof cm.active === "function") {
775
+ return cm;
776
+ }
777
+ }
778
+ return void 0;
779
+ }
780
+ function installTracingSuppressionHook() {
781
+ if (typeof globalThis.RAINDROP_SUPPRESS_TRACING === "function") return;
782
+ const hook = (fn) => {
783
+ const cm = findOtelContextManager();
784
+ if (!cm) return fn();
785
+ return cm.with(cm.active().setValue(SUPPRESS_TRACING_KEY, true), fn);
786
+ };
787
+ globalThis.RAINDROP_SUPPRESS_TRACING = hook;
788
+ }
789
+ installTracingSuppressionHook();
7
790
  function parseEveSessionParent(value) {
8
791
  if (typeof value !== "object" || value === null) return void 0;
9
792
  const p = value;
@@ -137,346 +920,79 @@ var EveTurnRegistry = class {
137
920
  }
138
921
  if (stack.length === 0) {
139
922
  this.stacks.delete(traceId);
140
- }
141
- });
142
- }
143
- /**
144
- * Drop all entries. Called from the SpanProcessor's `shutdown` hook
145
- * during exporter teardown.
146
- */
147
- clear() {
148
- this.stacks.clear();
149
- }
150
- /**
151
- * Total number of in-flight entries across all traces. For tests +
152
- * diagnostic logging.
153
- */
154
- get size() {
155
- let total = 0;
156
- for (const stack of this.stacks.values()) total += stack.length;
157
- return total;
158
- }
159
- };
160
- var registry = new EveTurnRegistry();
161
- function createEveTurnSpanProcessor() {
162
- return {
163
- onStart(span) {
164
- if (span.name !== EVE_TURN_SPAN_NAME) return;
165
- const attrs = span.attributes;
166
- if (!attrs) return;
167
- const ctx = span.spanContext();
168
- const continuationToken = typeof attrs[EVE_CONTINUATION_TOKEN_ATTR] === "string" ? attrs[EVE_CONTINUATION_TOKEN_ATTR] : void 0;
169
- const sessionId = typeof attrs[EVE_SESSION_ID_ATTR] === "string" ? attrs[EVE_SESSION_ID_ATTR] : void 0;
170
- registry.record(ctx.traceId, ctx.spanId, {
171
- continuationToken,
172
- sessionId
173
- });
174
- },
175
- onEnd(span) {
176
- if (span.name !== EVE_TURN_SPAN_NAME) return;
177
- const ctx = span.spanContext();
178
- registry.releaseAfterTick(ctx.traceId, ctx.spanId);
179
- },
180
- forceFlush() {
181
- return Promise.resolve();
182
- },
183
- shutdown() {
184
- registry.clear();
185
- return Promise.resolve();
186
- }
187
- };
188
- }
189
- function lookupEveTurn(traceId) {
190
- return registry.lookup(traceId);
191
- }
192
- function installEveTurnSpanProcessor(traceApi) {
193
- if (installState.installed) return true;
194
- try {
195
- let provider = traceApi.getTracerProvider();
196
- const proxyProvider = provider;
197
- if (typeof proxyProvider.getDelegate === "function") {
198
- const delegate = proxyProvider.getDelegate();
199
- if (delegate) provider = delegate;
200
- }
201
- const tp = provider;
202
- if (typeof tp.addSpanProcessor !== "function") {
203
- return false;
204
- }
205
- tp.addSpanProcessor(createEveTurnSpanProcessor());
206
- installState.installed = true;
207
- return true;
208
- } catch {
209
- return false;
210
- }
211
- }
212
- var installState = { installed: false };
213
- function runWithTracingSuppressed(fn) {
214
- const hook = globalThis.RAINDROP_SUPPRESS_TRACING;
215
- if (typeof hook !== "function") return fn();
216
- let started = false;
217
- try {
218
- return hook(() => {
219
- started = true;
220
- return fn();
221
- });
222
- } catch (err) {
223
- if (started) throw err;
224
- return fn();
225
- }
226
- }
227
- var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
228
- var MAX_RETRY_DELAY_MS = 3e4;
229
- function wait(ms) {
230
- return new Promise((resolve) => setTimeout(resolve, ms));
231
- }
232
- function formatEndpoint(endpoint) {
233
- if (!endpoint) return void 0;
234
- return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
235
- }
236
- function redactUrlForLog(url) {
237
- try {
238
- const parsed = new URL(url);
239
- parsed.username = "";
240
- parsed.password = "";
241
- parsed.search = "";
242
- parsed.hash = "";
243
- return parsed.toString();
244
- } catch (e) {
245
- return "<unparseable-url>";
246
- }
247
- }
248
- function parseRetryAfter(headers) {
249
- var _a;
250
- const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
251
- if (!value) return void 0;
252
- const asNumber = Number(value);
253
- if (value.trim() !== "" && !Number.isNaN(asNumber)) return asNumber * 1e3;
254
- const asDate = new Date(value).getTime();
255
- if (!Number.isNaN(asDate)) {
256
- const delta = asDate - Date.now();
257
- return delta > 0 ? delta : 0;
258
- }
259
- return void 0;
260
- }
261
- function getRetryDelayMs(attemptNumber, previousError) {
262
- if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
263
- const v = previousError.retryAfterMs;
264
- if (typeof v === "number") return Math.min(Math.max(0, v), MAX_RETRY_DELAY_MS);
265
- }
266
- if (attemptNumber <= 1) return 0;
267
- const base = 500;
268
- const factor = Math.pow(2, attemptNumber - 2);
269
- return Math.min(base * factor, MAX_RETRY_DELAY_MS);
270
- }
271
- async function withRetry(operation, opName, opts) {
272
- const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
273
- let lastError = void 0;
274
- for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
275
- if (attemptNumber > 1) {
276
- const delay = getRetryDelayMs(attemptNumber, lastError);
277
- if (opts.debug) {
278
- console.warn(
279
- `${prefix} ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
280
- );
281
- }
282
- if (delay > 0) await wait(delay);
283
- } else if (opts.debug) {
284
- console.log(`${prefix} ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
285
- }
286
- try {
287
- return await operation();
288
- } catch (err) {
289
- lastError = err;
290
- if (opts.debug) {
291
- const msg = err instanceof Error ? err.message : String(err);
292
- console.warn(
293
- `${prefix} ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
294
- );
295
- }
296
- if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
297
- break;
298
- if (attemptNumber === opts.maxAttempts) break;
299
- }
300
- }
301
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
302
- }
303
- async function postJson(url, body, headers, opts) {
304
- var _a;
305
- const opName = `POST ${redactUrlForLog(url)}`;
306
- const timeoutMs = (_a = opts.timeoutMs) != null ? _a : DEFAULT_REQUEST_TIMEOUT_MS;
307
- await withRetry(
308
- async () => {
309
- const resp = await runWithTracingSuppressed(
310
- () => fetch(url, {
311
- method: "POST",
312
- headers: {
313
- "Content-Type": "application/json",
314
- ...headers
315
- },
316
- body: JSON.stringify(body),
317
- signal: AbortSignal.timeout(timeoutMs)
318
- })
319
- );
320
- if (!resp.ok) {
321
- const text = await resp.text().catch(() => "");
322
- const err = new Error(
323
- `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
324
- );
325
- const retryAfterMs = parseRetryAfter(resp.headers);
326
- if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
327
- err.retryable = resp.status === 429 || resp.status >= 500;
328
- throw err;
329
- }
330
- },
331
- opName,
332
- opts
333
- );
334
- }
335
- var SpanStatusCode = {
336
- UNSET: 0,
337
- OK: 1,
338
- ERROR: 2
923
+ }
924
+ });
925
+ }
926
+ /**
927
+ * Drop all entries. Called from the SpanProcessor's `shutdown` hook
928
+ * during exporter teardown.
929
+ */
930
+ clear() {
931
+ this.stacks.clear();
932
+ }
933
+ /**
934
+ * Total number of in-flight entries across all traces. For tests +
935
+ * diagnostic logging.
936
+ */
937
+ get size() {
938
+ let total = 0;
939
+ for (const stack of this.stacks.values()) total += stack.length;
940
+ return total;
941
+ }
339
942
  };
340
- function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", serviceVersion = "0.0.0") {
943
+ var registry = new EveTurnRegistry();
944
+ function createEveTurnSpanProcessor() {
341
945
  return {
342
- resourceSpans: [
343
- {
344
- resource: {
345
- attributes: [{ key: "service.name", value: { stringValue: serviceName } }]
346
- },
347
- scopeSpans: [
348
- {
349
- scope: { name: serviceName, version: serviceVersion },
350
- spans
351
- }
352
- ]
353
- }
354
- ]
355
- };
356
- }
357
- var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
358
- var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
359
- var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
360
- function readEnvVar(name) {
361
- var _a;
362
- try {
363
- const env = (_a = globalThis == null ? void 0 : globalThis.process) == null ? void 0 : _a.env;
364
- if (env && typeof env[name] === "string" && env[name].length > 0) {
365
- return env[name];
946
+ onStart(span) {
947
+ if (span.name !== EVE_TURN_SPAN_NAME) return;
948
+ const attrs = span.attributes;
949
+ if (!attrs) return;
950
+ const ctx = span.spanContext();
951
+ const continuationToken = typeof attrs[EVE_CONTINUATION_TOKEN_ATTR] === "string" ? attrs[EVE_CONTINUATION_TOKEN_ATTR] : void 0;
952
+ const sessionId = typeof attrs[EVE_SESSION_ID_ATTR] === "string" ? attrs[EVE_SESSION_ID_ATTR] : void 0;
953
+ registry.record(ctx.traceId, ctx.spanId, {
954
+ continuationToken,
955
+ sessionId
956
+ });
957
+ },
958
+ onEnd(span) {
959
+ if (span.name !== EVE_TURN_SPAN_NAME) return;
960
+ const ctx = span.spanContext();
961
+ registry.releaseAfterTick(ctx.traceId, ctx.spanId);
962
+ },
963
+ forceFlush() {
964
+ return Promise.resolve();
965
+ },
966
+ shutdown() {
967
+ registry.clear();
968
+ return Promise.resolve();
366
969
  }
367
- } catch (e) {
368
- }
369
- return void 0;
370
- }
371
- function readWorkshopEnv() {
372
- const raw = readEnvVar(WORKSHOP_ENV_VAR);
373
- if (raw === void 0) return void 0;
374
- const trimmed = raw.trim();
375
- if (trimmed.length === 0) return void 0;
376
- if (/^https?:\/\//i.test(trimmed)) return { url: trimmed };
377
- if (/^(1|true|yes|on)$/i.test(trimmed)) return "enable";
378
- if (/^(0|false|no|off)$/i.test(trimmed)) return "disable";
379
- return void 0;
970
+ };
380
971
  }
381
- function isLocalDevHost(hostname) {
382
- if (!hostname) return false;
383
- if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0" || hostname === "::1") {
384
- return true;
385
- }
386
- if (hostname.endsWith(".localhost")) return true;
387
- return false;
972
+ function lookupEveTurn(traceId) {
973
+ return registry.lookup(traceId);
388
974
  }
389
- function readRuntimeHostname() {
975
+ function installEveTurnSpanProcessor(traceApi) {
976
+ if (installState.installed) return true;
390
977
  try {
391
- const loc = globalThis == null ? void 0 : globalThis.location;
392
- if (loc && typeof loc.hostname === "string" && loc.hostname.length > 0) {
393
- return loc.hostname;
978
+ let provider = traceApi.getTracerProvider();
979
+ const proxyProvider = provider;
980
+ if (typeof proxyProvider.getDelegate === "function") {
981
+ const delegate = proxyProvider.getDelegate();
982
+ if (delegate) provider = delegate;
394
983
  }
395
- } catch (e) {
396
- }
397
- return void 0;
398
- }
399
- function shouldAutoEnableLocalWorkshop() {
400
- if (isLocalDevHost(readRuntimeHostname())) return true;
401
- if (readEnvVar("NODE_ENV") === "development") return true;
402
- return false;
403
- }
404
- function resolveLocalDebuggerBaseUrl(baseUrl) {
405
- var _a, _b, _c;
406
- if (baseUrl === null) return null;
407
- if (typeof baseUrl === "string" && baseUrl.length > 0) {
408
- return (_a = formatEndpoint(baseUrl)) != null ? _a : null;
409
- }
410
- const explicitUrlEnv = readEnvVar(LOCAL_DEBUGGER_ENV_VAR);
411
- if (explicitUrlEnv) return (_b = formatEndpoint(explicitUrlEnv)) != null ? _b : null;
412
- const workshopEnv = readWorkshopEnv();
413
- if (workshopEnv === "disable") return null;
414
- if (workshopEnv === "enable") return DEFAULT_LOCAL_WORKSHOP_URL;
415
- if (workshopEnv && "url" in workshopEnv) return (_c = formatEndpoint(workshopEnv.url)) != null ? _c : null;
416
- if (shouldAutoEnableLocalWorkshop()) return DEFAULT_LOCAL_WORKSHOP_URL;
417
- return null;
418
- }
419
- function mirrorTraceExportToLocalDebugger(body, options = {}) {
420
- var _a;
421
- const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
422
- if (!baseUrl) return;
423
- void postJson(`${baseUrl}traces`, body, {}, {
424
- maxAttempts: 1,
425
- debug: (_a = options.debug) != null ? _a : false,
426
- sdkName: options.sdkName
427
- }).catch(() => {
428
- });
429
- }
430
- var PROJECT_ID_HEADER = "X-Raindrop-Project-Id";
431
- var PROJECT_ID_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
432
- function isValidProjectIdSlug(value) {
433
- return PROJECT_ID_SLUG_PATTERN.test(value);
434
- }
435
- function normalizeProjectId(raw, opts) {
436
- if (typeof raw !== "string") return void 0;
437
- const trimmed = raw.trim();
438
- if (!trimmed) return void 0;
439
- if (!isValidProjectIdSlug(trimmed) && opts.debug) {
440
- console.warn(
441
- `${opts.prefix} projectId "${trimmed}" does not match slug ${PROJECT_ID_SLUG_PATTERN.source}; sending anyway \u2014 backend may reject with HTTP 400`
442
- );
443
- }
444
- return trimmed;
445
- }
446
- function projectIdHeaders(projectId) {
447
- return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
448
- }
449
- var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
450
- "ai.request.providerOptions",
451
- "ai.response.providerMetadata"
452
- ];
453
- new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
454
- globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
455
- var SUPPRESS_TRACING_KEY = /* @__PURE__ */ Symbol.for(
456
- "OpenTelemetry SDK Context Key SUPPRESS_TRACING"
457
- );
458
- function findOtelContextManager() {
459
- var _a;
460
- for (const sym of Object.getOwnPropertySymbols(globalThis)) {
461
- if (!((_a = sym.description) == null ? void 0 : _a.startsWith("opentelemetry.js.api."))) continue;
462
- const api = globalThis[sym];
463
- const cm = api == null ? void 0 : api.context;
464
- if (cm && typeof cm.with === "function" && typeof cm.active === "function") {
465
- return cm;
984
+ const tp = provider;
985
+ if (typeof tp.addSpanProcessor !== "function") {
986
+ return false;
466
987
  }
988
+ tp.addSpanProcessor(createEveTurnSpanProcessor());
989
+ installState.installed = true;
990
+ return true;
991
+ } catch {
992
+ return false;
467
993
  }
468
- return void 0;
469
- }
470
- function installTracingSuppressionHook() {
471
- if (typeof globalThis.RAINDROP_SUPPRESS_TRACING === "function") return;
472
- const hook = (fn) => {
473
- const cm = findOtelContextManager();
474
- if (!cm) return fn();
475
- return cm.with(cm.active().setValue(SUPPRESS_TRACING_KEY, true), fn);
476
- };
477
- globalThis.RAINDROP_SUPPRESS_TRACING = hook;
478
994
  }
479
- installTracingSuppressionHook();
995
+ var installState = { installed: false };
480
996
 
481
997
  // src/internal/limits.ts
482
998
  var DEFAULT_MAX_TEXT_FIELD_CHARS2 = 1e6;
@@ -504,6 +1020,13 @@ function truncateText(value, limit) {
504
1020
  }
505
1021
 
506
1022
  // src/internal/exporter.ts
1023
+ var EVE_APP_GIT_OWNER_PREFIX = "eve-trace";
1024
+ var MAX_EVE_APP_GIT_ACTIVE_EVENTS = 1e4;
1025
+ var APP_GIT_KEYS2 = [
1026
+ "raindrop.app.commit_sha",
1027
+ "raindrop.app.commit_dirty",
1028
+ "raindrop.app.branch"
1029
+ ];
507
1030
  function hexToBase64(hex) {
508
1031
  if (!hex) return void 0;
509
1032
  if (hex.length === 0 || /^0+$/.test(hex)) return void 0;
@@ -556,6 +1079,45 @@ function attributesToKeyValues(attrs, maxChars) {
556
1079
  }
557
1080
  return out;
558
1081
  }
1082
+ function eventIdFromAttributes(attrs) {
1083
+ if (!attrs) return void 0;
1084
+ const value = attrs["raindrop.eventId"] ?? attrs["ai.telemetry.metadata.raindrop.eventId"] ?? attrs["traceloop.association.properties.event_id"];
1085
+ return typeof value === "string" ? value : void 0;
1086
+ }
1087
+ function appGitPropertiesFromReadableAttributes(attrs) {
1088
+ const properties = {};
1089
+ if (!attrs) return properties;
1090
+ for (const key of ["raindrop.app.commit_sha", "raindrop.app.commit_dirty", "raindrop.app.branch"]) {
1091
+ for (const attributeKey of [key, `ai.telemetry.metadata.${key}`, `traceloop.association.properties.${key}`]) {
1092
+ if (Object.prototype.hasOwnProperty.call(attrs, attributeKey)) {
1093
+ properties[key] = attrs[attributeKey];
1094
+ break;
1095
+ }
1096
+ }
1097
+ }
1098
+ return properties;
1099
+ }
1100
+ function appGitExplicitKeys2(properties) {
1101
+ const keys = /* @__PURE__ */ new Set();
1102
+ for (const key of APP_GIT_KEYS2) {
1103
+ if (Object.prototype.hasOwnProperty.call(properties, key)) keys.add(key);
1104
+ }
1105
+ return keys;
1106
+ }
1107
+ function appGitOwnerId(prefix) {
1108
+ try {
1109
+ return `${prefix}:${randomUUID()}`;
1110
+ } catch {
1111
+ return `${prefix}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
1112
+ }
1113
+ }
1114
+ function explicitAppGitSnapshot(context, properties, eventId) {
1115
+ try {
1116
+ return context.snapshotExplicit?.(properties, eventId) ?? properties;
1117
+ } catch {
1118
+ return properties;
1119
+ }
1120
+ }
559
1121
  function statusFromReadable(span) {
560
1122
  const code = span.status?.code;
561
1123
  if (code === void 0) return void 0;
@@ -567,7 +1129,7 @@ function statusFromReadable(span) {
567
1129
  }
568
1130
  return { code: SpanStatusCode.UNSET };
569
1131
  }
570
- function readableSpanToOtlp(span, maxChars) {
1132
+ function readableSpanToOtlp(span, maxChars, appGitContext, operationEventId, appGitOwner, appGitExplicitOnly, startedAppGitSnapshot, startedAppGitExplicitKeys) {
571
1133
  const ctx = span.spanContext();
572
1134
  const parentSpanIdHex = span.parentSpanContext?.spanId ?? span.parentSpanId;
573
1135
  const traceId = hexToBase64(ctx.traceId);
@@ -578,7 +1140,17 @@ function readableSpanToOtlp(span, maxChars) {
578
1140
  );
579
1141
  }
580
1142
  const parentSpanId = hexToBase64(parentSpanIdHex);
581
- const attrs = attributesToKeyValues(span.attributes, maxChars);
1143
+ eventIdFromAttributes(span.attributes);
1144
+ const appProperties = appGitPropertiesFromReadableAttributes(span.attributes);
1145
+ const appGitSnapshot = startedAppGitSnapshot !== void 0 ? appGitContext.mergeSnapshot ? appGitContext.mergeSnapshot(startedAppGitSnapshot, appProperties, startedAppGitExplicitKeys) : mergeAppGitSnapshot(startedAppGitSnapshot, appProperties, startedAppGitExplicitKeys) : appGitExplicitOnly ? explicitAppGitSnapshot(appGitContext, appProperties, operationEventId) : appGitContext.forOperation(
1146
+ operationEventId,
1147
+ appProperties,
1148
+ operationEventId ? appGitOwner : void 0
1149
+ );
1150
+ const attrs = withAppGitAttributes(
1151
+ attributesToKeyValues(span.attributes, maxChars),
1152
+ appGitSnapshot
1153
+ ).filter((attribute) => attribute !== void 0);
582
1154
  const otlp = {
583
1155
  traceId,
584
1156
  spanId,
@@ -593,7 +1165,10 @@ function readableSpanToOtlp(span, maxChars) {
593
1165
  return otlp;
594
1166
  }
595
1167
  var RaindropEveSpanExporter = class {
596
- constructor(opts = {}) {
1168
+ constructor(opts = {}, appGitContext) {
1169
+ this.startedAppGitSpans = /* @__PURE__ */ new WeakMap();
1170
+ this.activeAppGitEvents = /* @__PURE__ */ new Map();
1171
+ this.appGitOwner = appGitOwnerId(EVE_APP_GIT_OWNER_PREFIX);
597
1172
  this.inFlight = /* @__PURE__ */ new Set();
598
1173
  this.shuttingDown = false;
599
1174
  this.auxShutdowns = [];
@@ -611,6 +1186,10 @@ var RaindropEveSpanExporter = class {
611
1186
  });
612
1187
  const explicit = opts.localWorkshopUrl === false ? null : opts.localWorkshopUrl;
613
1188
  this.localDebuggerUrl = resolveLocalDebuggerBaseUrl(explicit) ?? void 0;
1189
+ this.appGitContext = appGitContext ?? createAppGitContext(
1190
+ this.writeKey || this.localDebuggerUrl ? opts.appGit : false,
1191
+ { allowLocalGit: false }
1192
+ );
614
1193
  if (this.debug) {
615
1194
  console.log(
616
1195
  `${this.prefix} Initialized`,
@@ -625,6 +1204,55 @@ var RaindropEveSpanExporter = class {
625
1204
  hasDestinations() {
626
1205
  return Boolean(this.writeKey || this.localDebuggerUrl);
627
1206
  }
1207
+ captureSpanStart(span) {
1208
+ if (this.startedAppGitSpans.has(span)) return;
1209
+ const eventId = eventIdFromAttributes(span.attributes);
1210
+ const appProperties = appGitPropertiesFromReadableAttributes(span.attributes);
1211
+ const snapshot = this.appGitContext.forOperation(
1212
+ eventId,
1213
+ appProperties,
1214
+ eventId ? this.appGitOwner : void 0
1215
+ );
1216
+ if (!eventId) {
1217
+ this.startedAppGitSpans.set(span, {
1218
+ eventId: void 0,
1219
+ snapshot,
1220
+ explicitKeys: appGitExplicitKeys2(appProperties)
1221
+ });
1222
+ return;
1223
+ }
1224
+ const tracksAppGit = this.activeAppGitEvents.has(eventId) || this.activeAppGitEvents.size < MAX_EVE_APP_GIT_ACTIVE_EVENTS;
1225
+ if (tracksAppGit) {
1226
+ this.activeAppGitEvents.set(eventId, (this.activeAppGitEvents.get(eventId) ?? 0) + 1);
1227
+ this.startedAppGitSpans.set(span, {
1228
+ eventId,
1229
+ snapshot,
1230
+ explicitKeys: appGitExplicitKeys2(appProperties)
1231
+ });
1232
+ } else {
1233
+ this.appGitContext.releaseOperation?.(eventId, this.appGitOwner);
1234
+ }
1235
+ }
1236
+ releaseStartedAppGitSpan(span, eventId) {
1237
+ const started = this.startedAppGitSpans.get(span);
1238
+ const startedEventId = started?.eventId;
1239
+ this.startedAppGitSpans.delete(span);
1240
+ const trackedEventId = startedEventId ?? eventId;
1241
+ if (!trackedEventId || !this.appGitContext.releaseOperation) return;
1242
+ if (!startedEventId) {
1243
+ if (!this.activeAppGitEvents.has(trackedEventId)) {
1244
+ this.appGitContext.releaseOperation(trackedEventId, this.appGitOwner);
1245
+ }
1246
+ return;
1247
+ }
1248
+ const remaining = (this.activeAppGitEvents.get(startedEventId) ?? 1) - 1;
1249
+ if (remaining > 0) {
1250
+ this.activeAppGitEvents.set(startedEventId, remaining);
1251
+ return;
1252
+ }
1253
+ this.activeAppGitEvents.delete(startedEventId);
1254
+ this.appGitContext.releaseOperation(startedEventId, this.appGitOwner);
1255
+ }
628
1256
  /**
629
1257
  * Update the OTLP `service.name` attribute. Called by Eve's
630
1258
  * `setup({ agentName })` so the resource attribute reflects the actual
@@ -649,12 +1277,28 @@ var RaindropEveSpanExporter = class {
649
1277
  const maxChars = effectiveAttributeLimit(this.maxTextFieldChars);
650
1278
  const otlpSpans = [];
651
1279
  for (const span of spans) {
1280
+ const eventId = eventIdFromAttributes(span.attributes);
1281
+ const startedAppGit = this.startedAppGitSpans.get(span);
1282
+ const appGitExplicitOnly = startedAppGit === void 0;
652
1283
  try {
653
- otlpSpans.push(readableSpanToOtlp(span, maxChars));
1284
+ otlpSpans.push(
1285
+ readableSpanToOtlp(
1286
+ span,
1287
+ maxChars,
1288
+ this.appGitContext,
1289
+ startedAppGit?.eventId ?? eventId,
1290
+ this.appGitOwner,
1291
+ appGitExplicitOnly,
1292
+ startedAppGit?.eventId ? void 0 : startedAppGit?.snapshot,
1293
+ startedAppGit?.eventId ? void 0 : startedAppGit?.explicitKeys
1294
+ )
1295
+ );
654
1296
  } catch (err) {
655
1297
  if (this.debug) {
656
1298
  console.warn(`${this.prefix} failed to convert span`, err);
657
1299
  }
1300
+ } finally {
1301
+ this.releaseStartedAppGitSpan(span, eventId);
658
1302
  }
659
1303
  }
660
1304
  if (otlpSpans.length === 0) {
@@ -706,11 +1350,18 @@ var RaindropEveSpanExporter = class {
706
1350
  }
707
1351
  async shutdown() {
708
1352
  this.shuttingDown = true;
709
- await this.forceFlush();
710
- await Promise.all(
711
- this.auxShutdowns.map((fn) => fn().catch(() => {
712
- }))
713
- );
1353
+ try {
1354
+ await this.forceFlush();
1355
+ await Promise.all(
1356
+ this.auxShutdowns.map((fn) => fn().catch(() => {
1357
+ }))
1358
+ );
1359
+ } finally {
1360
+ try {
1361
+ this.appGitContext.dispose();
1362
+ } catch {
1363
+ }
1364
+ }
714
1365
  }
715
1366
  /**
716
1367
  * Register an extra teardown hook to run during {@link shutdown}. Used to
@@ -723,11 +1374,44 @@ var RaindropEveSpanExporter = class {
723
1374
  this.auxShutdowns.push(fn);
724
1375
  }
725
1376
  };
1377
+ function installEveAppGitSpanProcessor(traceApi, exporter) {
1378
+ try {
1379
+ let provider = traceApi.getTracerProvider();
1380
+ if (provider === null || typeof provider !== "object" && typeof provider !== "function") return false;
1381
+ if ("getDelegate" in provider && typeof provider.getDelegate === "function") {
1382
+ const delegate = provider.getDelegate();
1383
+ if (delegate) provider = delegate;
1384
+ }
1385
+ if (provider === null || typeof provider !== "object" && typeof provider !== "function" || !("addSpanProcessor" in provider) || typeof provider.addSpanProcessor !== "function") return false;
1386
+ provider.addSpanProcessor(createEveAppGitSpanProcessor(exporter));
1387
+ return true;
1388
+ } catch {
1389
+ return false;
1390
+ }
1391
+ }
1392
+ function createEveAppGitSpanProcessor(exporter) {
1393
+ return {
1394
+ onStart(span) {
1395
+ try {
1396
+ exporter.captureSpanStart(span);
1397
+ } catch {
1398
+ }
1399
+ },
1400
+ onEnd() {
1401
+ },
1402
+ forceFlush() {
1403
+ return Promise.resolve();
1404
+ },
1405
+ shutdown() {
1406
+ return Promise.resolve();
1407
+ }
1408
+ };
1409
+ }
726
1410
 
727
1411
  // package.json
728
1412
  var package_default = {
729
1413
  name: "@raindrop-ai/eve",
730
- version: "0.0.22"};
1414
+ version: "0.0.24"};
731
1415
 
732
1416
  // src/internal/version.ts
733
1417
  var libraryName = package_default.name;
@@ -1009,18 +1693,21 @@ function buildEveStepStartedResolver(opts, staticMetadata) {
1009
1693
  };
1010
1694
  }
1011
1695
  function buildEveMetadataConfig(opts, staticMetadata) {
1012
- const resolve = buildEveStepStartedResolver(opts, staticMetadata);
1013
- return { "step.started": (input) => resolve(input) };
1696
+ const resolve2 = buildEveStepStartedResolver(opts, staticMetadata);
1697
+ return { "step.started": (input) => resolve2(input) };
1014
1698
  }
1015
1699
  function buildEveEventsConfig(opts, staticMetadata) {
1016
- const resolve = buildEveStepStartedResolver(opts, staticMetadata);
1017
- return { "step.started": (input) => ({ runtimeContext: resolve(input) }) };
1700
+ const resolve2 = buildEveStepStartedResolver(opts, staticMetadata);
1701
+ return { "step.started": (input) => ({ runtimeContext: resolve2(input) }) };
1018
1702
  }
1019
1703
  function defineRaindropInstrumentation(opts = {}) {
1020
1704
  const debug = opts.debug === true || envDebug();
1021
1705
  const writeKey = opts.writeKey ?? envWriteKey();
1022
1706
  const endpoint = opts.endpoint ?? envEndpoint();
1023
1707
  const projectId = opts.projectId ?? envProjectId();
1708
+ const localWorkshopInput = opts.localWorkshopUrl === false ? null : opts.localWorkshopUrl;
1709
+ const hasDestination = Boolean(writeKey?.trim()) || Boolean(resolveLocalDebuggerBaseUrl(localWorkshopInput));
1710
+ const appGitContext = createAppGitContext(hasDestination ? opts.appGit : false, { allowLocalGit: false });
1024
1711
  const exporter = new RaindropEveSpanExporter({
1025
1712
  writeKey,
1026
1713
  endpoint,
@@ -1031,7 +1718,7 @@ function defineRaindropInstrumentation(opts = {}) {
1031
1718
  sdkName: "eve",
1032
1719
  debug,
1033
1720
  maxTextFieldChars: opts.maxTextFieldChars
1034
- });
1721
+ }, appGitContext);
1035
1722
  const localWorkshopUrl = opts.localWorkshopUrl === false ? false : opts.localWorkshopUrl;
1036
1723
  const raindrop = createRaindropAISDK({
1037
1724
  writeKey,
@@ -1039,7 +1726,8 @@ function defineRaindropInstrumentation(opts = {}) {
1039
1726
  projectId,
1040
1727
  localWorkshopUrl,
1041
1728
  events: { debug },
1042
- traces: { debug }
1729
+ traces: { debug },
1730
+ appGitContext
1043
1731
  });
1044
1732
  exporter.attachAuxShutdown(() => raindrop.shutdown());
1045
1733
  const prefix = "[raindrop-ai/eve]";
@@ -1068,8 +1756,13 @@ function defineRaindropInstrumentation(opts = {}) {
1068
1756
  if (already === void 0) {
1069
1757
  opts.registerOTel({
1070
1758
  serviceName,
1071
- traceExporter: exporter
1759
+ traceExporter: exporter,
1760
+ spanProcessors: [
1761
+ "auto",
1762
+ createEveAppGitSpanProcessor(exporter)
1763
+ ]
1072
1764
  });
1765
+ installEveAppGitSpanProcessor(trace, exporter);
1073
1766
  g[RAINDROP_EVE_OTEL_REGISTERED] = { exporter };
1074
1767
  if (debug) {
1075
1768
  console.log(`${prefix} registered OTel for serviceName=${serviceName}`);
@@ -1113,6 +1806,6 @@ function defineRaindropInstrumentation(opts = {}) {
1113
1806
  }
1114
1807
  var index_default = defineRaindropInstrumentation;
1115
1808
 
1116
- export { RAINDROP_EVE_SDK_NAME, RAINDROP_EVE_SDK_VERSION, RaindropEveSpanExporter, _resetCanonicalTurnIds, index_default as default, defineRaindropInstrumentation };
1809
+ export { RAINDROP_EVE_SDK_NAME, RAINDROP_EVE_SDK_VERSION, RaindropEveSpanExporter, _resetCanonicalTurnIds, createEveAppGitSpanProcessor, index_default as default, defineRaindropInstrumentation };
1117
1810
  //# sourceMappingURL=index.mjs.map
1118
1811
  //# sourceMappingURL=index.mjs.map