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