@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.
@@ -60,7 +60,574 @@ function evalScopeAttributes() {
60
60
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
61
61
  }
62
62
 
63
- // ../core/dist/chunk-T53LQAH7.js
63
+ // ../core/dist/chunk-WJOR6M7H.js
64
+ var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
65
+ function state() {
66
+ const holder = globalThis;
67
+ let current = holder[STATE_KEY];
68
+ if (!current) {
69
+ let storage = null;
70
+ try {
71
+ const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
72
+ if (Ctor) storage = new Ctor();
73
+ } catch (e) {
74
+ storage = null;
75
+ }
76
+ current = {
77
+ storage,
78
+ syncDestination: void 0,
79
+ spanDestinations: /* @__PURE__ */ new WeakMap()
80
+ };
81
+ holder[STATE_KEY] = current;
82
+ }
83
+ return current;
84
+ }
85
+ function currentReplayTraceDestination() {
86
+ var _a, _b;
87
+ const routing = state();
88
+ return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
89
+ }
90
+ function rememberReplayTraceDestination(span) {
91
+ const destination = currentReplayTraceDestination();
92
+ if (destination) state().spanDestinations.set(span, destination);
93
+ }
94
+ function copyReplayTraceDestination(source, target) {
95
+ const destination = state().spanDestinations.get(source);
96
+ if (destination) state().spanDestinations.set(target, destination);
97
+ }
98
+ function replayTraceDestinationFor(value) {
99
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
100
+ return void 0;
101
+ }
102
+ return state().spanDestinations.get(value);
103
+ }
104
+ function recordReplayExportedSpan(destination, spanId, traceId) {
105
+ var _a, _b;
106
+ if (!destination || !spanId || !traceId) return;
107
+ (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
108
+ (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
109
+ }
110
+ function replayTraceUrl(baseUrl) {
111
+ return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
112
+ }
113
+ var NOOP_SPAN = {
114
+ traceIdB64: "",
115
+ spanIdB64: "",
116
+ eventId: "",
117
+ log() {
118
+ }
119
+ };
120
+ function getAsyncLocalStorageCtor() {
121
+ return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
122
+ }
123
+ var SynchronousContextStorage = class {
124
+ constructor() {
125
+ this._stack = [];
126
+ }
127
+ isEmpty() {
128
+ return this._stack.length === 0;
129
+ }
130
+ getStore() {
131
+ return this._stack[this._stack.length - 1];
132
+ }
133
+ run(store, callback) {
134
+ this._stack.push(store);
135
+ try {
136
+ return callback();
137
+ } finally {
138
+ this._stack.pop();
139
+ }
140
+ }
141
+ };
142
+ var ContextManager = class {
143
+ };
144
+ var RaindropContextManager = class extends ContextManager {
145
+ constructor() {
146
+ super();
147
+ this._fallback = null;
148
+ const Ctor = getAsyncLocalStorageCtor();
149
+ if (Ctor) {
150
+ this._storage = new Ctor();
151
+ return;
152
+ }
153
+ this._fallback = new SynchronousContextStorage();
154
+ this._storage = this._fallback;
155
+ }
156
+ maybeAdoptAsyncLocalStorage() {
157
+ if (!this._fallback || !this._fallback.isEmpty()) return;
158
+ const Ctor = getAsyncLocalStorageCtor();
159
+ if (!Ctor) return;
160
+ this._storage = new Ctor();
161
+ this._fallback = null;
162
+ }
163
+ isReady() {
164
+ return true;
165
+ }
166
+ getParentSpanIds() {
167
+ this.maybeAdoptAsyncLocalStorage();
168
+ const span = this._storage.getStore();
169
+ if (!span || span === NOOP_SPAN) return void 0;
170
+ return {
171
+ traceIdB64: span.traceIdB64,
172
+ spanIdB64: span.spanIdB64,
173
+ eventId: span.eventId
174
+ };
175
+ }
176
+ runInContext(span, callback) {
177
+ this.maybeAdoptAsyncLocalStorage();
178
+ return this._storage.run(span, callback);
179
+ }
180
+ getCurrentSpan() {
181
+ this.maybeAdoptAsyncLocalStorage();
182
+ return this._storage.getStore();
183
+ }
184
+ };
185
+ var _contextManager = null;
186
+ function getContextManager() {
187
+ if (!_contextManager) {
188
+ _contextManager = globalThis.RAINDROP_CONTEXT_MANAGER ? new globalThis.RAINDROP_CONTEXT_MANAGER() : new RaindropContextManager();
189
+ }
190
+ return _contextManager;
191
+ }
192
+ function currentSpan() {
193
+ var _a;
194
+ return (_a = getContextManager().getCurrentSpan()) != null ? _a : NOOP_SPAN;
195
+ }
196
+ function withCurrent(span, callback) {
197
+ return getContextManager().runInContext(span, callback);
198
+ }
199
+ async function getCurrentParentSpanContext() {
200
+ var _a, _b;
201
+ return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
202
+ }
203
+ async function runWithParentSpanContext(ctx, fn) {
204
+ const cm = getContextManager();
205
+ const span = {
206
+ traceIdB64: ctx.traceIdB64,
207
+ spanIdB64: ctx.spanIdB64,
208
+ eventId: ctx.eventId
209
+ };
210
+ return cm.runInContext(span, fn);
211
+ }
212
+ async function* asyncGeneratorWithCurrent(span, gen) {
213
+ let nextValue;
214
+ while (true) {
215
+ const result = await withCurrent(span, async () => {
216
+ try {
217
+ return await gen.next(nextValue);
218
+ } catch (e) {
219
+ return { value: void 0, done: true, error: e };
220
+ }
221
+ });
222
+ if ("error" in result && result.error !== void 0) {
223
+ throw result.error;
224
+ }
225
+ if (result.done) {
226
+ return result.value;
227
+ }
228
+ nextValue = yield result.value;
229
+ }
230
+ }
231
+ var MAX_BINDING_STACK = 128;
232
+ var EMPTY_STACK = [];
233
+ var ContextStackStorage = class {
234
+ /** Emitted once when this runtime cannot support an ambient push. */
235
+ constructor(noAmbientBindWarning) {
236
+ this.noAmbientBindWarning = noAmbientBindWarning;
237
+ this._als = null;
238
+ this._enterWithUsable = false;
239
+ this._syncStack = EMPTY_STACK;
240
+ this._adoptionChecked = false;
241
+ this._warnedNoAmbientBind = false;
242
+ }
243
+ maybeAdoptAsyncLocalStorage() {
244
+ if (this._adoptionChecked) return;
245
+ this._adoptionChecked = true;
246
+ const Ctor = getAsyncLocalStorageCtor();
247
+ if (!Ctor) return;
248
+ const als = new Ctor();
249
+ try {
250
+ als.run(EMPTY_STACK, () => {
251
+ });
252
+ } catch (e) {
253
+ return;
254
+ }
255
+ this._als = als;
256
+ if (typeof als.enterWith === "function") {
257
+ try {
258
+ als.enterWith(EMPTY_STACK);
259
+ this._enterWithUsable = true;
260
+ } catch (e) {
261
+ this._enterWithUsable = false;
262
+ }
263
+ }
264
+ }
265
+ getStack() {
266
+ var _a;
267
+ this.maybeAdoptAsyncLocalStorage();
268
+ if (this._als) return (_a = this._als.getStore()) != null ? _a : this._syncStack;
269
+ return this._syncStack;
270
+ }
271
+ /**
272
+ * Persist an ambient stack mutation. Returns false when an ALS is adopted but
273
+ * `enterWith` is unusable (workerd): callers must NOT fall back to the
274
+ * process-shared sync stack, since concurrent isolates would cross-stamp.
275
+ */
276
+ setAmbientStack(stack) {
277
+ if (this._als) {
278
+ if (!this._enterWithUsable) return false;
279
+ this._als.enterWith(stack);
280
+ return true;
281
+ }
282
+ this._syncStack = stack;
283
+ return true;
284
+ }
285
+ push(binding) {
286
+ this.maybeAdoptAsyncLocalStorage();
287
+ if (this._als && !this._enterWithUsable) {
288
+ this.warnNoAmbientBindOnce();
289
+ return;
290
+ }
291
+ let stack = this.getStack();
292
+ if (stack.length >= MAX_BINDING_STACK) {
293
+ stack = stack.filter((b) => b.isLive());
294
+ if (stack.length >= MAX_BINDING_STACK) {
295
+ stack = stack.slice(stack.length - (MAX_BINDING_STACK - 1));
296
+ }
297
+ }
298
+ this.setAmbientStack([...stack, binding]);
299
+ }
300
+ remove(binding) {
301
+ binding.markDead();
302
+ const stack = this.getStack();
303
+ const pruned = stack.filter((b) => b !== binding && b.isLive());
304
+ if (pruned.length !== stack.length) {
305
+ this.setAmbientStack(pruned);
306
+ }
307
+ }
308
+ runWith(binding, callback) {
309
+ this.maybeAdoptAsyncLocalStorage();
310
+ if (this._als) {
311
+ return this._als.run([...this.getStack(), binding], callback);
312
+ }
313
+ const previous = this._syncStack;
314
+ this._syncStack = [...previous, binding];
315
+ try {
316
+ return callback();
317
+ } finally {
318
+ this._syncStack = previous;
319
+ }
320
+ }
321
+ current() {
322
+ const stack = this.getStack();
323
+ if (stack.length === 0) return void 0;
324
+ const top = stack[stack.length - 1];
325
+ if (top.isLive()) return top;
326
+ const pruned = stack.filter((b) => b.isLive());
327
+ this.setAmbientStack(pruned);
328
+ return pruned.length > 0 ? pruned[pruned.length - 1] : void 0;
329
+ }
330
+ warnNoAmbientBindOnce() {
331
+ if (this._warnedNoAmbientBind) return;
332
+ this._warnedNoAmbientBind = true;
333
+ console.warn(this.noAmbientBindWarning);
334
+ }
335
+ };
336
+ 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.";
337
+ var ROUTING_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.routingContextStorage");
338
+ function routingStorage() {
339
+ const holder = globalThis;
340
+ let storage = holder[ROUTING_STORAGE_KEY];
341
+ if (!storage) {
342
+ storage = new ContextStackStorage(NO_AMBIENT_ROUTING_BIND_WARNING);
343
+ holder[ROUTING_STORAGE_KEY] = storage;
344
+ }
345
+ return storage;
346
+ }
347
+ function currentRoutingBinding() {
348
+ const bound = routingStorage().current();
349
+ if (!bound) return void 0;
350
+ return {
351
+ projectId: bound.projectId,
352
+ authHint: bound.authHint,
353
+ ...bound.appGit ? { appGit: bound.appGit } : {},
354
+ ...bound.appGitSource ? { appGitSource: bound.appGitSource } : {}
355
+ };
356
+ }
357
+ var APP_COMMIT_SHA = "raindrop.app.commit_sha";
358
+ var APP_COMMIT_DIRTY = "raindrop.app.commit_dirty";
359
+ var APP_BRANCH = "raindrop.app.branch";
360
+ var APP_GIT_KEYS = [APP_COMMIT_SHA, APP_COMMIT_DIRTY, APP_BRANCH];
361
+ var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
362
+ function appGitExplicitKeys(properties) {
363
+ const keys = /* @__PURE__ */ new Set();
364
+ if (!properties) return keys;
365
+ for (const key of APP_GIT_KEYS) {
366
+ if (own(properties, key)) keys.add(key);
367
+ }
368
+ return keys;
369
+ }
370
+ function mergeAppGitSnapshot(base, properties, explicitKeys = /* @__PURE__ */ new Set()) {
371
+ try {
372
+ const result = { ...base };
373
+ if (properties && own(properties, APP_COMMIT_SHA) && properties[APP_COMMIT_SHA] !== result[APP_COMMIT_SHA]) {
374
+ if (!explicitKeys.has(APP_COMMIT_DIRTY) && !own(properties, APP_COMMIT_DIRTY)) {
375
+ delete result[APP_COMMIT_DIRTY];
376
+ }
377
+ if (!explicitKeys.has(APP_BRANCH) && !own(properties, APP_BRANCH)) {
378
+ delete result[APP_BRANCH];
379
+ }
380
+ }
381
+ for (const key of APP_GIT_KEYS) {
382
+ if (properties && own(properties, key)) result[key] = properties[key];
383
+ }
384
+ return Object.freeze(result);
385
+ } catch (e) {
386
+ return Object.freeze({});
387
+ }
388
+ }
389
+ function validAppCommitSha(value) {
390
+ if (typeof value !== "string" || value.length > 128) return void 0;
391
+ const cleaned = value.trim();
392
+ return /^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(cleaned) ? cleaned.toLowerCase() : void 0;
393
+ }
394
+ function shortString(value) {
395
+ if (typeof value !== "string" || value.length > 1024) return void 0;
396
+ const cleaned = value.trim();
397
+ return cleaned.length > 0 ? cleaned : void 0;
398
+ }
399
+ function flag(value) {
400
+ if (value === true || value === "true" || value === "1") return true;
401
+ if (value === false || value === "false" || value === "0") return false;
402
+ return void 0;
403
+ }
404
+ function environment() {
405
+ try {
406
+ return typeof process === "undefined" ? {} : process.env;
407
+ } catch (e) {
408
+ return {};
409
+ }
410
+ }
411
+ var DEPLOYMENTS = [
412
+ ["VERCEL", "VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF"],
413
+ ["NETLIFY", "COMMIT_REF", "BRANCH"],
414
+ ["RAILWAY_ENVIRONMENT_NAME", "RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH"],
415
+ ["RAILWAY_ENVIRONMENT", "RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH"],
416
+ ["RENDER", "RENDER_GIT_COMMIT", "RENDER_GIT_BRANCH"],
417
+ ["DYNO", "HEROKU_BUILD_COMMIT", ""],
418
+ ["DYNO", "HEROKU_SLUG_COMMIT", ""],
419
+ ["AWS_APP_ID", "AWS_COMMIT_ID", "AWS_BRANCH"],
420
+ ["WORKERS_CI", "WORKERS_CI_COMMIT_SHA", "WORKERS_CI_BRANCH"]
421
+ ];
422
+ var CI_SOURCES = [
423
+ ["GITHUB_ACTIONS", "GITHUB_SHA", "GITHUB_REF_NAME"],
424
+ ["GITLAB_CI", "CI_COMMIT_SHA", "CI_COMMIT_REF_NAME"],
425
+ ["CIRCLECI", "CIRCLE_SHA1", "CIRCLE_BRANCH"]
426
+ ];
427
+ function detectedSource(env, table, detectBranch) {
428
+ for (const row of table) {
429
+ const [marker, shaKey, branchKey] = row;
430
+ if (!marker || !shaKey || !shortString(env[marker]) || flag(env[marker]) === false) continue;
431
+ const commitSha = validAppCommitSha(env[shaKey]);
432
+ if (commitSha)
433
+ return {
434
+ commitSha,
435
+ ...detectBranch && branchKey ? { branch: shortString(env[branchKey]) } : {}
436
+ };
437
+ }
438
+ return {};
439
+ }
440
+ var AppGitContextImpl = class {
441
+ constructor(options, runtime = {}) {
442
+ this.defaults = {};
443
+ this.explicit = {};
444
+ this.explicitKeys = /* @__PURE__ */ new Set();
445
+ this.disposed = false;
446
+ this.operations = /* @__PURE__ */ new Map();
447
+ this.operationOverflow = false;
448
+ this.detectBranch = false;
449
+ this.disabled = false;
450
+ var _a, _b, _c, _d, _e, _f;
451
+ try {
452
+ if (options === false) {
453
+ this.disabled = true;
454
+ return;
455
+ }
456
+ const opts = options != null ? options : {};
457
+ const env = (_a = runtime.env) != null ? _a : environment();
458
+ const detectBranch = (_c = (_b = flag(opts.detectBranch)) != null ? _b : flag(env.RAINDROP_GIT_DETECT_BRANCH)) != null ? _c : false;
459
+ this.detectBranch = detectBranch;
460
+ const collectBranch = detectBranch || runtime.captureLegacyReplayBranch === true;
461
+ const autoDetect = runtime.allowDiscovery === false ? false : (_e = (_d = flag(opts.autoDetect)) != null ? _d : flag(env.RAINDROP_GIT_AUTO_DETECT)) != null ? _e : true;
462
+ const configuredSha = opts.commitSha;
463
+ const explicitSha = configuredSha === void 0 ? env.RAINDROP_COMMIT_SHA : configuredSha;
464
+ if (explicitSha === null) this.explicit[APP_COMMIT_SHA] = null;
465
+ else if (typeof explicitSha === "string" && validAppCommitSha(explicitSha))
466
+ this.explicit[APP_COMMIT_SHA] = explicitSha;
467
+ const configuredDirty = opts.commitDirty;
468
+ const explicitDirty = configuredDirty === void 0 ? flag(env.RAINDROP_COMMIT_DIRTY) : configuredDirty;
469
+ if (explicitDirty === null || typeof explicitDirty === "boolean")
470
+ this.explicit[APP_COMMIT_DIRTY] = explicitDirty;
471
+ const configuredBranch = opts.branch;
472
+ const explicitBranch = configuredBranch === void 0 ? env.RAINDROP_BRANCH : configuredBranch;
473
+ if (explicitBranch === null) this.explicit[APP_BRANCH] = null;
474
+ else if (typeof explicitBranch === "string" && explicitBranch.length <= 1024)
475
+ this.explicit[APP_BRANCH] = explicitBranch;
476
+ this.explicitKeys = appGitExplicitKeys(this.explicit);
477
+ this.defaults = { ...this.explicit };
478
+ if (!autoDetect || explicitSha !== void 0) return;
479
+ const sourceDirectory = (_f = shortString(opts.sourceDirectory)) != null ? _f : shortString(env.RAINDROP_GIT_SOURCE_DIRECTORY);
480
+ if (runtime.allowLocalGit === false && !sourceDirectory) return;
481
+ const deploy = sourceDirectory ? {} : detectedSource(env, DEPLOYMENTS, collectBranch);
482
+ if (deploy.commitSha) {
483
+ this.accept(deploy);
484
+ return;
485
+ }
486
+ const fallback = sourceDirectory ? {} : detectedSource(env, CI_SOURCES, collectBranch);
487
+ if (runtime.resolveLocal && (runtime.allowLocalGit !== false || sourceDirectory)) {
488
+ this.cancel = runtime.resolveLocal(sourceDirectory, collectBranch, (result) => {
489
+ try {
490
+ if (!this.disposed) this.accept(result.commitSha ? result : fallback);
491
+ } catch (e) {
492
+ }
493
+ });
494
+ } else this.accept(fallback);
495
+ } catch (e) {
496
+ }
497
+ }
498
+ accept(result) {
499
+ const sha = validAppCommitSha(result.commitSha);
500
+ if (!sha) return;
501
+ this.replayBranch = shortString(result.branch);
502
+ this.defaults = {
503
+ [APP_COMMIT_SHA]: sha,
504
+ ...typeof result.commitDirty === "boolean" ? { [APP_COMMIT_DIRTY]: result.commitDirty } : {},
505
+ ...this.detectBranch && this.replayBranch ? { [APP_BRANCH]: this.replayBranch } : {},
506
+ ...this.explicit
507
+ };
508
+ }
509
+ snapshot(properties) {
510
+ var _a;
511
+ try {
512
+ const binding = currentRoutingBinding();
513
+ const base = this.disabled && (binding == null ? void 0 : binding.appGitSource) !== "replay-override" ? {} : (_a = binding == null ? void 0 : binding.appGit) != null ? _a : this.defaults;
514
+ return this.mergeSnapshot(base, properties);
515
+ } catch (e) {
516
+ return Object.freeze({});
517
+ }
518
+ }
519
+ /** Safe defaults when no operation/span start was observed; never infer identity. */
520
+ snapshotExplicit(properties, eventId) {
521
+ try {
522
+ const base = { ...this.explicit };
523
+ const operation = eventId ? this.operations.get(eventId) : void 0;
524
+ if (operation) {
525
+ for (const key of operation.explicitKeys) base[key] = operation.snapshot[key];
526
+ }
527
+ return this.mergeSnapshot(base, properties, new Set(Object.keys(base)));
528
+ } catch (e) {
529
+ return mergeAppGitSnapshot({}, properties);
530
+ }
531
+ }
532
+ /** Existing replay branch reporting stays separate from opt-in event properties. */
533
+ snapshotForReplay() {
534
+ const snapshot = this.snapshot();
535
+ if (this.replayBranch && !own(snapshot, APP_BRANCH) && snapshot[APP_COMMIT_SHA] === this.defaults[APP_COMMIT_SHA]) {
536
+ return Object.freeze({ ...snapshot, [APP_BRANCH]: this.replayBranch });
537
+ }
538
+ return snapshot;
539
+ }
540
+ /** Merge a frozen span snapshot without losing client-authored provenance. */
541
+ mergeSnapshot(base, properties, explicitKeys = this.explicitKeys) {
542
+ return mergeAppGitSnapshot(base, properties, /* @__PURE__ */ new Set([...this.explicitKeys, ...explicitKeys]));
543
+ }
544
+ /** Shippers belonging to one client share this bounded operation registry. */
545
+ forOperation(eventId, properties, owner) {
546
+ if (!eventId) return this.snapshot(properties);
547
+ let operation = this.operations.get(eventId);
548
+ if (!operation) {
549
+ if (this.operations.size >= 1e4) this.operationOverflow = true;
550
+ if (this.operationOverflow) return this.mergeSnapshot({}, properties);
551
+ operation = {
552
+ snapshot: this.snapshot(properties),
553
+ owners: /* @__PURE__ */ new Set(),
554
+ unowned: owner === void 0,
555
+ explicitKeys: appGitExplicitKeys(properties)
556
+ };
557
+ this.operations.set(eventId, operation);
558
+ } else if (properties && APP_GIT_KEYS.some((key) => own(properties, key))) {
559
+ const explicitKeys = /* @__PURE__ */ new Set([...this.explicitKeys, ...operation.explicitKeys]);
560
+ operation.snapshot = this.mergeSnapshot(operation.snapshot, properties, explicitKeys);
561
+ for (const key of appGitExplicitKeys(properties)) operation.explicitKeys.add(key);
562
+ }
563
+ if (!owner) operation.unowned = true;
564
+ if (owner) operation.owners.add(owner);
565
+ return operation.snapshot;
566
+ }
567
+ releaseOperation(eventId, owner) {
568
+ const operation = this.operations.get(eventId);
569
+ if (!operation) return;
570
+ operation.owners.delete(owner);
571
+ if (operation.owners.size === 0 && !operation.unowned) this.operations.delete(eventId);
572
+ }
573
+ finishOperation(eventId) {
574
+ this.operations.delete(eventId);
575
+ }
576
+ dispose() {
577
+ var _a;
578
+ this.disposed = true;
579
+ try {
580
+ (_a = this.cancel) == null ? void 0 : _a.call(this);
581
+ } catch (e) {
582
+ }
583
+ }
584
+ };
585
+ var AppGitContext = AppGitContextImpl;
586
+ function createAppGitContext(options, runtime = {}) {
587
+ return new AppGitContext(options, runtime);
588
+ }
589
+ function withAppGitProperties(properties, snapshot) {
590
+ try {
591
+ const merged = { ...properties };
592
+ for (const key of APP_GIT_KEYS)
593
+ if (!own(merged, key) && own(snapshot, key)) merged[key] = snapshot[key];
594
+ return merged;
595
+ } catch (e) {
596
+ return properties != null ? properties : {};
597
+ }
598
+ }
599
+ function withAppGitAttributes(attributes, snapshot) {
600
+ try {
601
+ const present = new Set(attributes.flatMap((attr) => attr ? [attr.key] : []));
602
+ const added = [];
603
+ for (const key of APP_GIT_KEYS) {
604
+ if (present.has(key) || present.has(`ai.telemetry.metadata.${key}`) || present.has(`traceloop.association.properties.${key}`))
605
+ continue;
606
+ const value = snapshot[key];
607
+ if (typeof value === "string") added.push({ key, value: { stringValue: value } });
608
+ else if (typeof value === "boolean") added.push({ key, value: { boolValue: value } });
609
+ }
610
+ return added.length ? [...attributes, ...added] : attributes;
611
+ } catch (e) {
612
+ return attributes;
613
+ }
614
+ }
615
+ function appGitPropertiesFromAttributes(attributes) {
616
+ var _a, _b, _c;
617
+ const properties = {};
618
+ try {
619
+ for (const attr of attributes) {
620
+ if (!attr) continue;
621
+ for (const key of APP_GIT_KEYS) {
622
+ if (attr.key === key || attr.key === `ai.telemetry.metadata.${key}` || attr.key === `traceloop.association.properties.${key}`) {
623
+ properties[key] = (_c = (_b = (_a = attr.value.stringValue) != null ? _a : attr.value.boolValue) != null ? _b : attr.value.intValue) != null ? _c : null;
624
+ }
625
+ }
626
+ }
627
+ } catch (e) {
628
+ }
629
+ return properties;
630
+ }
64
631
  function normalizeFeatureFlags(input) {
65
632
  if (Array.isArray(input)) {
66
633
  return Object.fromEntries(input.map((name) => [name, "true"]));
@@ -679,55 +1246,6 @@ function buildExportTraceServiceRequest(spans, serviceName = "raindrop.core", se
679
1246
  ]
680
1247
  };
681
1248
  }
682
- var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
683
- function state() {
684
- const holder = globalThis;
685
- let current = holder[STATE_KEY];
686
- if (!current) {
687
- let storage = null;
688
- try {
689
- const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
690
- if (Ctor) storage = new Ctor();
691
- } catch (e) {
692
- storage = null;
693
- }
694
- current = {
695
- storage,
696
- syncDestination: void 0,
697
- spanDestinations: /* @__PURE__ */ new WeakMap()
698
- };
699
- holder[STATE_KEY] = current;
700
- }
701
- return current;
702
- }
703
- function currentReplayTraceDestination() {
704
- var _a, _b;
705
- const routing = state();
706
- return (_b = (_a = routing.storage) == null ? void 0 : _a.getStore()) != null ? _b : routing.syncDestination;
707
- }
708
- function rememberReplayTraceDestination(span) {
709
- const destination = currentReplayTraceDestination();
710
- if (destination) state().spanDestinations.set(span, destination);
711
- }
712
- function copyReplayTraceDestination(source, target) {
713
- const destination = state().spanDestinations.get(source);
714
- if (destination) state().spanDestinations.set(target, destination);
715
- }
716
- function replayTraceDestinationFor(value) {
717
- if (typeof value !== "object" && typeof value !== "function" || value === null) {
718
- return void 0;
719
- }
720
- return state().spanDestinations.get(value);
721
- }
722
- function recordReplayExportedSpan(destination, spanId, traceId) {
723
- var _a, _b;
724
- if (!destination || !spanId || !traceId) return;
725
- (_a = destination.exportedSpanIds) == null ? void 0 : _a.add(spanId);
726
- (_b = destination.exportedTraceIds) == null ? void 0 : _b.add(traceId);
727
- }
728
- function replayTraceUrl(baseUrl) {
729
- return `${baseUrl.replace(/\/+$/, "")}/v1/traces`;
730
- }
731
1249
  var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
732
1250
  var WORKSHOP_ENV_VAR = "RAINDROP_WORKSHOP";
733
1251
  var DEFAULT_LOCAL_WORKSHOP_URL = "http://localhost:5899/v1/";
@@ -862,6 +1380,13 @@ function projectIdHeaders(projectId) {
862
1380
  }
863
1381
  var SHUTDOWN_DEADLINE_MS = 1e4;
864
1382
  var POST_SHUTDOWN_TIMEOUT_MS = 5e3;
1383
+ function appGitOwnerId(prefix) {
1384
+ try {
1385
+ return `${prefix}:${randomUUID()}`;
1386
+ } catch (e) {
1387
+ return `${prefix}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
1388
+ }
1389
+ }
865
1390
  function mergePatches(target, source) {
866
1391
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
867
1392
  const out = { ...target, ...source };
@@ -911,22 +1436,25 @@ function eventTelemetryProperties(patch) {
911
1436
  }
912
1437
  var EventShipper = class {
913
1438
  constructor(opts) {
1439
+ this.appGitOwner = appGitOwnerId("event");
914
1440
  this.buffers = /* @__PURE__ */ new Map();
915
1441
  this.sticky = /* @__PURE__ */ new Map();
916
1442
  this.timers = /* @__PURE__ */ new Map();
917
1443
  this.inFlight = /* @__PURE__ */ new Set();
918
1444
  this.hasShutdown = false;
919
- var _a, _b, _c, _d, _e, _f, _g, _h;
920
- this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
921
- this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
1445
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1446
+ this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
1447
+ this.ownsAppGitContext = opts.appGitContext === void 0;
1448
+ this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
1449
+ this.baseUrl = (_c = formatEndpoint(opts.endpoint)) != null ? _c : "https://api.raindrop.ai/v1/";
922
1450
  this.enabled = opts.enabled !== false;
923
1451
  this.debug = opts.debug;
924
- this.partialFlushMs = (_c = opts.partialFlushMs) != null ? _c : 1e3;
925
- this.sdkName = (_d = opts.sdkName) != null ? _d : "core";
1452
+ this.partialFlushMs = (_d = opts.partialFlushMs) != null ? _d : 1e3;
1453
+ this.sdkName = (_e = opts.sdkName) != null ? _e : "core";
926
1454
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
927
- this.defaultEventName = (_e = opts.defaultEventName) != null ? _e : "ai_generation";
1455
+ this.defaultEventName = (_f = opts.defaultEventName) != null ? _f : "ai_generation";
928
1456
  this.maxTextFieldCharsOpt = opts.maxTextFieldChars;
929
- this.localDebuggerUrl = (_f = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _f : void 0;
1457
+ this.localDebuggerUrl = (_g = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _g : void 0;
930
1458
  if (this.debug && this.localDebuggerUrl) {
931
1459
  console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
932
1460
  }
@@ -937,8 +1465,8 @@ var EventShipper = class {
937
1465
  const isNode = typeof process !== "undefined" && typeof process.version === "string";
938
1466
  this.context = {
939
1467
  library: {
940
- name: (_g = opts.libraryName) != null ? _g : "@raindrop-ai/core",
941
- version: (_h = opts.libraryVersion) != null ? _h : "0.0.0"
1468
+ name: (_h = opts.libraryName) != null ? _h : "@raindrop-ai/core",
1469
+ version: (_i = opts.libraryVersion) != null ? _i : "0.0.0"
942
1470
  },
943
1471
  metadata: {
944
1472
  jsRuntime: isNode ? "node" : "web",
@@ -946,6 +1474,9 @@ var EventShipper = class {
946
1474
  }
947
1475
  };
948
1476
  }
1477
+ ownAppGitContextForShutdown() {
1478
+ this.ownsAppGitContext = true;
1479
+ }
949
1480
  isDebugEnabled() {
950
1481
  return this.debug;
951
1482
  }
@@ -1024,6 +1555,13 @@ var EventShipper = class {
1024
1555
  }
1025
1556
  const sticky = (_c = this.sticky.get(eventId)) != null ? _c : {};
1026
1557
  const existing = (_d = this.buffers.get(eventId)) != null ? _d : {};
1558
+ patch = {
1559
+ ...patch,
1560
+ properties: withAppGitProperties(
1561
+ patch.properties,
1562
+ this.appGitContext.forOperation(eventId, patch.properties, this.appGitOwner)
1563
+ )
1564
+ };
1027
1565
  const merged = mergePatches(existing, patch);
1028
1566
  merged.isPending = (_g = (_f = (_e = patch.isPending) != null ? _e : existing.isPending) != null ? _f : sticky.isPending) != null ? _g : true;
1029
1567
  this.buffers.set(eventId, merged);
@@ -1037,6 +1575,8 @@ var EventShipper = class {
1037
1575
  if (t) clearTimeout(t);
1038
1576
  if (merged.isPending === false) {
1039
1577
  await this.flushOne(eventId);
1578
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(eventId, this.appGitOwner);
1579
+ else this.appGitContext.finishOperation(eventId);
1040
1580
  return;
1041
1581
  }
1042
1582
  const timeout = setTimeout(() => {
@@ -1068,6 +1608,7 @@ var EventShipper = class {
1068
1608
  if (!settled) this.warnShutdownDrop("in-flight request(s) at shutdown");
1069
1609
  } finally {
1070
1610
  this.shutdownDeadlineAt = void 0;
1611
+ if (this.ownsAppGitContext) this.appGitContext.dispose();
1071
1612
  }
1072
1613
  }
1073
1614
  async trackSignal(signal) {
@@ -1502,6 +2043,13 @@ function redactJsonAttributeValue(key, value) {
1502
2043
  if (scrubbedJson === json) return void 0;
1503
2044
  return { stringValue: scrubbedJson };
1504
2045
  }
2046
+ function appGitOwnerId2(prefix) {
2047
+ try {
2048
+ return `${prefix}:${randomUUID()}`;
2049
+ } catch (e) {
2050
+ return `${prefix}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
2051
+ }
2052
+ }
1505
2053
  function identityAttrs(args) {
1506
2054
  return [
1507
2055
  attrString("ai.telemetry.metadata.raindrop.ai.userId", args.userId),
@@ -1524,23 +2072,30 @@ function applyOtelSpanAttributeLimit(limit) {
1524
2072
  }
1525
2073
  var TraceShipper = class {
1526
2074
  constructor(opts) {
2075
+ this.appGitOwner = appGitOwnerId2("trace");
2076
+ this.appGitEventIds = /* @__PURE__ */ new WeakMap();
2077
+ this.appGitActiveSpans = /* @__PURE__ */ new Map();
2078
+ this.appGitCaptured = /* @__PURE__ */ new WeakSet();
2079
+ this.appGitAdded = /* @__PURE__ */ new WeakMap();
1527
2080
  this.queue = [];
1528
2081
  this.inFlight = /* @__PURE__ */ new Set();
1529
2082
  this.hasShutdown = false;
1530
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1531
- this.writeKey = (_a = opts.writeKey) == null ? void 0 : _a.trim();
1532
- this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
2083
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2084
+ this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
2085
+ this.ownsAppGitContext = opts.appGitContext === void 0;
2086
+ this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
2087
+ this.baseUrl = (_c = formatEndpoint(opts.endpoint)) != null ? _c : "https://api.raindrop.ai/v1/";
1533
2088
  this.enabled = opts.enabled !== false;
1534
2089
  this.debug = opts.debug;
1535
2090
  this.debugSpans = opts.debugSpans === true;
1536
- this.flushIntervalMs = (_c = opts.flushIntervalMs) != null ? _c : 1e3;
1537
- this.maxBatchSize = (_d = opts.maxBatchSize) != null ? _d : 50;
1538
- this.maxQueueSize = (_e = opts.maxQueueSize) != null ? _e : 5e3;
1539
- this.sdkName = (_f = opts.sdkName) != null ? _f : "core";
2091
+ this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
2092
+ this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
2093
+ this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
2094
+ this.sdkName = (_g = opts.sdkName) != null ? _g : "core";
1540
2095
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
1541
- this.serviceName = (_g = opts.serviceName) != null ? _g : "raindrop.core";
1542
- this.serviceVersion = (_h = opts.serviceVersion) != null ? _h : "0.0.0";
1543
- this.localDebuggerUrl = (_i = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _i : void 0;
2096
+ this.serviceName = (_h = opts.serviceName) != null ? _h : "raindrop.core";
2097
+ this.serviceVersion = (_i = opts.serviceVersion) != null ? _i : "0.0.0";
2098
+ this.localDebuggerUrl = (_j = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _j : void 0;
1544
2099
  if (this.debug && this.localDebuggerUrl) {
1545
2100
  console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
1546
2101
  }
@@ -1641,7 +2196,7 @@ var TraceShipper = class {
1641
2196
  return { ...this.authHeaders(), ...projectIdHeaders(this.projectId) };
1642
2197
  }
1643
2198
  startSpan(args) {
1644
- var _a, _b;
2199
+ var _a, _b, _c;
1645
2200
  const ids = createSpanIds(args.parent);
1646
2201
  const started = (_a = args.startTimeUnixNano) != null ? _a : nowUnixNanoString();
1647
2202
  const attrs = [
@@ -1651,13 +2206,24 @@ var TraceShipper = class {
1651
2206
  ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1652
2207
  ];
1653
2208
  if ((_b = args.attributes) == null ? void 0 : _b.length) attrs.push(...args.attributes);
2209
+ const tracksAppGit = this.appGitActiveSpans.has(args.eventId) || this.appGitActiveSpans.size < 1e4;
2210
+ const appGitOverrides = appGitPropertiesFromAttributes(attrs);
1654
2211
  const span = {
1655
2212
  ids,
1656
2213
  name: args.name,
1657
2214
  startTimeUnixNano: started,
1658
- attributes: attrs
2215
+ attributes: withAppGitAttributes(
2216
+ attrs,
2217
+ this.appGitContext.forOperation(args.eventId, appGitOverrides, this.appGitOwner)
2218
+ )
1659
2219
  };
1660
2220
  rememberReplayTraceDestination(span);
2221
+ this.appGitCaptured.add(span);
2222
+ this.appGitEventIds.set(span, args.eventId);
2223
+ if (tracksAppGit) {
2224
+ this.appGitActiveSpans.set(args.eventId, ((_c = this.appGitActiveSpans.get(args.eventId)) != null ? _c : 0) + 1);
2225
+ }
2226
+ this.appGitAdded.set(span, new Set(span.attributes.filter((attr) => !attrs.includes(attr))));
1661
2227
  const openSpan = buildOtlpSpan({
1662
2228
  ids: span.ids,
1663
2229
  name: span.name,
@@ -1697,11 +2263,17 @@ var TraceShipper = class {
1697
2263
  });
1698
2264
  }
1699
2265
  endSpan(span, extra) {
1700
- var _a, _b;
2266
+ var _a, _b, _c;
1701
2267
  if (span.endTimeUnixNano) return;
1702
2268
  span.endTimeUnixNano = (_a = extra == null ? void 0 : extra.endTimeUnixNano) != null ? _a : nowUnixNanoString();
1703
2269
  if ((_b = extra == null ? void 0 : extra.attributes) == null ? void 0 : _b.length) {
2270
+ const overrides = appGitPropertiesFromAttributes(extra.attributes);
2271
+ const eventId2 = this.appGitEventIds.get(span);
2272
+ const snapshot = eventId2 ? this.appGitContext.forOperation(eventId2, overrides, this.appGitOwner) : overrides;
2273
+ const added = this.appGitAdded.get(span);
2274
+ 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));
1704
2275
  span.attributes.push(...extra.attributes);
2276
+ span.attributes = withAppGitAttributes(span.attributes, snapshot);
1705
2277
  }
1706
2278
  let status = extra == null ? void 0 : extra.status;
1707
2279
  if (!status && (extra == null ? void 0 : extra.error) !== void 0) {
@@ -1717,8 +2289,19 @@ var TraceShipper = class {
1717
2289
  status
1718
2290
  });
1719
2291
  copyReplayTraceDestination(span, otlp);
2292
+ this.appGitCaptured.add(otlp);
1720
2293
  this.enqueue(otlp);
1721
2294
  this.mirrorToLocalDebugger(otlp, true);
2295
+ const eventId = this.appGitEventIds.get(span);
2296
+ if (eventId && this.appGitActiveSpans.has(eventId)) {
2297
+ const remaining = ((_c = this.appGitActiveSpans.get(eventId)) != null ? _c : 1) - 1;
2298
+ if (remaining > 0) this.appGitActiveSpans.set(eventId, remaining);
2299
+ else {
2300
+ this.appGitActiveSpans.delete(eventId);
2301
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(eventId, this.appGitOwner);
2302
+ else if (this.ownsAppGitContext) this.appGitContext.finishOperation(eventId);
2303
+ }
2304
+ }
1722
2305
  }
1723
2306
  createSpan(args) {
1724
2307
  var _a;
@@ -1729,20 +2312,41 @@ var TraceShipper = class {
1729
2312
  ...Object.entries(evalScopeAttributes()).map(([key, value]) => attrString(key, value))
1730
2313
  ];
1731
2314
  if ((_a = args.attributes) == null ? void 0 : _a.length) attrs.push(...args.attributes);
2315
+ const tracksAppGit = !this.appGitActiveSpans.has(args.eventId);
1732
2316
  const otlp = buildOtlpSpan({
1733
2317
  ids,
1734
2318
  name: args.name,
1735
2319
  startTimeUnixNano: args.startTimeUnixNano,
1736
2320
  endTimeUnixNano: args.endTimeUnixNano,
1737
- attributes: attrs,
2321
+ attributes: withAppGitAttributes(
2322
+ attrs,
2323
+ this.appGitContext.forOperation(
2324
+ args.eventId,
2325
+ appGitPropertiesFromAttributes(attrs),
2326
+ this.appGitOwner
2327
+ )
2328
+ ),
1738
2329
  status: args.status
1739
2330
  });
1740
2331
  rememberReplayTraceDestination(otlp);
2332
+ this.appGitCaptured.add(otlp);
2333
+ if (tracksAppGit) {
2334
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(args.eventId, this.appGitOwner);
2335
+ else if (this.ownsAppGitContext) this.appGitContext.finishOperation(args.eventId);
2336
+ }
1741
2337
  this.enqueue(otlp);
1742
2338
  this.mirrorToLocalDebugger(otlp, true);
1743
2339
  }
1744
2340
  enqueue(span) {
2341
+ var _a;
1745
2342
  if (!this.enabled) return;
2343
+ const attributes = (_a = span.attributes) != null ? _a : [];
2344
+ const enriched = this.appGitCaptured.has(span) ? attributes : withAppGitAttributes(attributes, this.appGitContext.snapshot(appGitPropertiesFromAttributes(attributes)));
2345
+ if (enriched !== attributes) {
2346
+ const original = span;
2347
+ span = { ...span, attributes: enriched.filter((attr) => attr !== void 0) };
2348
+ copyReplayTraceDestination(original, span);
2349
+ }
1746
2350
  if (this.debugSpans) {
1747
2351
  const short = (s) => s ? s.slice(-8) : "none";
1748
2352
  console.log(
@@ -1888,132 +2492,15 @@ var TraceShipper = class {
1888
2492
  }
1889
2493
  } finally {
1890
2494
  this.shutdownDeadlineAt = void 0;
2495
+ if (this.ownsAppGitContext) this.appGitContext.dispose();
1891
2496
  }
1892
2497
  }
1893
2498
  };
1894
- var NOOP_SPAN = {
1895
- traceIdB64: "",
1896
- spanIdB64: "",
1897
- eventId: "",
1898
- log() {
1899
- }
1900
- };
1901
- function getAsyncLocalStorageCtor() {
1902
- return globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
1903
- }
1904
- var SynchronousContextStorage = class {
1905
- constructor() {
1906
- this._stack = [];
1907
- }
1908
- isEmpty() {
1909
- return this._stack.length === 0;
1910
- }
1911
- getStore() {
1912
- return this._stack[this._stack.length - 1];
1913
- }
1914
- run(store, callback) {
1915
- this._stack.push(store);
1916
- try {
1917
- return callback();
1918
- } finally {
1919
- this._stack.pop();
1920
- }
1921
- }
1922
- };
1923
- var ContextManager = class {
1924
- };
1925
- var RaindropContextManager = class extends ContextManager {
1926
- constructor() {
1927
- super();
1928
- this._fallback = null;
1929
- const Ctor = getAsyncLocalStorageCtor();
1930
- if (Ctor) {
1931
- this._storage = new Ctor();
1932
- return;
1933
- }
1934
- this._fallback = new SynchronousContextStorage();
1935
- this._storage = this._fallback;
1936
- }
1937
- maybeAdoptAsyncLocalStorage() {
1938
- if (!this._fallback || !this._fallback.isEmpty()) return;
1939
- const Ctor = getAsyncLocalStorageCtor();
1940
- if (!Ctor) return;
1941
- this._storage = new Ctor();
1942
- this._fallback = null;
1943
- }
1944
- isReady() {
1945
- return true;
1946
- }
1947
- getParentSpanIds() {
1948
- this.maybeAdoptAsyncLocalStorage();
1949
- const span = this._storage.getStore();
1950
- if (!span || span === NOOP_SPAN) return void 0;
1951
- return {
1952
- traceIdB64: span.traceIdB64,
1953
- spanIdB64: span.spanIdB64,
1954
- eventId: span.eventId
1955
- };
1956
- }
1957
- runInContext(span, callback) {
1958
- this.maybeAdoptAsyncLocalStorage();
1959
- return this._storage.run(span, callback);
1960
- }
1961
- getCurrentSpan() {
1962
- this.maybeAdoptAsyncLocalStorage();
1963
- return this._storage.getStore();
1964
- }
1965
- };
1966
- var _contextManager = null;
1967
- function getContextManager() {
1968
- if (!_contextManager) {
1969
- _contextManager = globalThis.RAINDROP_CONTEXT_MANAGER ? new globalThis.RAINDROP_CONTEXT_MANAGER() : new RaindropContextManager();
1970
- }
1971
- return _contextManager;
1972
- }
1973
- function currentSpan() {
1974
- var _a;
1975
- return (_a = getContextManager().getCurrentSpan()) != null ? _a : NOOP_SPAN;
1976
- }
1977
- function withCurrent(span, callback) {
1978
- return getContextManager().runInContext(span, callback);
1979
- }
1980
- async function getCurrentParentSpanContext() {
1981
- var _a, _b;
1982
- return (_b = getContextManager().getParentSpanIds()) != null ? _b : (_a = currentReplayTraceDestination()) == null ? void 0 : _a.parentSpanContext;
1983
- }
1984
- async function runWithParentSpanContext(ctx, fn) {
1985
- const cm = getContextManager();
1986
- const span = {
1987
- traceIdB64: ctx.traceIdB64,
1988
- spanIdB64: ctx.spanIdB64,
1989
- eventId: ctx.eventId
1990
- };
1991
- return cm.runInContext(span, fn);
1992
- }
1993
- async function* asyncGeneratorWithCurrent(span, gen) {
1994
- let nextValue;
1995
- while (true) {
1996
- const result = await withCurrent(span, async () => {
1997
- try {
1998
- return await gen.next(nextValue);
1999
- } catch (e) {
2000
- return { value: void 0, done: true, error: e };
2001
- }
2002
- });
2003
- if ("error" in result && result.error !== void 0) {
2004
- throw result.error;
2005
- }
2006
- if (result.done) {
2007
- return result.value;
2008
- }
2009
- nextValue = yield result.value;
2010
- }
2011
- }
2012
2499
 
2013
2500
  // package.json
2014
2501
  var package_default = {
2015
2502
  name: "@raindrop-ai/ai-sdk",
2016
- version: "0.3.2"};
2503
+ version: "0.3.3"};
2017
2504
 
2018
2505
  // src/internal/version.ts
2019
2506
  var libraryName = package_default.name;
@@ -6511,11 +6998,11 @@ function userAttrsToOtlp(attrs) {
6511
6998
  function envDebugEnabled() {
6512
6999
  var _a;
6513
7000
  if (typeof process === "undefined") return false;
6514
- const flag = (_a = process.env) == null ? void 0 : _a.RAINDROP_AI_DEBUG;
6515
- return flag === "1" || flag === "true";
7001
+ const flag2 = (_a = process.env) == null ? void 0 : _a.RAINDROP_AI_DEBUG;
7002
+ return flag2 === "1" || flag2 === "true";
6516
7003
  }
6517
7004
  function createRaindropAISDK(opts) {
6518
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
7005
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
6519
7006
  const writeKey = opts.writeKey;
6520
7007
  const eventsRequested = ((_a = opts.events) == null ? void 0 : _a.enabled) !== false;
6521
7008
  const tracesRequested = ((_b = opts.traces) == null ? void 0 : _b.enabled) !== false;
@@ -6524,37 +7011,53 @@ function createRaindropAISDK(opts) {
6524
7011
  const localWorkshopInput = opts.localWorkshopUrl === false ? null : opts.localWorkshopUrl;
6525
7012
  const resolvedLocalDebuggerUrl = resolveLocalDebuggerBaseUrl(localWorkshopInput);
6526
7013
  const localDebuggerUrl = localWorkshopInput === null ? null : resolvedLocalDebuggerUrl != null ? resolvedLocalDebuggerUrl : void 0;
6527
- const hasDestination = !!writeKey || !!resolvedLocalDebuggerUrl;
7014
+ const hasDestination = Boolean(writeKey == null ? void 0 : writeKey.trim()) || Boolean(resolvedLocalDebuggerUrl);
6528
7015
  const eventsEnabled = eventsRequested && hasDestination;
6529
7016
  const tracesEnabled = tracesRequested && hasDestination;
7017
+ const appGitContext = (_c = opts.appGitContext) != null ? _c : createAppGitContext(
7018
+ eventsEnabled || tracesEnabled ? opts.appGit : false,
7019
+ { allowLocalGit: true }
7020
+ );
6530
7021
  if (!hasDestination && (eventsRequested || tracesRequested)) {
6531
7022
  console.warn(
6532
7023
  "[raindrop-ai/ai-sdk] writeKey not provided and no local Workshop reachable; telemetry shipping is disabled"
6533
7024
  );
6534
7025
  }
6535
- const eventShipper = new EventShipper2({
6536
- writeKey,
6537
- endpoint: opts.endpoint,
6538
- enabled: eventsEnabled,
6539
- debug: ((_c = opts.events) == null ? void 0 : _c.debug) === true || envDebug,
6540
- partialFlushMs: (_d = opts.events) == null ? void 0 : _d.partialFlushMs,
6541
- projectId: opts.projectId,
6542
- localDebuggerUrl
6543
- });
6544
- const traceShipper = new TraceShipper2({
6545
- writeKey,
6546
- endpoint: opts.endpoint,
6547
- enabled: tracesEnabled,
6548
- debug: ((_e = opts.traces) == null ? void 0 : _e.debug) === true || envDebug,
6549
- debugSpans: ((_f = opts.traces) == null ? void 0 : _f.debugSpans) === true || envDebug,
6550
- flushIntervalMs: (_g = opts.traces) == null ? void 0 : _g.flushIntervalMs,
6551
- maxBatchSize: (_h = opts.traces) == null ? void 0 : _h.maxBatchSize,
6552
- maxQueueSize: (_i = opts.traces) == null ? void 0 : _i.maxQueueSize,
6553
- projectId: opts.projectId,
6554
- localDebuggerUrl,
6555
- transformSpan: (_j = opts.traces) == null ? void 0 : _j.transformSpan,
6556
- disableDefaultRedaction: (_k = opts.traces) == null ? void 0 : _k.disableDefaultRedaction
6557
- });
7026
+ let eventShipper;
7027
+ let traceShipper;
7028
+ try {
7029
+ eventShipper = new EventShipper2({
7030
+ writeKey,
7031
+ endpoint: opts.endpoint,
7032
+ enabled: eventsEnabled,
7033
+ debug: ((_d = opts.events) == null ? void 0 : _d.debug) === true || envDebug,
7034
+ partialFlushMs: (_e = opts.events) == null ? void 0 : _e.partialFlushMs,
7035
+ projectId: opts.projectId,
7036
+ localDebuggerUrl,
7037
+ appGitContext
7038
+ });
7039
+ traceShipper = new TraceShipper2({
7040
+ writeKey,
7041
+ endpoint: opts.endpoint,
7042
+ enabled: tracesEnabled,
7043
+ debug: ((_f = opts.traces) == null ? void 0 : _f.debug) === true || envDebug,
7044
+ debugSpans: ((_g = opts.traces) == null ? void 0 : _g.debugSpans) === true || envDebug,
7045
+ flushIntervalMs: (_h = opts.traces) == null ? void 0 : _h.flushIntervalMs,
7046
+ maxBatchSize: (_i = opts.traces) == null ? void 0 : _i.maxBatchSize,
7047
+ maxQueueSize: (_j = opts.traces) == null ? void 0 : _j.maxQueueSize,
7048
+ projectId: opts.projectId,
7049
+ localDebuggerUrl,
7050
+ transformSpan: (_k = opts.traces) == null ? void 0 : _k.transformSpan,
7051
+ disableDefaultRedaction: (_l = opts.traces) == null ? void 0 : _l.disableDefaultRedaction,
7052
+ appGitContext
7053
+ });
7054
+ } catch (error) {
7055
+ try {
7056
+ appGitContext.dispose();
7057
+ } catch (e) {
7058
+ }
7059
+ throw error;
7060
+ }
6558
7061
  const settledEventIds = /* @__PURE__ */ new Set();
6559
7062
  const subagentApi = new SubagentApi({
6560
7063
  traceShipper,
@@ -6722,7 +7225,14 @@ function createRaindropAISDK(opts) {
6722
7225
  await Promise.all([eventShipper.flush(), traceShipper.flush()]);
6723
7226
  },
6724
7227
  async shutdown() {
6725
- await Promise.all([eventShipper.shutdown(), traceShipper.shutdown()]);
7228
+ try {
7229
+ await Promise.all([eventShipper.shutdown(), traceShipper.shutdown()]);
7230
+ } finally {
7231
+ try {
7232
+ appGitContext.dispose();
7233
+ } catch (e) {
7234
+ }
7235
+ }
6726
7236
  }
6727
7237
  };
6728
7238
  }