@bitfab/sdk 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,25 +30,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
- // src/version.generated.ts
34
- var __version__;
35
- var init_version_generated = __esm({
36
- "src/version.generated.ts"() {
37
- "use strict";
38
- __version__ = "0.14.0";
39
- }
40
- });
41
-
42
- // src/constants.ts
43
- var DEFAULT_SERVICE_URL;
44
- var init_constants = __esm({
45
- "src/constants.ts"() {
46
- "use strict";
47
- init_version_generated();
48
- DEFAULT_SERVICE_URL = "https://bitfab.ai";
49
- }
50
- });
51
-
52
33
  // src/errors.ts
53
34
  var BitfabError;
54
35
  var init_errors = __esm({
@@ -64,343 +45,6 @@ var init_errors = __esm({
64
45
  }
65
46
  });
66
47
 
67
- // src/http.ts
68
- function awaitOnExit(promise) {
69
- pendingTracePromises.add(promise);
70
- void promise.finally(() => {
71
- pendingTracePromises.delete(promise);
72
- }).catch(() => {
73
- });
74
- return promise;
75
- }
76
- async function flushTraces(timeoutMs = 5e3) {
77
- if (pendingTracePromises.size === 0) {
78
- return;
79
- }
80
- await Promise.race([
81
- Promise.allSettled(Array.from(pendingTracePromises)),
82
- new Promise((resolve) => setTimeout(resolve, timeoutMs))
83
- ]);
84
- }
85
- var pendingTracePromises, HttpClient;
86
- var init_http = __esm({
87
- "src/http.ts"() {
88
- "use strict";
89
- init_constants();
90
- init_errors();
91
- pendingTracePromises = /* @__PURE__ */ new Set();
92
- if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
93
- let isFlushing = false;
94
- process.on("beforeExit", () => {
95
- if (pendingTracePromises.size > 0 && !isFlushing) {
96
- isFlushing = true;
97
- Promise.allSettled(
98
- Array.from(pendingTracePromises).map(
99
- (p) => p.catch(() => {
100
- })
101
- )
102
- ).then(() => {
103
- isFlushing = false;
104
- }).catch(() => {
105
- isFlushing = false;
106
- });
107
- }
108
- });
109
- }
110
- HttpClient = class {
111
- constructor(config) {
112
- this.apiKey = config.apiKey;
113
- this.serviceUrl = config.serviceUrl;
114
- this.timeout = config.timeout ?? 12e4;
115
- }
116
- /**
117
- * Make an HTTP request to the Bitfab API. Defaults to POST; pass
118
- * `options.method` to use a different verb (e.g. "PATCH").
119
- *
120
- * @param endpoint - The API endpoint (without base URL)
121
- * @param payload - The request body
122
- * @param options - Optional request options
123
- * @returns The parsed JSON response
124
- * @throws {BitfabError} If the request fails
125
- */
126
- async request(endpoint, payload, options) {
127
- const url = `${this.serviceUrl}${endpoint}`;
128
- const timeout = options?.timeout ?? this.timeout;
129
- const method = options?.method ?? "POST";
130
- const controller = new AbortController();
131
- const timeoutId = setTimeout(() => controller.abort(), timeout);
132
- let body;
133
- let serializationError;
134
- try {
135
- body = JSON.stringify(payload);
136
- } catch (error) {
137
- serializationError = error instanceof Error ? error.message : String(error);
138
- body = JSON.stringify({
139
- ...Object.fromEntries(
140
- Object.entries(payload).filter(
141
- ([, v]) => typeof v === "string" || typeof v === "number"
142
- )
143
- ),
144
- rawSpan: {},
145
- errors: [
146
- { source: "sdk", step: "json_serialize", error: serializationError }
147
- ]
148
- });
149
- }
150
- try {
151
- const response = await fetch(url, {
152
- method,
153
- headers: {
154
- "Content-Type": "application/json",
155
- Authorization: `Bearer ${this.apiKey}`
156
- },
157
- body,
158
- signal: controller.signal
159
- });
160
- if (!response.ok) {
161
- const errorText = await response.text();
162
- throw new BitfabError(
163
- `HTTP ${response.status}: ${errorText.slice(0, 500)}`
164
- );
165
- }
166
- const result = await response.json();
167
- if (result.error) {
168
- if (result.url) {
169
- throw new BitfabError(
170
- `${result.error} Configure it at: ${this.serviceUrl}${result.url}`,
171
- result.url
172
- );
173
- }
174
- throw new BitfabError(result.error);
175
- }
176
- return result;
177
- } catch (error) {
178
- if (error instanceof BitfabError) {
179
- throw error;
180
- }
181
- if (error instanceof Error) {
182
- if (error.name === "AbortError") {
183
- throw new BitfabError(`Request timed out after ${timeout}ms`);
184
- }
185
- throw new BitfabError(error.message);
186
- }
187
- throw new BitfabError("Unknown error occurred");
188
- } finally {
189
- clearTimeout(timeoutId);
190
- }
191
- }
192
- /**
193
- * Look up a function by name.
194
- * Blocks until complete - needed for function execution.
195
- */
196
- async lookupFunction(name) {
197
- return this.request("/api/sdk/functions/lookup", { name });
198
- }
199
- /**
200
- * Send an internal trace (from BAML execution).
201
- * Fire-and-forget with awaitOnExit - doesn't block the caller.
202
- */
203
- sendInternalTrace(functionId, payload) {
204
- void awaitOnExit(
205
- this.request(`/api/sdk/functions/${functionId}/traces`, {
206
- ...payload,
207
- sdkVersion: __version__
208
- })
209
- ).catch((error) => {
210
- try {
211
- console.error("Bitfab: Failed to create trace:", error);
212
- } catch {
213
- }
214
- });
215
- }
216
- /**
217
- * Send an external span (from withSpan wrapper or OpenAI tracing).
218
- * Fire-and-forget with awaitOnExit - doesn't block the caller.
219
- * Returns the tracked promise so callers can optionally await it.
220
- */
221
- sendExternalSpan(payload) {
222
- return awaitOnExit(
223
- this.request("/api/sdk/externalSpans", {
224
- ...payload,
225
- sdkVersion: __version__
226
- })
227
- ).catch((error) => {
228
- try {
229
- console.error("Bitfab: Failed to create external span:", error);
230
- } catch {
231
- }
232
- });
233
- }
234
- /**
235
- * Send an external trace (from OpenAI tracing).
236
- * Fire-and-forget with awaitOnExit - doesn't block the caller.
237
- */
238
- sendExternalTrace(payload) {
239
- void awaitOnExit(
240
- this.request("/api/sdk/externalTraces", {
241
- ...payload,
242
- sdkVersion: __version__
243
- })
244
- ).catch((error) => {
245
- try {
246
- console.error("Bitfab: Failed to create external trace:", error);
247
- } catch {
248
- }
249
- });
250
- }
251
- /**
252
- * Partial update of an existing external trace identified by sourceTraceId.
253
- * Used by the detached `client.getTrace(id)` handle. Fire-and-forget;
254
- * returns a tracked promise that callers may optionally await.
255
- */
256
- patchTrace(sourceTraceId, payload) {
257
- const endpoint = `/api/sdk/externalTraces/${encodeURIComponent(sourceTraceId)}`;
258
- return awaitOnExit(
259
- this.request(endpoint, payload, { method: "PATCH" })
260
- ).catch((error) => {
261
- try {
262
- console.error("Bitfab: Failed to patch trace:", error);
263
- } catch {
264
- }
265
- });
266
- }
267
- /**
268
- * Start a replay session by fetching historical traces.
269
- * Blocking call — creates a test run and returns lightweight item references.
270
- */
271
- async startReplay(traceFunctionKey, limit, traceIds, codeChangeDescription, codeChangeFiles, includeDbBranchLease, experimentGroupId) {
272
- const payload = { traceFunctionKey };
273
- if (limit !== void 0) {
274
- payload.limit = limit;
275
- }
276
- if (traceIds) {
277
- payload.traceIds = traceIds;
278
- }
279
- if (codeChangeDescription !== void 0) {
280
- payload.codeChangeDescription = codeChangeDescription;
281
- }
282
- if (codeChangeFiles !== void 0) {
283
- payload.codeChangeFiles = codeChangeFiles;
284
- }
285
- if (includeDbBranchLease) {
286
- payload.includeDbBranchLease = true;
287
- }
288
- if (experimentGroupId !== void 0) {
289
- payload.experimentGroupId = experimentGroupId;
290
- }
291
- const timeout = includeDbBranchLease ? 18e4 : 3e4;
292
- return this.request("/api/sdk/replay/start", payload, {
293
- timeout
294
- });
295
- }
296
- /**
297
- * Fetch an external span by ID.
298
- * Blocking GET request.
299
- */
300
- async getExternalSpan(spanId) {
301
- const url = `${this.serviceUrl}/api/sdk/externalSpans/${spanId}`;
302
- const controller = new AbortController();
303
- const timeoutId = setTimeout(() => controller.abort(), 3e4);
304
- try {
305
- const response = await fetch(url, {
306
- method: "GET",
307
- headers: { Authorization: `Bearer ${this.apiKey}` },
308
- signal: controller.signal
309
- });
310
- if (!response.ok) {
311
- const errorText = await response.text();
312
- throw new BitfabError(
313
- `HTTP ${response.status}: ${errorText.slice(0, 500)}`
314
- );
315
- }
316
- return await response.json();
317
- } catch (error) {
318
- if (error instanceof BitfabError) {
319
- throw error;
320
- }
321
- if (error instanceof Error) {
322
- if (error.name === "AbortError") {
323
- throw new BitfabError("Request timed out after 30000ms");
324
- }
325
- throw new BitfabError(error.message);
326
- }
327
- throw new BitfabError("Unknown error occurred");
328
- } finally {
329
- clearTimeout(timeoutId);
330
- }
331
- }
332
- /**
333
- * Fetch the span tree for a root span.
334
- * Blocking GET request.
335
- */
336
- async getSpanTree(externalSpanId) {
337
- const url = `${this.serviceUrl}/api/sdk/replay/spanTree/${externalSpanId}`;
338
- const controller = new AbortController();
339
- const timeoutId = setTimeout(() => controller.abort(), 3e4);
340
- try {
341
- const response = await fetch(url, {
342
- method: "GET",
343
- headers: { Authorization: `Bearer ${this.apiKey}` },
344
- signal: controller.signal
345
- });
346
- if (!response.ok) {
347
- const errorText = await response.text();
348
- throw new BitfabError(
349
- `HTTP ${response.status}: ${errorText.slice(0, 500)}`
350
- );
351
- }
352
- return await response.json();
353
- } catch (error) {
354
- if (error instanceof BitfabError) {
355
- throw error;
356
- }
357
- if (error instanceof Error) {
358
- if (error.name === "AbortError") {
359
- throw new BitfabError("Request timed out after 30000ms");
360
- }
361
- throw new BitfabError(error.message);
362
- }
363
- throw new BitfabError("Unknown error occurred");
364
- } finally {
365
- clearTimeout(timeoutId);
366
- }
367
- }
368
- /**
369
- * Mark a replay test run as completed.
370
- * Blocking call.
371
- */
372
- async completeReplay(testRunId) {
373
- return this.request(
374
- "/api/sdk/replay/complete",
375
- { testRunId },
376
- { timeout: 3e4 }
377
- );
378
- }
379
- /**
380
- * Ask the server to materialize a per-trace DB branch lease from a
381
- * captured `dbSnapshotRef`. Blocking — the resolver creates a Neon
382
- * snapshot + preview branch and polls operations to readiness, which
383
- * can take seconds.
384
- */
385
- async resolveDbBranchLease(testRunId, traceId, dbSnapshotRef) {
386
- return this.request(
387
- "/api/sdk/replay/resolveDbBranchLease",
388
- { testRunId, traceId, dbSnapshotRef },
389
- { timeout: 9e4 }
390
- );
391
- }
392
- /** Release a previously-resolved DB branch by deleting its Neon branch. Idempotent server-side. */
393
- async releaseDbBranchLease(neonBranchId) {
394
- await this.request(
395
- "/api/sdk/replay/releaseDbBranchLease",
396
- { neonBranchId },
397
- { timeout: 3e4 }
398
- );
399
- }
400
- };
401
- }
402
- });
403
-
404
48
  // src/asyncStorage.ts
