@raindrop-ai/ai-sdk 0.3.2 → 0.3.3

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.
@@ -1,4 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'async_hooks';
2
+ import { execFile } from 'child_process';
3
+ import { resolve } from 'path';
2
4
 
3
5
  // ../core/dist/chunk-BYBMRLZM.js
4
6
  var EVAL_CORRELATION_ID_ATTRIBUTE = "raindrop.eval_correlation_id";
@@ -62,7 +64,574 @@ function evalScopeAttributes() {
62
64
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
63
65
  }
64
66
 
65
- // ../core/dist/chunk-T53LQAH7.js
67
+ // ../core/dist/chunk-WJOR6M7H.js
68
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
69
+ function state() {
70
+ const holder = globalThis;
71
+ let current = holder[STATE_KEY];
72
+ if (!current) {
73
+ let storage = null;
74
+ try {
75
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
76
+ if (Ctor) storage = new Ctor();
77
+ } catch (e) {
78
+ storage = null;
79
+ }
80
+ current = {
81
+ storage,
82
+ syncDestination: void 0,
83
+ spanDestinations: /* @__PURE__ */ new WeakMap()
84
+ };
85
+ holder[STATE_KEY] = current;
86
+ }
87
+ return current;
88
+ }
89
+ function currentReplayTraceDestination() {
90
+ var _a, _b;
91
+ const routing = state();
92
+ return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
93
+ }
94
+ function rememberReplayTraceDestination(span) {
95
+ const destination = currentReplayTraceDestination();
96
+ if (destination) state().spanDestinations.set(span, destination);
97
+ }
98
+ function copyReplayTraceDestination(source, target) {
99
+ const destination = state().spanDestinations.get(source);
100
+ if (destination) state().spanDestinations.set(target, destination);
101
+ }
102
+ function replayTraceDestinationFor(value) {
103
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
104
+ return void 0;
105
+ }
106
+ return state().spanDestinations.get(value);
107
+ }
108
+ function recordReplayExportedSpan(destination, spanId, traceId) {
109
+ var _a, _b;
110
+ if (!destination || !spanId || !traceId) return;
111
+ (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
112
+ (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
113
+ }
114
+ function replayTraceUrl(baseUrl) {
115
+ return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
116
+ }
117
+ var NOOP_SPAN = {
118
+ traceIdB64: "",
119
+ spanIdB64: "",
120
+ eventId: "",
121
+ log() {
122
+ }
123
+ };
124
+ function getAsyncLocalStorageCtor() {
125
+ return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
126
+ }
127
+ var SynchronousContextStorage = class {
128
+ constructor() {
129
+ this._stack = [];
130
+ }
131
+ isEmpty() {
132
+ return this._stack.length === 0;
133
+ }
134
+ getStore() {
135
+ return this._stack[this._stack.length - 1];
136
+ }
137
+ run(store, callback) {
138
+ this._stack.push(store);
139
+ try {
140
+ return callback();
141
+ } finally {
142
+ this._stack.pop();
143
+ }
144
+ }
145
+ };
146
+ var ContextManager = class {
147
+ };
148
+ var RaindropContextManager = class extends ContextManager {
149
+ constructor() {
150
+ super();
151
+ this._fallback = null;
152
+ const Ctor = getAsyncLocalStorageCtor();
153
+ if (Ctor) {
154
+ this._storage = new Ctor();
155
+ return;
156
+ }
157
+ this._fallback = new SynchronousContextStorage();
158
+ this._storage = this._fallback;
159
+ }
160
+ maybeAdoptAsyncLocalStorage() {
161
+ if (!this._fallback || !this._fallback.isEmpty()) return;
162
+ const Ctor = getAsyncLocalStorageCtor();
163
+ if (!Ctor) return;
164
+ this._storage = new Ctor();
165
+ this._fallback = null;
166
+ }
167
+ isReady() {
168
+ return true;
169
+ }
170
+ getParentSpanIds() {
171
+ this.maybeAdoptAsyncLocalStorage();
172
+ const span = this._storage.getStore();
173
+ if (!span || span === NOOP_SPAN) return void 0;
174
+ return {
175
+ traceIdB64: span.traceIdB64,
176
+ spanIdB64: span.spanIdB64,
177
+ eventId: span.eventId
178
+ };
179
+ }
180
+ runInContext(span, callback) {
181
+ this.maybeAdoptAsyncLocalStorage();
182
+ return this._storage.run(span, callback);
183
+ }
184
+ getCurrentSpan() {
185
+ this.maybeAdoptAsyncLocalStorage();
186
+ return this._storage.getStore();
187
+ }
188
+ };
189
+ var _contextManager = null;
190
+ function getContextManager() {
191
+ if (!_contextManager) {
192
+ _contextManager = globalThis.RAINDROP_CONTEXT_MANAGER ? new globalThis.RAINDROP_CONTEXT_MANAGER() : new RaindropContextManager();
193
+ }
194
+ return _contextManager;
195
+ }
196
+ function currentSpan() {
197
+ var _a;
198
+ return (_a = getContextManager().getCurrentSpan()) != null ? _a : NOOP_SPAN;
199
+ }
200
+ function withCurrent(span, callback) {
201
+ return getContextManager().runInContext(span, callback);
202
+ }
203
+ async function getCurrentParentSpanContext() {
204
+ var _a, _b;
205
+ return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
206
+ }
207
+ async function runWithParentSpanContext(ctx, fn) {
208
+ const cm = getContextManager();
209
+ const span = {
210
+ traceIdB64: ctx.traceIdB64,
211
+ spanIdB64: ctx.spanIdB64,
212
+ eventId: ctx.eventId
213
+ };
214
+ return cm.runInContext(span, fn);
215
+ }
216
+ async function* asyncGeneratorWithCurrent(span, gen) {
217
+ let nextValue;
218
+ while (true) {
219
+ const result = await withCurrent(span, async () => {
220
+ try {
221
+ return await gen.next(nextValue);
222
+ } catch (e) {
223
+ return { value: void 0, done: true, error: e };
224
+ }
225
+ });
226
+ if ("error" in result && result.error !== void 0) {
227
+ throw result.error;
228
+ }
229
+ if (result.done) {
230
+ return result.value;
231
+ }
232
+ nextValue = yield result.value;
233
+ }
234
+ }
235
+ var MAX_BINDING_STACK = 128;
236
+ var EMPTY_STACK = [];
237
+ var ContextStackStorage = class {
238
+ /** Emitted once when this runtime cannot support an ambient push. */
239
+ constructor(noAmbientBindWarning) {
240
+ this.noAmbientBindWarning = noAmbientBindWarning;
241
+ this._als = null;
242
+ this._enterWithUsable = false;
243
+ this._syncStack = EMPTY_STACK;
244
+ this._adoptionChecked = false;
245
+ this._warnedNoAmbientBind = false;
246
+ }
247
+ maybeAdoptAsyncLocalStorage() {
248
+ if (this._adoptionChecked) return;
249
+ this._adoptionChecked = true;
250
+ const Ctor = getAsyncLocalStorageCtor();
251
+ if (!Ctor) return;
252
+ const als = new Ctor();
253
+ try {
254
+ als.run(EMPTY_STACK, () => {
255
+ });
256
+ } catch (e) {
257
+ return;
258
+ }
259
+ this._als = als;
260
+ if (typeof als.enterWith === "function") {
261
+ try {
262
+ als.enterWith(EMPTY_STACK);
263
+ this._enterWithUsable = true;
264
+ } catch (e) {
265
+ this._enterWithUsable = false;
266
+ }
267
+ }
268
+ }
269
+ getStack() {
270
+ var _a;
271
+ this.maybeAdoptAsyncLocalStorage();
272
+ if (this._als) return (_a = this._als.getStore()) != null ? _a : this._syncStack;
273
+ return this._syncStack;
274
+ }
275
+ /**
276
+ * Persist an ambient stack mutation. Returns false when an ALS is adopted but
277
+ * `enterWith` is unusable (workerd): callers must NOT fall back to the
278
+ * process-shared sync stack, since concurrent isolates would cross-stamp.
279
+ */
280
+ setAmbientStack(stack) {
281
+ if (this._als) {
282
+ if (!this._enterWithUsable) return false;
283
+ this._als.enterWith(stack);
284
+ return true;
285
+ }
286
+ this._syncStack = stack;
287
+ return true;
288
+ }
289
+ push(binding) {
290
+ this.maybeAdoptAsyncLocalStorage();
291
+ if (this._als && !this._enterWithUsable) {
292
+ this.warnNoAmbientBindOnce();
293
+ return;
294
+ }
295
+ let stack = this.getStack();
296
+ if (stack.length >= MAX_BINDING_STACK) {
297
+ stack = stack.filter((b) => b.isLive());
298
+ if (stack.length >= MAX_BINDING_STACK) {
299
+ stack = stack.slice(stack.length - (MAX_BINDING_STACK - 1));
300
+ }
301
+ }
302
+ this.setAmbientStack([...stack, binding]);
303
+ }
304
+ remove(binding) {
305
+ binding.markDead();
306
+ const stack = this.getStack();
307
+ const pruned = stack.filter((b) => b !== binding && b.isLive());
308
+ if (pruned.length !== stack.length) {
309
+ this.setAmbientStack(pruned);
310
+ }
311
+ }
312
+ runWith(binding, callback) {
313
+ this.maybeAdoptAsyncLocalStorage();
314
+ if (this._als) {
315
+ return this._als.run([...this.getStack(), binding], callback);
316
+ }
317
+ const previous = this._syncStack;
318
+ this._syncStack = [...previous, binding];
319
+ try {
320
+ return callback();
321
+ } finally {
322
+ this._syncStack = previous;
323
+ }
324
+ }
325
+ current() {
326
+ const stack = this.getStack();
327
+ if (stack.length === 0) return void 0;
328
+ const top = stack[stack.length - 1];
329
+ if (top.isLive()) return top;
330
+ const pruned = stack.filter((b) => b.isLive());
331
+ this.setAmbientStack(pruned);
332
+ return pruned.length > 0 ? pruned[pruned.length - 1] : void 0;
333
+ }
334
+ warnNoAmbientBindOnce() {
335
+ if (this._warnedNoAmbientBind) return;
336
+ this._warnedNoAmbientBind = true;
337
+ console.warn(this.noAmbientBindWarning);
338
+ }
339
+ };
340
+ 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.";
341
+ var ROUTING_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.routingContextStorage");
342
+ function routingStorage() {
343
+ const holder = globalThis;
344
+ let storage = holder[ROUTING_STORAGE_KEY];
345
+ if (!storage) {
346
+ storage = new ContextStackStorage(NO_AMBIENT_ROUTING_BIND_WARNING);
347
+ holder[ROUTING_STORAGE_KEY] = storage;
348
+ }
349
+ return storage;
350
+ }
351
+ function currentRoutingBinding() {
352
+ const bound = routingStorage().current();
353
+ if (!bound) return void 0;
354
+ return {
355
+ projectId: bound.projectId,
356
+ authHint: bound.authHint,
357
+ ...bound.appGit ? { appGit: bound.appGit } : {},
358
+ ...bound.appGitSource ? { appGitSource: bound.appGitSource } : {}
359
+ };
360
+ }
361
+ var APP_COMMIT_SHA = "raindrop.app.commit_sha";
362
+ var APP_COMMIT_DIRTY = "raindrop.app.commit_dirty";
363
+ var APP_BRANCH = "raindrop.app.branch";
364
+ var APP_GIT_KEYS = [APP_COMMIT_SHA, APP_COMMIT_DIRTY, APP_BRANCH];
365
+ var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
366
+ function appGitExplicitKeys(properties) {
367
+ const keys = /* @__PURE__ */ new Set();
368
+ if (!properties) return keys;
369
+ for (const key of APP_GIT_KEYS) {
370
+ if (own(properties, key)) keys.add(key);
371
+ }
372
+ return keys;
373
+ }
374
+ function mergeAppGitSnapshot(base, properties, explicitKeys = /* @__PURE__ */ new Set()) {
375
+ try {
376
+ const result = { ...base };
377
+ if (properties && own(properties, APP_COMMIT_SHA) && properties[APP_COMMIT_SHA] !== result[APP_COMMIT_SHA]) {
378
+ if (!explicitKeys.has(APP_COMMIT_DIRTY) && !own(properties, APP_COMMIT_DIRTY)) {
379
+ delete result[APP_COMMIT_DIRTY];
380
+ }
381
+ if (!explicitKeys.has(APP_BRANCH) && !own(properties, APP_BRANCH)) {
382
+ delete result[APP_BRANCH];
383
+ }
384
+ }
385
+ for (const key of APP_GIT_KEYS) {
386
+ if (properties && own(properties, key)) result[key] = properties[key];
387
+ }
388
+ return Object.freeze(result);
389
+ } catch (e) {
390
+ return Object.freeze({});
391
+ }
392
+ }
393
+ function validAppCommitSha(value) {
394
+ if (typeof value !== "string" || value.length > 128) return void 0;
395
+ const cleaned = value.trim();
396
+ return /^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(cleaned) ? cleaned.toLowerCase() : void 0;
397
+ }
398
+ function shortString(value) {
399
+ if (typeof value !== "string" || value.length > 1024) return void 0;
400
+ const cleaned = value.trim();
401
+ return cleaned.length > 0 ? cleaned : void 0;
402
+ }
403
+ function flag(value) {
404
+ if (value === true || value === "true" || value === "1") return true;
405
+ if (value === false || value === "false" || value === "0") return false;
406
+ return void 0;
407
+ }
408
+ function environment() {
409
+ try {
410
+ return typeof process === "undefined" ? {} : process.env;
411
+ } catch (e) {
412
+ return {};
413
+ }
414
+ }
415
+ var DEPLOYMENTS = [
416
+ ["VERCEL", "VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
417
+ ["NETLIFY", "COMMIT_REF", "BRANCH"],
418
+ ["RAILWAY_ENVIRONMENT_NAME", "RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH"],
419
+ ["RAILWAY_ENVIRONMENT", "RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH"],
420
+ ["RENDER", "RENDER_GIT_COMMIT", "RENDER_GIT_BRANCH"],
421
+ ["DYNO", "HEROKU_BUILD_COMMIT", ""],
422
+ ["DYNO", "HEROKU_SLUG_COMMIT", ""],
423
+ ["AWS_APP_ID", "AWS_COMMIT_ID", "AWS_BRANCH"],
424
+ ["WORKERS_CI", "WORKERS_CI_COMMIT_SHA", "WORKERS_CI_BRANCH"]
425
+ ];
426
+ var CI_SOURCES = [
427
+ ["GITHUB_ACTIONS", "GITHUB_SHA", "GITHUB_REF_NAME"],
428
+ ["GITLAB_CI", "CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
429
+ ["CIRCLECI", "CIRCLE_SHA1", "CIRCLE_BRANCH"]
430
+ ];
431
+ function detectedSource(env, table, detectBranch) {
432
+ for (const row of table) {
433
+ const [marker, shaKey, branchKey] = row;
434
+ if (!marker || !shaKey || !shortString(env[marker]) || flag(env[marker]) === false) continue;
435
+ const commitSha = validAppCommitSha(env[shaKey]);
436
+ if (commitSha)
437
+ return {
438
+ commitSha,
439
+ ...detectBranch && branchKey ? { branch: shortString(env[branchKey]) } : {}
440
+ };
441
+ }
442
+ return {};
443
+ }
444
+ var AppGitContextImpl = class {
445
+ constructor(options, runtime = {}) {
446
+ this.defaults = {};
447
+ this.explicit = {};
448
+ this.explicitKeys = /* @__PURE__ */ new Set();
449
+ this.disposed = false;
450
+ this.operations = /* @__PURE__ */ new Map();
451
+ this.operationOverflow = false;
452
+ this.detectBranch = false;
453
+ this.disabled = false;
454
+ var _a, _b, _c, _d, _e, _f;
455
+ try {
456
+ if (options === false) {
457
+ this.disabled = true;
458
+ return;
459
+ }
460
+ const opts = options != null ? options : {};
461
+ const env = (_a = runtime.env) != null ? _a : environment();
462
+ const detectBranch = (_c = (_b = flag(opts.detectBranch)) != null ? _b : flag(env.RAINDROP_GIT_DETECT_BRANCH)) != null ? _c : false;
463
+ this.detectBranch = detectBranch;
464
+ const collectBranch = detectBranch || runtime.captureLegacyReplayBranch === true;
465
+ const autoDetect = runtime.allowDiscovery === false ? false : (_e = (_d = flag(opts.autoDetect)) != null ? _d : flag(env.RAINDROP_GIT_AUTO_DETECT)) != null ? _e : true;
466
+ const configuredSha = opts.commitSha;
467
+ const explicitSha = configuredSha === void 0 ? env.RAINDROP_COMMIT_SHA : configuredSha;
468
+ if (explicitSha === null) this.explicit[APP_COMMIT_SHA] = null;
469
+ else if (typeof explicitSha === "string" && validAppCommitSha(explicitSha))
470
+ this.explicit[APP_COMMIT_SHA] = explicitSha;
471
+ const configuredDirty = opts.commitDirty;
472
+ const explicitDirty = configuredDirty === void 0 ? flag(env.RAINDROP_COMMIT_DIRTY) : configuredDirty;
473
+ if (explicitDirty === null || typeof explicitDirty === "boolean")
474
+ this.explicit[APP_COMMIT_DIRTY] = explicitDirty;
475
+ const configuredBranch = opts.branch;
476
+ const explicitBranch = configuredBranch === void 0 ? env.RAINDROP_BRANCH : configuredBranch;
477
+ if (explicitBranch === null) this.explicit[APP_BRANCH] = null;
478
+ else if (typeof explicitBranch === "string" && explicitBranch.length <= 1024)
479
+ this.explicit[APP_BRANCH] = explicitBranch;
480
+ this.explicitKeys = appGitExplicitKeys(this.explicit);
481
+ this.defaults = { ...this.explicit };
482
+ if (!autoDetect || explicitSha !== void 0) return;
483
+ const sourceDirectory = (_f = shortString(opts.sourceDirectory)) != null ? _f : shortString(env.RAINDROP_GIT_SOURCE_DIRECTORY);
484
+ if (runtime.allowLocalGit === false && !sourceDirectory) return;
485
+ const deploy = sourceDirectory ? {} : detectedSource(env, DEPLOYMENTS, collectBranch);
486
+ if (deploy.commitSha) {
487
+ this.accept(deploy);
488
+ return;
489
+ }
490
+ const fallback = sourceDirectory ? {} : detectedSource(env, CI_SOURCES, collectBranch);
491
+ if (runtime.resolveLocal && (runtime.allowLocalGit !== false || sourceDirectory)) {
492
+ this.cancel = runtime.resolveLocal(sourceDirectory, collectBranch, (result) => {
493
+ try {
494
+ if (!this.disposed) this.accept(result.commitSha ? result : fallback);
495
+ } catch (e) {
496
+ }
497
+ });
498
+ } else this.accept(fallback);
499
+ } catch (e) {
500
+ }
501
+ }
502
+ accept(result) {
503
+ const sha = validAppCommitSha(result.commitSha);
504
+ if (!sha) return;
505
+ this.replayBranch = shortString(result.branch);
506
+ this.defaults = {
507
+ [APP_COMMIT_SHA]: sha,
508
+ ...typeof result.commitDirty === "boolean" ? { [APP_COMMIT_DIRTY]: result.commitDirty } : {},
509
+ ...this.detectBranch && this.replayBranch ? { [APP_BRANCH]: this.replayBranch } : {},
510
+ ...this.explicit
511
+ };
512
+ }
513
+ snapshot(properties) {
514
+ var _a;
515
+ try {
516
+ const binding = currentRoutingBinding();
517
+ const base = this.disabled && (binding == null ? void 0 : binding.appGitSource) !== "replay-override" ? {} : (_a = binding == null ? void 0 : binding.appGit) != null ? _a : this.defaults;
518
+ return this.mergeSnapshot(base, properties);
519
+ } catch (e) {
520
+ return Object.freeze({});
521
+ }
522
+ }
523
+ /** Safe defaults when no operation/span start was observed; never infer identity. */
524
+ snapshotExplicit(properties, eventId) {
525
+ try {
526
+ const base = { ...this.explicit };
527
+ const operation = eventId ? this.operations.get(eventId) : void 0;
528
+ if (operation) {
529
+ for (const key of operation.explicitKeys) base[key] = operation.snapshot[key];
530
+ }
531
+ return this.mergeSnapshot(base, properties, new Set(Object.keys(base)));
532
+ } catch (e) {
533
+ return mergeAppGitSnapshot({}, properties);
534
+ }
535
+ }
536
+ /** Existing replay branch reporting stays separate from opt-in event properties. */
537
+ snapshotForReplay() {
538
+ const snapshot = this.snapshot();
539
+ if (this.replayBranch && !own(snapshot, APP_BRANCH) && snapshot[APP_COMMIT_SHA] === this.defaults[APP_COMMIT_SHA]) {
540
+ return Object.freeze({ ...snapshot, [APP_BRANCH]: this.replayBranch });
541
+ }
542
+ return snapshot;
543
+ }
544
+ /** Merge a frozen span snapshot without losing client-authored provenance. */
545
+ mergeSnapshot(base, properties, explicitKeys = this.explicitKeys) {
546
+ return mergeAppGitSnapshot(base, properties, /* @__PURE__ */ new Set([...this.explicitKeys, ...explicitKeys]));
547
+ }
548
+ /** Shippers belonging to one client share this bounded operation registry. */
549
+ forOperation(eventId, properties, owner) {
550
+ if (!eventId) return this.snapshot(properties);
551
+ let operation = this.operations.get(eventId);
552
+ if (!operation) {
553
+ if (this.operations.size >= 1e4) this.operationOverflow = true;
554
+ if (this.operationOverflow) return this.mergeSnapshot({}, properties);
555
+ operation = {
556
+ snapshot: this.snapshot(properties),
557
+ owners: /* @__PURE__ */ new Set(),
558
+ unowned: owner === void 0,
559
+ explicitKeys: appGitExplicitKeys(properties)
560
+ };
561
+ this.operations.set(eventId, operation);
562
+ } else if (properties && APP_GIT_KEYS.some((key) => own(properties, key))) {
563
+ const explicitKeys = /* @__PURE__ */ new Set([...this.explicitKeys, ...operation.explicitKeys]);
564
+ operation.snapshot = this.mergeSnapshot(operation.snapshot, properties, explicitKeys);
565
+ for (const key of appGitExplicitKeys(properties)) operation.explicitKeys.add(key);
566
+ }
567
+ if (!owner) operation.unowned = true;
568
+ if (owner) operation.owners.add(owner);
569
+ return operation.snapshot;
570
+ }
571
+ releaseOperation(eventId, owner) {
572
+ const operation = this.operations.get(eventId);
573
+ if (!operation) return;
574
+ operation.owners.delete(owner);
575
+ if (operation.owners.size === 0 && !operation.unowned) this.operations.delete(eventId);
576
+ }
577
+ finishOperation(eventId) {
578
+ this.operations.delete(eventId);
579
+ }
580
+ dispose() {
581
+ var _a;
582
+ this.disposed = true;
583
+ try {
584
+ (_a = this.cancel) == null ? void 0 : _a.call(this);
585
+ } catch (e) {
586
+ }
587
+ }
588
+ };
589
+ var AppGitContext = AppGitContextImpl;
590
+ function createAppGitContext(options, runtime = {}) {
591
+ return new AppGitContext(options, runtime);
592
+ }
593
+ function withAppGitProperties(properties, snapshot) {
594
+ try {
595
+ const merged = { ...properties };
596
+ for (const key of APP_GIT_KEYS)
597
+ if (!own(merged, key) && own(snapshot, key)) merged[key] = snapshot[key];
598
+ return merged;
599
+ } catch (e) {
600
+ return properties != null ? properties : {};
601
+ }
602
+ }
603
+ function withAppGitAttributes(attributes, snapshot) {
604
+ try {
605
+ const present = new Set(attributes.flatMap((attr) => attr ? [attr.key] : []));
606
+ const added = [];
607
+ for (const key of APP_GIT_KEYS) {
608
+ if (present.has(key) || present.has(`ai.telemetry.metadata.${key}`) || present.has(`traceloop.association.properties.${key}`))
609
+ continue;
610
+ const value = snapshot[key];
611
+ if (typeof value === "string") added.push({ key, value: { stringValue: value } });
612
+ else if (typeof value === "boolean") added.push({ key, value: { boolValue: value } });
613
+ }
614
+ return added.length ? [...attributes, ...added] : attributes;
615
+ } catch (e) {
616
+ return attributes;
617
+ }
618
+ }
619
+ function appGitPropertiesFromAttributes(attributes) {
620
+ var _a, _b, _c;
621
+ const properties = {};
622
+ try {
623
+ for (const attr of attributes) {
624
+ if (!attr) continue;
625
+ for (const key of APP_GIT_KEYS) {
626
+ if (attr.key === key || attr.key === `ai.telemetry.metadata.${key}` || attr.key === `traceloop.association.properties.${key}`) {
627
+ properties[key] = (_c = (_b = (_a = attr.value.stringValue) != null ? _a : attr.value.boolValue) != null ? _b : attr.value.intValue) != null ? _c : null;
628
+ }
629
+ }
630
+ }
631
+ } catch (e) {
632
+ }
633
+ return properties;
634
+ }
66
635
  function normalizeFeatureFlags(input) {
67
636
  if (Array.isArray(input)) {
68
637
  return Object.fromEntries(input.map((name) => [name, "true"]));
@@ -447,7 +1016,7 @@ function runWithTracingSuppressed(fn) {
447
1016
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
448
1017
  var MAX_RETRY_DELAY_MS = 3e4;
449
1018
  function wait(ms) {
450
- return new Promise((resolve) => setTimeout(resolve, ms));
1019
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
451
1020
  }
452
1021
  function formatEndpoint(endpoint) {
453
1022
  if (!endpoint) return void 0;
@@ -484,9 +1053,9 @@ async function raceWithTimeout(promise, timeoutMs) {
484
1053
  () => true,
485
1054
  () => true
486
1055
  ),
487
- new Promise((resolve) => {
1056
+ new Promise((resolve2) => {
488
1057
  var _a;
489
- timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
1058
+ timer = setTimeout(() => resolve2(false), Math.max(0, timeoutMs));
490
1059
  (_a = timer.unref) == null ? void 0 : _a.call(timer);
491
1060
  })
492
1061
  ]);
@@ -681,55 +1250,6 @@ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", se
681
1250
  ]
682
1251
  };
683
1252
  }
684
- var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
685
- function state() {
686
- const holder = globalThis;
687
- let current = holder[STATE_KEY];
688
- if (!current) {
689
- let storage = null;
690
- try {
691
- const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
692
- if (Ctor) storage = new Ctor();
693
- } catch (e) {
694
- storage = null;
695
- }
696
- current = {
697
- storage,
698
- syncDestination: void 0,
699
- spanDestinations: /* @__PURE__ */ new WeakMap()
700
- };
701
- holder[STATE_KEY] = current;
702
- }
703
- return current;
704
- }
705
- function currentReplayTraceDestination() {
706
- var _a, _b;
707
- const routing = state();
708
- return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
709
- }
710
- function rememberReplayTraceDestination(span) {
711
- const destination = currentReplayTraceDestination();
712
- if (destination) state().spanDestinations.set(span, destination);
713
- }
714
- function copyReplayTraceDestination(source, target) {
715
- const destination = state().spanDestinations.get(source);
716
- if (destination) state().spanDestinations.set(target, destination);
717
- }
718
- function replayTraceDestinationFor(value) {
719
- if (typeof value !== "object" && typeof value !== "function" || value === null) {
720
- return void 0;
721
- }
722
- return state().spanDestinations.get(value);
723
- }
724
- function recordReplayExportedSpan(destination, spanId, traceId) {
725
- var _a, _b;
726
- if (!destination || !spanId || !traceId) return;
727
- (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
728
- (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
729
- }
730
- function replayTraceUrl(baseUrl) {
731
- return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
732
- }
733
1253
  var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
734
1254
  var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
735
1255
  var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
@@ -864,6 +1384,13 @@ function projectIdHeaders(projectId) {
864
1384
  }
865
1385
  var SHUTDOWN_DEADLINE_MS = 1e4;
866
1386
  var POST_SHUTDOWN_TIMEOUT_MS = 5e3;
1387
+ function appGitOwnerId(prefix) {
1388
+ try {
1389
+ return `${prefix}:${randomUUID()}`;
1390
+ } catch (e) {
1391
+ return `${prefix}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
1392
+ }
1393
+ }
867
1394
  function mergePatches(target, source) {
868
1395
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
869
1396
  const out = { ...target, ...source };
@@ -913,22 +1440,25 @@ function eventTelemetryProperties(patch) {
913
1440
  }
914
1441
  var EventShipper = class {
915
1442
  constructor(opts) {
1443
+ this.appGitOwner = appGitOwnerId("event");
916
1444
  this.buffers = /* @__PURE__ */ new Map();
917
1445
  this.sticky = /* @__PURE__ */ new Map();
918
1446
  this.timers = /* @__PURE__ */ new Map();
919
1447
  this.inFlight = /* @__PURE__ */ new Set();
920
1448
  this.hasShutdown = false;
921
- var _a, _b, _c, _d, _e, _f, _g, _h;
922
- this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
923
- this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
1449
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1450
+ this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
1451
+ this.ownsAppGitContext = opts.appGitContext === void 0;
1452
+ this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
1453
+ this.baseUrl = (_c = formatEndpoint(opts.endpoint)) != null ? _c : "https://api.raindrop.ai/v1/";
924
1454
  this.enabled = opts.enabled !== false;
925
1455
  this.debug = opts.debug;
926
- this.partialFlushMs = (_c = opts.partialFlushMs) != null ? _c : 1e3;
927
- this.sdkName = (_d = opts.sdkName) != null ? _d : "core";
1456
+ this.partialFlushMs = (_d = opts.partialFlushMs) != null ? _d : 1e3;
1457
+ this.sdkName = (_e = opts.sdkName) != null ? _e : "core";
928
1458
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
929
- this.defaultEventName = (_e = opts.defaultEventName) != null ? _e : "ai_generation";
1459
+ this.defaultEventName = (_f = opts.defaultEventName) != null ? _f : "ai_generation";
930
1460
  this.maxTextFieldCharsOpt = opts.maxTextFieldChars;
931
- this.localDebuggerUrl = (_f = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _f : void 0;
1461
+ this.localDebuggerUrl = (_g = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _g : void 0;
932
1462
  if (this.debug && this.localDebuggerUrl) {
933
1463
  console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
934
1464
  }
@@ -939,8 +1469,8 @@ var EventShipper = class {
939
1469
  const isNode = typeof process !== "undefined" && typeof process.version === "string";
940
1470
  this.context = {
941
1471
  library: {
942
- name: (_g = opts.libraryName) != null ? _g : "@raindrop-ai/core",
943
- version: (_h = opts.libraryVersion) != null ? _h : "0.0.0"
1472
+ name: (_h = opts.libraryName) != null ? _h : "@raindrop-ai/core",
1473
+ version: (_i = opts.libraryVersion) != null ? _i : "0.0.0"
944
1474
  },
945
1475
  metadata: {
946
1476
  jsRuntime: isNode ? "node" : "web",
@@ -948,6 +1478,9 @@ var EventShipper = class {
948
1478
  }
949
1479
  };
950
1480
  }
1481
+ ownAppGitContextForShutdown() {
1482
+ this.ownsAppGitContext = true;
1483
+ }
951
1484
  isDebugEnabled() {
952
1485
  return this.debug;
953
1486
  }
@@ -1026,6 +1559,13 @@ var EventShipper = class {
1026
1559
  }
1027
1560
  const sticky = (_c = this.sticky.get(eventId)) != null ? _c : {};
1028
1561
  const existing = (_d = this.buffers.get(eventId)) != null ? _d : {};
1562
+ patch = {
1563
+ ...patch,
1564
+ properties: withAppGitProperties(
1565
+ patch.properties,
1566
+ this.appGitContext.forOperation(eventId, patch.properties, this.appGitOwner)
1567
+ )
1568
+ };
1029
1569
  const merged = mergePatches(existing, patch);
1030
1570
  merged.isPending = (_g = (_f = (_e = patch.isPending) != null ? _e : existing.isPending) != null ? _f : sticky.isPending) != null ? _g : true;
1031
1571
  this.buffers.set(eventId, merged);
@@ -1039,6 +1579,8 @@ var EventShipper = class {
1039
1579
  if (t) clearTimeout(t);
1040
1580
  if (merged.isPending === false) {
1041
1581
  await this.flushOne(eventId);
1582
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(eventId, this.appGitOwner);
1583
+ else this.appGitContext.finishOperation(eventId);
1042
1584
  return;
1043
1585
  }
1044
1586
  const timeout = setTimeout(() => {
@@ -1070,6 +1612,7 @@ var EventShipper = class {
1070
1612
  if (!settled) this.warnShutdownDrop("in-flight request(s) at shutdown");
1071
1613
  } finally {
1072
1614
  this.shutdownDeadlineAt = void 0;
1615
+ if (this.ownsAppGitContext) this.appGitContext.dispose();
1073
1616
  }
1074
1617
  }
1075
1618
  async trackSignal(signal) {
@@ -1504,6 +2047,13 @@ function redactJsonAttributeValue(key, value) {
1504
2047
  if (scrubbedJson === json) return void 0;
1505
2048
  return { stringValue: scrubbedJson };
1506
2049
  }
2050
+ function appGitOwnerId2(prefix) {
2051
+ try {
2052
+ return `${prefix}:${randomUUID()}`;
2053
+ } catch (e) {
2054
+ return `${prefix}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
2055
+ }
2056
+ }
1507
2057
  function identityAttrs(args) {
1508
2058
  return [
1509
2059
  attrString("ai.telemetry.metadata.raindrop.ai.userId", args.userId),
@@ -1526,23 +2076,30 @@ function applyOtelSpanAttributeLimit(limit) {
1526
2076
  }
1527
2077
  var TraceShipper = class {
1528
2078
  constructor(opts) {
2079
+ this.appGitOwner = appGitOwnerId2("trace");
2080
+ this.appGitEventIds = /* @__PURE__ */ new WeakMap();
2081
+ this.appGitActiveSpans = /* @__PURE__ */ new Map();
2082
+ this.appGitCaptured = /* @__PURE__ */ new WeakSet();
2083
+ this.appGitAdded = /* @__PURE__ */ new WeakMap();
1529
2084
  this.queue = [];
1530
2085
  this.inFlight = /* @__PURE__ */ new Set();
1531
2086
  this.hasShutdown = false;
1532
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1533
- this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
1534
- this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
2087
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2088
+ this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
2089
+ this.ownsAppGitContext = opts.appGitContext === void 0;
2090
+ this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
2091
+ this.baseUrl = (_c = formatEndpoint(opts.endpoint)) != null ? _c : "https://api.raindrop.ai/v1/";
1535
2092
  this.enabled = opts.enabled !== false;
1536
2093
  this.debug = opts.debug;
1537
2094
  this.debugSpans = opts.debugSpans === true;
1538
- this.flushIntervalMs = (_c = opts.flushIntervalMs) != null ? _c : 1e3;
1539
- this.maxBatchSize = (_d = opts.maxBatchSize) != null ? _d : 50;
1540
- this.maxQueueSize = (_e = opts.maxQueueSize) != null ? _e : 5e3;
1541
- this.sdkName = (_f = opts.sdkName) != null ? _f : "core";
2095
+ this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
2096
+ this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
2097
+ this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
2098
+ this.sdkName = (_g = opts.sdkName) != null ? _g : "core";
1542
2099
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
1543
- this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
1544
- this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
1545
- this.localDebuggerUrl = (_i = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _i : void 0;
2100
+ this.serviceName = (_h = opts.serviceName) != null ? _h : "raindrop.core";
2101
+ this.serviceVersion = (_i = opts.serviceVersion) != null ? _i : "0.0.0";
2102
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _j : void 0;
1546
2103
  if (this.debug && this.localDebuggerUrl) {
1547
2104
  console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
1548
2105
  }
@@ -1643,7 +2200,7 @@ var TraceShipper = class {
1643
2200
  return { ...this.authHeaders(), ...projectIdHeaders(this.projectId) };
1644
2201
  }
1645
2202
  startSpan(args) {
1646
- var _a, _b;
2203
+ var _a, _b, _c;
1647
2204
  const ids = createSpanIds(args.parent);
1648
2205
  const started = (_a = args.startTimeUnixNano) != null ? _a : nowUnixNanoString();
1649
2206
  const attrs = [
@@ -1653,13 +2210,24 @@ var TraceShipper = class {
1653
2210
  ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1654
2211
  ];
1655
2212
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
2213
+ const tracksAppGit = this.appGitActiveSpans.has(args.eventId) || this.appGitActiveSpans.size < 1e4;
2214
+ const appGitOverrides = appGitPropertiesFromAttributes(attrs);
1656
2215
  const span = {
1657
2216
  ids,
1658
2217
  name: args.name,
1659
2218
  startTimeUnixNano: started,
1660
- attributes: attrs
2219
+ attributes: withAppGitAttributes(
2220
+ attrs,
2221
+ this.appGitContext.forOperation(args.eventId, appGitOverrides, this.appGitOwner)
2222
+ )
1661
2223
  };
1662
2224
  rememberReplayTraceDestination(span);
2225
+ this.appGitCaptured.add(span);
2226
+ this.appGitEventIds.set(span, args.eventId);
2227
+ if (tracksAppGit) {
2228
+ this.appGitActiveSpans.set(args.eventId, ((_c = this.appGitActiveSpans.get(args.eventId)) != null ? _c : 0) + 1);
2229
+ }
2230
+ this.appGitAdded.set(span, new Set(span.attributes.filter((attr) => !attrs.includes(attr))));
1663
2231
  const openSpan = buildOtlpSpan({
1664
2232
  ids: span.ids,
1665
2233
  name: span.name,
@@ -1699,11 +2267,17 @@ var TraceShipper = class {
1699
2267
  });
1700
2268
  }
1701
2269
  endSpan(span, extra) {
1702
- var _a, _b;
2270
+ var _a, _b, _c;
1703
2271
  if (span.endTimeUnixNano) return;
1704
2272
  span.endTimeUnixNano = (_a = extra == null ? void 0 : extra.endTimeUnixNano) != null ? _a : nowUnixNanoString();
1705
2273
  if ((_b = extra == null ? void 0 : extra.attributes) == null ? void 0 : _b.length) {
2274
+ const overrides = appGitPropertiesFromAttributes(extra.attributes);
2275
+ const eventId2 = this.appGitEventIds.get(span);
2276
+ const snapshot = eventId2 ? this.appGitContext.forOperation(eventId2, overrides, this.appGitOwner) : overrides;
2277
+ const added = this.appGitAdded.get(span);
2278
+ 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));
1706
2279
  span.attributes.push(...extra.attributes);
2280
+ span.attributes = withAppGitAttributes(span.attributes, snapshot);
1707
2281
  }
1708
2282
  let status = extra == null ? void 0 : extra.status;
1709
2283
  if (!status && (extra == null ? void 0 : extra.error) !== void 0) {
@@ -1719,8 +2293,19 @@ var TraceShipper = class {
1719
2293
  status
1720
2294
  });
1721
2295
  copyReplayTraceDestination(span, otlp);
2296
+ this.appGitCaptured.add(otlp);
1722
2297
  this.enqueue(otlp);
1723
2298
  this.mirrorToLocalDebugger(otlp, true);
2299
+ const eventId = this.appGitEventIds.get(span);
2300
+ if (eventId && this.appGitActiveSpans.has(eventId)) {
2301
+ const remaining = ((_c = this.appGitActiveSpans.get(eventId)) != null ? _c : 1) - 1;
2302
+ if (remaining > 0) this.appGitActiveSpans.set(eventId, remaining);
2303
+ else {
2304
+ this.appGitActiveSpans.delete(eventId);
2305
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(eventId, this.appGitOwner);
2306
+ else if (this.ownsAppGitContext) this.appGitContext.finishOperation(eventId);
2307
+ }
2308
+ }
1724
2309
  }
1725
2310
  createSpan(args) {
1726
2311
  var _a;
@@ -1731,20 +2316,41 @@ var TraceShipper = class {
1731
2316
  ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1732
2317
  ];
1733
2318
  if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
2319
+ const tracksAppGit = !this.appGitActiveSpans.has(args.eventId);
1734
2320
  const otlp = buildOtlpSpan({
1735
2321
  ids,
1736
2322
  name: args.name,
1737
2323
  startTimeUnixNano: args.startTimeUnixNano,
1738
2324
  endTimeUnixNano: args.endTimeUnixNano,
1739
- attributes: attrs,
2325
+ attributes: withAppGitAttributes(
2326
+ attrs,
2327
+ this.appGitContext.forOperation(
2328
+ args.eventId,
2329
+ appGitPropertiesFromAttributes(attrs),
2330
+ this.appGitOwner
2331
+ )
2332
+ ),
1740
2333
  status: args.status
1741
2334
  });
1742
2335
  rememberReplayTraceDestination(otlp);
2336
+ this.appGitCaptured.add(otlp);
2337
+ if (tracksAppGit) {
2338
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(args.eventId, this.appGitOwner);
2339
+ else if (this.ownsAppGitContext) this.appGitContext.finishOperation(args.eventId);
2340
+ }
1743
2341
  this.enqueue(otlp);
1744
2342
  this.mirrorToLocalDebugger(otlp, true);
1745
2343
  }
1746
2344
  enqueue(span) {
2345
+ var _a;
1747
2346
  if (!this.enabled) return;
2347
+ const attributes = (_a = span.attributes) != null ? _a : [];
2348
+ const enriched = this.appGitCaptured.has(span) ? attributes : withAppGitAttributes(attributes, this.appGitContext.snapshot(appGitPropertiesFromAttributes(attributes)));
2349
+ if (enriched !== attributes) {
2350
+ const original = span;
2351
+ span = { ...span, attributes: enriched.filter((attr) => attr !== void 0) };
2352
+ copyReplayTraceDestination(original, span);
2353
+ }
1748
2354
  if (this.debugSpans) {
1749
2355
  const short = (s) => s ? s.slice(-8) : "none";
1750
2356
  console.log(
@@ -1890,127 +2496,153 @@ var TraceShipper = class {
1890
2496
  }
1891
2497
  } finally {
1892
2498
  this.shutdownDeadlineAt = void 0;
2499
+ if (this.ownsAppGitContext) this.appGitContext.dispose();
1893
2500
  }
1894
2501
  }
1895
2502
  };
1896
- var NOOP_SPAN = {
1897
- traceIdB64: "",
1898
- spanIdB64: "",
1899
- eventId: "",
1900
- log() {
1901
- }
1902
- };
1903
- function getAsyncLocalStorageCtor() {
1904
- return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
1905
- }
1906
- var SynchronousContextStorage = class {
1907
- constructor() {
1908
- this._stack = [];
1909
- }
1910
- isEmpty() {
1911
- return this._stack.length === 0;
1912
- }
1913
- getStore() {
1914
- return this._stack[this._stack.length - 1];
1915
- }
1916
- run(store, callback) {
1917
- this._stack.push(store);
2503
+ var resolveLocal = (sourceDirectory, detectBranch, completed) => {
2504
+ const cwd = sourceDirectory ? resolve(sourceDirectory) : process.cwd();
2505
+ let cancelled = false;
2506
+ let active;
2507
+ let deadlineTimer;
2508
+ const deadline = Date.now() + 1e3;
2509
+ const run = (args, done) => {
2510
+ if (cancelled) return;
2511
+ const remaining = deadline - Date.now();
2512
+ if (remaining <= 0) {
2513
+ done(void 0);
2514
+ return;
2515
+ }
1918
2516
  try {
1919
- return callback();
1920
- } finally {
1921
- this._stack.pop();
2517
+ active = execFile(
2518
+ "git",
2519
+ args,
2520
+ {
2521
+ cwd,
2522
+ encoding: "utf8",
2523
+ maxBuffer: 4096,
2524
+ windowsHide: true,
2525
+ env: {
2526
+ ...process.env,
2527
+ // The selected application cwd, not the invoking shell's Git plumbing, owns identity.
2528
+ GIT_DIR: void 0,
2529
+ GIT_WORK_TREE: void 0,
2530
+ GIT_COMMON_DIR: void 0,
2531
+ GIT_NAMESPACE: void 0,
2532
+ GIT_INDEX_FILE: void 0,
2533
+ GIT_OBJECT_DIRECTORY: void 0,
2534
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: void 0,
2535
+ GIT_CONFIG_PARAMETERS: void 0,
2536
+ GIT_CONFIG_COUNT: "0",
2537
+ GIT_TERMINAL_PROMPT: "0",
2538
+ GIT_OPTIONAL_LOCKS: "0"
2539
+ }
2540
+ },
2541
+ (error, stdout) => {
2542
+ clearTimeout(deadlineTimer);
2543
+ deadlineTimer = void 0;
2544
+ active = void 0;
2545
+ if (!cancelled) {
2546
+ try {
2547
+ done(error ? void 0 : stdout.trim());
2548
+ } catch (e) {
2549
+ }
2550
+ }
2551
+ }
2552
+ );
2553
+ active.unref();
2554
+ if (active.stdout && "unref" in active.stdout && typeof active.stdout.unref === "function")
2555
+ active.stdout.unref();
2556
+ if (active.stderr && "unref" in active.stderr && typeof active.stderr.unref === "function")
2557
+ active.stderr.unref();
2558
+ deadlineTimer = setTimeout(() => {
2559
+ try {
2560
+ active == null ? void 0 : active.kill("SIGKILL");
2561
+ } catch (e) {
2562
+ }
2563
+ }, remaining);
2564
+ deadlineTimer.unref();
2565
+ } catch (e) {
2566
+ try {
2567
+ done(void 0);
2568
+ } catch (e2) {
2569
+ }
1922
2570
  }
1923
- }
1924
- };
1925
- var ContextManager = class {
1926
- };
1927
- var RaindropContextManager = class extends ContextManager {
1928
- constructor() {
1929
- super();
1930
- this._fallback = null;
1931
- const Ctor = getAsyncLocalStorageCtor();
1932
- if (Ctor) {
1933
- this._storage = new Ctor();
1934
- return;
2571
+ };
2572
+ const scheduled = setTimeout(() => {
2573
+ try {
2574
+ run(["rev-parse", "HEAD"], (rawSha) => {
2575
+ const commitSha = validAppCommitSha(rawSha);
2576
+ if (!commitSha) {
2577
+ completed({});
2578
+ return;
2579
+ }
2580
+ run(["-c", "core.fsmonitor=false", "status", "--porcelain"], (status) => {
2581
+ const finish = (branch) => {
2582
+ run(["rev-parse", "HEAD"], (finalSha) => {
2583
+ const coherent = validAppCommitSha(finalSha) === commitSha;
2584
+ completed({
2585
+ commitSha,
2586
+ ...coherent && status !== void 0 ? { commitDirty: status !== "" } : {},
2587
+ ...coherent && branch && branch !== "HEAD" ? { branch } : {}
2588
+ });
2589
+ });
2590
+ };
2591
+ if (detectBranch) run(["symbolic-ref", "--quiet", "--short", "HEAD"], finish);
2592
+ else finish();
2593
+ });
2594
+ });
2595
+ } catch (e) {
2596
+ completed({});
2597
+ }
2598
+ }, 0);
2599
+ scheduled.unref();
2600
+ return () => {
2601
+ cancelled = true;
2602
+ clearTimeout(scheduled);
2603
+ clearTimeout(deadlineTimer);
2604
+ try {
2605
+ active == null ? void 0 : active.kill("SIGKILL");
2606
+ } catch (e) {
1935
2607
  }
1936
- this._fallback = new SynchronousContextStorage();
1937
- this._storage = this._fallback;
1938
- }
1939
- maybeAdoptAsyncLocalStorage() {
1940
- if (!this._fallback || !this._fallback.isEmpty()) return;
1941
- const Ctor = getAsyncLocalStorageCtor();
1942
- if (!Ctor) return;
1943
- this._storage = new Ctor();
1944
- this._fallback = null;
1945
- }
1946
- isReady() {
1947
- return true;
1948
- }
1949
- getParentSpanIds() {
1950
- this.maybeAdoptAsyncLocalStorage();
1951
- const span = this._storage.getStore();
1952
- if (!span || span === NOOP_SPAN) return void 0;
1953
- return {
1954
- traceIdB64: span.traceIdB64,
1955
- spanIdB64: span.spanIdB64,
1956
- eventId: span.eventId
1957
- };
1958
- }
1959
- runInContext(span, callback) {
1960
- this.maybeAdoptAsyncLocalStorage();
1961
- return this._storage.run(span, callback);
1962
- }
1963
- getCurrentSpan() {
1964
- this.maybeAdoptAsyncLocalStorage();
1965
- return this._storage.getStore();
1966
- }
2608
+ };
1967
2609
  };
1968
- var _contextManager = null;
1969
- function getContextManager() {
1970
- if (!_contextManager) {
1971
- _contextManager = globalThis.RAINDROP_CONTEXT_MANAGER ? new globalThis.RAINDROP_CONTEXT_MANAGER() : new RaindropContextManager();
1972
- }
1973
- return _contextManager;
2610
+ function createAppGitContext2(options, runtime = {}) {
2611
+ return new AppGitContext(options, { ...runtime, resolveLocal });
1974
2612
  }
1975
- function currentSpan() {
2613
+ function hasDestination(options) {
1976
2614
  var _a;
1977
- return (_a = getContextManager().getCurrentSpan()) != null ? _a : NOOP_SPAN;
1978
- }
1979
- function withCurrent(span, callback) {
1980
- return getContextManager().runInContext(span, callback);
1981
- }
1982
- async function getCurrentParentSpanContext() {
1983
- var _a, _b;
1984
- return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
1985
- }
1986
- async function runWithParentSpanContext(ctx, fn) {
1987
- const cm = getContextManager();
1988
- const span = {
1989
- traceIdB64: ctx.traceIdB64,
1990
- spanIdB64: ctx.spanIdB64,
1991
- eventId: ctx.eventId
1992
- };
1993
- return cm.runInContext(span, fn);
2615
+ if (options.enabled === false) return false;
2616
+ return Boolean(((_a = options.writeKey) == null ? void 0 : _a.trim()) || resolveLocalDebuggerBaseUrl(options.localDebuggerUrl));
1994
2617
  }
1995
- async function* asyncGeneratorWithCurrent(span, gen) {
1996
- let nextValue;
1997
- while (true) {
1998
- const result = await withCurrent(span, async () => {
1999
- try {
2000
- return await gen.next(nextValue);
2001
- } catch (e) {
2002
- return { value: void 0, done: true, error: e };
2003
- }
2004
- });
2005
- if ("error" in result && result.error !== void 0) {
2006
- throw result.error;
2618
+ var EventShipper2 = class extends EventShipper {
2619
+ constructor(options) {
2620
+ var _a;
2621
+ const ownsAppGitContext = options.appGitContext === void 0;
2622
+ const appGitContext = (_a = options.appGitContext) != null ? _a : createAppGitContext2(options.appGit, { allowDiscovery: hasDestination(options) });
2623
+ try {
2624
+ super({ ...options, appGitContext });
2625
+ } catch (error) {
2626
+ if (ownsAppGitContext) appGitContext.dispose();
2627
+ throw error;
2007
2628
  }
2008
- if (result.done) {
2009
- return result.value;
2629
+ if (ownsAppGitContext) this.ownAppGitContextForShutdown();
2630
+ }
2631
+ };
2632
+ var TraceShipper2 = class extends TraceShipper {
2633
+ constructor(options) {
2634
+ var _a;
2635
+ const ownsAppGitContext = options.appGitContext === void 0;
2636
+ const appGitContext = (_a = options.appGitContext) != null ? _a : createAppGitContext2(options.appGit, { allowDiscovery: hasDestination(options) });
2637
+ try {
2638
+ super({ ...options, appGitContext });
2639
+ } catch (error) {
2640
+ if (ownsAppGitContext) appGitContext.dispose();
2641
+ throw error;
2010
2642
  }
2011
- nextValue = yield result.value;
2643
+ this.ownsAppGitContext = ownsAppGitContext;
2012
2644
  }
2013
- }
2645
+ };
2014
2646
  globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
2015
2647
  var SUPPRESS_TRACING_KEY = /* @__PURE__ */ Symbol.for(
2016
2648
  "OpenTelemetry SDK Context Key SUPPRESS_TRACING"
@@ -6452,14 +7084,14 @@ function mergeAttachments(...groups) {
6452
7084
  // package.json
6453
7085
  var package_default = {
6454
7086
  name: "@raindrop-ai/ai-sdk",
6455
- version: "0.3.2"};
7087
+ version: "0.3.3"};
6456
7088
 
6457
7089
  // src/internal/version.ts
6458
7090
  var libraryName = package_default.name;
6459
7091
  var libraryVersion = package_default.version;
6460
7092
 
6461
7093
  // src/internal/events.ts
6462
- var EventShipper2 = class extends EventShipper {
7094
+ var EventShipper3 = class extends EventShipper2 {
6463
7095
  constructor(opts) {
6464
7096
  var _a, _b, _c;
6465
7097
  super({
@@ -6472,7 +7104,7 @@ var EventShipper2 = class extends EventShipper {
6472
7104
  };
6473
7105
 
6474
7106
  // src/internal/traces.ts
6475
- var TraceShipper2 = class extends TraceShipper {
7107
+ var TraceShipper3 = class extends TraceShipper2 {
6476
7108
  constructor(opts) {
6477
7109
  var _a, _b, _c;
6478
7110
  super({
@@ -6539,11 +7171,11 @@ function userAttrsToOtlp(attrs) {
6539
7171
  function envDebugEnabled() {
6540
7172
  var _a;
6541
7173
  if (typeof process === "undefined") return false;
6542
- const flag = (_a = process.env) == null ? void 0 : _a.RAINDROP_AI_DEBUG;
6543
- return flag === "1" || flag === "true";
7174
+ const flag2 = (_a = process.env) == null ? void 0 : _a.RAINDROP_AI_DEBUG;
7175
+ return flag2 === "1" || flag2 === "true";
6544
7176
  }
6545
7177
  function createRaindropAISDK(opts) {
6546
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
7178
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
6547
7179
  const writeKey = opts.writeKey;
6548
7180
  const eventsRequested = ((_a = opts.events) == null ? void 0 : _a.enabled) !== false;
6549
7181
  const tracesRequested = ((_b = opts.traces) == null ? void 0 : _b.enabled) !== false;
@@ -6552,37 +7184,53 @@ function createRaindropAISDK(opts) {
6552
7184
  const localWorkshopInput = opts.localWorkshopUrl === false ? null : opts.localWorkshopUrl;
6553
7185
  const resolvedLocalDebuggerUrl = resolveLocalDebuggerBaseUrl(localWorkshopInput);
6554
7186
  const localDebuggerUrl = localWorkshopInput === null ? null : resolvedLocalDebuggerUrl != null ? resolvedLocalDebuggerUrl : void 0;
6555
- const hasDestination = !!writeKey || !!resolvedLocalDebuggerUrl;
6556
- const eventsEnabled = eventsRequested && hasDestination;
6557
- const tracesEnabled = tracesRequested && hasDestination;
6558
- if (!hasDestination && (eventsRequested || tracesRequested)) {
7187
+ const hasDestination2 = Boolean(writeKey == null ? void 0 : writeKey.trim()) || Boolean(resolvedLocalDebuggerUrl);
7188
+ const eventsEnabled = eventsRequested && hasDestination2;
7189
+ const tracesEnabled = tracesRequested && hasDestination2;
7190
+ const appGitContext = (_c = opts.appGitContext) != null ? _c : createAppGitContext2(
7191
+ eventsEnabled || tracesEnabled ? opts.appGit : false,
7192
+ { allowLocalGit: true }
7193
+ );
7194
+ if (!hasDestination2 && (eventsRequested || tracesRequested)) {
6559
7195
  console.warn(
6560
7196
  "[raindrop-ai/ai-sdk] writeKey not provided and no local Workshop reachable; telemetry shipping is disabled"
6561
7197
  );
6562
7198
  }
6563
- const eventShipper = new EventShipper2({
6564
- writeKey,
6565
- endpoint: opts.endpoint,
6566
- enabled: eventsEnabled,
6567
- debug: ((_c = opts.events) == null ? void 0 : _c.debug) === true || envDebug,
6568
- partialFlushMs: (_d = opts.events) == null ? void 0 : _d.partialFlushMs,
6569
- projectId: opts.projectId,
6570
- localDebuggerUrl
6571
- });
6572
- const traceShipper = new TraceShipper2({
6573
- writeKey,
6574
- endpoint: opts.endpoint,
6575
- enabled: tracesEnabled,
6576
- debug: ((_e = opts.traces) == null ? void 0 : _e.debug) === true || envDebug,
6577
- debugSpans: ((_f = opts.traces) == null ? void 0 : _f.debugSpans) === true || envDebug,
6578
- flushIntervalMs: (_g = opts.traces) == null ? void 0 : _g.flushIntervalMs,
6579
- maxBatchSize: (_h = opts.traces) == null ? void 0 : _h.maxBatchSize,
6580
- maxQueueSize: (_i = opts.traces) == null ? void 0 : _i.maxQueueSize,
6581
- projectId: opts.projectId,
6582
- localDebuggerUrl,
6583
- transformSpan: (_j = opts.traces) == null ? void 0 : _j.transformSpan,
6584
- disableDefaultRedaction: (_k = opts.traces) == null ? void 0 : _k.disableDefaultRedaction
6585
- });
7199
+ let eventShipper;
7200
+ let traceShipper;
7201
+ try {
7202
+ eventShipper = new EventShipper3({
7203
+ writeKey,
7204
+ endpoint: opts.endpoint,
7205
+ enabled: eventsEnabled,
7206
+ debug: ((_d = opts.events) == null ? void 0 : _d.debug) === true || envDebug,
7207
+ partialFlushMs: (_e = opts.events) == null ? void 0 : _e.partialFlushMs,
7208
+ projectId: opts.projectId,
7209
+ localDebuggerUrl,
7210
+ appGitContext
7211
+ });
7212
+ traceShipper = new TraceShipper3({
7213
+ writeKey,
7214
+ endpoint: opts.endpoint,
7215
+ enabled: tracesEnabled,
7216
+ debug: ((_f = opts.traces) == null ? void 0 : _f.debug) === true || envDebug,
7217
+ debugSpans: ((_g = opts.traces) == null ? void 0 : _g.debugSpans) === true || envDebug,
7218
+ flushIntervalMs: (_h = opts.traces) == null ? void 0 : _h.flushIntervalMs,
7219
+ maxBatchSize: (_i = opts.traces) == null ? void 0 : _i.maxBatchSize,
7220
+ maxQueueSize: (_j = opts.traces) == null ? void 0 : _j.maxQueueSize,
7221
+ projectId: opts.projectId,
7222
+ localDebuggerUrl,
7223
+ transformSpan: (_k = opts.traces) == null ? void 0 : _k.transformSpan,
7224
+ disableDefaultRedaction: (_l = opts.traces) == null ? void 0 : _l.disableDefaultRedaction,
7225
+ appGitContext
7226
+ });
7227
+ } catch (error) {
7228
+ try {
7229
+ appGitContext.dispose();
7230
+ } catch (e) {
7231
+ }
7232
+ throw error;
7233
+ }
6586
7234
  const settledEventIds = /* @__PURE__ */ new Set();
6587
7235
  const subagentApi = new SubagentApi({
6588
7236
  traceShipper,
@@ -6750,7 +7398,14 @@ function createRaindropAISDK(opts) {
6750
7398
  await Promise.all([eventShipper.flush(), traceShipper.flush()]);
6751
7399
  },
6752
7400
  async shutdown() {
6753
- await Promise.all([eventShipper.shutdown(), traceShipper.shutdown()]);
7401
+ try {
7402
+ await Promise.all([eventShipper.shutdown(), traceShipper.shutdown()]);
7403
+ } finally {
7404
+ try {
7405
+ appGitContext.dispose();
7406
+ } catch (e) {
7407
+ }
7408
+ }
6754
7409
  }
6755
7410
  };
6756
7411
  }