@bitfab/sdk 0.65.6 → 0.65.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2213 +1,35 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __exportAll = (all, no_symbols) => {
9
- let target = {};
10
- for (var name in all) __defProp(target, name, {
11
- get: all[name],
12
- enumerable: true
13
- });
14
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
15
- return target;
16
- };
17
- var __copyProps = (to, from, except, desc) => {
18
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
19
- key = keys[i];
20
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
21
- get: ((k) => from[k]).bind(null, key),
22
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
23
- });
24
- }
25
- return to;
26
- };
27
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
28
- value: mod,
29
- enumerable: true
30
- }) : target, mod));
31
- //#endregion
32
- const require_autoTrace = require("./autoTrace-CQw0qMBt.cjs");
33
- let _opentelemetry_api = require("@opentelemetry/api");
34
- let _opentelemetry_core = require("@opentelemetry/core");
35
- let _opentelemetry_resources = require("@opentelemetry/resources");
36
- let _opentelemetry_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
37
- let superjson = require("superjson");
38
- superjson = __toESM(superjson, 1);
39
- //#region src/categories.ts
40
- const CATEGORIES_PATH = "/api/sdk/categories";
41
- var CategoriesClient = class {
42
- constructor(httpClient) {
43
- this.httpClient = httpClient;
44
- }
45
- async save(params) {
46
- return (await this.httpClient.request(CATEGORIES_PATH, params)).category;
47
- }
48
- async get(id) {
49
- return (await this.httpClient.get(`${CATEGORIES_PATH}/${encodeURIComponent(id)}`)).category;
50
- }
51
- async list() {
52
- return (await this.httpClient.get(CATEGORIES_PATH)).categories;
53
- }
54
- async delete(id) {
55
- return (await this.httpClient.request(`${CATEGORIES_PATH}/${encodeURIComponent(id)}`, {}, { method: "DELETE" })).category;
56
- }
57
- };
58
- const AssertionCategoriesClient = CategoriesClient;
59
- //#endregion
60
- //#region src/version.generated.ts
61
- const __version__ = "0.65.6";
62
- const __packageName__ = "@bitfab/sdk";
63
- //#endregion
64
- //#region src/constants.ts
65
- const DEFAULT_SERVICE_URL = "https://bitfab.ai";
66
- //#endregion
67
- //#region src/traceCompletion.ts
68
- var TraceCompletion = class {
69
- constructor() {
70
- this.traces = /* @__PURE__ */ new Map();
71
- this.closed = /* @__PURE__ */ new Map();
72
- }
73
- state(traceId) {
74
- let state = this.traces.get(traceId);
75
- if (state === void 0) {
76
- state = {
77
- spanIds: /* @__PURE__ */ new Set(),
78
- active: /* @__PURE__ */ new Set()
79
- };
80
- this.traces.set(traceId, state);
81
- }
82
- return state;
83
- }
84
- start(traceId, spanId) {
85
- if (this.closed.has(traceId)) return;
86
- const state = this.state(traceId);
87
- state.spanIds.add(spanId);
88
- state.active.add(spanId);
89
- }
90
- open(traceId) {
91
- if (!this.closed.has(traceId)) this.state(traceId);
92
- }
93
- hold(traceId, key) {
94
- this.state(traceId).active.add(key);
95
- }
96
- record(traceId, spanId) {
97
- if (!this.closed.has(traceId)) this.state(traceId).spanIds.add(spanId);
98
- }
99
- end(traceId, spanId) {
100
- const state = this.traces.get(traceId);
101
- if (state !== void 0) {
102
- state.active.delete(spanId);
103
- this.drain(traceId, state);
104
- }
105
- }
106
- abort(traceId, spanId) {
107
- const state = this.traces.get(traceId);
108
- if (state === void 0) return;
109
- state.active.delete(spanId);
110
- state.spanIds.delete(spanId);
111
- if (state.active.size === 0 && state.spanIds.size === 0 && state.complete === void 0) {
112
- this.traces.delete(traceId);
113
- return;
114
- }
115
- this.drain(traceId, state);
116
- }
117
- close(traceId, complete, dropped = false) {
118
- const count = this.closed.get(traceId);
119
- if (count !== void 0) {
120
- complete(count);
121
- return;
122
- }
123
- const state = this.traces.get(traceId);
124
- if (state === void 0) return;
125
- state.complete = complete;
126
- if (dropped) state.active.clear();
127
- this.drain(traceId, state);
128
- }
129
- drain(traceId, state) {
130
- if (state.active.size !== 0 || state.complete === void 0) return;
131
- this.traces.delete(traceId);
132
- this.closed.set(traceId, state.spanIds.size);
133
- if (this.closed.size > 1024) {
134
- const oldest = this.closed.keys().next().value;
135
- if (oldest !== void 0) this.closed.delete(oldest);
136
- }
137
- state.complete(state.spanIds.size);
138
- }
139
- };
140
- //#endregion
141
- //#region src/readEnv.ts
142
- function readEnv$1(name) {
143
- if (typeof process !== "undefined" && process.env) return process.env[name];
144
- }
145
- //#endregion
146
- //#region src/compress.ts
147
- const DISABLE_COMPRESSION_ENV = "BITFAB_DISABLE_COMPRESSION";
148
- const MIN_COMPRESSED_BYTES = 8192;
149
- let gzipNode;
150
- (typeof process !== "undefined" && process.versions?.node ? import(
151
- /* webpackIgnore: true */
152
- ["node", "zlib"].join(":")
153
- ).then(({ gzip }) => {
154
- gzipNode = (data) => new Promise((resolve, reject) => {
155
- gzip(data, (error, result) => {
156
- if (error) reject(error);
157
- else resolve(result);
158
- });
159
- });
160
- }).catch(() => {}) : Promise.resolve()).then(() => {});
161
- function toArrayBuffer(view) {
162
- return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
163
- }
164
- function compressedRequest(body, rawBytes, compressed) {
165
- if (compressed.byteLength >= rawBytes) return {
166
- body,
167
- rawBytes,
168
- wireBytes: rawBytes
169
- };
170
- return {
171
- body: compressed instanceof Uint8Array ? toArrayBuffer(compressed) : compressed,
172
- contentEncoding: "gzip",
173
- rawBytes,
174
- wireBytes: compressed.byteLength
175
- };
176
- }
177
- async function gzipViaStream(bytes) {
178
- const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip"));
179
- return await new Response(stream).arrayBuffer();
180
- }
181
- function encodeRequestBody(body) {
182
- if (readEnv$1(DISABLE_COMPRESSION_ENV)) {
183
- const rawBytes = new TextEncoder().encode(body).byteLength;
184
- return {
185
- body,
186
- rawBytes,
187
- wireBytes: rawBytes
188
- };
189
- }
190
- const bytes = new TextEncoder().encode(body);
191
- if (bytes.byteLength < MIN_COMPRESSED_BYTES) return {
192
- body,
193
- rawBytes: bytes.byteLength,
194
- wireBytes: bytes.byteLength
195
- };
196
- if (gzipNode) return gzipNode(bytes).then((compressed) => compressedRequest(body, bytes.byteLength, compressed), () => ({
197
- body,
198
- rawBytes: bytes.byteLength,
199
- wireBytes: bytes.byteLength
200
- }));
201
- if (typeof CompressionStream === "undefined") return {
202
- body,
203
- rawBytes: bytes.byteLength,
204
- wireBytes: bytes.byteLength
205
- };
206
- return gzipViaStream(bytes).then((compressed) => compressedRequest(body, bytes.byteLength, compressed), () => ({
207
- body,
208
- rawBytes: bytes.byteLength,
209
- wireBytes: bytes.byteLength
210
- }));
211
- }
212
- //#endregion
213
- //#region src/errors.ts
214
- var BitfabError = class extends Error {
215
- constructor(message, url, status, retryAfterMs) {
216
- super(message);
217
- this.url = url;
218
- this.status = status;
219
- this.retryAfterMs = retryAfterMs;
220
- this.name = "BitfabError";
221
- }
222
- };
223
- var MixedTracingError = class extends Error {
224
- constructor(message) {
225
- super(message);
226
- this.name = "MixedTracingError";
227
- }
228
- };
229
- //#endregion
230
- //#region src/gitCommand.ts
231
- const EXIT_GRACE_MS = 500;
232
- function isUnrefable(value) {
233
- return typeof value === "object" && value !== null && "unref" in value && typeof value.unref === "function";
234
- }
235
- function unrefStream(stream) {
236
- if (isUnrefable(stream)) stream.unref();
237
- }
238
- function terminate(child) {
239
- if (child.pid && process.platform !== "win32") try {
240
- process.kill(-child.pid, "SIGTERM");
241
- return;
242
- } catch {
243
- child.kill("SIGTERM");
244
- return;
245
- }
246
- child.kill("SIGTERM");
247
- }
248
- async function gitRunner(options) {
249
- let spawn;
250
- try {
251
- ({spawn} = await import("child_process"));
252
- } catch {
253
- return null;
254
- }
255
- return (dir, args, env) => new Promise((resolve) => {
256
- let child;
257
- try {
258
- child = spawn("git", args, {
259
- cwd: dir,
260
- detached: process.platform !== "win32",
261
- stdio: [
262
- "ignore",
263
- "pipe",
264
- "pipe"
265
- ],
266
- ...env ? { env: {
267
- ...process.env,
268
- ...env
269
- } } : {}
270
- });
271
- } catch {
272
- resolve(null);
273
- return;
274
- }
275
- const chunks = [];
276
- let size = 0;
277
- let overflow = false;
278
- let exitCode = null;
279
- let done = false;
280
- const timers = [];
281
- const schedule = (callback, ms) => {
282
- const timer = setTimeout(callback, ms);
283
- if (!options.keepProcessAlive) timer.unref();
284
- timers.push(timer);
285
- };
286
- const finish = () => {
287
- if (done) return;
288
- done = true;
289
- for (const timer of timers) clearTimeout(timer);
290
- child.stdout?.destroy();
291
- child.stderr?.destroy();
292
- resolve(exitCode === 0 && !overflow ? Buffer.concat(chunks).toString("utf8") : null);
293
- };
294
- child.stdout?.on("data", (chunk) => {
295
- size += chunk.length;
296
- if (size > options.maxBuffer) {
297
- overflow = true;
298
- terminate(child);
299
- return;
300
- }
301
- chunks.push(chunk);
302
- });
303
- child.stderr?.resume();
304
- child.on("error", () => {
305
- exitCode = null;
306
- finish();
307
- });
308
- child.on("exit", (code) => {
309
- exitCode = code;
310
- schedule(finish, EXIT_GRACE_MS);
311
- });
312
- child.on("close", (code) => {
313
- exitCode = code ?? exitCode;
314
- finish();
315
- });
316
- schedule(() => terminate(child), options.timeoutMs);
317
- if (!options.keepProcessAlive) {
318
- child.unref();
319
- unrefStream(child.stdout);
320
- unrefStream(child.stderr);
321
- }
322
- });
323
- }
324
- //#endregion
325
- //#region src/gitState.ts
326
- const GIT_TIMEOUT_MS$1 = 3e4;
327
- const GIT_MAX_BUFFER$1 = 1048576;
328
- const DISABLE_ENV$1 = "BITFAB_DISABLE_GIT_STATE";
329
- const SHA_PATTERN = /^[0-9a-f]{40}$/;
330
- function sha(value) {
331
- const trimmed = value?.trim();
332
- return trimmed && SHA_PATTERN.test(trimmed) ? trimmed : null;
333
- }
334
- function text(value) {
335
- const trimmed = value?.trim();
336
- return trimmed ? trimmed : null;
337
- }
338
- function isEmptyGitState(state) {
339
- return Object.values(state).every((value) => value === null);
340
- }
341
- async function resolveGitState(cwd) {
342
- const git = await gitRunner({
343
- timeoutMs: GIT_TIMEOUT_MS$1,
344
- maxBuffer: GIT_MAX_BUFFER$1,
345
- keepProcessAlive: true
346
- });
347
- if (!git) return null;
348
- const run = async (args, env) => (await git(cwd, args, env))?.trim() ?? null;
349
- const [refs, email, branch] = await Promise.all([
350
- run([
351
- "rev-parse",
352
- "--show-toplevel",
353
- "HEAD",
354
- "HEAD^{tree}"
355
- ]),
356
- run(["config", "user.email"]),
357
- run([
358
- "symbolic-ref",
359
- "--short",
360
- "-q",
361
- "HEAD"
362
- ])
363
- ]);
364
- const [root, commitSha, baseSha] = (refs ?? "").split("\n");
365
- if (!root) return null;
366
- const state = {
367
- githubEmail: text(email),
368
- branch: text(branch),
369
- commitSha: sha(commitSha),
370
- baseSha: sha(baseSha),
371
- experimentSha: await resolveWorkingTreeSha(run, root.trim())
372
- };
373
- return isEmptyGitState(state) ? null : state;
374
- }
375
- async function resolveWorkingTreeSha(run, root) {
376
- let indexPath;
377
- let cleanup;
378
- try {
379
- const { mkdtemp, rm } = await import("fs/promises");
380
- const { join } = await import("path");
381
- const { tmpdir } = await import("os");
382
- const dir = await mkdtemp(join(tmpdir(), "bitfab-git-"));
383
- indexPath = join(dir, "index");
384
- cleanup = () => rm(dir, {
385
- recursive: true,
386
- force: true
387
- });
388
- } catch {
389
- return null;
390
- }
391
- try {
392
- const env = { GIT_INDEX_FILE: indexPath };
393
- if (await run(["read-tree", "HEAD"], env) === null) return null;
394
- if (await run([
395
- "add",
396
- "-A",
397
- "--",
398
- root
399
- ], env) === null) return null;
400
- return sha(await run(["write-tree"], env));
401
- } catch {
402
- return null;
403
- } finally {
404
- await cleanup().catch(() => {});
405
- }
406
- }
407
- function resolvedGitState() {
408
- if (typeof process === "undefined" || process.env?.[DISABLE_ENV$1]) return Promise.resolve(null);
409
- let cwd;
410
- try {
411
- cwd = process.cwd?.() ?? ".";
412
- } catch {
413
- return Promise.resolve(null);
414
- }
415
- return resolveGitState(cwd).catch(() => null);
416
- }
417
- //#endregion
418
- //#region src/replayContext.ts
419
- let replayContextStorage = null;
420
- const REPLAY_CONTEXT_STORAGE_SYMBOL = Symbol.for("bitfab.replayContextStorage");
421
- const replayContextReady = require_autoTrace.asyncStorageReady.then(() => {
422
- const shared = globalThis;
423
- const existing = shared[REPLAY_CONTEXT_STORAGE_SYMBOL];
424
- if (existing) {
425
- replayContextStorage = existing;
426
- return;
427
- }
428
- const created = require_autoTrace.createAsyncLocalStorage();
429
- if (created) {
430
- shared[REPLAY_CONTEXT_STORAGE_SYMBOL] = created;
431
- replayContextStorage = created;
432
- }
433
- });
434
- function getReplayContext() {
435
- return replayContextStorage?.getStore() ?? null;
436
- }
437
- function runWithReplayContext(ctx, fn) {
438
- if (replayContextStorage) return replayContextStorage.run(ctx, fn);
439
- return fn();
440
- }
441
- //#endregion
442
- //#region src/payloadBudget.ts
443
- const MAX_SPAN_CARRIER_BYTES = 28e5;
444
- const MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES = 78e5;
445
- const textEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
446
- function byteLength(value) {
447
- return textEncoder ? textEncoder.encode(value).length : value.length;
448
- }
449
- function carrierByteLength(body) {
450
- return carrierBytesOf(textEncoder ? textEncoder.encode(body) : null, body);
451
- }
452
- function carrierBytesOf(encoded, body) {
453
- if (!encoded) return body.length + 2;
454
- let extra = 2;
455
- for (let i = 0; i < encoded.length; i++) {
456
- const byte = encoded[i];
457
- if (byte === 34 || byte === 92) extra += 1;
458
- else if (byte < 32) extra += byte === 8 || byte === 9 || byte === 10 || byte === 12 || byte === 13 ? 1 : 5;
459
- }
460
- return encoded.length + extra;
461
- }
462
- const MAX_BYTES_PER_UNIT = 3;
463
- function fitsCarrierBudget(body, maxBytes = MAX_SPAN_CARRIER_BYTES) {
464
- const units = body.length;
465
- if (units * MAX_BYTES_PER_UNIT + 2 <= maxBytes) return true;
466
- if (units + 2 > maxBytes) return false;
467
- return carrierByteLength(body) <= maxBytes;
468
- }
469
- const STRUCTURAL_SPAN_KEYS = /* @__PURE__ */ new Set([
470
- "name",
471
- "type",
472
- "function_name",
473
- "error_source"
474
- ]);
475
- function asRecord(value) {
476
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
477
- }
478
- function cloneTrimmable(payload) {
479
- const copy = { ...payload };
480
- const containers = [];
481
- const spanData = asRecord(copy.span_data);
482
- if (spanData) {
483
- const clone = { ...spanData };
484
- copy.span_data = clone;
485
- containers.push(clone);
486
- }
487
- const rawSpan = asRecord(copy.rawSpan);
488
- const rawSpanData = rawSpan && asRecord(rawSpan.span_data);
489
- if (rawSpan && rawSpanData) {
490
- const clone = { ...rawSpanData };
491
- copy.rawSpan = {
492
- ...rawSpan,
493
- span_data: clone
494
- };
495
- containers.push(clone);
496
- }
497
- if (containers.length === 0) containers.push(copy);
498
- return {
499
- copy,
500
- containers
501
- };
502
- }
503
- function collectCandidates(containers) {
504
- const candidates = [];
505
- for (const container of containers) for (const [key, value] of Object.entries(container)) {
506
- if (STRUCTURAL_SPAN_KEYS.has(key) || value == null) continue;
507
- let size;
508
- try {
509
- size = byteLength(JSON.stringify(value) ?? "");
510
- } catch {
511
- continue;
512
- }
513
- candidates.push({
514
- container,
515
- key,
516
- size
517
- });
518
- }
519
- return candidates.sort((a, b) => b.size - a.size);
520
- }
521
- function trimPayloadToBudget(payload, encode, maxBytes = MAX_SPAN_CARRIER_BYTES) {
522
- const { copy, containers } = cloneTrimmable(payload);
523
- const candidates = collectCandidates(containers);
524
- if (candidates.length === 0) return;
525
- const trimmed = [];
526
- for (const candidate of candidates) {
527
- candidate.container[candidate.key] = `<unserializable: too_large_${candidate.size}_bytes>`;
528
- trimmed.push(candidate.key);
529
- let body;
530
- try {
531
- body = encode(copy);
532
- } catch {
533
- return;
534
- }
535
- if (fitsCarrierBudget(body, maxBytes)) return {
536
- value: copy,
537
- trimmed
538
- };
539
- }
540
- }
541
- function markPayloadTrimmed(value, trimmed, maxBytes = MAX_SPAN_CARRIER_BYTES) {
542
- value.errors = [...Array.isArray(value.errors) ? value.errors : [], {
543
- source: "sdk",
544
- step: "payload_budget",
545
- error: `trimmed oversized field(s) to fit the ${maxBytes}-byte span carrier budget: ${[...new Set(trimmed)].join(", ")}`
546
- }];
547
- }
548
- //#endregion
549
- //#region src/serializePayload.ts
550
- function serializePayloadBody(payload, maxCarrierBytes = MAX_SPAN_CARRIER_BYTES) {
551
- return require_autoTrace.runWithCaptureSuppressed(() => encodeWithinBudget(payload, maxCarrierBytes));
552
- }
553
- function encodeWithinBudget(payload, maxCarrierBytes) {
554
- const encoded = encodePayloadBody(payload);
555
- if (fitsCarrierBudget(encoded.body, maxCarrierBytes)) return {
556
- body: encoded.body,
557
- dropped: encoded.dropped
558
- };
559
- return applyPayloadBudget(encoded, maxCarrierBytes);
560
- }
561
- function applyPayloadBudget(encoded, maxCarrierBytes) {
562
- const result = encoded.value ? trimPayloadToBudget(encoded.value, (value) => encodePayloadBody(value).body, maxCarrierBytes) : void 0;
563
- if (!result) return {
564
- body: encoded.body,
565
- dropped: encoded.dropped
566
- };
567
- require_autoTrace.warnOnce("payload:over-budget", `a span payload exceeded the ${maxCarrierBytes}-byte carrier budget; its largest field(s) (${[...new Set(result.trimmed)].join(", ")}) were replaced with placeholders so the span still ships. The span is incomplete and may not be replayable.`);
568
- markPayloadTrimmed(result.value, result.trimmed, maxCarrierBytes);
569
- return {
570
- body: encodePayloadBody(result.value).body,
571
- dropped: encoded.dropped
572
- };
573
- }
574
- function encodePayloadBody(payload) {
575
- try {
576
- return {
577
- body: JSON.stringify(payload),
578
- dropped: [],
579
- value: payload
580
- };
581
- } catch {
582
- const dropped = [];
583
- const sanitize = (value, seen) => {
584
- const t = typeof value;
585
- if (value === null || t === "string" || t === "number" || t === "boolean") return value;
586
- if (t === "bigint") {
587
- dropped.push("BigInt");
588
- return "<unserializable: BigInt>";
589
- }
590
- if (t === "function") {
591
- const name = value.name || "Function";
592
- dropped.push(name);
593
- return `<unserializable: ${name}>`;
594
- }
595
- if (t === "symbol") {
596
- dropped.push("Symbol");
597
- return "<unserializable: Symbol>";
598
- }
599
- if (t !== "object") return;
600
- const obj = value;
601
- const className = obj.constructor?.name || "object";
602
- if (seen.has(obj)) {
603
- dropped.push(className);
604
- return `<cycle: ${className}>`;
605
- }
606
- seen.add(obj);
607
- let result;
608
- if (Array.isArray(obj)) result = obj.map((item) => sanitize(item, seen));
609
- else if (typeof obj.toJSON === "function") try {
610
- result = sanitize(obj.toJSON(), seen);
611
- } catch {
612
- dropped.push(className);
613
- result = `<unserializable: ${className}>`;
614
- }
615
- else try {
616
- const out = {};
617
- for (const [k, v] of Object.entries(obj)) out[k] = sanitize(v, seen);
618
- result = out;
619
- } catch {
620
- require_autoTrace.warnOnce("payload:field-getter-threw", "a value with a throwing getter/proxy could not be serialized into a span payload; it was replaced with a placeholder. The span still ships with its other fields intact.");
621
- dropped.push(className);
622
- result = `<unserializable: ${className}>`;
623
- }
624
- seen.delete(obj);
625
- return result;
626
- };
627
- let sanitized;
628
- try {
629
- sanitized = sanitize(payload, /* @__PURE__ */ new WeakSet());
630
- } catch (error) {
631
- const marker = { error: `payload_serialize_failed: ${error instanceof Error ? error.message : String(error)}` };
632
- return {
633
- body: JSON.stringify(marker),
634
- dropped,
635
- value: marker
636
- };
637
- }
638
- const isRecord = typeof sanitized === "object" && sanitized !== null && !Array.isArray(sanitized);
639
- if (dropped.length > 0 && isRecord) {
640
- const obj = sanitized;
641
- obj.errors = [...Array.isArray(obj.errors) ? obj.errors : [], {
642
- source: "sdk",
643
- step: "json_serialize",
644
- error: `stubbed non-serializable value(s): ${[...new Set(dropped)].join(", ")}`
645
- }];
646
- }
647
- return {
648
- body: JSON.stringify(sanitized),
649
- dropped,
650
- value: isRecord ? sanitized : void 0
651
- };
652
- }
653
- }
654
- //#endregion
655
- //#region src/policyRefresh.ts
656
- var PolicyRefresh = class {
657
- constructor() {
658
- this.refreshAfter = 0;
659
- }
660
- due() {
661
- return this.inFlight === void 0 && Date.now() >= this.refreshAfter;
662
- }
663
- hold(durationMs) {
664
- this.refreshAfter = Date.now() + durationMs;
665
- }
666
- releaseHold() {
667
- this.refreshAfter = 0;
668
- }
669
- run(read, onLoaded, onFailed) {
670
- if (!this.due()) return;
671
- let request;
672
- try {
673
- request = read().then(onLoaded).catch(onFailed).finally(() => {
674
- this.inFlight = void 0;
675
- });
676
- } catch (error) {
677
- onFailed(error);
678
- return;
679
- }
680
- this.inFlight = request;
681
- }
682
- };
683
- //#endregion
684
- //#region src/spanOrigin.ts
685
- const SPAN_ORIGIN_NAME = "bitfab.sdk.typescript";
686
- const SPAN_INSTRUMENTATIONS = [
687
- "span",
688
- "trace",
689
- "openai-agents",
690
- "langgraph",
691
- "claude-agent-sdk",
692
- "vercel-ai",
693
- "rivet"
694
- ];
695
- const FRAMEWORK_INSTRUMENTATION_SET = /* @__PURE__ */ new Set([
696
- "openai-agents",
697
- "langgraph",
698
- "claude-agent-sdk",
699
- "vercel-ai",
700
- "rivet"
701
- ]);
702
- function isFrameworkInstrumentation(value) {
703
- return typeof value === "string" && FRAMEWORK_INSTRUMENTATION_SET.has(value);
704
- }
705
- function makeSpanOrigin(instrumentation) {
706
- return {
707
- name: SPAN_ORIGIN_NAME,
708
- version: __version__,
709
- instrumentation: { name: instrumentation }
710
- };
711
- }
712
- function isRecord$4(value) {
713
- return typeof value === "object" && value !== null && !Array.isArray(value);
714
- }
715
- function spanOriginOf(payload) {
716
- const rawSpan = payload.rawSpan;
717
- if (!isRecord$4(rawSpan)) return;
718
- const origin = rawSpan.span_origin;
719
- if (!isRecord$4(origin) || !isRecord$4(origin.instrumentation)) return;
720
- const { name, version } = origin;
721
- const instrumentation = origin.instrumentation.name;
722
- if (typeof name !== "string" || typeof version !== "string" || typeof instrumentation !== "string" || !SPAN_INSTRUMENTATIONS.includes(instrumentation)) return;
723
- return {
724
- name,
725
- version,
726
- instrumentation: { name: instrumentation }
727
- };
728
- }
729
- function spanInstrumentationOf(payload) {
730
- return spanOriginOf(payload)?.instrumentation.name;
731
- }
732
- function recordedByFramework(payload) {
733
- return isFrameworkInstrumentation(spanInstrumentationOf(payload));
734
- }
735
- //#endregion
736
- //#region src/simulationPlan.ts
737
- const SIMULATION_PLAN_REFRESH_MS = 6e4;
738
- const SIMULATION_PLAN_RETRY_MS = 1e4;
739
- const SIMULATION_PLAN_READ_TIMEOUT_MS = 5e3;
740
- const SIMULATION_PLAN_MAX_HELD = 1e3;
741
- const DISABLE_SIMULATION_PLAN_ENV = "BITFAB_DISABLE_SIM_PLAN";
742
- const NO_API_KEY_FOR_SIMULATION_PLAN = "no API key is set";
743
- const ROOT_TRACE_FUNCTION_KEY_FIELD = "rootTraceFunctionKey";
744
- const DECLARED_NODE_FIELD = "declaredNode";
745
- const CONTENT_OFF_KEY = "content_off_by_simulation_plan";
746
- const CONTENT_KEYS = [
747
- "input",
748
- "input_meta",
749
- "output",
750
- "output_meta",
751
- "replay_recording",
752
- "prompt"
753
- ];
754
- function planWaitSliceMs(timeoutMs) {
755
- return Math.min(SIMULATION_PLAN_READ_TIMEOUT_MS, Math.max(timeoutMs, 0) / 2);
756
- }
757
- function parseSimulationPlan(body) {
758
- if (typeof body !== "object" || body === null) return null;
759
- const nodes = body.nodes;
760
- if (!Array.isArray(nodes)) return null;
761
- const contentOff = /* @__PURE__ */ new Map();
762
- for (const node of nodes) {
763
- if (typeof node !== "object" || node === null) continue;
764
- const { traceFunctionKey, name, captureContent } = node;
765
- if (typeof traceFunctionKey !== "string" || typeof name !== "string" || typeof captureContent !== "boolean") continue;
766
- if (captureContent) continue;
767
- const names = contentOff.get(traceFunctionKey) ?? /* @__PURE__ */ new Set();
768
- names.add(name);
769
- contentOff.set(traceFunctionKey, names);
770
- }
771
- return contentOff;
772
- }
773
- function traceIdOf(payload) {
774
- const traceId = payload.traceId;
775
- if (typeof traceId === "string") return traceId;
776
- const id = payload.id;
777
- return typeof id === "string" ? id : void 0;
778
- }
779
- function isRecord$3(value) {
780
- return typeof value === "object" && value !== null;
781
- }
782
- function rawSpanOf(payload) {
783
- return isRecord$3(payload.rawSpan) ? payload.rawSpan : void 0;
784
- }
785
- function spanDataOf(payload) {
786
- const spanData = rawSpanOf(payload)?.span_data;
787
- return isRecord$3(spanData) ? spanData : void 0;
788
- }
789
- function spanNameOf(payload) {
790
- const name = spanDataOf(payload)?.name;
791
- return typeof name === "string" ? name : void 0;
792
- }
793
- function stripContent(payload) {
794
- const rawSpan = rawSpanOf(payload);
795
- const spanData = spanDataOf(payload);
796
- if (rawSpan === void 0 || spanData === void 0) return payload;
797
- const kept = { ...spanData };
798
- for (const key of CONTENT_KEYS) delete kept[key];
799
- kept[CONTENT_OFF_KEY] = true;
800
- return {
801
- ...payload,
802
- rawSpan: {
803
- ...rawSpan,
804
- span_data: kept
805
- }
806
- };
807
- }
808
- function simulationPlanEnvDisabled() {
809
- const value = readEnv$1(DISABLE_SIMULATION_PLAN_ENV);
810
- return typeof value === "string" && value.trim() !== "";
811
- }
812
- function missingSimulationPlanEndpoint(error) {
813
- return error instanceof BitfabError && error.status === 404;
814
- }
815
- function isTraceRootSpan(payload) {
816
- const parentId = rawSpanOf(payload)?.parent_id;
817
- return parentId === void 0 || parentId === null;
818
- }
819
- function declaredInCode(payload) {
820
- return payload[DECLARED_NODE_FIELD] === true;
821
- }
822
- function recordedError(payload) {
823
- const error = spanDataOf(payload)?.error;
824
- return error !== void 0 && error !== null;
825
- }
826
- var SimulationPlan = class {
827
- constructor(source, enabled = true) {
828
- this.source = source;
829
- this.enabled = enabled;
830
- this.policyRefresh = new PolicyRefresh();
831
- this.firstReadOver = false;
832
- this.rootWaitOver = false;
833
- this.held = [];
834
- this.stopped = false;
835
- this.loaded = new Promise((resolve) => {
836
- this.resolveLoaded = resolve;
837
- });
838
- this.firstReadEnded = new Promise((resolve) => {
839
- this.resolveFirstReadEnded = resolve;
840
- });
841
- }
842
- disabled() {
843
- return !this.enabled || simulationPlanEnvDisabled();
844
- }
845
- refresh() {
846
- if (this.stopped || this.disabled()) return;
847
- this.policyRefresh.run(() => this.source.getSimulationPlan(), (body) => {
848
- const parsed = parseSimulationPlan(body);
849
- if (parsed === null) this.scheduleRetry("sim-plan-unreadable", "the sim plan response was not understood");
850
- else this.markLoaded(parsed);
851
- this.endFirstRead();
852
- }, (error) => {
853
- if (missingSimulationPlanEndpoint(error)) this.markLoaded(/* @__PURE__ */ new Map());
854
- else this.scheduleRetry("sim-plan-unavailable", `could not read the sim plan: ${error instanceof Error ? error.message : String(error)}`);
855
- this.endFirstRead();
856
- });
857
- }
858
- markLoaded(parsed) {
859
- if (this.stopped) return;
860
- this.contentOffByKey = parsed;
861
- this.policyRefresh.hold(SIMULATION_PLAN_REFRESH_MS);
862
- this.resolveLoaded?.();
863
- this.resolveLoaded = void 0;
864
- }
865
- scheduleRetry(warnKey, reason) {
866
- if (this.stopped) return;
867
- this.policyRefresh.hold(SIMULATION_PLAN_RETRY_MS);
868
- if (this.contentOffByKey !== void 0) return;
869
- require_autoTrace.warnOnce(warnKey, `${reason}. Until a read succeeds, spans are sent without their inputs and outputs, except each trace's root span and spans recorded by a framework integration. The read is retried on the next span after ${SIMULATION_PLAN_RETRY_MS / 1e3}s.`);
870
- }
871
- endFirstRead() {
872
- this.endRootWait();
873
- if (!this.firstReadOver) {
874
- this.firstReadOver = true;
875
- this.resolveFirstReadEnded?.();
876
- this.resolveFirstReadEnded = void 0;
877
- }
878
- this.releaseHeld();
879
- }
880
- endRootWait() {
881
- this.rootWaitOver = true;
882
- if (this.rootWaitTimer !== void 0) {
883
- clearTimeout(this.rootWaitTimer);
884
- this.rootWaitTimer = void 0;
885
- }
886
- this.resolveRootWait?.();
887
- this.resolveRootWait = void 0;
888
- }
889
- waitForFirstRead() {
890
- this.refresh();
891
- if (this.rootWaitOver || this.disabled() || !this.holdingForFirstRead()) return;
892
- if (this.rootWait === void 0) {
893
- this.rootWait = new Promise((resolve) => {
894
- this.resolveRootWait = resolve;
895
- });
896
- this.rootWaitTimer = setTimeout(() => this.endRootWait(), SIMULATION_PLAN_READ_TIMEOUT_MS);
897
- }
898
- return this.rootWait;
899
- }
900
- holdingForFirstRead() {
901
- return this.contentOffByKey === void 0 && !this.firstReadOver && !this.stopped;
902
- }
903
- unavailableNow() {
904
- return !this.disabled() && this.contentOffByKey === void 0 && this.firstReadOver;
905
- }
906
- firstLoad() {
907
- if (this.contentOffByKey !== void 0 || this.stopped || this.disabled()) return;
908
- return this.loaded;
909
- }
910
- send(payload, traceFunctionKey, submit, drop) {
911
- this.refresh();
912
- if (this.disabled() || traceFunctionKey === void 0 || spanNameOf(payload) === void 0 || recordedByFramework(payload)) {
913
- submit(payload);
914
- return;
915
- }
916
- const entry = {
917
- payload,
918
- traceFunctionKey,
919
- submit,
920
- drop
921
- };
922
- if (this.holdingForFirstRead()) {
923
- this.hold(entry);
924
- return;
925
- }
926
- this.submitEntry(entry);
927
- }
928
- sendTrace(payload, submit) {
929
- this.refresh();
930
- if (this.disabled() || !this.holdingForFirstRead() || !this.holdsSpanOfTrace(traceIdOf(payload))) {
931
- submit(payload);
932
- return;
933
- }
934
- this.hold({
935
- payload,
936
- traceFunctionKey: void 0,
937
- submit
938
- });
939
- }
940
- holdsSpanOfTrace(traceId) {
941
- if (traceId === void 0) return false;
942
- return this.held.some((entry) => entry.traceFunctionKey !== void 0 && traceIdOf(entry.payload) === traceId);
943
- }
944
- hold(entry) {
945
- this.held.push(entry);
946
- let overflowed = false;
947
- while (this.held.length > SIMULATION_PLAN_MAX_HELD) {
948
- const oldest = this.held.shift();
949
- this.submitEntry(oldest);
950
- overflowed = true;
951
- }
952
- if (overflowed) require_autoTrace.warnOnce("sim-plan-held-overflow", `more than ${SIMULATION_PLAN_MAX_HELD} records were waiting for the sim plan, so the oldest were sent without their inputs and outputs.`);
953
- }
954
- payloadToSend(entry) {
955
- if (entry.traceFunctionKey === void 0 || declaredInCode(entry.payload)) return entry.payload;
956
- if (this.contentOffByKey !== void 0) return this.apply(entry.payload, entry.traceFunctionKey);
957
- if (recordedByFramework(entry.payload) || isTraceRootSpan(entry.payload)) return entry.payload;
958
- return stripContent(entry.payload);
959
- }
960
- submitEntry(entry) {
961
- if (entry.traceFunctionKey !== void 0 && this.skipsSpan(entry.payload, entry.traceFunctionKey)) {
962
- entry.drop?.();
963
- return;
964
- }
965
- try {
966
- entry.submit(this.payloadToSend(entry));
967
- } catch (error) {
968
- entry.drop?.();
969
- require_autoTrace.warnOnce("sim-plan-held-span-dropped", `a span held for the sim plan was dropped when released: ${error instanceof Error ? error.message : String(error)}`);
970
- }
971
- }
972
- releaseHeld() {
973
- const held = this.held;
974
- this.held = [];
975
- for (const entry of held) this.submitEntry(entry);
976
- }
977
- releaseHeldWithoutPlan() {
978
- if (this.held.length === 0) return;
979
- if (this.contentOffByKey === void 0) require_autoTrace.warnOnce("sim-plan-not-loaded-at-release", `${this.held.length} record(s) were sent without their inputs and outputs because the sim plan had not loaded`);
980
- this.releaseHeld();
981
- }
982
- async release(timeoutMs) {
983
- this.refresh();
984
- if (this.held.length > 0) await this.waitForFirstReadEnd(timeoutMs);
985
- this.releaseHeldWithoutPlan();
986
- }
987
- waitForFirstReadEnd(timeoutMs) {
988
- if (this.firstReadOver) return Promise.resolve();
989
- return new Promise((resolve) => {
990
- const timer = setTimeout(resolve, Math.max(timeoutMs, 0));
991
- this.firstReadEnded.then(() => {
992
- clearTimeout(timer);
993
- resolve();
994
- });
995
- });
996
- }
997
- stop() {
998
- if (this.stopped) return;
999
- this.releaseHeldWithoutPlan();
1000
- this.stopped = true;
1001
- this.endFirstRead();
1002
- }
1003
- contentOff(traceFunctionKey, spanName) {
1004
- return this.contentOffByKey?.get(traceFunctionKey)?.has(spanName) === true;
1005
- }
1006
- contentOffNow(traceFunctionKey, spanName) {
1007
- return !this.stopped && !this.disabled() && this.contentOff(traceFunctionKey, spanName);
1008
- }
1009
- skipsSpan(payload, traceFunctionKey) {
1010
- const name = spanNameOf(payload);
1011
- return name !== void 0 && this.contentOff(traceFunctionKey, name) && !isTraceRootSpan(payload) && !declaredInCode(payload) && spanInstrumentationOf(payload) !== void 0 && !recordedByFramework(payload) && !recordedError(payload);
1012
- }
1013
- apply(payload, traceFunctionKey) {
1014
- if (recordedByFramework(payload) || declaredInCode(payload)) return payload;
1015
- const name = spanNameOf(payload);
1016
- if (name === void 0 || !this.contentOff(traceFunctionKey, name)) return payload;
1017
- return stripContent(payload);
1018
- }
1019
- };
1020
- const activeRecords = /* @__PURE__ */ new Map();
1021
- const completedRecords = /* @__PURE__ */ new Map();
1022
- function findRecord(traceId) {
1023
- return activeRecords.get(traceId) ?? completedRecords.get(traceId);
1024
- }
1025
- function recordCallerTraceMetadata(traceId, metadata) {
1026
- if (typeof traceId !== "string" || traceId === "") return;
1027
- if (typeof metadata !== "object" || metadata === null) return;
1028
- if (Object.keys(metadata).length === 0) return;
1029
- const existing = findRecord(traceId);
1030
- if (existing) {
1031
- Object.assign(existing.caller, metadata);
1032
- return;
1033
- }
1034
- activeRecords.set(traceId, {
1035
- caller: { ...metadata },
1036
- derived: {},
1037
- warnedKeys: /* @__PURE__ */ new Set()
1038
- });
1039
- }
1040
- function callerTraceMetadata(traceId) {
1041
- const record = findRecord(traceId);
1042
- if (!record || Object.keys(record.caller).length === 0) return;
1043
- return { ...record.caller };
1044
- }
1045
- function retireTraceMetadata(traceId) {
1046
- const record = activeRecords.get(traceId);
1047
- if (!record) return;
1048
- activeRecords.delete(traceId);
1049
- completedRecords.set(traceId, record);
1050
- while (completedRecords.size > 128) {
1051
- const oldest = completedRecords.keys().next();
1052
- if (oldest.done) return;
1053
- completedRecords.delete(oldest.value);
1054
- }
1055
- }
1056
- function warnAboutShadowedKeys(traceId, record) {
1057
- const shadowed = Object.keys(record.derived).filter((key) => key in record.caller && record.caller[key] !== record.derived[key] && !record.warnedKeys.has(key)).sort();
1058
- if (shadowed.length === 0) return;
1059
- for (const key of shadowed) record.warnedKeys.add(key);
1060
- require_autoTrace.warn(`trace metadata key(s) ${shadowed.join(", ")} on trace ${traceId} were set both by the caller and by an integration's own trace export; the caller's value is the one kept on the trace.`);
1061
- }
1062
- function mergeCallerMetadataIntoTracePayload(payload) {
1063
- const externalTrace = payload.externalTrace;
1064
- if (typeof externalTrace !== "object" || externalTrace === null) return payload;
1065
- const external = externalTrace;
1066
- const traceId = typeof payload.id === "string" && payload.id !== "" ? payload.id : external.id;
1067
- if (typeof traceId !== "string" || traceId === "") return payload;
1068
- const record = findRecord(traceId);
1069
- if (!record || Object.keys(record.caller).length === 0) return payload;
1070
- const exported = external.metadata;
1071
- if (typeof exported === "object" && exported !== null) Object.assign(record.derived, exported);
1072
- warnAboutShadowedKeys(traceId, record);
1073
- return {
1074
- ...payload,
1075
- externalTrace: {
1076
- ...external,
1077
- metadata: {
1078
- ...record.derived,
1079
- ...record.caller
1080
- }
1081
- }
1082
- };
1083
- }
1084
- //#endregion
1085
- //#region src/transportTypes.ts
1086
- var DeliveryError = class extends Error {
1087
- constructor(message, options = {}) {
1088
- super(message);
1089
- this.name = "DeliveryError";
1090
- this.retryable = options.retryable ?? false;
1091
- this.oversized = options.oversized ?? false;
1092
- this.retryAfterMs = options.retryAfterMs;
1093
- }
1094
- };
1095
- //#endregion
1096
- //#region src/unrefTimer.ts
1097
- function unrefTimer(timer) {
1098
- const handle = timer;
1099
- if (typeof handle.unref === "function") handle.unref();
1100
- }
1101
- //#endregion
1102
- //#region src/otel.ts
1103
- const OPERATION_ATTRIBUTE = "bitfab.operation";
1104
- const PAYLOAD_ATTRIBUTE = "bitfab.payload";
1105
- const MAX_EXPORT_REQUEST_BYTES = 3e6;
1106
- const MAX_DECOMPRESSED_REQUEST_BYTES = 8e6;
1107
- const MAX_REQUEST_BYTES_ENV = "BITFAB_OTEL_MAX_REQUEST_BYTES";
1108
- const EXPORT_CONCURRENCY_ENV = "BITFAB_OTEL_EXPORT_CONCURRENCY";
1109
- const MAX_QUEUE_SIZE = 16384;
1110
- const DIRECT_MAX_EXPORT_BATCH_SIZE = 512;
1111
- const DIRECT_MAX_REQUEST_BATCH_SIZE = 256;
1112
- const DEFAULT_EXPORT_CONCURRENCY = 32;
1113
- const MAX_EXPORT_CONCURRENCY = 64;
1114
- const SCHEDULE_DELAY_MILLIS = 5e3;
1115
- const EXPORT_TIMEOUT_MILLIS = 3e4;
1116
- const RETRY_BASE_DELAY_MILLIS = 100;
1117
- const RETRY_BACKOFF_CEILING_MILLIS = 5e3;
1118
- const MAX_SEND_ATTEMPTS = 3;
1119
- const DEFAULT_LIFECYCLE_TIMEOUT_MS$1 = 3e4;
1120
- const liveTransports = /* @__PURE__ */ new Set();
1121
- const carrierRefs = /* @__PURE__ */ new WeakMap();
1122
- function readBoundedIntEnv(name, max, fallback, warnKey) {
1123
- const raw = readEnv$1(name);
1124
- if (raw === void 0) return fallback;
1125
- const value = Number(raw);
1126
- if (Number.isInteger(value) && value > 0 && value <= max) return value;
1127
- require_autoTrace.warnOnce(warnKey, `${name} must be a positive integer no greater than ${max}; using ${fallback}`);
1128
- return fallback;
1129
- }
1130
- function logError(message, error) {
1131
- try {
1132
- if (error === void 0) console.error(`[bitfab] ${message}`);
1133
- else console.error(`[bitfab] ${message}`, error);
1134
- } catch {}
1135
- }
1136
- function otlpValue(value) {
1137
- if (typeof value === "boolean") return { boolValue: value };
1138
- if (typeof value === "number") return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };
1139
- if (typeof value === "string") return { stringValue: value };
1140
- if (Array.isArray(value)) return { arrayValue: { values: value.map(otlpValue) } };
1141
- return { stringValue: String(value) };
1142
- }
1143
- function otlpAttributes(attributes) {
1144
- if (!attributes) return [];
1145
- return Object.entries(attributes).filter(([, value]) => value !== void 0).map(([key, value]) => ({
1146
- key,
1147
- value: otlpValue(value)
1148
- }));
1149
- }
1150
- function hrTimeToNanoString(time) {
1151
- if (!time) return "0";
1152
- return `${time[0]}${String(time[1]).padStart(9, "0")}`;
1153
- }
1154
- function spanToOtlp(span) {
1155
- const spanContext = span.spanContext();
1156
- const result = {
1157
- traceId: spanContext.traceId,
1158
- spanId: spanContext.spanId,
1159
- name: span.name,
1160
- kind: span.kind + 1,
1161
- startTimeUnixNano: hrTimeToNanoString(span.startTime),
1162
- endTimeUnixNano: hrTimeToNanoString(span.endTime),
1163
- attributes: otlpAttributes(span.attributes),
1164
- droppedAttributesCount: span.droppedAttributesCount,
1165
- droppedEventsCount: span.droppedEventsCount,
1166
- droppedLinksCount: span.droppedLinksCount,
1167
- status: {
1168
- code: span.status.code,
1169
- ...span.status.message ? { message: span.status.message } : {}
1170
- },
1171
- flags: spanContext.traceFlags
1172
- };
1173
- const parentSpanId = span.parentSpanContext?.spanId;
1174
- if (parentSpanId) result.parentSpanId = parentSpanId;
1175
- if (spanContext.traceState) result.traceState = spanContext.traceState.serialize();
1176
- return result;
1177
- }
1178
- const SPAN_SEPARATOR_BYTES = 1;
1179
- function encodeSpan(span) {
1180
- const json = JSON.stringify(spanToOtlp(span));
1181
- return {
1182
- json,
1183
- size: byteLength(json),
1184
- ref: carrierRefs.get(span)
1185
- };
1186
- }
1187
- function trimEncodedSpan(span) {
1188
- try {
1189
- const carrier = JSON.parse(span.json);
1190
- const attribute = carrier.attributes?.find((entry) => entry.key === PAYLOAD_ATTRIBUTE);
1191
- const payloadBody = attribute?.value?.stringValue;
1192
- if (!attribute?.value || payloadBody === void 0) return;
1193
- const payload = JSON.parse(payloadBody);
1194
- attribute.value.stringValue = serializePayloadBody(payload, MAX_SPAN_CARRIER_BYTES).body;
1195
- const json = JSON.stringify(carrier);
1196
- return {
1197
- json,
1198
- size: byteLength(json)
1199
- };
1200
- } catch {
1201
- return;
1202
- }
1203
- }
1204
- async function prepareRequest(body) {
1205
- const prepared = encodeRequestBody(body);
1206
- return prepared instanceof Promise ? await prepared : prepared;
1207
- }
1208
- function requestEnvelope(first) {
1209
- const scope = first.instrumentationScope;
1210
- const head = `{"resourceSpans":[{"resource":${JSON.stringify({ attributes: otlpAttributes(first.resource.attributes) })},"scopeSpans":[{"scope":${JSON.stringify({
1211
- name: scope.name,
1212
- version: scope.version ?? ""
1213
- })},"spans":[`;
1214
- const tail = "]}]}]}";
1215
- return {
1216
- head,
1217
- tail,
1218
- size: byteLength(head) + byteLength(tail)
1219
- };
1220
- }
1221
- function encodeRequest(envelope, spans) {
1222
- return envelope.head + spans.map((span) => span.json).join(",") + envelope.tail;
1223
- }
1224
- function delay(ms) {
1225
- return new Promise((resolve) => {
1226
- unrefTimer(setTimeout(resolve, ms));
1227
- });
1228
- }
1229
- async function withDeadline(work, timeoutMs) {
1230
- let timer;
1231
- try {
1232
- return await Promise.race([work, new Promise((resolve) => {
1233
- timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
1234
- unrefTimer(timer);
1235
- })]);
1236
- } finally {
1237
- if (timer) clearTimeout(timer);
1238
- }
1239
- }
1240
- async function mapWithConcurrency$1(items, limit, task) {
1241
- const results = new Array(items.length);
1242
- let next = 0;
1243
- const workers = Array.from({ length: Math.min(Math.max(limit, 1), items.length) }, async () => {
1244
- while (next < items.length) {
1245
- const index = next;
1246
- next += 1;
1247
- results[index] = await task(items[index]);
1248
- }
1249
- });
1250
- await Promise.all(workers);
1251
- return results;
1252
- }
1253
- function isRetryable(error) {
1254
- return error instanceof DeliveryError && error.retryable;
1255
- }
1256
- function isOversized(error) {
1257
- return error instanceof DeliveryError && error.oversized;
1258
- }
1259
- function retryWaitMillis(error, attempt, remainingMillis) {
1260
- const requested = error instanceof DeliveryError ? error.retryAfterMs : void 0;
1261
- const affordable = remainingMillis / 2;
1262
- if (requested !== void 0) return requested < affordable ? requested : null;
1263
- const backoff = Math.min(RETRY_BASE_DELAY_MILLIS * 2 ** attempt, RETRY_BACKOFF_CEILING_MILLIS);
1264
- const jittered = backoff / 2 + Math.random() * (backoff / 2);
1265
- return jittered < affordable ? jittered : null;
1266
- }
1267
- var BitfabSpanExporter = class {
1268
- constructor(directSender, maxRequestBytes, maxRequestBatchSize, exportConcurrency, onDelivered, exportTimeoutMillis = EXPORT_TIMEOUT_MILLIS) {
1269
- this.directSender = directSender;
1270
- this.maxRequestBytes = maxRequestBytes;
1271
- this.maxRequestBatchSize = maxRequestBatchSize;
1272
- this.exportConcurrency = exportConcurrency;
1273
- this.onDelivered = onDelivered;
1274
- this.exportTimeoutMillis = exportTimeoutMillis;
1275
- this.throttledUntil = 0;
1276
- }
1277
- export(spans, resultCallback) {
1278
- this.exportAsync(spans).then((succeeded) => {
1279
- resultCallback({ code: succeeded ? _opentelemetry_core.ExportResultCode.SUCCESS : _opentelemetry_core.ExportResultCode.FAILED });
1280
- }, (error) => {
1281
- resultCallback({
1282
- code: _opentelemetry_core.ExportResultCode.FAILED,
1283
- error
1284
- });
1285
- });
1286
- }
1287
- async exportAsync(spans) {
1288
- if (spans.length === 0) return true;
1289
- let encoded;
1290
- let envelope;
1291
- try {
1292
- encoded = spans.map(encodeSpan);
1293
- envelope = requestEnvelope(spans[0]);
1294
- } catch (error) {
1295
- logError("failed to encode an OpenTelemetry span batch", error);
1296
- return false;
1297
- }
1298
- return (await mapWithConcurrency$1(this.buildRequestBatches(envelope, encoded), this.exportConcurrency, (batch) => this.send(envelope, batch))).every(Boolean);
1299
- }
1300
- buildRequestBatches(envelope, spans) {
1301
- const batches = [];
1302
- let current = [];
1303
- let size = envelope.size;
1304
- for (const span of spans) {
1305
- const addition = span.size + (current.length > 0 ? SPAN_SEPARATOR_BYTES : 0);
1306
- if (current.length > 0 && (current.length >= this.maxRequestBatchSize || size + addition > this.maxRequestBytes)) {
1307
- batches.push({
1308
- spans: current,
1309
- size
1310
- });
1311
- current = [];
1312
- size = envelope.size;
1313
- }
1314
- current.push(span);
1315
- size += span.size + (current.length > 1 ? SPAN_SEPARATOR_BYTES : 0);
1316
- }
1317
- if (current.length > 0) batches.push({
1318
- spans: current,
1319
- size
1320
- });
1321
- return batches;
1322
- }
1323
- async send(envelope, batch) {
1324
- try {
1325
- let requestSpans = batch.spans;
1326
- let requestRawBytes = batch.size;
1327
- let alreadyTrimmed = false;
1328
- while (true) {
1329
- if (requestRawBytes <= MAX_DECOMPRESSED_REQUEST_BYTES) {
1330
- const prepared = await prepareRequest(encodeRequest(envelope, requestSpans));
1331
- if (prepared.wireBytes <= this.maxRequestBytes) {
1332
- await this.sendWithRetries(prepared);
1333
- this.reportDelivered(batch.spans);
1334
- return true;
1335
- }
1336
- }
1337
- if (batch.spans.length !== 1) {
1338
- logError("an OpenTelemetry span batch exceeded the configured request-size target and could not be exported");
1339
- return false;
1340
- }
1341
- if (alreadyTrimmed) {
1342
- logError("a single OpenTelemetry span exceeded the configured request-size target after trimming");
1343
- return false;
1344
- }
1345
- const trimmed = trimEncodedSpan(batch.spans[0]);
1346
- if (!trimmed) {
1347
- logError("a single OpenTelemetry span exceeded the configured request-size target and could not be trimmed");
1348
- return false;
1349
- }
1350
- requestSpans = [trimmed];
1351
- requestRawBytes = envelope.size + trimmed.size;
1352
- alreadyTrimmed = true;
1353
- }
1354
- } catch (error) {
1355
- if (isOversized(error)) {
1356
- logError(batch.spans.length === 1 ? "a single OpenTelemetry span exceeded the ingestion request limit and could not be exported" : "an OpenTelemetry span batch exceeded the ingestion request limit and could not be exported");
1357
- return false;
1358
- }
1359
- logError("failed to export an OpenTelemetry span batch", error);
1360
- return false;
1361
- }
1362
- }
1363
- recordThrottle(error) {
1364
- const requested = error instanceof DeliveryError ? error.retryAfterMs : void 0;
1365
- if (requested !== void 0) this.throttledUntil = Math.max(this.throttledUntil, Date.now() + requested);
1366
- }
1367
- async awaitThrottle(deadline) {
1368
- const remaining = this.throttledUntil - Date.now();
1369
- if (remaining <= 0) return;
1370
- if (remaining >= (deadline - Date.now()) / 2) throw new DeliveryError(`OTLP ingestion is throttled for another ${remaining}ms, longer than the export budget`);
1371
- await delay(remaining);
1372
- }
1373
- async sendWithRetries(request) {
1374
- const deadline = Date.now() + this.exportTimeoutMillis;
1375
- for (let attempt = 0; attempt < MAX_SEND_ATTEMPTS; attempt += 1) try {
1376
- await this.awaitThrottle(deadline);
1377
- await this.directSender(request, Math.max(0, deadline - Date.now()));
1378
- return;
1379
- } catch (error) {
1380
- if (isOversized(error)) throw error;
1381
- this.recordThrottle(error);
1382
- if (attempt === 2 || !isRetryable(error)) throw error;
1383
- const wait = retryWaitMillis(error, attempt, deadline - Date.now());
1384
- if (wait === null) throw error;
1385
- await delay(wait);
1386
- }
1387
- }
1388
- reportDelivered(spans) {
1389
- if (this.onDelivered === void 0) return;
1390
- const refs = spans.map((span) => span.ref).filter((ref) => ref !== void 0);
1391
- if (refs.length === 0) return;
1392
- try {
1393
- this.onDelivered(refs);
1394
- } catch (error) {
1395
- logError("a delivery listener threw", error);
1396
- }
1397
- }
1398
- async shutdown() {}
1399
- async forceFlush() {}
1400
- };
1401
- var DeliveryTrackingExporter = class {
1402
- constructor(exporter) {
1403
- this.exporter = exporter;
1404
- this.failedExports = 0;
1405
- }
1406
- export(spans, resultCallback) {
1407
- try {
1408
- this.exporter.export(spans, (result) => {
1409
- if (result.code !== _opentelemetry_core.ExportResultCode.SUCCESS) this.failedExports += 1;
1410
- resultCallback(result);
1411
- });
1412
- } catch (error) {
1413
- this.failedExports += 1;
1414
- resultCallback({
1415
- code: _opentelemetry_core.ExportResultCode.FAILED,
1416
- error
1417
- });
1418
- }
1419
- }
1420
- takeFailedExports() {
1421
- const failed = this.failedExports;
1422
- this.failedExports = 0;
1423
- return failed;
1424
- }
1425
- shutdown() {
1426
- return this.exporter.shutdown();
1427
- }
1428
- forceFlush() {
1429
- return this.exporter.forceFlush?.() ?? Promise.resolve();
1
+ const require_bamlPeer = require("./bamlPeer-BUoZgNxZ.cjs");
2
+ const require_http = require("./http-Cy8I9KDT.cjs");
3
+ const require_autoTrace = require("./autoTrace-CQw0qMBt.cjs");
4
+ let superjson = require("superjson");
5
+ superjson = require_bamlPeer.__toESM(superjson, 1);
6
+ //#region src/categories.ts
7
+ const CATEGORIES_PATH = "/api/sdk/categories";
8
+ var CategoriesClient = class {
9
+ constructor(httpClient) {
10
+ this.httpClient = httpClient;
1430
11
  }
1431
- };
1432
- var OtelBatchTransport = class {
1433
- constructor(options) {
1434
- this.closed = false;
1435
- const maxRequestBytes = options.maxRequestBytes ?? MAX_EXPORT_REQUEST_BYTES;
1436
- const maxRequestBatchSize = options.maxRequestBatchSize ?? DIRECT_MAX_REQUEST_BATCH_SIZE;
1437
- if (maxRequestBatchSize <= 0) throw new BitfabError("maxRequestBatchSize must be a positive integer");
1438
- this.deliveryTracker = new DeliveryTrackingExporter(new BitfabSpanExporter(options.directSender, maxRequestBytes, maxRequestBatchSize, options.exportConcurrency ?? DEFAULT_EXPORT_CONCURRENCY, options.onDelivered, options.exportTimeoutMillis ?? EXPORT_TIMEOUT_MILLIS));
1439
- this.processor = new _opentelemetry_sdk_trace_base.BatchSpanProcessor(this.deliveryTracker, {
1440
- maxQueueSize: options.maxQueueSize ?? MAX_QUEUE_SIZE,
1441
- maxExportBatchSize: options.maxExportBatchSize ?? DIRECT_MAX_EXPORT_BATCH_SIZE,
1442
- scheduledDelayMillis: SCHEDULE_DELAY_MILLIS,
1443
- exportTimeoutMillis: options.exportTimeoutMillis ?? EXPORT_TIMEOUT_MILLIS
1444
- });
1445
- this.provider = new _opentelemetry_sdk_trace_base.BasicTracerProvider({
1446
- sampler: new _opentelemetry_sdk_trace_base.AlwaysOnSampler(),
1447
- resource: (0, _opentelemetry_resources.resourceFromAttributes)({
1448
- "service.name": "bitfab-typescript-sdk",
1449
- "service.version": __version__
1450
- }),
1451
- spanLimits: {
1452
- attributeCountLimit: 2,
1453
- attributeValueLengthLimit: Number.POSITIVE_INFINITY
1454
- },
1455
- spanProcessors: [this.processor]
1456
- });
1457
- this.tracer = this.provider.getTracer("bitfab", __version__);
1458
- liveTransports.add(this);
12
+ async save(params) {
13
+ return (await this.httpClient.request(CATEGORIES_PATH, params)).category;
1459
14
  }
1460
- submit(operation, payload, meta = {}) {
1461
- if (this.closed) {
1462
- require_autoTrace.warnOnce("otel-submit-after-shutdown", "OpenTelemetry transport is shut down; dropping spans");
1463
- return;
1464
- }
1465
- try {
1466
- const { body, dropped } = serializePayloadBody(payload, MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES);
1467
- if (dropped.length > 0) require_autoTrace.warnOnce("otel-carrier-payload-stubbed", `a span payload held non-serializable value(s) (${[...new Set(dropped)].join(", ")}); they were stubbed so the span still ships, but the trace may be incomplete or not replayable.`);
1468
- const span = this.tracer.startSpan(meta.name ?? `bitfab.${operation}`, {
1469
- attributes: {
1470
- [OPERATION_ATTRIBUTE]: operation,
1471
- [PAYLOAD_ATTRIBUTE]: body
1472
- },
1473
- startTime: meta.startTime
1474
- });
1475
- if (meta.ref !== void 0) carrierRefs.set(span, meta.ref);
1476
- if (meta.errored === true) span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
1477
- endSpan(span, meta.endTime);
1478
- } catch (error) {
1479
- logError("failed to queue an OpenTelemetry span", error);
1480
- }
15
+ async get(id) {
16
+ return (await this.httpClient.get(`${CATEGORIES_PATH}/${encodeURIComponent(id)}`)).category;
1481
17
  }
1482
- async flush(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS$1) {
1483
- const pending = (this.pendingFlush ?? Promise.resolve(true)).then(() => this.forceFlushOnce());
1484
- this.pendingFlush = pending.catch(() => false);
1485
- return withDeadline(pending, timeoutMs);
18
+ async list() {
19
+ return (await this.httpClient.get(CATEGORIES_PATH)).categories;
1486
20
  }
1487
- async forceFlushOnce() {
1488
- try {
1489
- await this.processor.forceFlush();
1490
- } catch (error) {
1491
- logError("failed to flush OpenTelemetry spans", error);
1492
- this.deliveryTracker.takeFailedExports();
1493
- return false;
1494
- }
1495
- return this.deliveryTracker.takeFailedExports() === 0;
1496
- }
1497
- async shutdown(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS$1) {
1498
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1499
- this.closed = true;
1500
- const flushed = await this.flush(Math.max(0, deadline - Date.now()));
1501
- liveTransports.delete(this);
1502
- const shutdownCompleted = await withDeadline(this.provider.shutdown().then(() => true).catch((error) => {
1503
- logError("failed to shut down the OpenTelemetry transport", error);
1504
- return false;
1505
- }), Math.max(0, deadline - Date.now()));
1506
- return flushed && shutdownCompleted;
21
+ async delete(id) {
22
+ return (await this.httpClient.request(`${CATEGORIES_PATH}/${encodeURIComponent(id)}`, {}, { method: "DELETE" })).category;
1507
23
  }
1508
24
  };
1509
- function endSpan(span, endTime) {
1510
- span.end(endTime);
1511
- }
1512
- function createOtelTransport(options) {
1513
- return new OtelBatchTransport({
1514
- ...options,
1515
- exportConcurrency: readBoundedIntEnv(EXPORT_CONCURRENCY_ENV, MAX_EXPORT_CONCURRENCY, DEFAULT_EXPORT_CONCURRENCY, "otel-export-concurrency-invalid"),
1516
- maxRequestBytes: readBoundedIntEnv(MAX_REQUEST_BYTES_ENV, MAX_EXPORT_REQUEST_BYTES, MAX_EXPORT_REQUEST_BYTES, "otel-max-request-bytes-invalid")
1517
- });
1518
- }
1519
- async function forEachLiveTransport(timeoutMs, run) {
1520
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1521
- let succeeded = true;
1522
- for (const transport of [...liveTransports]) succeeded = await run(transport, Math.max(0, deadline - Date.now())) && succeeded;
1523
- return succeeded;
1524
- }
1525
- function flushOtelTransports(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS$1) {
1526
- return forEachLiveTransport(timeoutMs, (transport, remaining) => transport.flush(remaining));
1527
- }
1528
- function shutdownOtelTransports(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS$1) {
1529
- return forEachLiveTransport(timeoutMs, (transport, remaining) => transport.shutdown(remaining));
1530
- }
1531
- //#endregion
1532
- //#region src/transport.ts
1533
- function createTraceTransport(options) {
1534
- return createOtelTransport(options);
1535
- }
1536
- function flushTraceTransports(timeoutMs) {
1537
- return flushOtelTransports(timeoutMs);
1538
- }
1539
- function shutdownTraceTransports(timeoutMs) {
1540
- return shutdownOtelTransports(timeoutMs);
1541
- }
25
+ const AssertionCategoriesClient = CategoriesClient;
1542
26
  //#endregion
1543
- //#region src/http.ts
1544
- var http_exports = /* @__PURE__ */ __exportAll({
1545
- BitfabError: () => BitfabError,
1546
- HttpClient: () => HttpClient,
1547
- SPAN_TYPES: () => SPAN_TYPES,
1548
- awaitOnExit: () => awaitOnExit,
1549
- awaitPendingRequests: () => awaitPendingRequests,
1550
- experimentIdWireFields: () => experimentIdWireFields,
1551
- flushTraces: () => flushTraces,
1552
- parseRetryAfterMs: () => parseRetryAfterMs,
1553
- serializePayloadBody: () => serializePayloadBody
1554
- });
1555
- const REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS = 3e5;
1556
- const REPLAY_COMPLETE_REQUEST_TIMEOUT_MS = 12e4;
1557
- const REPLAY_INTERRUPT_REQUEST_TIMEOUT_MS = 5e3;
1558
- const REPLAY_HEARTBEAT_REQUEST_TIMEOUT_MS = 5e3;
1559
- const OTLP_TRACES_ENDPOINT = "/api/sdk/otel/v1/traces";
1560
- const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
1561
- 429,
1562
- 500,
1563
- 502,
1564
- 503,
1565
- 504
1566
- ]);
1567
- const EXIT_FLUSH_TIMEOUT_MS = 5e3;
1568
- const DEFAULT_LIFECYCLE_TIMEOUT_MS = 3e4;
1569
- const pendingTracePromises = /* @__PURE__ */ new Set();
1570
- const liveHttpClients = /* @__PURE__ */ new Set();
1571
- async function releaseHeldExternalSpans(timeoutMs) {
1572
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1573
- let released = true;
1574
- for (const client of [...liveHttpClients]) released = await client.releaseHeldExternalSpans?.(Math.max(0, deadline - Date.now())) !== false && released;
1575
- return released;
1576
- }
1577
- function stopSimulationPlans() {
1578
- for (const client of [...liveHttpClients]) client.stopSimulationPlan?.();
1579
- }
1580
- function awaitOnExit(promise) {
1581
- pendingTracePromises.add(promise);
1582
- promise.finally(() => {
1583
- pendingTracePromises.delete(promise);
1584
- }).catch(() => {});
1585
- return promise;
1586
- }
1587
- async function flushTraces(timeoutMs = 5e3) {
1588
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1589
- const released = await releaseHeldExternalSpans(planWaitSliceMs(timeoutMs));
1590
- const requestsFlushed = await awaitPendingRequests(Math.max(0, deadline - Date.now()));
1591
- const releasedAfterDeferred = await releaseHeldExternalSpans(0);
1592
- const transportsFlushed = await flushTraceTransports(Math.max(0, deadline - Date.now()));
1593
- return released && releasedAfterDeferred && requestsFlushed && transportsFlushed;
1594
- }
1595
- async function awaitPendingRequests(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS) {
1596
- await replayContextReady.catch(() => {});
1597
- return waitForPromises(Array.from(pendingTracePromises), timeoutMs);
1598
- }
1599
- async function waitForPromises(promises, timeoutMs) {
1600
- if (promises.length === 0) return true;
1601
- let timer;
1602
- try {
1603
- return await Promise.race([Promise.allSettled(promises).then(() => true), new Promise((resolve) => {
1604
- timer = setTimeout(() => resolve(false), timeoutMs);
1605
- unrefTimer(timer);
1606
- })]);
1607
- } finally {
1608
- if (timer) clearTimeout(timer);
1609
- }
1610
- }
1611
- if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
1612
- let isFlushing = false;
1613
- process.on("beforeExit", () => {
1614
- if (isFlushing) return;
1615
- isFlushing = true;
1616
- const planWaitMs = SIMULATION_PLAN_READ_TIMEOUT_MS;
1617
- const stopFlushing = () => {
1618
- isFlushing = false;
1619
- };
1620
- const deadline = setTimeout(stopFlushing, 1e4);
1621
- unrefTimer(deadline);
1622
- releaseHeldExternalSpans(planWaitMs).catch(() => {}).then(() => {
1623
- stopSimulationPlans();
1624
- }).then(() => Promise.allSettled([...Array.from(pendingTracePromises).map((p) => p.catch(() => {})), shutdownTraceTransports(EXIT_FLUSH_TIMEOUT_MS).catch(() => false)])).then(() => {
1625
- clearTimeout(deadline);
1626
- stopFlushing();
1627
- });
1628
- });
1629
- }
1630
- const SPAN_TYPES = [
1631
- "llm",
1632
- "agent",
1633
- "function",
1634
- "guardrail",
1635
- "handoff",
1636
- "custom"
1637
- ];
1638
- function readHeader(response, name) {
1639
- try {
1640
- return response.headers?.get(name) ?? null;
1641
- } catch {
1642
- return null;
1643
- }
1644
- }
1645
- function parseRetryAfterMs(header) {
1646
- const value = header?.trim();
1647
- if (!value) return;
1648
- const seconds = Number(value);
1649
- if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1e3 : void 0;
1650
- const at = Date.parse(value);
1651
- if (Number.isNaN(at)) return;
1652
- return Math.max(0, at - Date.now());
1653
- }
1654
- function carrierMeta(operation, payload, ref) {
1655
- return {
1656
- ref,
1657
- name: carrierName(operation, payload),
1658
- startTime: payloadTimestamp(payload, "started_at"),
1659
- endTime: payloadTimestamp(payload, "ended_at"),
1660
- errored: payloadHasError(payload)
1661
- };
1662
- }
1663
- function carrierName(operation, payload) {
1664
- if (operation === "external_span") {
1665
- const spanData = asPayloadRecord(asPayloadRecord(payload.rawSpan)?.span_data);
1666
- if (typeof spanData?.name === "string") return spanData.name;
1667
- }
1668
- if (typeof payload.traceFunctionKey === "string") return payload.traceFunctionKey;
1669
- return `bitfab.${operation}`;
1670
- }
1671
- function payloadTimestamp(payload, field) {
1672
- const rawSpan = asPayloadRecord(payload.rawSpan);
1673
- const rawTrace = asPayloadRecord(payload.externalTrace) ?? asPayloadRecord(payload.rawTrace);
1674
- const raw = rawSpan?.[field] ?? rawTrace?.[field];
1675
- if (typeof raw !== "string") return;
1676
- const parsed = Date.parse(raw);
1677
- return Number.isNaN(parsed) ? void 0 : parsed;
1678
- }
1679
- function payloadHasError(payload) {
1680
- if (asPayloadRecord(asPayloadRecord(payload.rawSpan)?.span_data)?.error != null) return true;
1681
- const errors = payload.errors;
1682
- return Array.isArray(errors) ? errors.length > 0 : Boolean(errors);
1683
- }
1684
- function asPayloadRecord(value) {
1685
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1686
- }
1687
- function carrierRef(payload) {
1688
- const traceId = sourceTraceIdOf(payload);
1689
- if (traceId === void 0) return;
1690
- const rawSpan = payload.rawSpan;
1691
- if (rawSpan === void 0) return { traceId };
1692
- const spanId = rawSpan?.id;
1693
- return {
1694
- traceId,
1695
- spanId: typeof spanId === "string" ? spanId : `submission-${++carrierSeq}`
1696
- };
1697
- }
1698
- function sourceTraceIdOf(payload) {
1699
- if (typeof payload.sourceTraceId === "string") return payload.sourceTraceId;
1700
- const id = (payload.externalTrace ?? payload.rawTrace)?.id;
1701
- return typeof id === "string" ? id : void 0;
1702
- }
1703
- let carrierSeq = 0;
1704
- function describeError(error) {
1705
- return error instanceof Error ? error.message : String(error);
1706
- }
1707
- function warnDroppedExternalSpan(error) {
1708
- require_autoTrace.warnOnce("external-span-dropped", `a span was dropped because the send step failed: ${describeError(error)}`);
1709
- }
1710
- function warnDroppedExternalTrace(error) {
1711
- require_autoTrace.warnOnce("external-trace-dropped", `a trace was dropped because the send step failed: ${describeError(error)}`);
1712
- }
1713
- var HttpClient = class {
1714
- constructor(config) {
1715
- this.traceDeliveries = /* @__PURE__ */ new Map();
1716
- this.deferredWork = /* @__PURE__ */ new Set();
1717
- this.traceCompletion = new TraceCompletion();
1718
- this.closed = false;
1719
- this.apiKey = config.apiKey;
1720
- this.serviceUrl = config.serviceUrl;
1721
- this.timeout = config.timeout ?? 12e4;
1722
- liveHttpClients.add(this);
1723
- }
1724
- resolveApiKey() {
1725
- return typeof this.apiKey === "function" ? this.apiKey() : this.apiKey;
1726
- }
1727
- hasApiKey() {
1728
- try {
1729
- const apiKey = this.resolveApiKey();
1730
- return apiKey !== void 0 && apiKey.trim() !== "";
1731
- } catch {
1732
- return false;
1733
- }
1734
- }
1735
- getTraceTransport() {
1736
- if (this.closed) {
1737
- require_autoTrace.warnOnce("http-client-closed", "the Bitfab client is closed; dropping spans");
1738
- return;
1739
- }
1740
- if (!this.traceTransport) this.traceTransport = createTraceTransport({
1741
- directSender: (request, timeoutMs) => this.deliverCarriers(request, timeoutMs),
1742
- onDelivered: (refs) => this.recordDeliveredCarriers(refs)
1743
- });
1744
- return this.traceTransport;
1745
- }
1746
- async deliverCarriers(request, timeoutMs) {
1747
- let response;
1748
- try {
1749
- response = await this.sendPrepared(OTLP_TRACES_ENDPOINT, request, { timeout: timeoutMs });
1750
- } catch (error) {
1751
- const status = error instanceof BitfabError ? error.status : void 0;
1752
- if (status === void 0) throw new DeliveryError(`OTLP ingestion failed: ${String(error)}`, { retryable: true });
1753
- throw new DeliveryError(`OTLP ingestion failed with HTTP ${status}`, {
1754
- retryable: RETRYABLE_STATUSES.has(status),
1755
- oversized: status === 413,
1756
- ...error instanceof BitfabError && error.retryAfterMs !== void 0 ? { retryAfterMs: error.retryAfterMs } : {}
1757
- });
1758
- }
1759
- const serverTraceIds = asPayloadRecord(response?.traceIds);
1760
- if (serverTraceIds !== void 0) this.recordServerTraceIds(serverTraceIds);
1761
- const partialSuccess = asPayloadRecord(response?.partialSuccess);
1762
- const rejected = partialSuccess?.rejectedSpans;
1763
- if (rejected !== void 0 && rejected !== "0" && rejected !== 0) throw new DeliveryError(`OTLP ingestion rejected ${rejected} span(s): ${partialSuccess?.errorMessage ?? "no reason provided"}`);
1764
- }
1765
- trackTraceDeliveries(traceIds) {
1766
- for (const traceId of traceIds) if (!this.traceDeliveries.has(traceId)) this.traceDeliveries.set(traceId, {
1767
- submittedSpanIds: /* @__PURE__ */ new Set(),
1768
- ackedSpanIds: /* @__PURE__ */ new Set(),
1769
- closed: false,
1770
- closingAcked: false
1771
- });
1772
- }
1773
- peekServerTraceId(traceId) {
1774
- return this.traceDeliveries.get(traceId)?.serverTraceId;
1775
- }
1776
- hasClosedDeliveries(traceIds) {
1777
- return traceIds.some((traceId) => this.traceDeliveries.get(traceId)?.closed);
1778
- }
1779
- takeTraceDeliveries(traceIds) {
1780
- const reports = {};
1781
- for (const traceId of traceIds) {
1782
- const delivery = this.traceDeliveries.get(traceId);
1783
- if (delivery === void 0) continue;
1784
- this.traceDeliveries.delete(traceId);
1785
- reports[traceId] = {
1786
- spanCount: delivery.submittedSpanIds.size,
1787
- closed: delivery.closed,
1788
- delivered: delivery.closingAcked && [...delivery.submittedSpanIds].every((spanId) => delivery.ackedSpanIds.has(spanId)),
1789
- serverTraceId: delivery.serverTraceId
1790
- };
1791
- }
1792
- return reports;
1793
- }
1794
- recordedMeta(operation, payload, ref) {
1795
- this.recordSubmittedCarrier(ref);
1796
- return carrierMeta(operation, payload, ref);
1797
- }
1798
- recordSubmittedCarrier(ref) {
1799
- if (ref === void 0) return;
1800
- const delivery = this.traceDeliveries.get(ref.traceId);
1801
- if (delivery === void 0) return;
1802
- if (ref.spanId === void 0) delivery.closed = true;
1803
- else delivery.submittedSpanIds.add(ref.spanId);
1804
- }
1805
- recordServerTraceIds(map) {
1806
- for (const [sourceTraceId, serverTraceId] of Object.entries(map)) {
1807
- if (typeof serverTraceId !== "string") continue;
1808
- const delivery = this.traceDeliveries.get(sourceTraceId);
1809
- if (delivery === void 0) continue;
1810
- delivery.serverTraceId = serverTraceId;
1811
- }
1812
- }
1813
- recordDeliveredCarriers(refs) {
1814
- for (const ref of refs) {
1815
- const delivery = this.traceDeliveries.get(ref.traceId);
1816
- if (delivery === void 0) continue;
1817
- if (ref.spanId === void 0) delivery.closingAcked = true;
1818
- else delivery.ackedSpanIds.add(ref.spanId);
1819
- }
1820
- }
1821
- trackDeferred(promise) {
1822
- this.deferredWork.add(promise);
1823
- promise.finally(() => this.deferredWork.delete(promise)).catch(() => {});
1824
- return awaitOnExit(promise);
1825
- }
1826
- async settleDeferredWork(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS) {
1827
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1828
- const released = await this.releaseHeldExternalSpans?.(planWaitSliceMs(timeoutMs));
1829
- await replayContextReady.catch(() => {});
1830
- const settled = await waitForPromises(Array.from(this.deferredWork), Math.max(0, deadline - Date.now()));
1831
- const releasedAfterDeferred = await this.releaseHeldExternalSpans?.(0);
1832
- return released !== false && releasedAfterDeferred !== false && settled;
1833
- }
1834
- async waitForPendingRequests(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS) {
1835
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1836
- const settled = await this.settleDeferredWork(Math.max(0, deadline - Date.now()));
1837
- const flushed = await this.traceTransport?.flush(Math.max(0, deadline - Date.now())) ?? true;
1838
- return settled && flushed;
1839
- }
1840
- close(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS) {
1841
- if (this.closing) return this.closing;
1842
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1843
- this.closing = (async () => {
1844
- liveHttpClients.delete(this);
1845
- const settled = await this.settleDeferredWork(Math.max(0, deadline - Date.now()));
1846
- this.stopSimulationPlan?.();
1847
- this.closed = true;
1848
- this.externalSpanTransform = void 0;
1849
- this.externalTraceTransform = void 0;
1850
- this.releaseHeldExternalSpans = void 0;
1851
- this.stopSimulationPlan = void 0;
1852
- const transport = this.traceTransport;
1853
- this.traceTransport = void 0;
1854
- const shutdownOk = await transport?.shutdown(Math.max(0, deadline - Date.now())) ?? true;
1855
- return settled && shutdownOk;
1856
- })();
1857
- return this.closing;
1858
- }
1859
- async request(endpoint, payload, options) {
1860
- const { body, dropped } = serializePayloadBody(payload);
1861
- if (dropped.length > 0) try {
1862
- console.warn(`Bitfab: request body to ${endpoint} held ${dropped.length} non-serializable value(s) (${[...new Set(dropped)].join(", ")}); they were stubbed so the span still sends, but the trace may be incomplete or not replayable. Capture a JSON-safe projection of this input to make it replayable.`);
1863
- } catch {}
1864
- return this.sendEncoded(endpoint, body, options);
1865
- }
1866
- async sendEncoded(endpoint, body, options) {
1867
- const prepared = encodeRequestBody(body);
1868
- const encoded = prepared instanceof Promise ? await prepared : prepared;
1869
- return this.sendPrepared(endpoint, encoded, options);
1870
- }
1871
- async sendPrepared(endpoint, encoded, options) {
1872
- const url = `${this.serviceUrl}${endpoint}`;
1873
- const timeout = options?.timeout ?? this.timeout;
1874
- const method = options?.method ?? "POST";
1875
- const controller = new AbortController();
1876
- const timeoutId = setTimeout(() => controller.abort(), timeout);
1877
- const headers = {
1878
- "Content-Type": "application/json",
1879
- Authorization: `Bearer ${this.resolveApiKey() ?? ""}`
1880
- };
1881
- if (encoded.contentEncoding) headers["Content-Encoding"] = encoded.contentEncoding;
1882
- try {
1883
- const response = await fetch(url, {
1884
- method,
1885
- headers,
1886
- body: encoded.body,
1887
- signal: controller.signal
1888
- });
1889
- if (!response.ok) {
1890
- const errorText = await response.text();
1891
- throw new BitfabError(`HTTP ${response.status}: ${errorText.slice(0, 500)}`, void 0, response.status, parseRetryAfterMs(readHeader(response, "retry-after")));
1892
- }
1893
- const result = await response.json();
1894
- if (result.error) {
1895
- if (result.url) throw new BitfabError(`${result.error} Configure it at: ${this.serviceUrl}${result.url}`, result.url);
1896
- throw new BitfabError(result.error);
1897
- }
1898
- return result;
1899
- } catch (error) {
1900
- if (error instanceof BitfabError) throw error;
1901
- if (error instanceof Error) {
1902
- if (error.name === "AbortError") throw new BitfabError(`Request timed out after ${timeout}ms`);
1903
- throw new BitfabError(error.message);
1904
- }
1905
- throw new BitfabError("Unknown error occurred");
1906
- } finally {
1907
- clearTimeout(timeoutId);
1908
- }
1909
- }
1910
- async lookupFunction(name) {
1911
- return this.request("/api/sdk/functions/lookup", { name });
1912
- }
1913
- async getSimulationPlan() {
1914
- if (!this.hasApiKey()) throw new BitfabError(NO_API_KEY_FOR_SIMULATION_PLAN);
1915
- return this.get("/api/sdk/sim-plan", SIMULATION_PLAN_READ_TIMEOUT_MS);
1916
- }
1917
- async getTraceSpan(traceId, lookup) {
1918
- const searchParams = new URLSearchParams();
1919
- if (lookup.id !== void 0) searchParams.set("id", lookup.id);
1920
- else {
1921
- if (lookup.name !== void 0) searchParams.set("name", lookup.name);
1922
- if (lookup.type !== void 0) searchParams.set("type", lookup.type);
1923
- searchParams.set("occurrence", String(lookup.occurrence ?? "last"));
1924
- }
1925
- const endpoint = `/api/sdk/traces/${encodeURIComponent(traceId)}/span?${searchParams.toString()}`;
1926
- return (await this.get(endpoint)).span;
1927
- }
1928
- async getSpan(spanId) {
1929
- return (await this.get(`/api/sdk/spans/${encodeURIComponent(spanId)}`)).span;
1930
- }
1931
- async get(endpoint, timeoutMs, extraHeaders) {
1932
- const url = `${this.serviceUrl}${endpoint}`;
1933
- const timeout = timeoutMs ?? this.timeout;
1934
- const controller = new AbortController();
1935
- const timeoutId = setTimeout(() => controller.abort(), timeout);
1936
- try {
1937
- const response = await fetch(url, {
1938
- method: "GET",
1939
- headers: {
1940
- Authorization: `Bearer ${this.resolveApiKey() ?? ""}`,
1941
- ...extraHeaders
1942
- },
1943
- signal: controller.signal
1944
- });
1945
- if (!response.ok) {
1946
- const errorText = await response.text();
1947
- throw new BitfabError(`HTTP ${response.status}: ${errorText.slice(0, 500)}`, void 0, response.status, parseRetryAfterMs(readHeader(response, "retry-after")));
1948
- }
1949
- return await response.json();
1950
- } catch (error) {
1951
- if (error instanceof BitfabError) throw error;
1952
- if (error instanceof Error) {
1953
- if (error.name === "AbortError") throw new BitfabError(`Request timed out after ${timeout}ms`);
1954
- throw new BitfabError(error.message);
1955
- }
1956
- throw new BitfabError("Unknown error occurred");
1957
- } finally {
1958
- clearTimeout(timeoutId);
1959
- }
1960
- }
1961
- sendInternalTrace(functionId, payload) {
1962
- const body = {
1963
- ...payload,
1964
- functionId,
1965
- sdkPackage: __packageName__,
1966
- sdkVersion: __version__
1967
- };
1968
- this.getTraceTransport()?.submit("internal_trace", body, carrierMeta("internal_trace", body, void 0));
1969
- }
1970
- sendExternalSpan(payload) {
1971
- const ref = carrierRef(payload);
1972
- if (ref?.spanId !== void 0) this.traceCompletion.record(ref.traceId, ref.spanId);
1973
- const drop = () => {
1974
- if (ref?.spanId !== void 0) this.traceCompletion.abort(ref.traceId, ref.spanId);
1975
- };
1976
- const gate = this.externalSpanTransform;
1977
- if (gate === void 0) {
1978
- this.submitExternalSpan(payload);
1979
- return;
1980
- }
1981
- try {
1982
- gate(payload, (ready) => this.submitExternalSpan(ready), drop);
1983
- } catch (error) {
1984
- drop();
1985
- warnDroppedExternalSpan(error);
1986
- }
1987
- }
1988
- submitExternalSpan(payload) {
1989
- const body = {
1990
- ...payload,
1991
- sdkVersion: __version__
1992
- };
1993
- delete body[ROOT_TRACE_FUNCTION_KEY_FIELD];
1994
- delete body[DECLARED_NODE_FIELD];
1995
- this.getTraceTransport()?.submit("external_span", body, this.recordedMeta("external_span", payload, carrierRef(payload)));
1996
- }
1997
- sendExternalTrace(rawPayload) {
1998
- const payload = mergeCallerMetadataIntoTracePayload(rawPayload);
1999
- const traceId = sourceTraceIdOf(payload);
2000
- if (payload.completed === true && traceId !== void 0) {
2001
- this.traceCompletion.close(traceId, (expectedSpanCount) => this.sendCountedExternalTrace({
2002
- ...payload,
2003
- expectedSpanCount
2004
- }), payload.dropped === true);
2005
- return;
2006
- }
2007
- if (traceId !== void 0) this.traceCompletion.open(traceId);
2008
- this.sendCountedExternalTrace(payload);
2009
- }
2010
- sendCountedExternalTrace(payload) {
2011
- try {
2012
- const gate = this.externalTraceTransform;
2013
- if (gate === void 0) this.submitExternalTrace(payload);
2014
- else gate(payload, (ready) => this.submitExternalTrace(ready));
2015
- } catch (error) {
2016
- warnDroppedExternalTrace(error);
2017
- }
2018
- }
2019
- submitExternalTrace(payload) {
2020
- this.getTraceTransport()?.submit("external_trace", {
2021
- ...payload,
2022
- sdkPackage: __packageName__,
2023
- sdkVersion: __version__
2024
- }, this.recordedMeta("external_trace", payload, payload.completed === true ? carrierRef(payload) : void 0));
2025
- }
2026
- async patchTrace(traceId, payload) {
2027
- const endpoint = `/api/sdk/traces/${encodeURIComponent(traceId)}`;
2028
- await this.request(endpoint, payload, { method: "PATCH" });
2029
- }
2030
- async startReplay(traceFunctionKey, limit, traceIds, name, codeChangeDescription, codeChangeFiles, includeDbBranchLease, experimentGroupId, datasetIds, graderIds, dbBranchSettings, attempts, includeOriginalMetadata, onlyWithAssertions, skipAssertionJudging, experimentalSelectiveReplay, notes, metadata, dryRun, experimentGroupName, invocation) {
2031
- const payload = { traceFunctionKey };
2032
- if (experimentalSelectiveReplay !== void 0) payload.experimentalSelectiveReplay = experimentalSelectiveReplay;
2033
- if (limit !== void 0) payload.limit = limit;
2034
- if (traceIds) payload.traceIds = traceIds;
2035
- if (name !== void 0) payload.name = name;
2036
- if (notes !== void 0) payload.notes = notes;
2037
- if (metadata !== void 0) payload.metadata = metadata;
2038
- if (codeChangeDescription !== void 0) payload.codeChangeDescription = codeChangeDescription;
2039
- if (codeChangeFiles !== void 0) payload.codeChangeFiles = codeChangeFiles;
2040
- if (includeDbBranchLease) {
2041
- payload.includeDbBranchLease = true;
2042
- payload.lazyDbBranchLease = true;
2043
- }
2044
- if (experimentGroupId !== void 0) payload.experimentGroupId = experimentGroupId;
2045
- if (experimentGroupName !== void 0) payload.experimentGroupName = experimentGroupName;
2046
- if (datasetIds !== void 0) {
2047
- if (datasetIds.length === 1) payload.datasetId = datasetIds[0];
2048
- else payload.datasetIds = datasetIds;
2049
- }
2050
- if (graderIds !== void 0) payload.graderIds = graderIds;
2051
- if (dbBranchSettings !== void 0) payload.dbBranchSettings = dbBranchSettings;
2052
- if (attempts !== void 0 && attempts > 1) payload.attempts = attempts;
2053
- if (includeOriginalMetadata) payload.includeOriginalMetadata = true;
2054
- if (onlyWithAssertions) payload.onlyWithAssertions = true;
2055
- if (skipAssertionJudging !== true) payload.judgeAssertions = true;
2056
- if (dryRun) payload.dryRun = true;
2057
- if (invocation !== void 0) payload.invocation = invocation;
2058
- const git = await resolvedGitState();
2059
- if (git && !isEmptyGitState(git)) payload.git = git;
2060
- const timeout = includeDbBranchLease ? REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS : 3e4;
2061
- const response = await this.request("/api/sdk/replay/start", payload, { timeout });
2062
- const { testRunId, testRunUrl, ...rest } = response;
2063
- const experimentId = response.experimentId ?? testRunId;
2064
- const experimentUrl = response.experimentUrl ?? testRunUrl;
2065
- if (dryRun && response.experimentId === null) return {
2066
- ...rest,
2067
- experimentId: null,
2068
- experimentUrl: null
2069
- };
2070
- if (experimentId === void 0 || experimentId === null || experimentUrl === void 0 || experimentUrl === null) throw new BitfabError("Replay start response is missing the experiment ID or URL.");
2071
- return {
2072
- ...rest,
2073
- experimentId,
2074
- experimentUrl
2075
- };
2076
- }
2077
- async resumeReplay(experimentId, traceFunctionKey, codeChangeFiles, force) {
2078
- const payload = {
2079
- experimentId,
2080
- traceFunctionKey,
2081
- lazyDbBranchLease: true
2082
- };
2083
- if (force === true) payload.force = true;
2084
- if (codeChangeFiles !== void 0) payload.codeChangeFiles = codeChangeFiles;
2085
- const git = await resolvedGitState();
2086
- if (git && !isEmptyGitState(git)) payload.git = git;
2087
- const response = await this.request("/api/sdk/replay/resume", payload, { timeout: REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS });
2088
- const { testRunId, testRunUrl, ...rest } = response;
2089
- const resumedExperimentId = response.experimentId ?? testRunId;
2090
- const experimentUrl = response.experimentUrl ?? testRunUrl;
2091
- if (resumedExperimentId === void 0 || experimentUrl === void 0) throw new BitfabError("Replay resume response is missing the experiment ID or URL.");
2092
- return {
2093
- ...rest,
2094
- experimentId: resumedExperimentId,
2095
- experimentUrl,
2096
- work: rest.work ?? [],
2097
- finished: rest.finished ?? [],
2098
- skippedOriginalTraceIds: rest.skippedOriginalTraceIds ?? [],
2099
- includeDbBranchLease: rest.includeDbBranchLease ?? false,
2100
- dbBranchSettings: rest.dbBranchSettings ?? null
2101
- };
2102
- }
2103
- async getExternalSpan(spanId, options) {
2104
- const query = options?.view === "replay" ? "?view=replay" : "";
2105
- const url = `${this.serviceUrl}/api/sdk/externalSpans/${spanId}${query}`;
2106
- const controller = new AbortController();
2107
- const timeoutId = setTimeout(() => controller.abort(), 3e4);
2108
- try {
2109
- const response = await fetch(url, {
2110
- method: "GET",
2111
- headers: { Authorization: `Bearer ${this.resolveApiKey() ?? ""}` },
2112
- signal: controller.signal
2113
- });
2114
- if (!response.ok) {
2115
- const errorText = await response.text();
2116
- throw new BitfabError(`HTTP ${response.status}: ${errorText.slice(0, 500)}`);
2117
- }
2118
- return await response.json();
2119
- } catch (error) {
2120
- if (error instanceof BitfabError) throw error;
2121
- if (error instanceof Error) {
2122
- if (error.name === "AbortError") throw new BitfabError("Request timed out after 30000ms");
2123
- throw new BitfabError(error.message);
2124
- }
2125
- throw new BitfabError("Unknown error occurred");
2126
- } finally {
2127
- clearTimeout(timeoutId);
2128
- }
2129
- }
2130
- async getSpanTree(externalSpanId, options) {
2131
- const searchParams = new URLSearchParams();
2132
- if (options?.includeOutputs === false) searchParams.set("includeOutputs", "false");
2133
- if (options?.includeRootOutput === false) searchParams.set("includeRootOutput", "false");
2134
- const encodedQuery = searchParams.toString();
2135
- const query = encodedQuery ? `?${encodedQuery}` : "";
2136
- const url = `${this.serviceUrl}/api/sdk/replay/spanTree/${externalSpanId}${query}`;
2137
- const controller = new AbortController();
2138
- const timeoutId = setTimeout(() => controller.abort(), 3e4);
2139
- try {
2140
- const response = await fetch(url, {
2141
- method: "GET",
2142
- headers: { Authorization: `Bearer ${this.resolveApiKey() ?? ""}` },
2143
- signal: controller.signal
2144
- });
2145
- if (!response.ok) {
2146
- const errorText = await response.text();
2147
- throw new BitfabError(`HTTP ${response.status}: ${errorText.slice(0, 500)}`);
2148
- }
2149
- return await response.json();
2150
- } catch (error) {
2151
- if (error instanceof BitfabError) throw error;
2152
- if (error instanceof Error) {
2153
- if (error.name === "AbortError") throw new BitfabError("Request timed out after 30000ms");
2154
- throw new BitfabError(error.message);
2155
- }
2156
- throw new BitfabError("Unknown error occurred");
2157
- } finally {
2158
- clearTimeout(timeoutId);
2159
- }
2160
- }
2161
- async getReplayStatus(experimentId, expectedSpanCounts) {
2162
- return this.request("/api/sdk/replay/status", {
2163
- ...experimentIdWireFields(experimentId),
2164
- expectedSpanCounts
2165
- }, { timeout: 3e4 });
2166
- }
2167
- async completeReplay(experimentId) {
2168
- return this.request("/api/sdk/replay/complete", experimentIdWireFields(experimentId), { timeout: REPLAY_COMPLETE_REQUEST_TIMEOUT_MS });
2169
- }
2170
- async interruptReplay(experimentId) {
2171
- try {
2172
- await this.request("/api/sdk/replay/interrupt", experimentIdWireFields(experimentId), { timeout: REPLAY_INTERRUPT_REQUEST_TIMEOUT_MS });
2173
- return true;
2174
- } catch {
2175
- return false;
2176
- }
2177
- }
2178
- async heartbeatReplay(experimentId) {
2179
- try {
2180
- await this.request("/api/sdk/replay/heartbeat", experimentIdWireFields(experimentId), { timeout: REPLAY_HEARTBEAT_REQUEST_TIMEOUT_MS });
2181
- } catch {}
2182
- }
2183
- async getReseedSource(traceId) {
2184
- return this.get(`/api/sdk/traces/${encodeURIComponent(traceId)}/reseedSource`);
2185
- }
2186
- async reseedTrace(traceId, runTraceId) {
2187
- return this.request(`/api/sdk/traces/${encodeURIComponent(traceId)}/reseed`, { runTraceId }, { timeout: 3e4 });
2188
- }
2189
- async resolveDbBranchLease(experimentId, traceId, dbBranchSettings, attempt) {
2190
- return this.request("/api/sdk/replay/resolveDbBranchLease", {
2191
- ...experimentIdWireFields(experimentId),
2192
- traceId,
2193
- dbBranchSettings,
2194
- ...attempt !== void 0 && attempt > 0 ? { attempt } : {}
2195
- }, { timeout: REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS });
2196
- }
2197
- async releaseDbBranchLease(neonBranchId) {
2198
- await this.request("/api/sdk/replay/releaseDbBranchLease", { neonBranchId }, { timeout: 3e4 });
2199
- }
2200
- };
2201
- function experimentIdWireFields(experimentId) {
2202
- return {
2203
- experimentId,
2204
- testRunId: experimentId
2205
- };
2206
- }
27
+ //#region src/constants.ts
28
+ const DEFAULT_SERVICE_URL = "https://bitfab.ai";
2207
29
  //#endregion
2208
30
  //#region src/serialize.ts
2209
- const MAX_SERIALIZED_BYTES = MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES;
2210
- const MAX_FRAMEWORK_SERIALIZED_BYTES = MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES;
31
+ const MAX_SERIALIZED_BYTES = require_http.MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES;
32
+ const MAX_FRAMEWORK_SERIALIZED_BYTES = require_http.MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES;
2211
33
  function describeValue(value) {
2212
34
  try {
2213
35
  const ctorName = value?.constructor?.name;
@@ -2441,7 +263,7 @@ var BitfabClaudeAgentHandler = class {
2441
263
  this.activeSubagentSpans = /* @__PURE__ */ new Map();
2442
264
  this.hasRootInput = false;
2443
265
  this.ownsHttpClient = config._httpClient === void 0;
2444
- this.httpClient = config._httpClient ?? new HttpClient({
266
+ this.httpClient = config._httpClient ?? new require_http.HttpClient({
2445
267
  apiKey: config.apiKey,
2446
268
  serviceUrl: config.serviceUrl ?? "https://bitfab.ai",
2447
269
  timeout: config.timeout ?? 1e4
@@ -2534,7 +356,7 @@ var BitfabClaudeAgentHandler = class {
2534
356
  trace_id: spanInfo.traceId,
2535
357
  started_at: spanInfo.startedAt,
2536
358
  ended_at: spanInfo.endedAt ?? nowIso$1(),
2537
- span_origin: makeSpanOrigin("claude-agent-sdk"),
359
+ span_origin: require_http.makeSpanOrigin("claude-agent-sdk"),
2538
360
  span_data: spanData
2539
361
  };
2540
362
  if (spanInfo.parentId !== null) rawSpan.parent_id = spanInfo.parentId;
@@ -2796,25 +618,11 @@ var BitfabClaudeAgentHandler = class {
2796
618
  }
2797
619
  };
2798
620
  //#endregion
2799
- //#region src/optionalPeer.ts
2800
- function importOptionalPeer(specifierParts) {
2801
- return import(
2802
- /* webpackIgnore: true */
2803
- /* @vite-ignore */
2804
- specifierParts.join("/")
2805
- );
2806
- }
2807
- //#endregion
2808
621
  //#region src/baml.ts
2809
- let cachedBaml = null;
2810
622
  async function loadBaml() {
2811
- if (cachedBaml) return cachedBaml;
2812
- try {
2813
- cachedBaml = await importOptionalPeer(["@boundaryml", "baml"]);
2814
- return cachedBaml;
2815
- } catch {
2816
- throw new Error("@boundaryml/baml is required for Bitfab.call(). Install it with: npm install @boundaryml/baml");
2817
- }
623
+ const baml = await require_bamlPeer.loadBamlModule();
624
+ if (!baml) throw new Error("@boundaryml/baml is required for Bitfab.call(). Install it with: npm install @boundaryml/baml. If it is installed and your app is bundled (Next.js with Turbopack, for example), add `import \"@bitfab/sdk/baml\"` once in your server code.");
625
+ return baml;
2818
626
  }
2819
627
  function capitalize(str) {
2820
628
  return str.charAt(0).toUpperCase() + str.slice(1);
@@ -3012,10 +820,10 @@ async function runFunctionWithBaml(bamlSource, inputs, providers, envVars) {
3012
820
  //#region src/bitfabIds.ts
3013
821
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
3014
822
  function validateTraceId(traceId) {
3015
- if (typeof traceId !== "string" || !UUID_PATTERN.test(traceId)) throw new BitfabError("traceId must be a valid Bitfab trace ID");
823
+ if (typeof traceId !== "string" || !UUID_PATTERN.test(traceId)) throw new require_http.BitfabError("traceId must be a valid Bitfab trace ID");
3016
824
  }
3017
825
  function validateSpanId(id) {
3018
- if (typeof id !== "string" || !UUID_PATTERN.test(id)) throw new BitfabError("id must be a valid Bitfab span ID");
826
+ if (typeof id !== "string" || !UUID_PATTERN.test(id)) throw new require_http.BitfabError("id must be a valid Bitfab span ID");
3019
827
  }
3020
828
  const SURFACE_API = {
3021
829
  "opt-in": "withSpan()",
@@ -3031,7 +839,8 @@ function resolveSurface(requested, parentSurface) {
3031
839
  return requested;
3032
840
  }
3033
841
  function mixedTracingError(enteredApi, entered, enclosing, traceFunctionKey) {
3034
- return new MixedTracingError(`opt-in and opt-out tracing can't be mixed in one call stack: ${enteredApi} (${entered})${traceFunctionKey === void 0 ? "" : ` for "${traceFunctionKey}"`} was entered inside a ${SURFACE_API[enclosing]} call (${enclosing}). ${MIXED_SURFACE_REMEDY[entered]}`);
842
+ const subject = traceFunctionKey === void 0 ? "" : ` for "${traceFunctionKey}"`;
843
+ return new require_http.MixedTracingError(`opt-in and opt-out tracing can't be mixed in one call stack: ${enteredApi} (${entered})${subject} was entered inside a ${SURFACE_API[enclosing]} call (${enclosing}). ${MIXED_SURFACE_REMEDY[entered]}`);
3035
844
  }
3036
845
  function assertSurfacesCompatible(requested, resolved, parentSurface, traceFunctionKey) {
3037
846
  if (requested === "inherit" || requested === "neutral") return;
@@ -3169,7 +978,7 @@ function resolveCommitRefFromEnv(env) {
3169
978
  };
3170
979
  }
3171
980
  async function resolveCommitRefFromGit(cwd) {
3172
- const git = await gitRunner({
981
+ const git = await require_http.gitRunner({
3173
982
  timeoutMs: GIT_TIMEOUT_MS,
3174
983
  maxBuffer: GIT_MAX_BUFFER,
3175
984
  keepProcessAlive: false
@@ -3220,11 +1029,11 @@ let gitStarted = false;
3220
1029
  Promise.resolve();
3221
1030
  function startCommitRefResolution() {
3222
1031
  if (resolved || gitStarted) return;
3223
- if (read(readEnv$1, DISABLE_ENV) !== null) {
1032
+ if (read(require_http.readEnv, DISABLE_ENV) !== null) {
3224
1033
  resolved = true;
3225
1034
  return;
3226
1035
  }
3227
- const fromEnv = resolveCommitRefFromEnv(readEnv$1);
1036
+ const fromEnv = resolveCommitRefFromEnv(require_http.readEnv);
3228
1037
  if (fromEnv) {
3229
1038
  ref = fromEnv;
3230
1039
  resolved = true;
@@ -3312,7 +1121,7 @@ var DatasetsClient = class {
3312
1121
  }));
3313
1122
  }
3314
1123
  async update(datasetId, params) {
3315
- if (params.name === void 0 && params.description === void 0 && params.golden === void 0) throw new BitfabError("Provide name, description, and/or golden to update.");
1124
+ if (params.name === void 0 && params.description === void 0 && params.golden === void 0) throw new require_http.BitfabError("Provide name, description, and/or golden to update.");
3316
1125
  return normalizeDataset((await this.httpClient.request(datasetPath(datasetId), {
3317
1126
  ...params.name === void 0 ? {} : { name: params.name },
3318
1127
  ...params.description === void 0 ? {} : { description: params.description },
@@ -3382,7 +1191,7 @@ var DatasetsClient = class {
3382
1191
  //#region src/dbSnapshot.ts
3383
1192
  const SUPPORTED_PROVIDERS = ["neon"];
3384
1193
  function validateDbSnapshotConfig(config) {
3385
- if (!SUPPORTED_PROVIDERS.includes(config.provider)) throw new BitfabError(`dbSnapshot.provider "${config.provider}" is not supported. Supported providers: ${SUPPORTED_PROVIDERS.join(", ")}.`);
1194
+ if (!SUPPORTED_PROVIDERS.includes(config.provider)) throw new require_http.BitfabError(`dbSnapshot.provider "${config.provider}" is not supported. Supported providers: ${SUPPORTED_PROVIDERS.join(", ")}.`);
3386
1195
  }
3387
1196
  function buildSnapshotRef(config, sdkWallClockBeforeFn) {
3388
1197
  return {
@@ -3440,7 +1249,7 @@ var GradersClient = class {
3440
1249
  async getLabels(params) {
3441
1250
  const hasTraceIds = params.traceIds !== void 0 && params.traceIds.length > 0;
3442
1251
  const hasGraderId = params.graderId !== void 0;
3443
- if (!hasTraceIds && !hasGraderId) throw new BitfabError("Pass traceIds, graderId, or both: there is nothing to read otherwise.");
1252
+ if (!hasTraceIds && !hasGraderId) throw new require_http.BitfabError("Pass traceIds, graderId, or both: there is nothing to read otherwise.");
3444
1253
  const query = new URLSearchParams();
3445
1254
  if (params.traceIds !== void 0 && params.traceIds.length > 0) query.set("traceIds", params.traceIds.join(","));
3446
1255
  if (params.graderId !== void 0) query.set("graderId", params.graderId);
@@ -3461,11 +1270,17 @@ const LABELS_PATH = "/api/sdk/traces/labels";
3461
1270
  const HUMAN_LABELS_PATH = "/api/sdk/traces/labels/human";
3462
1271
  function assertEveryVerdictNamesAnAssertion(updates) {
3463
1272
  const unscoped = updates.filter((update) => !("archive" in update && update.archive === true) && (typeof update.assertionId !== "string" || update.assertionId === ""));
3464
- if (unscoped.length > 0) throw new BitfabError(`Agent verdicts must name an assertion: ${unscoped.map((update) => update.traceId ?? update.originalTraceId).join(", ")}. Pass the assertionId of the assertion each verdict scores to labels.save, saveAll, skip, and abstain. Only archive may omit it, to clear an old whole-trace verdict.`);
1273
+ if (unscoped.length > 0) {
1274
+ const targets = unscoped.map((update) => update.traceId ?? update.originalTraceId);
1275
+ throw new require_http.BitfabError(`Agent verdicts must name an assertion: ${targets.join(", ")}. Pass the assertionId of the assertion each verdict scores to labels.save, saveAll, skip, and abstain. Only archive may omit it, to clear an old whole-trace verdict.`);
1276
+ }
3465
1277
  }
3466
1278
  function assertEveryHumanVerdictNamesAnAssertion(updates) {
3467
1279
  const unscoped = updates.filter((update) => typeof update.assertionId !== "string" || update.assertionId === "");
3468
- if (unscoped.length > 0) throw new BitfabError(`Human verdicts must name an assertion: ${unscoped.map((update) => update.traceId).join(", ")}. Pass the assertionId of the assertion each verdict scores to labels.saveHuman and saveHumanAll.`);
1280
+ if (unscoped.length > 0) {
1281
+ const targets = unscoped.map((update) => update.traceId);
1282
+ throw new require_http.BitfabError(`Human verdicts must name an assertion: ${targets.join(", ")}. Pass the assertionId of the assertion each verdict scores to labels.saveHuman and saveHumanAll.`);
1283
+ }
3469
1284
  }
3470
1285
  function labelEvidencePath(traceId, assertionId) {
3471
1286
  return `/api/sdk/traces/${encodeURIComponent(traceId)}/assertions/${encodeURIComponent(assertionId)}/evidence`;
@@ -3482,7 +1297,7 @@ var LabelsClient = class {
3482
1297
  assertEveryVerdictNamesAnAssertion(updates);
3483
1298
  return (await this.httpClient.request(LABELS_PATH, {
3484
1299
  labels: updates,
3485
- ...experimentId === void 0 ? {} : experimentIdWireFields(experimentId)
1300
+ ...experimentId === void 0 ? {} : require_http.experimentIdWireFields(experimentId)
3486
1301
  })).labels;
3487
1302
  }
3488
1303
  async skip(target, experimentId) {
@@ -3702,7 +1517,7 @@ var BitfabLangGraphCallbackHandler = class {
3702
1517
  this.runToSpan = /* @__PURE__ */ new Map();
3703
1518
  this.invocations = /* @__PURE__ */ new Map();
3704
1519
  this.ownsHttpClient = config._httpClient === void 0;
3705
- this.httpClient = config._httpClient ?? new HttpClient({
1520
+ this.httpClient = config._httpClient ?? new require_http.HttpClient({
3706
1521
  apiKey: config.apiKey,
3707
1522
  serviceUrl: config.serviceUrl ?? "https://bitfab.ai",
3708
1523
  timeout: config.timeout ?? 1e4
@@ -3803,7 +1618,7 @@ var BitfabLangGraphCallbackHandler = class {
3803
1618
  trace_id: spanInfo.traceId,
3804
1619
  started_at: spanInfo.startedAt,
3805
1620
  ended_at: spanInfo.endedAt ?? nowIso(),
3806
- span_origin: makeSpanOrigin("langgraph"),
1621
+ span_origin: require_http.makeSpanOrigin("langgraph"),
3807
1622
  span_data: spanData
3808
1623
  };
3809
1624
  if (spanInfo.parentId !== null) rawSpan.parent_id = spanInfo.parentId;
@@ -4005,20 +1820,20 @@ function isEncodedToolResult(value) {
4005
1820
  }
4006
1821
  async function loadLangChainCore() {
4007
1822
  try {
4008
- return await importOptionalPeer([
1823
+ return await require_bamlPeer.importOptionalPeer([
4009
1824
  "@langchain",
4010
1825
  "core",
4011
1826
  "messages"
4012
1827
  ]);
4013
1828
  } catch {
4014
- throw new BitfabError("LangGraph tool replay requires @langchain/core. Install @langchain/langgraph before using getLangGraphIntegration().", "https://docs.bitfab.ai/frameworks/langgraph");
1829
+ throw new require_http.BitfabError("LangGraph tool replay requires @langchain/core. Install @langchain/langgraph before using getLangGraphIntegration().", "https://docs.bitfab.ai/frameworks/langgraph");
4015
1830
  }
4016
1831
  }
4017
1832
  async function loadLangGraph() {
4018
1833
  try {
4019
- return await importOptionalPeer(["@langchain", "langgraph"]);
1834
+ return await require_bamlPeer.importOptionalPeer(["@langchain", "langgraph"]);
4020
1835
  } catch {
4021
- throw new BitfabError("Replaying a LangGraph Command requires @langchain/langgraph.", "https://docs.bitfab.ai/frameworks/langgraph");
1836
+ throw new require_http.BitfabError("Replaying a LangGraph Command requires @langchain/langgraph.", "https://docs.bitfab.ai/frameworks/langgraph");
4022
1837
  }
4023
1838
  }
4024
1839
  async function reviveNested(value, toolCallId) {
@@ -4071,7 +1886,7 @@ var BitfabLangGraphIntegration = class {
4071
1886
  }
4072
1887
  wrapTool(tool) {
4073
1888
  const toolName = tool.name;
4074
- if (typeof toolName !== "string" || toolName.length === 0) throw new BitfabError("LangGraph replayable tools must have a name.", "https://docs.bitfab.ai/frameworks/langgraph");
1889
+ if (typeof toolName !== "string" || toolName.length === 0) throw new require_http.BitfabError("LangGraph replayable tools must have a name.", "https://docs.bitfab.ai/frameworks/langgraph");
4075
1890
  const mockToolsOnReplay = this.mockToolsOnReplay;
4076
1891
  const shouldMock = typeof mockToolsOnReplay === "boolean" ? mockToolsOnReplay : mockToolsOnReplay.includes(toolName);
4077
1892
  const originalInvoke = tool.invoke.bind(tool);
@@ -4096,7 +1911,7 @@ var BitfabLangGraphIntegration = class {
4096
1911
  } });
4097
1912
  }
4098
1913
  assertReplayToolResultExists(toolName, shouldMock) {
4099
- const replayContext = getReplayContext();
1914
+ const replayContext = require_http.getReplayContext();
4100
1915
  if (!replayContext?.mockTree) return;
4101
1916
  const counterKey = `${this.traceFunctionKey}:${toolName}`;
4102
1917
  const callIndex = replayContext.callCounters?.get(counterKey) ?? 0;
@@ -4108,7 +1923,7 @@ var BitfabLangGraphIntegration = class {
4108
1923
  originalSpanId: mockSpan?.sourceSpanId
4109
1924
  }));
4110
1925
  const expectsRecordedOutput = replayContext.mockStrategy === "all" || replayContext.mockStrategy === "marked" && shouldMock;
4111
- if (hasMatchingOverride !== true && expectsRecordedOutput && !mockSpan) throw new BitfabError(`No recorded LangGraph tool result for "${toolName}" at call ${callIndex + 1}; refusing to execute the live tool during replay.`, "https://docs.bitfab.ai/frameworks/langgraph");
1926
+ if (hasMatchingOverride !== true && expectsRecordedOutput && !mockSpan) throw new require_http.BitfabError(`No recorded LangGraph tool result for "${toolName}" at call ${callIndex + 1}; refusing to execute the live tool during replay.`, "https://docs.bitfab.ai/frameworks/langgraph");
4112
1927
  }
4113
1928
  wrapInvoke(fn) {
4114
1929
  return this.client.withSpan(this.traceFunctionKey, {
@@ -4150,7 +1965,7 @@ var BitfabOpenAIAgentHandler = class {
4150
1965
  this.getActiveSpanContext = config.getActiveSpanContext;
4151
1966
  }
4152
1967
  async wrapRun(agent, input, options) {
4153
- const { run } = await importOptionalPeer(["@openai", "agents"]);
1968
+ const { run } = await require_bamlPeer.importOptionalPeer(["@openai", "agents"]);
4154
1969
  if (this.getActiveSpanContext?.() != null) return run(agent, input, options);
4155
1970
  const isStreaming = options?.stream === true;
4156
1971
  const finalize = async (result) => {
@@ -4277,7 +2092,7 @@ async function captureCodeChangeFromGit(cwd, label) {
4277
2092
  } catch {
4278
2093
  return null;
4279
2094
  }
4280
- const git = await gitRunner({
2095
+ const git = await require_http.gitRunner({
4281
2096
  timeoutMs: 3e4,
4282
2097
  maxBuffer: 67108864,
4283
2098
  keepProcessAlive: true
@@ -4472,7 +2287,7 @@ function startReplayHeartbeat(send) {
4472
2287
  inFlight = void 0;
4473
2288
  });
4474
2289
  }, REPLAY_HEARTBEAT_INTERVAL_MS);
4475
- unrefTimer(timer);
2290
+ require_http.unrefTimer(timer);
4476
2291
  return { stop: async () => {
4477
2292
  stopped = true;
4478
2293
  clearInterval(timer);
@@ -4571,9 +2386,9 @@ const OPTION_FLAG_NAMES = {
4571
2386
  datasetIds: "dataset-ids"
4572
2387
  };
4573
2388
  function replayEnvironment() {
4574
- if (readEnv$1(REPLAY_EXECUTION_TARGET_ENV) === HOSTED_EXECUTION_TARGET) return "cloud_replay";
4575
- if (CI_TRUE_VALUES.has((readEnv$1(CI_ENV) ?? "").toLowerCase())) return "ci";
4576
- if (CI_PRESENCE_ENV_VARS.some((name) => (readEnv$1(name) ?? "") !== "")) return "ci";
2389
+ if (require_http.readEnv(REPLAY_EXECUTION_TARGET_ENV) === HOSTED_EXECUTION_TARGET) return "cloud_replay";
2390
+ if (CI_TRUE_VALUES.has((require_http.readEnv(CI_ENV) ?? "").toLowerCase())) return "ci";
2391
+ if (CI_PRESENCE_ENV_VARS.some((name) => (require_http.readEnv(name) ?? "") !== "")) return "ci";
4577
2392
  return "local";
4578
2393
  }
4579
2394
  function flagScalar(value) {
@@ -4612,7 +2427,7 @@ function buildReplayInvocation(entries = []) {
4612
2427
  flags: invocationFlags(entries),
4613
2428
  sdk: {
4614
2429
  language: "typescript",
4615
- version: __version__
2430
+ version: require_http.__version__
4616
2431
  },
4617
2432
  environment: replayEnvironment()
4618
2433
  };
@@ -4662,7 +2477,7 @@ function jsonFingerprint(value) {
4662
2477
  //#region src/selectiveReplayRuntime.ts
4663
2478
  function validateSelectiveReplayOptions(options) {
4664
2479
  const validNodes = (nodes) => Array.isArray(nodes) && nodes.length <= 100 && nodes.every((node) => typeof node?.traceFunctionKey === "string" && node.traceFunctionKey.length > 0 && node.traceFunctionKey.length <= 500 && typeof node.spanName === "string" && node.spanName.length > 0 && node.spanName.length <= 500);
4665
- if (!options || !validNodes(options.mustRun) || options.mustRun.length === 0 || Object.keys(options).some((key) => key !== "mustRun")) throw new BitfabError("experimentalSelectiveReplay accepts only 1–100 mustRun with traceFunctionKey and spanName. Declare replayReusable on eligible spans, not reusableNodes in the replay request.");
2480
+ if (!options || !validNodes(options.mustRun) || options.mustRun.length === 0 || Object.keys(options).some((key) => key !== "mustRun")) throw new require_http.BitfabError("experimentalSelectiveReplay accepts only 1–100 mustRun with traceFunctionKey and spanName. Declare replayReusable on eligible spans, not reusableNodes in the replay request.");
4666
2481
  }
4667
2482
  function policyKey(options) {
4668
2483
  return JSON.stringify(options.mustRun.map(replayNodeKey).sort());
@@ -4684,12 +2499,12 @@ var SelectiveReplayRuntime = class {
4684
2499
  this.observedNames = /* @__PURE__ */ new Map();
4685
2500
  this.unresolvedAssertions = [];
4686
2501
  validateSelectiveReplayOptions(options);
4687
- if (plan?.version !== 4 || !Array.isArray(plan.nodes) || plan.nodes.length === 0 || plan.nodes.length > 500 || !Array.isArray(plan.unresolvedMustRun) || !Array.isArray(plan.assertions) || !plan.options) throw new BitfabError("Server did not return a compatible selective replay plan. Update the server or disable experimentalSelectiveReplay.");
2502
+ if (plan?.version !== 4 || !Array.isArray(plan.nodes) || plan.nodes.length === 0 || plan.nodes.length > 500 || !Array.isArray(plan.unresolvedMustRun) || !Array.isArray(plan.assertions) || !plan.options) throw new require_http.BitfabError("Server did not return a compatible selective replay plan. Update the server or disable experimentalSelectiveReplay.");
4688
2503
  validateSelectiveReplayOptions(plan.options);
4689
- if (policyKey(plan.options) !== policyKey(options)) throw new BitfabError("Selective replay plan does not match the requested mustRun nodes.");
2504
+ if (policyKey(plan.options) !== policyKey(options)) throw new require_http.BitfabError("Selective replay plan does not match the requested mustRun nodes.");
4690
2505
  this.required = new Set(options.mustRun.map(replayNodeKey));
4691
2506
  for (const node of plan.nodes) {
4692
- if (typeof node.id !== "string" || this.nodes.has(node.id) || typeof node.traceFunctionKey !== "string" || typeof node.spanName !== "string" || typeof node.mustRun !== "boolean" || typeof node.reusable !== "boolean") throw new BitfabError("Invalid selective replay node.");
2507
+ if (typeof node.id !== "string" || this.nodes.has(node.id) || typeof node.traceFunctionKey !== "string" || typeof node.spanName !== "string" || typeof node.mustRun !== "boolean" || typeof node.reusable !== "boolean") throw new require_http.BitfabError("Invalid selective replay node.");
4693
2508
  this.nodes.set(node.id, node);
4694
2509
  if (node.recording !== void 0) this.recordings.set(node.id, {
4695
2510
  input: node.recording.kwargs === void 0 ? jsonFingerprint(node.recording.input) : void 0,
@@ -4702,16 +2517,16 @@ var SelectiveReplayRuntime = class {
4702
2517
  }
4703
2518
  }
4704
2519
  const root = this.nodes.get(plan.rootId);
4705
- if (!root || root.parentId !== null || !root.mustRun) throw new BitfabError("Selective replay requires a live recorded root.");
2520
+ if (!root || root.parentId !== null || !root.mustRun) throw new require_http.BitfabError("Selective replay requires a live recorded root.");
4706
2521
  const assertionIds = /* @__PURE__ */ new Set();
4707
2522
  let wholeTrace = false;
4708
2523
  for (const assertion of plan.assertions) {
4709
2524
  const target = assertion?.target;
4710
- if (typeof assertion?.id !== "string" || assertion.id.length === 0 || assertionIds.has(assertion.id) || target !== null && (typeof target !== "object" || target.kind !== "output" && target.kind !== "span")) throw new BitfabError("Invalid selective replay assertion requirements.");
2525
+ if (typeof assertion?.id !== "string" || assertion.id.length === 0 || assertionIds.has(assertion.id) || target !== null && (typeof target !== "object" || target.kind !== "output" && target.kind !== "span")) throw new require_http.BitfabError("Invalid selective replay assertion requirements.");
4711
2526
  assertionIds.add(assertion.id);
4712
2527
  if (target === null) wholeTrace = true;
4713
2528
  else if (target.kind === "span") {
4714
- if (typeof target.name !== "string" || target.name.length === 0 || target.occurrence !== void 0 && target.occurrence !== "first" && target.occurrence !== "last" && !(Number.isInteger(target.occurrence) && typeof target.occurrence === "number" && target.occurrence >= 0)) throw new BitfabError("Invalid selective replay assertion target.");
2529
+ if (typeof target.name !== "string" || target.name.length === 0 || target.occurrence !== void 0 && target.occurrence !== "first" && target.occurrence !== "last" && !(Number.isInteger(target.occurrence) && typeof target.occurrence === "number" && target.occurrence >= 0)) throw new require_http.BitfabError("Invalid selective replay assertion target.");
4715
2530
  this.assertionNames.add(target.name);
4716
2531
  if (plan.nodes.filter((node) => node.spanName === target.name).length <= (typeof target.occurrence === "number" ? target.occurrence : 0)) this.unresolvedAssertions.push(assertion.id);
4717
2532
  }
@@ -4719,7 +2534,7 @@ var SelectiveReplayRuntime = class {
4719
2534
  this.fullTraceForAssertions = wholeTrace || this.unresolvedAssertions.length > 0;
4720
2535
  const recordedKeys = new Set(plan.nodes.map(replayNodeKey));
4721
2536
  const unresolved = options.mustRun.filter((node) => !recordedKeys.has(replayNodeKey(node)));
4722
- if (JSON.stringify(unresolved.map(replayNodeKey).sort()) !== JSON.stringify(plan.unresolvedMustRun.map(replayNodeKey).sort())) throw new BitfabError("Selective replay plan has incomplete mustRun coverage.");
2537
+ if (JSON.stringify(unresolved.map(replayNodeKey).sort()) !== JSON.stringify(plan.unresolvedMustRun.map(replayNodeKey).sort())) throw new require_http.BitfabError("Selective replay plan has incomplete mustRun coverage.");
4723
2538
  for (const node of plan.nodes) {
4724
2539
  const ancestors = /* @__PURE__ */ new Set([node.id]);
4725
2540
  let requiredByManifest = this.required.has(replayNodeKey(node));
@@ -4727,14 +2542,14 @@ var SelectiveReplayRuntime = class {
4727
2542
  let parentId = node.parentId;
4728
2543
  while (parentId !== null) {
4729
2544
  const parent = this.nodes.get(parentId);
4730
- if (!parent || ancestors.has(parentId) || node.mustRun && !parent.mustRun) throw new BitfabError("Invalid selective replay ancestry.");
2545
+ if (!parent || ancestors.has(parentId) || node.mustRun && !parent.mustRun) throw new require_http.BitfabError("Invalid selective replay ancestry.");
4731
2546
  ancestors.add(parentId);
4732
2547
  requiredByManifest || (requiredByManifest = this.required.has(replayNodeKey(parent)));
4733
2548
  requiredForAssertion || (requiredForAssertion = this.assertionNames.has(parent.spanName));
4734
2549
  parentId = parent.parentId;
4735
2550
  }
4736
- if (!ancestors.has(plan.rootId) || (requiredByManifest || unresolved.length > 0) && !node.mustRun) throw new BitfabError("Selective replay plan could hide required code.");
4737
- if (requiredForAssertion && !node.mustRun) throw new BitfabError("Selective replay plan could hide assertion evidence.");
2551
+ if (!ancestors.has(plan.rootId) || (requiredByManifest || unresolved.length > 0) && !node.mustRun) throw new require_http.BitfabError("Selective replay plan could hide required code.");
2552
+ if (requiredForAssertion && !node.mustRun) throw new require_http.BitfabError("Selective replay plan could hide assertion evidence.");
4738
2553
  }
4739
2554
  }
4740
2555
  enter(params) {
@@ -4780,7 +2595,7 @@ var SelectiveReplayRuntime = class {
4780
2595
  };
4781
2596
  if (params.safetyMock && (mustRun || !reusable)) {
4782
2597
  decision("blocked", `safety-conflict:${reason}`);
4783
- this.failure = new BitfabError(`Selective replay cannot execute or safely reuse safety-mocked node ${params.spanName} (${reason}).`);
2598
+ this.failure = new require_http.BitfabError(`Selective replay cannot execute or safely reuse safety-mocked node ${params.spanName} (${reason}).`);
4784
2599
  throw this.failure;
4785
2600
  }
4786
2601
  if (!mustRun && reusable && (params.safetyMock || node?.reusable === true && params.reuseAllowed)) {
@@ -4811,7 +2626,7 @@ var SelectiveReplayRuntime = class {
4811
2626
  };
4812
2627
  //#endregion
4813
2628
  //#region src/replay.ts
4814
- var replay_exports = /* @__PURE__ */ __exportAll({
2629
+ var replay_exports = /* @__PURE__ */ require_bamlPeer.__exportAll({
4815
2630
  BITFAB_PROGRESS_PREFIX: () => BITFAB_PROGRESS_PREFIX,
4816
2631
  DbBranchReplayError: () => DbBranchReplayError,
4817
2632
  JUDGE_ASSERTIONS_DEPRECATION_WARNING: () => JUDGE_ASSERTIONS_DEPRECATION_WARNING,
@@ -4845,15 +2660,15 @@ const RESUME_CONFLICTING_OPTIONS = [
4845
2660
  ];
4846
2661
  const CARRIED_OVER_ERROR = "This item errored in an earlier run of this experiment, before it was resumed.";
4847
2662
  function validateResume(resume, options) {
4848
- if (resume.trim().length === 0) throw new BitfabError("resume must be the ID of the experiment to resume.");
2663
+ if (resume.trim().length === 0) throw new require_http.BitfabError("resume must be the ID of the experiment to resume.");
4849
2664
  const conflicting = RESUME_CONFLICTING_OPTIONS.filter((name) => options[name] !== void 0 && options[name] !== false);
4850
- if (conflicting.length > 0) throw new BitfabError(`resume continues experiment ${resume} with the traces, attempts, and graders it started with, so it cannot be combined with ${conflicting.join(", ")}. Drop those options, or start a new replay without resume.`);
2665
+ if (conflicting.length > 0) throw new require_http.BitfabError(`resume continues experiment ${resume} with the traces, attempts, and graders it started with, so it cannot be combined with ${conflicting.join(", ")}. Drop those options, or start a new replay without resume.`);
4851
2666
  }
4852
2667
  async function resumeReplaySession(httpClient, experimentId, traceFunctionKey, codeChangeFiles, force, requestedDbBranch) {
4853
2668
  const response = await httpClient.resumeReplay(experimentId, traceFunctionKey, codeChangeFiles, force);
4854
2669
  const work = response.work.map(({ itemIndex, attempt }) => {
4855
2670
  const serverItem = response.items[itemIndex];
4856
- if (serverItem === void 0) throw new BitfabError(`Replay resume for experiment ${response.experimentId} named item ${itemIndex}, but the server returned only ${response.items.length} item(s).`);
2671
+ if (serverItem === void 0) throw new require_http.BitfabError(`Replay resume for experiment ${response.experimentId} named item ${itemIndex}, but the server returned only ${response.items.length} item(s).`);
4857
2672
  return {
4858
2673
  serverItem,
4859
2674
  attempt
@@ -4902,14 +2717,14 @@ function carriedOverReplayItem(finished) {
4902
2717
  }
4903
2718
  function resolveAttempts(attempts) {
4904
2719
  if (attempts === void 0) return 1;
4905
- if (!Number.isInteger(attempts) || attempts < 1 || attempts > MAX_REPLAY_ATTEMPTS) throw new BitfabError(`attempts must be an integer from 1 to ${MAX_REPLAY_ATTEMPTS} (got ${attempts}).`);
2720
+ if (!Number.isInteger(attempts) || attempts < 1 || attempts > MAX_REPLAY_ATTEMPTS) throw new require_http.BitfabError(`attempts must be an integer from 1 to ${MAX_REPLAY_ATTEMPTS} (got ${attempts}).`);
4906
2721
  return attempts;
4907
2722
  }
4908
2723
  function resolveDatasetIds(options) {
4909
- if (options?.datasetId !== void 0 && options?.datasetIds !== void 0) throw new BitfabError("datasetId and datasetIds are the same selector: pass one dataset through datasetId, or several through datasetIds.");
2724
+ if (options?.datasetId !== void 0 && options?.datasetIds !== void 0) throw new require_http.BitfabError("datasetId and datasetIds are the same selector: pass one dataset through datasetId, or several through datasetIds.");
4910
2725
  if (options?.datasetId !== void 0) return [options.datasetId];
4911
2726
  if (options?.datasetIds === void 0) return;
4912
- if (options.datasetIds.length === 0) throw new BitfabError("datasetIds must contain at least one dataset ID.");
2727
+ if (options.datasetIds.length === 0) throw new require_http.BitfabError("datasetIds must contain at least one dataset ID.");
4913
2728
  return [...new Set(options.datasetIds)];
4914
2729
  }
4915
2730
  function dbBranchEnabled(dbBranch) {
@@ -4973,7 +2788,7 @@ function reportReplayProgress(progress) {
4973
2788
  stderr.write(`${BITFAB_PROGRESS_PREFIX}${JSON.stringify(progress, replayJsonReplacer)}\n`);
4974
2789
  } catch {}
4975
2790
  }
4976
- var ReplayError = class extends BitfabError {
2791
+ var ReplayError = class extends require_http.BitfabError {
4977
2792
  constructor(message, items, experimentId, experimentUrl, cause) {
4978
2793
  super(message, experimentUrl);
4979
2794
  this.items = items;
@@ -4985,7 +2800,7 @@ var ReplayError = class extends BitfabError {
4985
2800
  this.testRunUrl = experimentUrl;
4986
2801
  }
4987
2802
  };
4988
- var DbBranchReplayError = class extends BitfabError {
2803
+ var DbBranchReplayError = class extends require_http.BitfabError {
4989
2804
  constructor(code, message, originalTraceId, cause) {
4990
2805
  super(message);
4991
2806
  this.code = code;
@@ -5106,7 +2921,7 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
5106
2921
  }
5107
2922
  if (leaseError) throw new DbBranchReplayError(leaseError.code, leaseError.message, originalTraceId);
5108
2923
  if (selectiveOptions !== void 0) {
5109
- if (serverItem.selectiveReplayPlan === void 0) throw new BitfabError("Server did not return a selective replay plan. Update the server or disable experimentalSelectiveReplay.");
2924
+ if (serverItem.selectiveReplayPlan === void 0) throw new require_http.BitfabError("Server did not return a selective replay plan. Update the server or disable experimentalSelectiveReplay.");
5110
2925
  selectiveReplay = new SelectiveReplayRuntime(serverItem.selectiveReplayPlan, selectiveOptions);
5111
2926
  }
5112
2927
  const span = await httpClient.getExternalSpan(originalSpanId, { view: "replay" });
@@ -5133,7 +2948,7 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
5133
2948
  includeOutputs,
5134
2949
  includeRootOutput: false
5135
2950
  });
5136
- if (!treeResponse.root) throw new BitfabError(`Replay mock strategy "${mockStrategy}"${hasOverrides ? " with overrides" : ""} requires a span tree root for original span ${originalSpanId}.`);
2951
+ if (!treeResponse.root) throw new require_http.BitfabError(`Replay mock strategy "${mockStrategy}"${hasOverrides ? " with overrides" : ""} requires a span tree root for original span ${originalSpanId}.`);
5137
2952
  mockTree = buildMockTree(treeResponse.root);
5138
2953
  } catch (error) {
5139
2954
  if (mockStrategy !== "marked" || hasOverrides) throw error;
@@ -5173,7 +2988,7 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
5173
2988
  };
5174
2989
  try {
5175
2990
  replayStarted = performance.now();
5176
- const maybePromise = runWithReplayContext({
2991
+ const maybePromise = require_http.runWithReplayContext({
5177
2992
  experimentId,
5178
2993
  traceId: replayedTraceId,
5179
2994
  inputSourceSpanId: span.id,
@@ -5241,13 +3056,13 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
5241
3056
  async function waitForReplayPersistence(httpClient, experimentId, replayedTraceIds, replayLabels = {}, warn = console.warn) {
5242
3057
  if (!await httpClient.settleDeferredWork(REPLAY_PERSISTENCE_TIMEOUT_MS)) {
5243
3058
  httpClient.takeTraceDeliveries(replayedTraceIds);
5244
- throw new BitfabError(`Replay could not settle deferred span work before the deadline, so the expected span counts are incomplete (experiment ${experimentId}).`);
3059
+ throw new require_http.BitfabError(`Replay could not settle deferred span work before the deadline, so the expected span counts are incomplete (experiment ${experimentId}).`);
5245
3060
  }
5246
3061
  if (!httpClient.hasClosedDeliveries(replayedTraceIds)) {
5247
3062
  httpClient.takeTraceDeliveries(replayedTraceIds);
5248
3063
  return {};
5249
3064
  }
5250
- const flushed = await flushTraces(REPLAY_PERSISTENCE_TIMEOUT_MS);
3065
+ const flushed = await require_http.flushTraces(REPLAY_PERSISTENCE_TIMEOUT_MS);
5251
3066
  const deliveries = httpClient.takeTraceDeliveries(replayedTraceIds);
5252
3067
  const expectedSpanCounts = {};
5253
3068
  const readBackTraceIds = {};
@@ -5303,15 +3118,15 @@ function warnJudgeAssertionsDeprecated(write = console.warn) {
5303
3118
  async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options, registeredOverrides = []) {
5304
3119
  if (options?.judgeAssertions !== void 0) warnJudgeAssertionsDeprecated();
5305
3120
  if (options?.resume !== void 0) validateResume(options.resume, options);
5306
- else if (options?.force === true) throw new BitfabError("force only applies when resuming an experiment. Pass it together with resume.");
5307
- if (options?.experimentGroupName !== void 0 && options.experimentGroupId === void 0) throw new BitfabError("experimentGroupName only applies with experimentGroupId. Pass it together with experimentGroupId.");
3121
+ else if (options?.force === true) throw new require_http.BitfabError("force only applies when resuming an experiment. Pass it together with resume.");
3122
+ if (options?.experimentGroupName !== void 0 && options.experimentGroupId === void 0) throw new require_http.BitfabError("experimentGroupName only applies with experimentGroupId. Pass it together with experimentGroupId.");
5308
3123
  if (options?.experimentalSelectiveReplay !== void 0) {
5309
3124
  validateSelectiveReplayOptions(options.experimentalSelectiveReplay);
5310
- if ((options.mock ?? "marked") !== "marked" || normalizeMockOverrides(options.mockOverride).length > 0 || registeredOverrides.length > 0) throw new BitfabError("experimentalSelectiveReplay requires mock: 'marked' and cannot be combined with mock overrides.");
3125
+ if ((options.mock ?? "marked") !== "marked" || normalizeMockOverrides(options.mockOverride).length > 0 || registeredOverrides.length > 0) throw new require_http.BitfabError("experimentalSelectiveReplay requires mock: 'marked' and cannot be combined with mock overrides.");
5311
3126
  }
5312
3127
  if (options?.traceIds !== void 0) {
5313
- if (options.traceIds.length === 0) throw new BitfabError("traceIds must contain at least one trace ID.");
5314
- if (options.traceIds.length > 100) throw new BitfabError(`traceIds supports at most 100 trace IDs per replay (got ${options.traceIds.length}).`);
3128
+ if (options.traceIds.length === 0) throw new require_http.BitfabError("traceIds must contain at least one trace ID.");
3129
+ if (options.traceIds.length > 100) throw new require_http.BitfabError(`traceIds supports at most 100 trace IDs per replay (got ${options.traceIds.length}).`);
5315
3130
  }
5316
3131
  const datasetIds = resolveDatasetIds(options);
5317
3132
  if (options?.limit !== void 0 && options?.traceIds !== void 0) try {
@@ -5319,8 +3134,8 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options, reg
5319
3134
  } catch {}
5320
3135
  const requestedAttempts = resolveAttempts(options?.attempts);
5321
3136
  const maxConcurrency = options?.maxConcurrency ?? 10;
5322
- if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1) throw new BitfabError(`maxConcurrency must be a positive integer (got ${maxConcurrency}).`);
5323
- await replayContextReady;
3137
+ if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1) throw new require_http.BitfabError(`maxConcurrency must be a positive integer (got ${maxConcurrency}).`);
3138
+ await require_http.replayContextReady;
5324
3139
  let codeChangeDescription = options?.codeChangeDescription;
5325
3140
  let codeChangeFiles = options?.codeChangeFiles;
5326
3141
  if (codeChangeFiles === void 0) {
@@ -5378,7 +3193,7 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options, reg
5378
3193
  }
5379
3194
  function throwIfInterrupted(interrupted, items, experimentId, experimentUrl) {
5380
3195
  if (!interrupted()) return;
5381
- const cause = new BitfabError(`Experiment ${experimentId} was interrupted, so it was not completed or graded. Resume it by passing { resume: "${experimentId}" } to replay, or with bitfab-replay --resume ${experimentId}.`, experimentUrl);
3196
+ const cause = new require_http.BitfabError(`Experiment ${experimentId} was interrupted, so it was not completed or graded. Resume it by passing { resume: "${experimentId}" } to replay, or with bitfab-replay --resume ${experimentId}.`, experimentUrl);
5382
3197
  throw new ReplayError(cause.message, items, experimentId, experimentUrl, cause);
5383
3198
  }
5384
3199
  async function runReplaySession(httpClient, fn, session, fullExperimentUrl, maxConcurrency, stopInterruptingOnSignal, markCompleteReturned, interrupted, options, registeredOverrides) {
@@ -5411,7 +3226,7 @@ async function runReplaySession(httpClient, fn, session, fullExperimentUrl, maxC
5411
3226
  while (flushPending) {
5412
3227
  flushPending = false;
5413
3228
  await httpClient.settleDeferredWork(REPLAY_PERSISTENCE_TIMEOUT_MS);
5414
- await flushTraces(REPLAY_PERSISTENCE_TIMEOUT_MS);
3229
+ await require_http.flushTraces(REPLAY_PERSISTENCE_TIMEOUT_MS);
5415
3230
  }
5416
3231
  } finally {
5417
3232
  flushInFlight = null;
@@ -5536,7 +3351,7 @@ async function runReplaySession(httpClient, fn, session, fullExperimentUrl, maxC
5536
3351
  }
5537
3352
  if (completedCount > 0 && missing.length === completedCount) {
5538
3353
  const serverCount = completeResult.traceCount !== void 0 ? ` The server persisted ${completeResult.traceCount} trace(s) for this run.` : "";
5539
- const cause = new BitfabError(`Replay completed but the server has no persisted trace for any of the ${completedCount} completed item(s) (experiment ${experimentId}).${serverCount} Trace uploads were awaited, so either the uploads failed (check for "Bitfab: Failed to create" errors above) or the replayed function is not wrapped with withSpan.`);
3354
+ const cause = new require_http.BitfabError(`Replay completed but the server has no persisted trace for any of the ${completedCount} completed item(s) (experiment ${experimentId}).${serverCount} Trace uploads were awaited, so either the uploads failed (check for "Bitfab: Failed to create" errors above) or the replayed function is not wrapped with withSpan.`);
5540
3355
  throw new ReplayError(cause.message, resultItems, experimentId, fullExperimentUrl, cause);
5541
3356
  }
5542
3357
  if (missing.length > 0) try {
@@ -5817,7 +3632,7 @@ function snapshotContext(context) {
5817
3632
  return snapshot;
5818
3633
  }
5819
3634
  function unavailableCapability(path) {
5820
- return new BitfabError(`Rivet context capability "${path}" is unavailable during replay. Add first-class support for that public context path before replaying code that uses it.`, RIVET_DOCS_URL);
3635
+ return new require_http.BitfabError(`Rivet context capability "${path}" is unavailable during replay. Add first-class support for that public context path before replaying code that uses it.`, RIVET_DOCS_URL);
5821
3636
  }
5822
3637
  function effectNode(traceFunctionKey, effect, mockSpanId) {
5823
3638
  return {
@@ -5842,15 +3657,15 @@ function replayEffectStatus(replay, traceFunctionKey, effect, marked) {
5842
3657
  function assertReplayEffectAvailable(replay, traceFunctionKey, effect, marked) {
5843
3658
  if (!replay) return;
5844
3659
  const status = replayEffectStatus(replay, traceFunctionKey, effect, marked);
5845
- if (!status.willMock) throw new BitfabError(`Rivet effect "${effect}" has no live actor context during replay. Add "${effect}" to mockOnReplay or provide a replay override.`, RIVET_DOCS_URL);
5846
- if (!status.hasRecordedSpan && !status.hasOverride) throw new BitfabError(`No recorded Rivet effect "${effect}" exists at call ${status.callIndex + 1}; the live effect was not executed.`, RIVET_DOCS_URL);
3660
+ if (!status.willMock) throw new require_http.BitfabError(`Rivet effect "${effect}" has no live actor context during replay. Add "${effect}" to mockOnReplay or provide a replay override.`, RIVET_DOCS_URL);
3661
+ if (!status.hasRecordedSpan && !status.hasOverride) throw new require_http.BitfabError(`No recorded Rivet effect "${effect}" exists at call ${status.callIndex + 1}; the live effect was not executed.`, RIVET_DOCS_URL);
5847
3662
  }
5848
3663
  function fixtureName(traceFunctionKey) {
5849
3664
  return `rivet:${traceFunctionKey}`;
5850
3665
  }
5851
3666
  function snapshotFromReplay(traceFunctionKey, replay) {
5852
3667
  const fixture = replay.integrationFixtures?.get(fixtureName(traceFunctionKey));
5853
- if (!isRecord(fixture)) throw new BitfabError(`Trace "${traceFunctionKey}" has no Rivet context fixture. Capture a fresh trace with the Rivet integration before replaying it.`, RIVET_DOCS_URL);
3668
+ if (!isRecord(fixture)) throw new require_http.BitfabError(`Trace "${traceFunctionKey}" has no Rivet context fixture. Capture a fresh trace with the Rivet integration before replaying it.`, RIVET_DOCS_URL);
5854
3669
  return fixture;
5855
3670
  }
5856
3671
  var BitfabRivetIntegration = class {
@@ -5861,7 +3676,7 @@ var BitfabRivetIntegration = class {
5861
3676
  this.markedEffects = new Set(options.mockOnReplay ?? []);
5862
3677
  }
5863
3678
  withContext(context, fn) {
5864
- if (!isRecord(context)) throw new BitfabError("Rivet withContext requires a context object");
3679
+ if (!isRecord(context)) throw new require_http.BitfabError("Rivet withContext requires a context object");
5865
3680
  return runWithRivetContext({
5866
3681
  context,
5867
3682
  fixtureContext: createIntegrationFixtureContext(fixtureName(this.traceFunctionKey), snapshotContext(context)),
@@ -5875,7 +3690,7 @@ var BitfabRivetIntegration = class {
5875
3690
  };
5876
3691
  }
5877
3692
  getContext() {
5878
- const replay = getReplayContext();
3693
+ const replay = require_http.getReplayContext();
5879
3694
  if (replay) {
5880
3695
  const existing = this.replayProxies.get(replay);
5881
3696
  if (existing) return existing;
@@ -5884,13 +3699,13 @@ var BitfabRivetIntegration = class {
5884
3699
  return proxy;
5885
3700
  }
5886
3701
  const binding = getRivetContextBinding();
5887
- if (!binding) throw new BitfabError("No Rivet context is bound. Call rivet.bind(handler) or rivet.withContext(context, callback) at the Rivet boundary.", RIVET_DOCS_URL);
3702
+ if (!binding) throw new require_http.BitfabError("No Rivet context is bound. Call rivet.bind(handler) or rivet.withContext(context, callback) at the Rivet boundary.", RIVET_DOCS_URL);
5888
3703
  this.runtime.recordRootFixture(binding.fixtureContext, binding.recordedRoots);
5889
3704
  if (!binding.proxy) binding.proxy = this.createContextProxy(binding.context, binding);
5890
3705
  return binding.proxy;
5891
3706
  }
5892
3707
  createContextProxy(target, binding) {
5893
- const replay = getReplayContext();
3708
+ const replay = require_http.getReplayContext();
5894
3709
  const dbProxy = this.createDbProxy(binding, replay);
5895
3710
  const groupProxies = /* @__PURE__ */ new Map();
5896
3711
  for (const group of Object.keys(RIVET_GROUP_EFFECT_METHODS)) if (group !== "db") groupProxies.set(group, this.createGroupProxy(group, binding, replay));
@@ -5954,7 +3769,7 @@ var BitfabRivetIntegration = class {
5954
3769
  createEffect(effect, targetProvider, methodName, replay) {
5955
3770
  const marked = this.markedEffects.has(effect);
5956
3771
  const invoke = (...args) => {
5957
- assertReplayEffectAvailable(getReplayContext(), this.traceFunctionKey, effect, marked);
3772
+ assertReplayEffectAvailable(require_http.getReplayContext(), this.traceFunctionKey, effect, marked);
5958
3773
  const target = targetProvider();
5959
3774
  const method = target ? readProperty(target, methodName) : void 0;
5960
3775
  if (typeof method !== "function") throw unavailableCapability(effect);
@@ -5972,7 +3787,7 @@ var BitfabRivetIntegration = class {
5972
3787
  }
5973
3788
  createTransaction(binding, replay) {
5974
3789
  return async (callback, options) => {
5975
- if (typeof callback !== "function") throw new BitfabError("Rivet db.transaction requires a callback");
3790
+ if (typeof callback !== "function") throw new require_http.BitfabError("Rivet db.transaction requires a callback");
5976
3791
  if (replay) return await callback(this.createMethodProxy(() => void 0, "db.transaction", ["execute"], replay));
5977
3792
  const context = binding?.context;
5978
3793
  const db = context ? readProperty(context, "db") : void 0;
@@ -6193,7 +4008,7 @@ var BitfabOpenAITracingProcessor = class {
6193
4008
  this.startedSpans = /* @__PURE__ */ new Map();
6194
4009
  this.endedTraces = /* @__PURE__ */ new Set();
6195
4010
  this.ownsHttpClient = config._httpClient === void 0;
6196
- this.httpClient = config._httpClient ?? new HttpClient({
4011
+ this.httpClient = config._httpClient ?? new require_http.HttpClient({
6197
4012
  apiKey: config.apiKey,
6198
4013
  serviceUrl: config.serviceUrl ?? "https://bitfab.ai",
6199
4014
  timeout: config.timeout ?? 1e4
@@ -6339,7 +4154,7 @@ var BitfabOpenAITracingProcessor = class {
6339
4154
  }
6340
4155
  }
6341
4156
  buildSpanPayload(serializedSpan, errors) {
6342
- serializedSpan.span_origin = makeSpanOrigin("openai-agents");
4157
+ serializedSpan.span_origin = require_http.makeSpanOrigin("openai-agents");
6343
4158
  const payload = {
6344
4159
  id: randomUuid(),
6345
4160
  type: "openai",
@@ -6541,7 +4356,7 @@ function markTracedFunction(target, traceFunctionKey, original) {
6541
4356
  }
6542
4357
  function resolveSpanExperimentId(options) {
6543
4358
  const { experimentId, testRunId } = options;
6544
- if (experimentId !== void 0 && testRunId !== void 0 && experimentId !== testRunId) throw new BitfabError(`experimentId ("${experimentId}") and its deprecated alias testRunId ("${testRunId}") were both passed with different values. Pass only experimentId.`);
4359
+ if (experimentId !== void 0 && testRunId !== void 0 && experimentId !== testRunId) throw new require_http.BitfabError(`experimentId ("${experimentId}") and its deprecated alias testRunId ("${testRunId}") were both passed with different values. Pass only experimentId.`);
6545
4360
  return experimentId ?? testRunId;
6546
4361
  }
6547
4362
  const TRUNCATION_LIMIT_ORDER = ["max_depth", "max_captured_subtree_spans"];
@@ -6557,7 +4372,7 @@ function rootTraceFunctionKeyOfTrace(traceId, fallback) {
6557
4372
  return activeTraceStates.get(traceId)?.traceFunctionKey ?? fallback;
6558
4373
  }
6559
4374
  function rootTraceFunctionKeyOf(payload) {
6560
- const captured = payload[ROOT_TRACE_FUNCTION_KEY_FIELD];
4375
+ const captured = payload[require_http.ROOT_TRACE_FUNCTION_KEY_FIELD];
6561
4376
  if (typeof captured === "string") return captured;
6562
4377
  const traceId = payload.traceId;
6563
4378
  const live = typeof traceId === "string" ? activeTraceStates.get(traceId)?.traceFunctionKey : void 0;
@@ -6667,13 +4482,10 @@ function wrapAsyncGenerator(source, spanStack, sendSpan) {
6667
4482
  let cachedCollectorClass;
6668
4483
  async function loadCollectorClass() {
6669
4484
  if (cachedCollectorClass !== void 0) return cachedCollectorClass;
6670
- try {
6671
- cachedCollectorClass = (await importOptionalPeer(["@boundaryml", "baml"])).Collector;
6672
- return cachedCollectorClass;
6673
- } catch {
6674
- cachedCollectorClass = null;
6675
- return null;
6676
- }
4485
+ const baml = await require_bamlPeer.loadBamlModule();
4486
+ if (!baml) return null;
4487
+ cachedCollectorClass = baml.Collector;
4488
+ return cachedCollectorClass;
6677
4489
  }
6678
4490
  function extractPromptFromCollector(collector) {
6679
4491
  try {
@@ -6723,7 +4535,7 @@ function extractContextFromCollector(collector) {
6723
4535
  }
6724
4536
  }
6725
4537
  function isSpanType(value) {
6726
- return SPAN_TYPES.some((spanType) => spanType === value);
4538
+ return require_http.SPAN_TYPES.some((spanType) => spanType === value);
6727
4539
  }
6728
4540
  const noOpSpan = {
6729
4541
  id: "",
@@ -6760,7 +4572,7 @@ function getCurrentSpan() {
6760
4572
  };
6761
4573
  }
6762
4574
  function getCurrentReplayBranch() {
6763
- const ctx = getReplayContext();
4575
+ const ctx = require_http.getReplayContext();
6764
4576
  if (!ctx?.dbBranchLease) return null;
6765
4577
  const traceId = ctx.sourceBitfabTraceId ?? ctx.inputSourceTraceId;
6766
4578
  if (!traceId) return null;
@@ -6799,7 +4611,7 @@ function getCurrentTrace() {
6799
4611
  setMetadata(metadata) {
6800
4612
  try {
6801
4613
  if (typeof metadata !== "object" || metadata === null) return;
6802
- recordCallerTraceMetadata(traceId, metadata);
4614
+ require_http.recordCallerTraceMetadata(traceId, metadata);
6803
4615
  } catch {}
6804
4616
  },
6805
4617
  addContext(context) {
@@ -6876,12 +4688,15 @@ var Bitfab = class {
6876
4688
  if (config.dbSnapshot) validateDbSnapshotConfig(config.dbSnapshot);
6877
4689
  this.dbSnapshot = config.dbSnapshot;
6878
4690
  startCommitRefResolution();
6879
- this.httpClient = new HttpClient({
4691
+ this.httpClient = new require_http.HttpClient({
6880
4692
  apiKey: () => this.resolveApiKey(),
6881
4693
  serviceUrl: this.serviceUrl,
6882
4694
  timeout: this.timeout
6883
4695
  });
6884
- this.simulationPlan = new SimulationPlan(this.httpClient, config.simulationPlan ?? true);
4696
+ this.simulationPlan = new require_http.SimulationPlan({
4697
+ getSimulationPlan: () => this.httpClient.getSimulationPlan(),
4698
+ canRead: () => this.canReadSimulationPlan()
4699
+ }, config.simulationPlan ?? true);
6885
4700
  this.httpClient.externalSpanTransform = (payload, submit, drop) => this.applySimulationPlan(payload, submit, drop);
6886
4701
  this.httpClient.externalTraceTransform = (payload, submit) => this.simulationPlan.sendTrace(payload, submit);
6887
4702
  this.httpClient.releaseHeldExternalSpans = (timeoutMs) => this.simulationPlan.release(timeoutMs);
@@ -6902,13 +4717,13 @@ var Bitfab = class {
6902
4717
  if (args.length === 3) {
6903
4718
  const propertyKey = args[1];
6904
4719
  const descriptor = args[2];
6905
- if (!descriptor || typeof descriptor.value !== "function") throw new BitfabError("@bitfab.trace can only decorate methods");
4720
+ if (!descriptor || typeof descriptor.value !== "function") throw new require_http.BitfabError("@bitfab.trace can only decorate methods");
6906
4721
  descriptor.value = this.createAutoTraceRoot(traceFunctionKey, String(propertyKey), options, descriptor.value);
6907
4722
  return;
6908
4723
  }
6909
4724
  const method = args[0];
6910
4725
  const context = args[1];
6911
- if (typeof method !== "function" || context?.kind !== "method" || context.name === void 0) throw new BitfabError("@bitfab.trace can only decorate methods");
4726
+ if (typeof method !== "function" || context?.kind !== "method" || context.name === void 0) throw new require_http.BitfabError("@bitfab.trace can only decorate methods");
6912
4727
  return this.createAutoTraceRoot(traceFunctionKey, String(context.name), options, method);
6913
4728
  };
6914
4729
  return decorator;
@@ -6916,7 +4731,7 @@ var Bitfab = class {
6916
4731
  withTrace(traceFunctionKey, optionsOrFn, maybeFn) {
6917
4732
  const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
6918
4733
  const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
6919
- if (!fn) throw new BitfabError("bitfab.withTrace requires a function");
4734
+ if (!fn) throw new require_http.BitfabError("bitfab.withTrace requires a function");
6920
4735
  const name = fn.name !== "" ? fn.name : traceFunctionKey;
6921
4736
  return this.createAutoTraceRoot(traceFunctionKey, name, options, fn, AUTO_TRACE_NODE_FUNCTION_NAMES.get(fn) ?? fn.name.replace(/^bound /, ""));
6922
4737
  }
@@ -6925,13 +4740,13 @@ var Bitfab = class {
6925
4740
  const decorator = (...args) => {
6926
4741
  if (args.length === 3) {
6927
4742
  const descriptor = args[2];
6928
- if (!descriptor || typeof descriptor.value !== "function") throw new BitfabError("@bitfab.node can only decorate methods");
4743
+ if (!descriptor || typeof descriptor.value !== "function") throw new require_http.BitfabError("@bitfab.node can only decorate methods");
6929
4744
  descriptor.value = this.createAutoTraceNode(configuration, descriptor.value, String(args[1]));
6930
4745
  return;
6931
4746
  }
6932
4747
  const method = args[0];
6933
4748
  const context = args[1];
6934
- if (typeof method !== "function" || context?.kind !== "method") throw new BitfabError("@bitfab.node can only decorate methods");
4749
+ if (typeof method !== "function" || context?.kind !== "method") throw new require_http.BitfabError("@bitfab.node can only decorate methods");
6935
4750
  return this.createAutoTraceNode(configuration, method, String(context.name));
6936
4751
  };
6937
4752
  return decorator;
@@ -6939,15 +4754,15 @@ var Bitfab = class {
6939
4754
  withNode(optionsOrFn, maybeFn, internalFunctionName) {
6940
4755
  const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
6941
4756
  const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
6942
- if (!fn) throw new BitfabError("bitfab.withNode requires a function");
4757
+ if (!fn) throw new require_http.BitfabError("bitfab.withNode requires a function");
6943
4758
  const configuration = this.resolveNodeConfiguration(options);
6944
4759
  const functionName = internalFunctionName ?? fn.name;
6945
- if (functionName === "") throw new BitfabError("bitfab.withNode requires a named function so the subtree transform can bind its configuration to the correct call.");
4760
+ if (functionName === "") throw new require_http.BitfabError("bitfab.withNode requires a named function so the subtree transform can bind its configuration to the correct call.");
6946
4761
  return this.createAutoTraceNode(configuration, fn, functionName);
6947
4762
  }
6948
4763
  resolveNodeConfiguration(options) {
6949
4764
  const capture = options.capture ?? true;
6950
- if (!capture && options.mockOnReplay === true) throw new BitfabError("bitfab.node({ capture: false }) cannot use mockOnReplay: true because an uncaptured node has no recorded output.");
4765
+ if (!capture && options.mockOnReplay === true) throw new require_http.BitfabError("bitfab.node({ capture: false }) cannot use mockOnReplay: true because an uncaptured node has no recorded output.");
6951
4766
  const experimentId = resolveSpanExperimentId(options);
6952
4767
  return {
6953
4768
  capture,
@@ -7091,7 +4906,7 @@ var Bitfab = class {
7091
4906
  if (firstPlanRead !== void 0) return firstPlanRead.then(() => tracedRoot.apply(this, args));
7092
4907
  return tracedRoot.apply(this, args);
7093
4908
  }
7094
- const link = getReplayContext() || inSeedScope() ? void 0 : { traceFunctionKey };
4909
+ const link = require_http.getReplayContext() || inSeedScope() ? void 0 : { traceFunctionKey };
7095
4910
  const rootName = rootNameFor(this);
7096
4911
  const spanDetails = { contexts: [] };
7097
4912
  return require_autoTrace.invokeThroughAutoTraceEntries(enclosing, (entry, next) => entry.context.invokeNestedRoot(rootName, name, args, next, entry, link, spanDetails), () => {
@@ -7134,7 +4949,7 @@ var Bitfab = class {
7134
4949
  resolveApiKey() {
7135
4950
  const key = this.findApiKey(true);
7136
4951
  if (key) return key;
7137
- if (this.strict) throw new BitfabError("Bitfab: no API key resolved. Set BITFAB_API_KEY or pass apiKey to new Bitfab(). If a script loads env with dotenv, load it before the module that constructs the client is imported (e.g. `node --env-file=.env script.ts`), or pass `apiKey: () => process.env.BITFAB_API_KEY`.");
4952
+ if (this.strict) throw new require_http.BitfabError("Bitfab: no API key resolved. Set BITFAB_API_KEY or pass apiKey to new Bitfab(). If a script loads env with dotenv, load it before the module that constructs the client is imported (e.g. `node --env-file=.env script.ts`), or pass `apiKey: () => process.env.BITFAB_API_KEY`.");
7138
4953
  if (this.isCaptureConfigured() && !this.apiKeyWarned) {
7139
4954
  this.apiKeyWarned = true;
7140
4955
  console.warn("Bitfab: apiKey is empty - tracing is disabled. Provide a valid API key to enable tracing.");
@@ -7150,9 +4965,12 @@ var Bitfab = class {
7150
4965
  return this.resolveApiKey() !== void 0;
7151
4966
  }
7152
4967
  shouldRecord() {
7153
- if (!this.isCaptureConfigured() && !getReplayContext() && !inSeedScope()) return false;
4968
+ if (!this.isCaptureConfigured() && !require_http.getReplayContext() && !inSeedScope()) return false;
7154
4969
  return this.resolveApiKey() !== void 0;
7155
4970
  }
4971
+ canReadSimulationPlan() {
4972
+ return ((this.captureConfiguredInCode ?? this.captureConfiguredFromEnv ?? readBooleanEnv(CAPTURE_ENABLED_ENV) ?? true) || require_http.getReplayContext() !== null || inSeedScope()) && this.findApiKey(true) !== void 0;
4973
+ }
7156
4974
  prepareFrameworkIntegration() {
7157
4975
  if (this.isCaptureConfigured() && this.strict) this.resolveApiKey();
7158
4976
  }
@@ -7161,8 +4979,8 @@ var Bitfab = class {
7161
4979
  }
7162
4980
  async fetchFunctionVersion(methodName) {
7163
4981
  const result = await this.httpClient.lookupFunction(methodName);
7164
- if (result.id === null) throw new BitfabError(`Function "${methodName}" not found. Create it at: ${this.serviceUrl}/functions`, "/functions");
7165
- if (!result.prompt) throw new BitfabError(`Function "${methodName}" has no prompt configured. Add one at: ${this.serviceUrl}/functions/${result.id}`, `/functions/${result.id}`);
4982
+ if (result.id === null) throw new require_http.BitfabError(`Function "${methodName}" not found. Create it at: ${this.serviceUrl}/functions`, "/functions");
4983
+ if (!result.prompt) throw new require_http.BitfabError(`Function "${methodName}" has no prompt configured. Add one at: ${this.serviceUrl}/functions/${result.id}`, `/functions/${result.id}`);
7166
4984
  return result;
7167
4985
  }
7168
4986
  async call(methodName, inputs = {}) {
@@ -7185,9 +5003,9 @@ var Bitfab = class {
7185
5003
  });
7186
5004
  return executionResult.result;
7187
5005
  } catch (error) {
7188
- if (error instanceof BitfabError) throw error;
7189
- if (error instanceof Error) throw new BitfabError(error.message);
7190
- throw new BitfabError("Unknown error occurred during local execution");
5006
+ if (error instanceof require_http.BitfabError) throw error;
5007
+ if (error instanceof Error) throw new require_http.BitfabError(error.message);
5008
+ throw new require_http.BitfabError("Unknown error occurred during local execution");
7191
5009
  }
7192
5010
  }
7193
5011
  getOpenAiTracingProcessor() {
@@ -7303,14 +5121,15 @@ var Bitfab = class {
7303
5121
  bamlClient = this.bamlClient;
7304
5122
  method = methodOrClient;
7305
5123
  options = maybeMethodOrOptions;
7306
- if (!bamlClient) throw new BitfabError("bamlClient is required for wrapBAML. Pass it in the constructor or as the first argument.");
5124
+ if (!bamlClient) throw new require_http.BitfabError("bamlClient is required for wrapBAML. Pass it in the constructor or as the first argument.");
7307
5125
  }
7308
5126
  const methodName = method.name;
7309
- if (!methodName) throw new BitfabError("wrapBAML requires a named function (e.g., b.ClassifyText).");
5127
+ if (!methodName) throw new require_http.BitfabError("wrapBAML requires a named function (e.g., b.ClassifyText).");
7310
5128
  loadCollectorClass();
7311
5129
  const wrappedFn = async (...args) => {
7312
5130
  const CollectorClass = await loadCollectorClass();
7313
5131
  if (!CollectorClass) {
5132
+ require_autoTrace.warnOnce("wrapBAML-collector-unavailable", `@boundaryml/baml could not be loaded, so "${methodName}" and every other wrapBAML call run untraced: no prompt, model, or token usage is recorded and onCollector is not called. If @boundaryml/baml is installed and your app is bundled (Next.js with Turbopack, for example), add \`import "@bitfab/sdk/baml"\` once in your server code.`);
7314
5133
  wrappedFn.collector = null;
7315
5134
  return await bamlClient[methodName](...args);
7316
5135
  }
@@ -7320,7 +5139,7 @@ var Bitfab = class {
7320
5139
  try {
7321
5140
  trackedClient = bamlClient.withOptions({ collector });
7322
5141
  const method = trackedClient[methodName];
7323
- if (typeof method !== "function") throw new BitfabError("bamlClient.withOptions did not return the wrapped method");
5142
+ if (typeof method !== "function") throw new require_http.BitfabError("bamlClient.withOptions did not return the wrapped method");
7324
5143
  trackedMethod = method;
7325
5144
  } catch {
7326
5145
  require_autoTrace.warnOnce(`wrapBAML-setup:${methodName}`, `BAML tracing setup failed for "${methodName}" (incompatible bamlClient or BAML version); calling it untraced. The call still runs; no span is recorded.`);
@@ -7377,7 +5196,7 @@ var Bitfab = class {
7377
5196
  try {
7378
5197
  hasParent = getSpanStack().length > 0;
7379
5198
  } catch (setupError) {
7380
- if (getReplayContext()) throw setupError;
5199
+ if (require_http.getReplayContext()) throw setupError;
7381
5200
  require_autoTrace.warnOnce(`withSpan-setup:${traceFunctionKey}`, `tracing setup failed for "${traceFunctionKey}"; running it untraced. The function still runs and returns normally; no span is recorded.`);
7382
5201
  return fn.apply(this, args);
7383
5202
  }
@@ -7390,7 +5209,7 @@ var Bitfab = class {
7390
5209
  try {
7391
5210
  const currentStack = getSpanStack();
7392
5211
  const parentContext = currentStack[currentStack.length - 1];
7393
- const replayCtxForTraceId = parentContext ? null : getReplayContext();
5212
+ const replayCtxForTraceId = parentContext ? null : require_http.getReplayContext();
7394
5213
  const seedCtxForTraceId = parentContext ? null : getSeedContext();
7395
5214
  const traceId = parentContext?.traceId ?? replayCtxForTraceId?.traceId ?? seedCtxForTraceId?.traceId ?? randomUuid();
7396
5215
  const spanId = randomUuid();
@@ -7421,7 +5240,7 @@ var Bitfab = class {
7421
5240
  newStack = [...currentStack, newContext];
7422
5241
  const inputs = args;
7423
5242
  const startedAt = nowIsoTimestamp();
7424
- const replayCtxAtStart = getReplayContext();
5243
+ const replayCtxAtStart = require_http.getReplayContext();
7425
5244
  const experimentId = replayCtxAtStart?.experimentId ?? optionExperimentId;
7426
5245
  if (isRootSpan && !activeTraceStates.has(traceId)) {
7427
5246
  const dbSnapshotRef = buildSnapshotRef(self.dbSnapshot, startedAt);
@@ -7466,7 +5285,7 @@ var Bitfab = class {
7466
5285
  enclosingTrace: options.enclosingTrace
7467
5286
  };
7468
5287
  const sendSpan = async (params) => {
7469
- const replayCtx = getReplayContext();
5288
+ const replayCtx = require_http.getReplayContext();
7470
5289
  try {
7471
5290
  const endedAt = nowIsoTimestamp();
7472
5291
  if (!(activeTraceStates.get(traceId)?.dropped === true)) self.sendWrapperSpan({
@@ -7481,7 +5300,7 @@ var Bitfab = class {
7481
5300
  if (isRootSpan) {
7482
5301
  const traceState = activeTraceStates.get(traceId);
7483
5302
  const truncated = truncationMetadata(traceState?.truncation);
7484
- if (truncated !== void 0) recordCallerTraceMetadata(traceId, truncated);
5303
+ if (truncated !== void 0) require_http.recordCallerTraceMetadata(traceId, truncated);
7485
5304
  self.sendTraceCompletion({
7486
5305
  traceFunctionKey,
7487
5306
  traceId,
@@ -7489,7 +5308,7 @@ var Bitfab = class {
7489
5308
  endedAt,
7490
5309
  sessionId: traceState?.sessionId,
7491
5310
  name: traceState?.name,
7492
- metadata: callerTraceMetadata(traceId),
5311
+ metadata: require_http.callerTraceMetadata(traceId),
7493
5312
  contexts: traceState?.contexts ?? [],
7494
5313
  experimentId: traceState?.experimentId,
7495
5314
  inputSourceTraceId: traceState?.inputSourceTraceId,
@@ -7507,7 +5326,7 @@ var Bitfab = class {
7507
5326
  } }
7508
5327
  });
7509
5328
  activeTraceStates.delete(traceId);
7510
- retireTraceMetadata(traceId);
5329
+ require_http.retireTraceMetadata(traceId);
7511
5330
  }
7512
5331
  } catch {} finally {
7513
5332
  self.httpClient.traceCompletion.end(traceId, spanId);
@@ -7553,7 +5372,7 @@ var Bitfab = class {
7553
5372
  recordSpan(result);
7554
5373
  return result;
7555
5374
  };
7556
- const replayCtxForMock = getReplayContext();
5375
+ const replayCtxForMock = require_http.getReplayContext();
7557
5376
  if (replayCtxForMock?.selectiveReplay) {
7558
5377
  const decision = replayCtxForMock.selectiveReplay.enter({
7559
5378
  traceFunctionKey,
@@ -7593,7 +5412,7 @@ var Bitfab = class {
7593
5412
  return output;
7594
5413
  };
7595
5414
  const emitMockAsync = (pending, mockSource) => {
7596
- if (!fnReturnsPromise) throw new BitfabError(`Cannot mock synchronous span "${traceFunctionKey}" with an asynchronously-resolved value (lazy recorded-output fetch or an async value function). Make the wrapped function async, or use mock: "all" so recorded outputs are fetched eagerly.`);
5415
+ if (!fnReturnsPromise) throw new require_http.BitfabError(`Cannot mock synchronous span "${traceFunctionKey}" with an asynchronously-resolved value (lazy recorded-output fetch or an async value function). Make the wrapped function async, or use mock: "all" so recorded outputs are fetched eagerly.`);
7597
5416
  return (async () => {
7598
5417
  const output = await resolveMockOrAbort(() => pending);
7599
5418
  sendSpan({
@@ -7607,7 +5426,7 @@ var Bitfab = class {
7607
5426
  };
7608
5427
  const resolveRecordedOutput = () => {
7609
5428
  if (!(mockSpan?.output !== void 0 || mockSpan?.outputMeta !== void 0) && replayCtxForMock.fetchSpanOutput && mockSpan?.externalSpanId) return replayCtxForMock.fetchSpanOutput(mockSpan.externalSpanId);
7610
- if (!mockSpan) return Promise.reject(new BitfabError(`No recorded span to source output for "${traceFunctionKey}".`));
5429
+ if (!mockSpan) return Promise.reject(new require_http.BitfabError(`No recorded span to source output for "${traceFunctionKey}".`));
7611
5430
  let output = mockSpan.output;
7612
5431
  if (mockSpan.outputMeta !== void 0 && mockSpan.outputMeta !== null) output = deserializeValue({
7613
5432
  json: mockSpan.output,
@@ -7647,7 +5466,7 @@ var Bitfab = class {
7647
5466
  };
7648
5467
  const resolution = resolveOverrideFrom(0);
7649
5468
  if (resolution instanceof Promise) {
7650
- if (!fnReturnsPromise) throw new BitfabError(`Cannot resolve an asynchronous mock override for synchronous span "${traceFunctionKey}". Make the wrapped function async or return NO_MOCK_OVERRIDE synchronously.`);
5469
+ if (!fnReturnsPromise) throw new require_http.BitfabError(`Cannot resolve an asynchronous mock override for synchronous span "${traceFunctionKey}". Make the wrapped function async or return NO_MOCK_OVERRIDE synchronously.`);
7651
5470
  return runWithSpanStack(newStack, async () => {
7652
5471
  const resolved = await resolveMockOrAbort(() => resolution);
7653
5472
  if (resolved.matched) {
@@ -7659,7 +5478,7 @@ var Bitfab = class {
7659
5478
  });
7660
5479
  return resolved.output;
7661
5480
  }
7662
- if (shouldMockWithBaseStrategy && !mockSpan) throw new BitfabError(`Replay selected span "${traceFunctionKey}:${baseSpanParams.spanName}" for mocking, but recorded occurrence ${callIndex + 1} is unavailable. The real span was not executed.`);
5481
+ if (shouldMockWithBaseStrategy && !mockSpan) throw new require_http.BitfabError(`Replay selected span "${traceFunctionKey}:${baseSpanParams.spanName}" for mocking, but recorded occurrence ${callIndex + 1} is unavailable. The real span was not executed.`);
7663
5482
  if (shouldMockWithBaseStrategy) {
7664
5483
  const output = await resolveMockOrAbort(() => resolveBaseOutput());
7665
5484
  sendSpan({
@@ -7675,7 +5494,7 @@ var Bitfab = class {
7675
5494
  }
7676
5495
  if (resolution.matched) return emitMock(resolution.output, "override");
7677
5496
  }
7678
- if (shouldMockWithBaseStrategy && !mockSpan) throw new BitfabError(`Replay selected span "${traceFunctionKey}:${baseSpanParams.spanName}" for mocking, but recorded occurrence ${callIndex + 1} is unavailable. The real span was not executed.`);
5497
+ if (shouldMockWithBaseStrategy && !mockSpan) throw new require_http.BitfabError(`Replay selected span "${traceFunctionKey}:${baseSpanParams.spanName}" for mocking, but recorded occurrence ${callIndex + 1} is unavailable. The real span was not executed.`);
7679
5498
  if (shouldMockWithBaseStrategy) {
7680
5499
  const recorded = resolveBaseOutput();
7681
5500
  if (recorded instanceof Promise) return emitMockAsync(recorded, "recorded");
@@ -7686,10 +5505,10 @@ var Bitfab = class {
7686
5505
  if (startedSpan) self.httpClient.traceCompletion.abort(startedSpan.traceId, startedSpan.spanId);
7687
5506
  if (registeredTraceId) {
7688
5507
  activeTraceStates.delete(registeredTraceId);
7689
- retireTraceMetadata(registeredTraceId);
5508
+ require_http.retireTraceMetadata(registeredTraceId);
7690
5509
  }
7691
- if (setupError instanceof MixedTracingError) throw setupError;
7692
- if (getReplayContext() || inSeedScope()) throw setupError;
5510
+ if (setupError instanceof require_http.MixedTracingError) throw setupError;
5511
+ if (require_http.getReplayContext() || inSeedScope()) throw setupError;
7693
5512
  require_autoTrace.warnOnce(`withSpan-setup:${traceFunctionKey}`, `tracing setup failed for "${traceFunctionKey}"; running it untraced. The function still runs and returns normally; no span is recorded.`);
7694
5513
  return fn.apply(this, args);
7695
5514
  }
@@ -7699,7 +5518,7 @@ var Bitfab = class {
7699
5518
  }
7700
5519
  span(traceFunctionKey, options = {}) {
7701
5520
  return (originalMethod, context) => {
7702
- if (context.kind !== "method") throw new BitfabError(`Bitfab span decorators can only decorate methods; ${String(context.name)} is a ${context.kind}`);
5521
+ if (context.kind !== "method") throw new require_http.BitfabError(`Bitfab span decorators can only decorate methods; ${String(context.name)} is a ${context.kind}`);
7703
5522
  return this.withSpan(traceFunctionKey, options, originalMethod);
7704
5523
  };
7705
5524
  }
@@ -7728,18 +5547,18 @@ var Bitfab = class {
7728
5547
  async getTraceSpan(traceId, lookup) {
7729
5548
  validateTraceId(traceId);
7730
5549
  const hasId = lookup.id !== void 0;
7731
- if (hasId === (lookup.name !== void 0 || lookup.type !== void 0)) throw new BitfabError("Provide id, or name and/or type");
5550
+ if (hasId === (lookup.name !== void 0 || lookup.type !== void 0)) throw new require_http.BitfabError("Provide id, or name and/or type");
7732
5551
  if (hasId) validateSpanId(lookup.id);
7733
5552
  else {
7734
- if (lookup.name !== void 0 && lookup.name.length === 0) throw new BitfabError("name must be a non-empty string");
7735
- if (lookup.type !== void 0 && !isSpanType(lookup.type)) throw new BitfabError(`type must be one of ${SPAN_TYPES.join(", ")}`);
5553
+ if (lookup.name !== void 0 && lookup.name.length === 0) throw new require_http.BitfabError("name must be a non-empty string");
5554
+ if (lookup.type !== void 0 && !isSpanType(lookup.type)) throw new require_http.BitfabError(`type must be one of ${require_http.SPAN_TYPES.join(", ")}`);
7736
5555
  const occurrence = lookup.occurrence ?? "last";
7737
- if (occurrence !== "first" && occurrence !== "last" && (!Number.isInteger(occurrence) || occurrence < 0)) throw new BitfabError("occurrence must be \"first\", \"last\", or a non-negative integer");
5556
+ if (occurrence !== "first" && occurrence !== "last" && (!Number.isInteger(occurrence) || occurrence < 0)) throw new require_http.BitfabError("occurrence must be \"first\", \"last\", or a non-negative integer");
7738
5557
  }
7739
5558
  return this.httpClient.getTraceSpan(traceId, lookup);
7740
5559
  }
7741
5560
  async getSpan(spanId) {
7742
- if (typeof spanId !== "string" || spanId.trim().length === 0) throw new BitfabError("spanId must be a non-empty string");
5561
+ if (typeof spanId !== "string" || spanId.trim().length === 0) throw new require_http.BitfabError("spanId must be a non-empty string");
7743
5562
  return this.httpClient.getSpan(spanId);
7744
5563
  }
7745
5564
  getFunction(traceFunctionKey) {
@@ -7781,11 +5600,11 @@ var Bitfab = class {
7781
5600
  completed: true,
7782
5601
  ...params.dropped && { dropped: true },
7783
5602
  ...params.sessionId && { sessionId: params.sessionId },
7784
- ...params.experimentId !== void 0 && experimentIdWireFields(params.experimentId)
5603
+ ...params.experimentId !== void 0 && require_http.experimentIdWireFields(params.experimentId)
7785
5604
  });
7786
5605
  }
7787
5606
  sendsSpanOnCompletion(context) {
7788
- return context.isRoot || context.declaredNode || isFrameworkInstrumentation(context.instrumentation) || !this.simulationPlan.contentOffNow(context.rootTraceFunctionKey, context.spanName);
5607
+ return context.isRoot || context.declaredNode || require_http.isFrameworkInstrumentation(context.instrumentation) || !this.simulationPlan.contentOffNow(context.rootTraceFunctionKey, context.spanName);
7789
5608
  }
7790
5609
  nearestCapturedAncestorSpanIdOf(stack) {
7791
5610
  for (let index = stack.length - 1; index >= 0; index -= 1) {
@@ -7795,7 +5614,7 @@ var Bitfab = class {
7795
5614
  return null;
7796
5615
  }
7797
5616
  contentOffBySimulationPlan(params) {
7798
- if (params.rootTraceFunctionKey === void 0 || isFrameworkInstrumentation(params.instrumentation)) return false;
5617
+ if (params.rootTraceFunctionKey === void 0 || require_http.isFrameworkInstrumentation(params.instrumentation)) return false;
7799
5618
  return this.simulationPlan.contentOffNow(params.rootTraceFunctionKey, params.spanName) || params.parentSpanId !== null && this.simulationPlan.unavailableNow();
7800
5619
  }
7801
5620
  sendWrapperSpan(params) {
@@ -7808,7 +5627,7 @@ var Bitfab = class {
7808
5627
  trace_id: params.traceId,
7809
5628
  started_at: params.startedAt,
7810
5629
  ended_at: params.endedAt,
7811
- span_origin: makeSpanOrigin(params.instrumentation),
5630
+ span_origin: require_http.makeSpanOrigin(params.instrumentation),
7812
5631
  span_data: {
7813
5632
  name: params.spanName,
7814
5633
  ...params.replayReusable !== void 0 && { replay_reusable: params.replayReusable },
@@ -7863,7 +5682,7 @@ var Bitfab = class {
7863
5682
  ...params.rootTraceFunctionKey !== void 0 && { ["rootTraceFunctionKey"]: params.rootTraceFunctionKey },
7864
5683
  ...params.declaredNode === true && { ["declaredNode"]: true },
7865
5684
  rawSpan: externalSpan,
7866
- ...params.experimentId !== void 0 && experimentIdWireFields(params.experimentId),
5685
+ ...params.experimentId !== void 0 && require_http.experimentIdWireFields(params.experimentId),
7867
5686
  ...params.mocked && { mocked: true },
7868
5687
  ...params.mockTarget && { mockTarget: params.mockTarget },
7869
5688
  ...params.mockSource && { mockSource: params.mockSource }
@@ -7873,7 +5692,7 @@ var Bitfab = class {
7873
5692
  let override;
7874
5693
  if (typeof overrideOrResolverOrMatch === "string") {
7875
5694
  const keyedOverride = values[0];
7876
- if (values.length !== 1 || keyedOverride === void 0) throw new BitfabError("registerMockOverride(traceFunctionKey, override) requires a resolver function or { match, value } override.");
5695
+ if (values.length !== 1 || keyedOverride === void 0) throw new require_http.BitfabError("registerMockOverride(traceFunctionKey, override) requires a resolver function or { match, value } override.");
7877
5696
  if (typeof keyedOverride === "function") override = {
7878
5697
  match: (node) => node.traceFunctionKey === overrideOrResolverOrMatch,
7879
5698
  value: keyedOverride
@@ -7882,7 +5701,7 @@ var Bitfab = class {
7882
5701
  match: (node) => node.traceFunctionKey === overrideOrResolverOrMatch && keyedOverride.match(node),
7883
5702
  value: keyedOverride.value
7884
5703
  };
7885
- else throw new BitfabError("registerMockOverride(traceFunctionKey, override) requires a resolver function or { match, value } override.");
5704
+ else throw new require_http.BitfabError("registerMockOverride(traceFunctionKey, override) requires a resolver function or { match, value } override.");
7886
5705
  } else if (typeof overrideOrResolverOrMatch !== "function") override = overrideOrResolverOrMatch;
7887
5706
  else if (values.length === 0) override = {
7888
5707
  match: () => true,
@@ -7904,10 +5723,10 @@ var Bitfab = class {
7904
5723
  seedTraceFromCase(traceFunctionKey, options) {
7905
5724
  const { input } = options;
7906
5725
  const fn = options.fn?._bitfabWrappedFn ?? options.fn;
7907
- if (fn && input.length < fn.length) throw new BitfabError(`Seeded case supplies ${input.length} argument(s) but ${fn.name === "" ? "the function" : fn.name} requires ${fn.length}. Fix the case, or omit fn to seed it anyway.`);
5726
+ if (fn && input.length < fn.length) throw new require_http.BitfabError(`Seeded case supplies ${input.length} argument(s) but ${fn.name === "" ? "the function" : fn.name} requires ${fn.length}. Fix the case, or omit fn to seed it anyway.`);
7908
5727
  const traceId = randomUuid();
7909
5728
  const startedAt = nowIsoTimestamp();
7910
- if (options.metadata !== void 0) recordCallerTraceMetadata(traceId, options.metadata);
5729
+ if (options.metadata !== void 0) require_http.recordCallerTraceMetadata(traceId, options.metadata);
7911
5730
  activeTraceStates.set(traceId, {
7912
5731
  traceId,
7913
5732
  traceFunctionKey,
@@ -7940,13 +5759,13 @@ var Bitfab = class {
7940
5759
  endedAt: startedAt,
7941
5760
  sessionId: options.sessionId,
7942
5761
  name: options.name,
7943
- metadata: callerTraceMetadata(traceId),
5762
+ metadata: require_http.callerTraceMetadata(traceId),
7944
5763
  contexts: [],
7945
5764
  ingestionType: "seeded"
7946
5765
  });
7947
5766
  } finally {
7948
5767
  activeTraceStates.delete(traceId);
7949
- retireTraceMetadata(traceId);
5768
+ require_http.retireTraceMetadata(traceId);
7950
5769
  }
7951
5770
  return traceId;
7952
5771
  }
@@ -7960,10 +5779,10 @@ var Bitfab = class {
7960
5779
  surface: "neutral"
7961
5780
  };
7962
5781
  target = this.withSpan(traceFunctionKey, seedRootOptions, fn);
7963
- } else if (wrappedKey !== traceFunctionKey) throw new BitfabError(`Function is wrapped with trace function key '${wrappedKey}' but seedTrace was called with '${traceFunctionKey}'. Pass matching keys, or pass the unwrapped function to seed it under the explicit key.`);
5782
+ } else if (wrappedKey !== traceFunctionKey) throw new require_http.BitfabError(`Function is wrapped with trace function key '${wrappedKey}' but seedTrace was called with '${traceFunctionKey}'. Pass matching keys, or pass the unwrapped function to seed it under the explicit key.`);
7964
5783
  await seedContextReady;
7965
5784
  const traceId = randomUuid();
7966
- if (options?.metadata !== void 0) recordCallerTraceMetadata(traceId, options.metadata);
5785
+ if (options?.metadata !== void 0) require_http.recordCallerTraceMetadata(traceId, options.metadata);
7967
5786
  activeTraceStates.set(traceId, {
7968
5787
  traceId,
7969
5788
  traceFunctionKey,
@@ -7979,19 +5798,19 @@ var Bitfab = class {
7979
5798
  await runWithSeedContext({ traceId }, async () => target(...args));
7980
5799
  } finally {
7981
5800
  try {
7982
- const { flushTraces } = await Promise.resolve().then(() => http_exports);
5801
+ const { flushTraces } = await Promise.resolve().then(() => require("./http-Cy8I9KDT.cjs")).then((n) => n.http_exports);
7983
5802
  await flushTraces(3e4);
7984
5803
  } finally {
7985
5804
  unrecorded = activeTraceStates.delete(traceId);
7986
- retireTraceMetadata(traceId);
5805
+ require_http.retireTraceMetadata(traceId);
7987
5806
  }
7988
5807
  }
7989
- if (unrecorded) throw new BitfabError(`seedTrace recorded nothing for '${traceFunctionKey}': the call finished without a root span. Check that an API key resolves (BITFAB_API_KEY or apiKey), and that fn is a regular or async function rather than a generator.`);
5808
+ if (unrecorded) throw new require_http.BitfabError(`seedTrace recorded nothing for '${traceFunctionKey}': the call finished without a root span. Check that an API key resolves (BITFAB_API_KEY or apiKey), and that fn is a regular or async function rather than a generator.`);
7990
5809
  return traceId;
7991
5810
  }
7992
5811
  async reseedTrace(traceFunctionKey, fn, options) {
7993
5812
  const source = await this.httpClient.getReseedSource(options.traceId);
7994
- if (source.traceFunctionKey !== traceFunctionKey) throw new BitfabError(`Trace ${options.traceId} belongs to '${source.traceFunctionKey}', not '${traceFunctionKey}'.`);
5813
+ if (source.traceFunctionKey !== traceFunctionKey) throw new require_http.BitfabError(`Trace ${options.traceId} belongs to '${source.traceFunctionKey}', not '${traceFunctionKey}'.`);
7995
5814
  const args = deserializeInputs({
7996
5815
  input: source.input,
7997
5816
  input_meta: source.inputMeta
@@ -8018,7 +5837,7 @@ var Bitfab = class {
8018
5837
  surface: "neutral"
8019
5838
  };
8020
5839
  replayFn = this.withSpan(traceFunctionKey, replayRootOptions, fn);
8021
- } else if (wrappedKey !== traceFunctionKey) throw new BitfabError(`Function is wrapped with trace function key '${wrappedKey}' but replay was called with '${traceFunctionKey}'. Pass matching keys, or pass the unwrapped function to replay it under the explicit key.`);
5840
+ } else if (wrappedKey !== traceFunctionKey) throw new require_http.BitfabError(`Function is wrapped with trace function key '${wrappedKey}' but replay was called with '${traceFunctionKey}'. Pass matching keys, or pass the unwrapped function to replay it under the explicit key.`);
8022
5841
  const { replay: doReplay } = await Promise.resolve().then(() => replay_exports);
8023
5842
  return doReplay(this.httpClient, this.serviceUrl, traceFunctionKey, replayFn, options, this.mockOverrides);
8024
5843
  }
@@ -8038,7 +5857,7 @@ var BitfabFunction = class {
8038
5857
  }
8039
5858
  withTrace(optionsOrFn, maybeFn) {
8040
5859
  if (typeof optionsOrFn === "function") return this.client.withTrace(this.traceFunctionKey, optionsOrFn);
8041
- if (!maybeFn) throw new BitfabError("BitfabFunction.withTrace requires a function");
5860
+ if (!maybeFn) throw new require_http.BitfabError("BitfabFunction.withTrace requires a function");
8042
5861
  return this.client.withTrace(this.traceFunctionKey, optionsOrFn, maybeFn);
8043
5862
  }
8044
5863
  trace(options = {}) {
@@ -8126,14 +5945,14 @@ const REGISTRATION_FIELDS = /* @__PURE__ */ new Set([
8126
5945
  ]);
8127
5946
  function validateReplayRegistry(registry) {
8128
5947
  for (const [pipeline, registration] of Object.entries(registry)) {
8129
- if (typeof registration !== "object" || registration === null) throw new BitfabError(`Replay registry entry '${pipeline}' must be an object with client and fn.`);
5948
+ if (typeof registration !== "object" || registration === null) throw new require_http.BitfabError(`Replay registry entry '${pipeline}' must be an object with client and fn.`);
8130
5949
  const unknownFields = Object.keys(registration).filter((field) => !REGISTRATION_FIELDS.has(field));
8131
5950
  if (unknownFields.length > 0) require_autoTrace.warnOnce(`replay-registry-unknown-fields:${pipeline}:${unknownFields.join(",")}`, `Replay registry entry '${pipeline}' has unknown field(s): ${unknownFields.join(", ")}. They are ignored. An entry takes client, fn, traceFunctionKey, options, and optionsFactory. Put replay options such as adaptInputs, mock, and mockOverride inside options. A later SDK release will reject unknown fields.`);
8132
5951
  }
8133
5952
  }
8134
5953
  async function reseedFromRegistry(registry, pipeline, traceIds) {
8135
5954
  const registration = registry[pipeline];
8136
- if (registration === void 0) throw new BitfabError(`Unknown pipeline '${pipeline}'. Registered: ${Object.keys(registry).join(", ")}`);
5955
+ if (registration === void 0) throw new require_http.BitfabError(`Unknown pipeline '${pipeline}'. Registered: ${Object.keys(registry).join(", ")}`);
8137
5956
  const traceFunctionKey = resolveTraceFunctionKey(registration);
8138
5957
  const reseeded = [];
8139
5958
  for (const traceId of traceIds) reseeded.push(await registration.client.reseedTrace(traceFunctionKey, registration.fn, { traceId }));
@@ -8145,7 +5964,7 @@ async function reseedFromRegistry(registry, pipeline, traceIds) {
8145
5964
  }
8146
5965
  async function seedFromRegistry(registry, pipeline, cases, options = {}) {
8147
5966
  const registration = registry[pipeline];
8148
- if (registration === void 0) throw new BitfabError(`Unknown pipeline '${pipeline}'. Registered: ${Object.keys(registry).join(", ")}`);
5967
+ if (registration === void 0) throw new require_http.BitfabError(`Unknown pipeline '${pipeline}'. Registered: ${Object.keys(registry).join(", ")}`);
8149
5968
  const traceFunctionKey = resolveTraceFunctionKey(registration);
8150
5969
  if (options.run === true) {
8151
5970
  const traceIds = [];
@@ -8167,7 +5986,7 @@ async function seedFromRegistry(registry, pipeline, cases, options = {}) {
8167
5986
  metadata: seedCase.metadata,
8168
5987
  sessionId: seedCase.sessionId
8169
5988
  }));
8170
- const { flushTraces } = await Promise.resolve().then(() => http_exports);
5989
+ const { flushTraces } = await Promise.resolve().then(() => require("./http-Cy8I9KDT.cjs")).then((n) => n.http_exports);
8171
5990
  await flushTraces(3e4);
8172
5991
  return {
8173
5992
  pipeline,
@@ -8178,7 +5997,7 @@ async function seedFromRegistry(registry, pipeline, cases, options = {}) {
8178
5997
  function resolveTraceFunctionKey(registration) {
8179
5998
  const wrappedKey = registration.fn._bitfabTraceFunctionKey;
8180
5999
  const key = registration.traceFunctionKey ?? wrappedKey;
8181
- if (key === void 0) throw new BitfabError("Replay registry entry uses a plain function. Set traceFunctionKey to the key its production handler records.");
6000
+ if (key === void 0) throw new require_http.BitfabError("Replay registry entry uses a plain function. Set traceFunctionKey to the key its production handler records.");
8182
6001
  return key;
8183
6002
  }
8184
6003
  //#endregion
@@ -8218,12 +6037,6 @@ Object.defineProperty(exports, "BitfabClaudeAgentHandler", {
8218
6037
  return BitfabClaudeAgentHandler;
8219
6038
  }
8220
6039
  });
8221
- Object.defineProperty(exports, "BitfabError", {
8222
- enumerable: true,
8223
- get: function() {
8224
- return BitfabError;
8225
- }
8226
- });
8227
6040
  Object.defineProperty(exports, "BitfabFunction", {
8228
6041
  enumerable: true,
8229
6042
  get: function() {
@@ -8314,24 +6127,12 @@ Object.defineProperty(exports, "GradersClient", {
8314
6127
  return GradersClient;
8315
6128
  }
8316
6129
  });
8317
- Object.defineProperty(exports, "HttpClient", {
8318
- enumerable: true,
8319
- get: function() {
8320
- return HttpClient;
8321
- }
8322
- });
8323
6130
  Object.defineProperty(exports, "LabelsClient", {
8324
6131
  enumerable: true,
8325
6132
  get: function() {
8326
6133
  return LabelsClient;
8327
6134
  }
8328
6135
  });
8329
- Object.defineProperty(exports, "MixedTracingError", {
8330
- enumerable: true,
8331
- get: function() {
8332
- return MixedTracingError;
8333
- }
8334
- });
8335
6136
  Object.defineProperty(exports, "NO_MOCK_OVERRIDE", {
8336
6137
  enumerable: true,
8337
6138
  get: function() {
@@ -8368,12 +6169,6 @@ Object.defineProperty(exports, "TracesClient", {
8368
6169
  return TracesClient;
8369
6170
  }
8370
6171
  });
8371
- Object.defineProperty(exports, "__version__", {
8372
- enumerable: true,
8373
- get: function() {
8374
- return __version__;
8375
- }
8376
- });
8377
6172
  Object.defineProperty(exports, "defineReplayRegistry", {
8378
6173
  enumerable: true,
8379
6174
  get: function() {
@@ -8386,12 +6181,6 @@ Object.defineProperty(exports, "finalizers", {
8386
6181
  return finalizers;
8387
6182
  }
8388
6183
  });
8389
- Object.defineProperty(exports, "flushTraces", {
8390
- enumerable: true,
8391
- get: function() {
8392
- return flushTraces;
8393
- }
8394
- });
8395
6184
  Object.defineProperty(exports, "getCurrentReplayBranch", {
8396
6185
  enumerable: true,
8397
6186
  get: function() {
@@ -8435,4 +6224,4 @@ Object.defineProperty(exports, "serializeReplayResult", {
8435
6224
  }
8436
6225
  });
8437
6226
 
8438
- //# sourceMappingURL=src-FFSCRXpz.cjs.map
6227
+ //# sourceMappingURL=src-gxbiiKid.cjs.map