405
49
  function registerAsyncLocalStorageClass(cls) {
406
50
  if (!AsyncLocalStorageClass) {
@@ -574,18 +218,25 @@ function buildMockTree(rootNode) {
574
218
  }
575
219
  return { spans };
576
220
  }
577
- async function processItem(httpClient, serverItem, fn, testRunId, mockStrategy, environment) {
221
+ async function processItem(httpClient, serverItem, fn, testRunId, mockStrategy, environment, adaptInputs) {
578
222
  const lease = environment ? serverItem.dbBranchLease : void 0;
579
223
  let inputs = [];
580
224
  let originalOutput;
581
225
  let result;
582
226
  let error = null;
583
227
  const replayedTraceId = crypto.randomUUID();
228
+ const pendingPersistence = [];
584
229
  try {
585
230
  const span = await httpClient.getExternalSpan(serverItem.externalSpanId);
586
231
  const spanData = span.rawData?.span_data ?? {};
587
232
  inputs = deserializeInputs(spanData);
588
233
  originalOutput = deserializeOutput(spanData);
234
+ if (adaptInputs) {
235
+ inputs = adaptInputs(inputs, {
236
+ traceId: serverItem.traceId,
237
+ sourceSpanId: serverItem.externalSpanId
238
+ });
239
+ }
589
240
  let mockTree;
590
241
  if (mockStrategy === "all" || mockStrategy === "marked") {
591
242
  const treeResponse = await httpClient.getSpanTree(
@@ -603,7 +254,8 @@ async function processItem(httpClient, serverItem, fn, testRunId, mockStrategy,
603
254
  mockTree,
604
255
  callCounters: mockTree ? /* @__PURE__ */ new Map() : void 0,
605
256
  mockStrategy,
606
- dbBranchLease: lease
257
+ dbBranchLease: lease,
258
+ pendingPersistence
607
259
  },
608
260
  () => fn(...inputs)
609
261
  );
@@ -611,6 +263,7 @@ async function processItem(httpClient, serverItem, fn, testRunId, mockStrategy,
611
263
  } catch (e) {
612
264
  error = e instanceof Error ? e.message : String(e);
613
265
  } finally {
266
+ await Promise.allSettled(pendingPersistence);
614
267
  if (lease) {
615
268
  try {
616
269
  await httpClient.releaseDbBranchLease(lease.neonBranchId);
@@ -694,24 +347,51 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options) {
694
347
  fn,
695
348
  testRunId,
696
349
  mockStrategy,
697
- options?.environment
350
+ options?.environment,
351
+ options?.adaptInputs
698
352
  )
699
353
  );
700
354
  const resultItems = await mapWithConcurrency(tasks, maxConcurrency);
701
- await flushTraces();
702
- let serverTraceIds = {};
703
- try {
704
- const completeResult = await httpClient.completeReplay(testRunId);
705
- serverTraceIds = completeResult.traceIds ?? {};
706
- } catch (e) {
355
+ const completeResult = await httpClient.completeReplay(testRunId);
356
+ const serverTraceIds = completeResult.traceIds;
357
+ if (serverTraceIds === void 0) {
707
358
  try {
708
- console.error("Bitfab: Failed to complete replay:", e);
359
+ console.warn(
360
+ "Bitfab: server did not return replay trace IDs; item.traceId will be null (server upgrade required for verdict persistence)"
361
+ );
709
362
  } catch {
710
363
  }
711
- }
712
- for (const item of resultItems) {
713
- if (item.traceId) {
714
- item.traceId = serverTraceIds[item.traceId] ?? null;
364
+ for (const item of resultItems) {
365
+ item.traceId = null;
366
+ }
367
+ } else {
368
+ const missing = [];
369
+ let completedCount = 0;
370
+ for (const item of resultItems) {
371
+ if (item.traceId) {
372
+ const mapped = serverTraceIds[item.traceId];
373
+ if (item.error === null) {
374
+ completedCount += 1;
375
+ if (mapped === void 0) {
376
+ missing.push(item.traceId);
377
+ }
378
+ }
379
+ item.traceId = mapped ?? null;
380
+ }
381
+ }
382
+ if (missing.length > 0) {
383
+ const serverCount = completeResult.traceCount !== void 0 ? ` The server persisted ${completeResult.traceCount} trace(s) for this run.` : "";
384
+ if (missing.length === completedCount) {
385
+ throw new BitfabError(
386
+ `Replay completed but the server has no persisted trace for any of the ${completedCount} completed item(s) (testRunId ${testRunId}).${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.`
387
+ );
388
+ }
389
+ try {
390
+ console.error(
391
+ `Bitfab: server has no persisted trace for ${missing.length} of ${completedCount} completed replay item(s) (testRunId ${testRunId}).${serverCount} Their traceId is null and verdicts cannot be persisted for them. Missing: ${missing.join(", ")}`
392
+ );
393
+ } catch {
394
+ }
715
395
  }
716
396
  }
717
397
  return {
@@ -724,7 +404,6 @@ var init_replay = __esm({
724
404
  "src/replay.ts"() {
725
405
  "use strict";
726
406
  init_errors();
727
- init_http();
728
407
  init_replayContext();
729
408
  init_serialize();
730
409
  }
@@ -749,9 +428,346 @@ __export(index_exports, {
749
428
  });
750
429
  module.exports = __toCommonJS(index_exports);
751
430
 
431
+ // src/version.generated.ts
432
+ var __version__ = "0.16.0";
433
+
434
+ // src/constants.ts
435
+ var DEFAULT_SERVICE_URL = "https://bitfab.ai";
436
+
437
+ // src/http.ts
438
+ init_errors();
439
+ var pendingTracePromises = /* @__PURE__ */ new Set();
440
+ function awaitOnExit(promise) {
441
+ pendingTracePromises.add(promise);
442
+ void promise.finally(() => {
443
+ pendingTracePromises.delete(promise);
444
+ }).catch(() => {
445
+ });
446
+ return promise;
447
+ }
448
+ async function flushTraces(timeoutMs = 5e3) {
449
+ if (pendingTracePromises.size === 0) {
450
+ return;
451
+ }
452
+ await Promise.race([
453
+ Promise.allSettled(Array.from(pendingTracePromises)),
454
+ new Promise((resolve) => setTimeout(resolve, timeoutMs))
455
+ ]);
456
+ }
457
+ if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
458
+ let isFlushing = false;
459
+ process.on("beforeExit", () => {
460
+ if (pendingTracePromises.size > 0 && !isFlushing) {
461
+ isFlushing = true;
462
+ Promise.allSettled(
463
+ Array.from(pendingTracePromises).map(
464
+ (p) => p.catch(() => {
465
+ })
466
+ )
467
+ ).then(() => {
468
+ isFlushing = false;
469
+ }).catch(() => {
470
+ isFlushing = false;
471
+ });
472
+ }
473
+ });
474
+ }
475
+ var HttpClient = class {
476
+ constructor(config) {
477
+ this.apiKey = config.apiKey;
478
+ this.serviceUrl = config.serviceUrl;
479
+ this.timeout = config.timeout ?? 12e4;
480
+ }
481
+ /**
482
+ * Make an HTTP request to the Bitfab API. Defaults to POST; pass
483
+ * `options.method` to use a different verb (e.g. "PATCH").
484
+ *
485
+ * @param endpoint - The API endpoint (without base URL)
486
+ * @param payload - The request body
487
+ * @param options - Optional request options
488
+ * @returns The parsed JSON response
489
+ * @throws {BitfabError} If the request fails
490
+ */
491
+ async request(endpoint, payload, options) {
492
+ const url = `${this.serviceUrl}${endpoint}`;
493
+ const timeout = options?.timeout ?? this.timeout;
494
+ const method = options?.method ?? "POST";
495
+ const controller = new AbortController();
496
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
497
+ let body;
498
+ let serializationError;
499
+ try {
500
+ body = JSON.stringify(payload);
501
+ } catch (error) {
502
+ serializationError = error instanceof Error ? error.message : String(error);
503
+ body = JSON.stringify({
504
+ ...Object.fromEntries(
505
+ Object.entries(payload).filter(
506
+ ([, v]) => typeof v === "string" || typeof v === "number"
507
+ )
508
+ ),
509
+ rawSpan: {},
510
+ errors: [
511
+ { source: "sdk", step: "json_serialize", error: serializationError }
512
+ ]
513
+ });
514
+ }
515
+ try {
516
+ const response = await fetch(url, {
517
+ method,
518
+ headers: {
519
+ "Content-Type": "application/json",
520
+ Authorization: `Bearer ${this.apiKey}`
521
+ },
522
+ body,
523
+ signal: controller.signal
524
+ });
525
+ if (!response.ok) {
526
+ const errorText = await response.text();
527
+ throw new BitfabError(
528
+ `HTTP ${response.status}: ${errorText.slice(0, 500)}`
529
+ );
530
+ }
531
+ const result = await response.json();
532
+ if (result.error) {
533
+ if (result.url) {
534
+ throw new BitfabError(
535
+ `${result.error} Configure it at: ${this.serviceUrl}${result.url}`,
536
+ result.url
537
+ );
538
+ }
539
+ throw new BitfabError(result.error);
540
+ }
541
+ return result;
542
+ } catch (error) {
543
+ if (error instanceof BitfabError) {
544
+ throw error;
545
+ }
546
+ if (error instanceof Error) {
547
+ if (error.name === "AbortError") {
548
+ throw new BitfabError(`Request timed out after ${timeout}ms`);
549
+ }
550
+ throw new BitfabError(error.message);
551
+ }
552
+ throw new BitfabError("Unknown error occurred");
553
+ } finally {
554
+ clearTimeout(timeoutId);
555
+ }
556
+ }
557
+ /**
558
+ * Look up a function by name.
559
+ * Blocks until complete - needed for function execution.
560
+ */
561
+ async lookupFunction(name) {
562
+ return this.request("/api/sdk/functions/lookup", { name });
563
+ }
564
+ /**
565
+ * Send an internal trace (from BAML execution).
566
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
567
+ */
568
+ sendInternalTrace(functionId, payload) {
569
+ void awaitOnExit(
570
+ this.request(`/api/sdk/functions/${functionId}/traces`, {
571
+ ...payload,
572
+ sdkVersion: __version__
573
+ })
574
+ ).catch((error) => {
575
+ try {
576
+ console.error("Bitfab: Failed to create trace:", error);
577
+ } catch {
578
+ }
579
+ });
580
+ }
581
+ /**
582
+ * Send an external span (from withSpan wrapper or OpenAI tracing).
583
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
584
+ * Returns the tracked promise so callers can optionally await it.
585
+ */
586
+ sendExternalSpan(payload) {
587
+ return awaitOnExit(
588
+ this.request("/api/sdk/externalSpans", {
589
+ ...payload,
590
+ sdkVersion: __version__
591
+ })
592
+ ).catch((error) => {
593
+ try {
594
+ console.error("Bitfab: Failed to create external span:", error);
595
+ } catch {
596
+ }
597
+ });
598
+ }
599
+ /**
600
+ * Send an external trace (from OpenAI tracing).
601
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
602
+ * Returns the tracked promise so callers can optionally await it
603
+ * (the replay path does, so trace completions are persisted before
604
+ * `completeReplay` builds the trace-ID mapping).
605
+ */
606
+ sendExternalTrace(payload) {
607
+ return awaitOnExit(
608
+ this.request("/api/sdk/externalTraces", {
609
+ ...payload,
610
+ sdkVersion: __version__
611
+ })
612
+ ).catch((error) => {
613
+ try {
614
+ console.error("Bitfab: Failed to create external trace:", error);
615
+ } catch {
616
+ }
617
+ });
618
+ }
619
+ /**
620
+ * Partial update of an existing external trace identified by sourceTraceId.
621
+ * Used by the detached `client.getTrace(id)` handle. Fire-and-forget;
622
+ * returns a tracked promise that callers may optionally await.
623
+ */
624
+ patchTrace(sourceTraceId, payload) {
625
+ const endpoint = `/api/sdk/externalTraces/${encodeURIComponent(sourceTraceId)}`;
626
+ return awaitOnExit(
627
+ this.request(endpoint, payload, { method: "PATCH" })
628
+ ).catch((error) => {
629
+ try {
630
+ console.error("Bitfab: Failed to patch trace:", error);
631
+ } catch {
632
+ }
633
+ });
634
+ }
635
+ /**
636
+ * Start a replay session by fetching historical traces.
637
+ * Blocking call — creates a test run and returns lightweight item references.
638
+ */
639
+ async startReplay(traceFunctionKey, limit, traceIds, codeChangeDescription, codeChangeFiles, includeDbBranchLease, experimentGroupId) {
640
+ const payload = { traceFunctionKey };
641
+ if (limit !== void 0) {
642
+ payload.limit = limit;
643
+ }
644
+ if (traceIds) {
645
+ payload.traceIds = traceIds;
646
+ }
647
+ if (codeChangeDescription !== void 0) {
648
+ payload.codeChangeDescription = codeChangeDescription;
649
+ }
650
+ if (codeChangeFiles !== void 0) {
651
+ payload.codeChangeFiles = codeChangeFiles;
652
+ }
653
+ if (includeDbBranchLease) {
654
+ payload.includeDbBranchLease = true;
655
+ }
656
+ if (experimentGroupId !== void 0) {
657
+ payload.experimentGroupId = experimentGroupId;
658
+ }
659
+ const timeout = includeDbBranchLease ? 18e4 : 3e4;
660
+ return this.request("/api/sdk/replay/start", payload, {
661
+ timeout
662
+ });
663
+ }
664
+ /**
665
+ * Fetch an external span by ID.
666
+ * Blocking GET request.
667
+ */
668
+ async getExternalSpan(spanId) {
669
+ const url = `${this.serviceUrl}/api/sdk/externalSpans/${spanId}`;
670
+ const controller = new AbortController();
671
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
672
+ try {
673
+ const response = await fetch(url, {
674
+ method: "GET",
675
+ headers: { Authorization: `Bearer ${this.apiKey}` },
676
+ signal: controller.signal
677
+ });
678
+ if (!response.ok) {
679
+ const errorText = await response.text();
680
+ throw new BitfabError(
681
+ `HTTP ${response.status}: ${errorText.slice(0, 500)}`
682
+ );
683
+ }
684
+ return await response.json();
685
+ } catch (error) {
686
+ if (error instanceof BitfabError) {
687
+ throw error;
688
+ }
689
+ if (error instanceof Error) {
690
+ if (error.name === "AbortError") {
691
+ throw new BitfabError("Request timed out after 30000ms");
692
+ }
693
+ throw new BitfabError(error.message);
694
+ }
695
+ throw new BitfabError("Unknown error occurred");
696
+ } finally {
697
+ clearTimeout(timeoutId);
698
+ }
699
+ }
700
+ /**
701
+ * Fetch the span tree for a root span.
702
+ * Blocking GET request.
703
+ */
704
+ async getSpanTree(externalSpanId) {
705
+ const url = `${this.serviceUrl}/api/sdk/replay/spanTree/${externalSpanId}`;
706
+ const controller = new AbortController();
707
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
708
+ try {
709
+ const response = await fetch(url, {
710
+ method: "GET",
711
+ headers: { Authorization: `Bearer ${this.apiKey}` },
712
+ signal: controller.signal
713
+ });
714
+ if (!response.ok) {
715
+ const errorText = await response.text();
716
+ throw new BitfabError(
717
+ `HTTP ${response.status}: ${errorText.slice(0, 500)}`
718
+ );
719
+ }
720
+ return await response.json();
721
+ } catch (error) {
722
+ if (error instanceof BitfabError) {
723
+ throw error;
724
+ }
725
+ if (error instanceof Error) {
726
+ if (error.name === "AbortError") {
727
+ throw new BitfabError("Request timed out after 30000ms");
728
+ }
729
+ throw new BitfabError(error.message);
730
+ }
731
+ throw new BitfabError("Unknown error occurred");
732
+ } finally {
733
+ clearTimeout(timeoutId);
734
+ }
735
+ }
736
+ /**
737
+ * Mark a replay test run as completed.
738
+ * Blocking call.
739
+ */
740
+ async completeReplay(testRunId) {
741
+ return this.request(
742
+ "/api/sdk/replay/complete",
743
+ { testRunId },
744
+ { timeout: 3e4 }
745
+ );
746
+ }
747
+ /**
748
+ * Ask the server to materialize a per-trace DB branch lease from a
749
+ * captured `dbSnapshotRef`. Blocking — the resolver creates a Neon
750
+ * snapshot + preview branch and polls operations to readiness, which
751
+ * can take seconds.
752
+ */
753
+ async resolveDbBranchLease(testRunId, traceId, dbSnapshotRef) {
754
+ return this.request(
755
+ "/api/sdk/replay/resolveDbBranchLease",
756
+ { testRunId, traceId, dbSnapshotRef },
757
+ { timeout: 9e4 }
758
+ );
759
+ }
760
+ /** Release a previously-resolved DB branch by deleting its Neon branch. Idempotent server-side. */
761
+ async releaseDbBranchLease(neonBranchId) {
762
+ await this.request(
763
+ "/api/sdk/replay/releaseDbBranchLease",
764
+ { neonBranchId },
765
+ { timeout: 3e4 }
766
+ );
767
+ }
768
+ };
769
+
752
770
  // src/claudeAgentSdk.ts
753
- init_constants();
754
- init_http();
755
771
  function nowIso() {
756
772
  return (/* @__PURE__ */ new Date()).toISOString();
757
773
  }
@@ -1516,9 +1532,6 @@ async function runFunctionWithBaml(bamlSource, inputs, providers, envVars) {
1516
1532
  };
1517
1533
  }
1518
1534
 
1519
- // src/client.ts
1520
- init_constants();
1521
-
1522
1535
  // src/dbSnapshot.ts
1523
1536
  init_errors();
1524
1537
  var SUPPORTED_PROVIDERS = ["neon"];
@@ -1536,12 +1549,7 @@ function buildSnapshotRef(config, sdkWallClockBeforeFn) {
1536
1549
  };
1537
1550
  }
1538
1551
 
1539
- // src/client.ts
1540
- init_http();
1541
-
1542
1552
  // src/langgraph.ts
1543
- init_constants();
1544
- init_http();
1545
1553
  var LANGSMITH_HIDDEN_TAG = "langsmith:hidden";
1546
1554
  var LANGGRAPH_METADATA_KEYS = [
1547
1555
  "langgraph_step",
@@ -2089,8 +2097,6 @@ var ReplayEnvironment = class {
2089
2097
  init_serialize();
2090
2098
 
2091
2099
  // src/tracing.ts
2092
- init_constants();
2093
- init_http();
2094
2100
  var BitfabOpenAITracingProcessor = class {
2095
2101
  /**
2096
2102
  * Initialize the tracing processor.
@@ -2924,9 +2930,18 @@ var Bitfab = class {
2924
2930
  spanType: options.type ?? "custom"
2925
2931
  };
2926
2932
  const sendSpan = async (params) => {
2933
+ const replayCtx = getReplayContext();
2934
+ const persistenceCollector = isRootSpan ? replayCtx?.pendingPersistence : void 0;
2935
+ let resolvePersistence;
2936
+ if (persistenceCollector) {
2937
+ persistenceCollector.push(
2938
+ new Promise((resolve) => {
2939
+ resolvePersistence = resolve;
2940
+ })
2941
+ );
2942
+ }
2927
2943
  try {
2928
2944
  const endedAt = (/* @__PURE__ */ new Date()).toISOString();
2929
- const replayCtx = getReplayContext();
2930
2945
  const spanPromise = self.sendWrapperSpan({
2931
2946
  ...baseSpanParams,
2932
2947
  ...params,
@@ -2941,13 +2956,17 @@ var Bitfab = class {
2941
2956
  if (isRootSpan) {
2942
2957
  const pending = pendingSpanPromises.get(traceId) ?? [];
2943
2958
  pending.push(spanPromise);
2944
- await Promise.race([
2945
- Promise.allSettled(pending),
2946
- new Promise((resolve) => setTimeout(resolve, 5e3))
2947
- ]);
2959
+ if (persistenceCollector) {
2960
+ await Promise.allSettled(pending);
2961
+ } else {
2962
+ await Promise.race([
2963
+ Promise.allSettled(pending),
2964
+ new Promise((resolve) => setTimeout(resolve, 5e3))
2965
+ ]);
2966
+ }
2948
2967
  pendingSpanPromises.delete(traceId);
2949
2968
  const traceState = activeTraceStates.get(traceId);
2950
- self.sendTraceCompletion({
2969
+ const completionPromise = self.sendTraceCompletion({
2951
2970
  traceFunctionKey,
2952
2971
  traceId,
2953
2972
  startedAt: traceState?.startedAt ?? startedAt,
@@ -2960,6 +2979,9 @@ var Bitfab = class {
2960
2979
  dbSnapshotRef: traceState?.dbSnapshotRef
2961
2980
  });
2962
2981
  activeTraceStates.delete(traceId);
2982
+ if (persistenceCollector) {
2983
+ await completionPromise;
2984
+ }
2963
2985
  } else {
2964
2986
  const pending = pendingSpanPromises.get(traceId);
2965
2987
  if (pending) {
@@ -2969,6 +2991,8 @@ var Bitfab = class {
2969
2991
  }
2970
2992
  }
2971
2993
  } catch {
2994
+ } finally {
2995
+ resolvePersistence?.();
2972
2996
  }
2973
2997
  };
2974
2998
  const replayCtxForMock = getReplayContext();
@@ -3121,7 +3145,7 @@ var Bitfab = class {
3121
3145
  if (params.dbSnapshotRef) {
3122
3146
  rawTrace.db_snapshot_ref = params.dbSnapshotRef;
3123
3147
  }
3124
- this.httpClient.sendExternalTrace({
3148
+ return this.httpClient.sendExternalTrace({
3125
3149
  type: "sdk-function",
3126
3150
  source: "typescript-sdk-function",
3127
3151
  traceFunctionKey: params.traceFunctionKey,
@@ -3265,10 +3289,6 @@ var BitfabFunction = class {
3265
3289
  );
3266
3290
  }
3267
3291
  };
3268
-
3269
- // src/index.ts
3270
- init_constants();
3271
- init_http();
3272
3292
  // Annotate the CommonJS export names for ESM import in node:
3273
3293
  0 && (module.exports = {
3274
3294
  Bitfab,