bitfab 0.9.2

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 ADDED
@@ -0,0 +1,1731 @@
1
+ "use strict";
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 __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/asyncStorage.ts
34
+ function registerAsyncLocalStorageClass(cls) {
35
+ if (!AsyncLocalStorageClass) {
36
+ AsyncLocalStorageClass = cls;
37
+ }
38
+ initDone = true;
39
+ }
40
+ function isAsyncStorageInitDone() {
41
+ return initDone;
42
+ }
43
+ function createAsyncLocalStorage() {
44
+ return AsyncLocalStorageClass ? new AsyncLocalStorageClass() : null;
45
+ }
46
+ var AsyncLocalStorageClass, initDone, asyncStorageReady;
47
+ var init_asyncStorage = __esm({
48
+ "src/asyncStorage.ts"() {
49
+ "use strict";
50
+ AsyncLocalStorageClass = null;
51
+ initDone = false;
52
+ asyncStorageReady = (typeof process !== "undefined" && process.versions?.node ? (
53
+ // The join trick hides "node:async_hooks" from static analysis so
54
+ // bundlers that ban Node.js built-ins don't fail at build time.
55
+ // webpackIgnore tells webpack/turbopack to emit a native import()
56
+ // so Node.js can resolve the module at runtime.
57
+ import(
58
+ /* webpackIgnore: true */
59
+ ["node", "async_hooks"].join(":")
60
+ ).then(
61
+ (mod) => {
62
+ registerAsyncLocalStorageClass(mod.AsyncLocalStorage);
63
+ }
64
+ ).catch(() => {
65
+ })
66
+ ) : Promise.resolve()).then(() => {
67
+ initDone = true;
68
+ });
69
+ }
70
+ });
71
+
72
+ // src/version.generated.ts
73
+ var __version__;
74
+ var init_version_generated = __esm({
75
+ "src/version.generated.ts"() {
76
+ "use strict";
77
+ __version__ = "0.9.2";
78
+ }
79
+ });
80
+
81
+ // src/constants.ts
82
+ var DEFAULT_SERVICE_URL;
83
+ var init_constants = __esm({
84
+ "src/constants.ts"() {
85
+ "use strict";
86
+ init_version_generated();
87
+ DEFAULT_SERVICE_URL = "https://bitfab.ai";
88
+ }
89
+ });
90
+
91
+ // src/http.ts
92
+ function awaitOnExit(promise) {
93
+ pendingTracePromises.add(promise);
94
+ void promise.finally(() => {
95
+ pendingTracePromises.delete(promise);
96
+ }).catch(() => {
97
+ });
98
+ return promise;
99
+ }
100
+ async function flushTraces(timeoutMs = 5e3) {
101
+ if (pendingTracePromises.size === 0) {
102
+ return;
103
+ }
104
+ await Promise.race([
105
+ Promise.allSettled(Array.from(pendingTracePromises)),
106
+ new Promise((resolve) => setTimeout(resolve, timeoutMs))
107
+ ]);
108
+ }
109
+ var BitfabError, pendingTracePromises, HttpClient;
110
+ var init_http = __esm({
111
+ "src/http.ts"() {
112
+ "use strict";
113
+ init_constants();
114
+ BitfabError = class extends Error {
115
+ constructor(message, url) {
116
+ super(message);
117
+ this.url = url;
118
+ this.name = "BitfabError";
119
+ }
120
+ };
121
+ pendingTracePromises = /* @__PURE__ */ new Set();
122
+ if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
123
+ let isFlushing = false;
124
+ process.on("beforeExit", () => {
125
+ if (pendingTracePromises.size > 0 && !isFlushing) {
126
+ isFlushing = true;
127
+ Promise.allSettled(
128
+ Array.from(pendingTracePromises).map(
129
+ (p) => p.catch(() => {
130
+ })
131
+ )
132
+ ).then(() => {
133
+ isFlushing = false;
134
+ }).catch(() => {
135
+ isFlushing = false;
136
+ });
137
+ }
138
+ });
139
+ }
140
+ HttpClient = class {
141
+ constructor(config) {
142
+ this.apiKey = config.apiKey;
143
+ this.serviceUrl = config.serviceUrl;
144
+ this.timeout = config.timeout ?? 12e4;
145
+ }
146
+ /**
147
+ * Make an HTTP POST request to the Bitfab API.
148
+ *
149
+ * @param endpoint - The API endpoint (without base URL)
150
+ * @param payload - The request body
151
+ * @param options - Optional request options
152
+ * @returns The parsed JSON response
153
+ * @throws {BitfabError} If the request fails
154
+ */
155
+ async request(endpoint, payload, options) {
156
+ const url = `${this.serviceUrl}${endpoint}`;
157
+ const timeout = options?.timeout ?? this.timeout;
158
+ const controller = new AbortController();
159
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
160
+ let body;
161
+ let serializationError;
162
+ try {
163
+ body = JSON.stringify(payload);
164
+ } catch (error) {
165
+ serializationError = error instanceof Error ? error.message : String(error);
166
+ body = JSON.stringify({
167
+ ...Object.fromEntries(
168
+ Object.entries(payload).filter(
169
+ ([, v]) => typeof v === "string" || typeof v === "number"
170
+ )
171
+ ),
172
+ rawSpan: {},
173
+ errors: [{ step: "json_serialize", error: serializationError }]
174
+ });
175
+ }
176
+ try {
177
+ const response = await fetch(url, {
178
+ method: "POST",
179
+ headers: {
180
+ "Content-Type": "application/json",
181
+ Authorization: `Bearer ${this.apiKey}`
182
+ },
183
+ body,
184
+ signal: controller.signal
185
+ });
186
+ if (!response.ok) {
187
+ const errorText = await response.text();
188
+ throw new BitfabError(
189
+ `HTTP ${response.status}: ${errorText.slice(0, 500)}`
190
+ );
191
+ }
192
+ const result = await response.json();
193
+ if (result.error) {
194
+ if (result.url) {
195
+ throw new BitfabError(
196
+ `${result.error} Configure it at: ${this.serviceUrl}${result.url}`,
197
+ result.url
198
+ );
199
+ }
200
+ throw new BitfabError(result.error);
201
+ }
202
+ return result;
203
+ } catch (error) {
204
+ if (error instanceof BitfabError) {
205
+ throw error;
206
+ }
207
+ if (error instanceof Error) {
208
+ if (error.name === "AbortError") {
209
+ throw new BitfabError(`Request timed out after ${timeout}ms`);
210
+ }
211
+ throw new BitfabError(error.message);
212
+ }
213
+ throw new BitfabError("Unknown error occurred");
214
+ } finally {
215
+ clearTimeout(timeoutId);
216
+ }
217
+ }
218
+ /**
219
+ * Look up a function by name.
220
+ * Blocks until complete - needed for function execution.
221
+ */
222
+ async lookupFunction(name) {
223
+ return this.request("/api/sdk/functions/lookup", { name });
224
+ }
225
+ /**
226
+ * Send an internal trace (from BAML execution).
227
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
228
+ */
229
+ sendInternalTrace(functionId, payload) {
230
+ void awaitOnExit(
231
+ this.request(`/api/sdk/functions/${functionId}/traces`, {
232
+ ...payload,
233
+ sdkVersion: __version__
234
+ })
235
+ ).catch((error) => {
236
+ try {
237
+ console.error("Bitfab: Failed to create trace:", error);
238
+ } catch {
239
+ }
240
+ });
241
+ }
242
+ /**
243
+ * Send an external span (from withSpan wrapper or OpenAI tracing).
244
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
245
+ * Returns the tracked promise so callers can optionally await it.
246
+ */
247
+ sendExternalSpan(payload) {
248
+ return awaitOnExit(
249
+ this.request("/api/sdk/externalSpans", {
250
+ ...payload,
251
+ sdkVersion: __version__
252
+ })
253
+ ).catch((error) => {
254
+ try {
255
+ console.error("Bitfab: Failed to create external span:", error);
256
+ } catch {
257
+ }
258
+ });
259
+ }
260
+ /**
261
+ * Send an external trace (from OpenAI tracing).
262
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
263
+ */
264
+ sendExternalTrace(payload) {
265
+ void awaitOnExit(
266
+ this.request("/api/sdk/externalTraces", {
267
+ ...payload,
268
+ sdkVersion: __version__
269
+ })
270
+ ).catch((error) => {
271
+ try {
272
+ console.error("Bitfab: Failed to create external trace:", error);
273
+ } catch {
274
+ }
275
+ });
276
+ }
277
+ /**
278
+ * Start a replay session by fetching historical traces.
279
+ * Blocking call — creates a test run and returns lightweight item references.
280
+ */
281
+ async startReplay(traceFunctionKey, limit, traceIds) {
282
+ const payload = { traceFunctionKey, limit };
283
+ if (traceIds) {
284
+ payload.traceIds = traceIds;
285
+ }
286
+ return this.request("/api/sdk/replay/start", payload, {
287
+ timeout: 3e4
288
+ });
289
+ }
290
+ /**
291
+ * Fetch an external span by ID.
292
+ * Blocking GET request.
293
+ */
294
+ async getExternalSpan(spanId) {
295
+ const url = `${this.serviceUrl}/api/sdk/externalSpans/${spanId}`;
296
+ const controller = new AbortController();
297
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
298
+ try {
299
+ const response = await fetch(url, {
300
+ method: "GET",
301
+ headers: { Authorization: `Bearer ${this.apiKey}` },
302
+ signal: controller.signal
303
+ });
304
+ if (!response.ok) {
305
+ const errorText = await response.text();
306
+ throw new BitfabError(
307
+ `HTTP ${response.status}: ${errorText.slice(0, 500)}`
308
+ );
309
+ }
310
+ return await response.json();
311
+ } catch (error) {
312
+ if (error instanceof BitfabError) {
313
+ throw error;
314
+ }
315
+ if (error instanceof Error) {
316
+ if (error.name === "AbortError") {
317
+ throw new BitfabError("Request timed out after 30000ms");
318
+ }
319
+ throw new BitfabError(error.message);
320
+ }
321
+ throw new BitfabError("Unknown error occurred");
322
+ } finally {
323
+ clearTimeout(timeoutId);
324
+ }
325
+ }
326
+ /**
327
+ * Mark a replay test run as completed.
328
+ * Blocking call.
329
+ */
330
+ async completeReplay(testRunId) {
331
+ return this.request(
332
+ "/api/sdk/replay/complete",
333
+ { testRunId },
334
+ { timeout: 3e4 }
335
+ );
336
+ }
337
+ };
338
+ }
339
+ });
340
+
341
+ // src/replayContext.ts
342
+ function getReplayContext() {
343
+ return replayContextStorage?.getStore() ?? null;
344
+ }
345
+ function runWithReplayContext(ctx, fn) {
346
+ if (replayContextStorage) {
347
+ return replayContextStorage.run(ctx, fn);
348
+ }
349
+ return fn();
350
+ }
351
+ var replayContextStorage, replayContextReady;
352
+ var init_replayContext = __esm({
353
+ "src/replayContext.ts"() {
354
+ "use strict";
355
+ init_asyncStorage();
356
+ replayContextStorage = null;
357
+ replayContextReady = asyncStorageReady.then(() => {
358
+ replayContextStorage = createAsyncLocalStorage();
359
+ });
360
+ }
361
+ });
362
+
363
+ // src/serialize.ts
364
+ function serializeValue(value) {
365
+ try {
366
+ const { json, meta } = import_superjson.default.serialize(value);
367
+ return meta ? { json, meta } : { json };
368
+ } catch {
369
+ try {
370
+ return { json: JSON.parse(JSON.stringify(value)) };
371
+ } catch {
372
+ return { json: String(value) };
373
+ }
374
+ }
375
+ }
376
+ function deserializeValue(serialized) {
377
+ if (serialized.meta === void 0) {
378
+ return serialized.json;
379
+ }
380
+ return import_superjson.default.deserialize({
381
+ json: serialized.json,
382
+ meta: serialized.meta
383
+ });
384
+ }
385
+ var import_superjson;
386
+ var init_serialize = __esm({
387
+ "src/serialize.ts"() {
388
+ "use strict";
389
+ import_superjson = __toESM(require("superjson"), 1);
390
+ }
391
+ });
392
+
393
+ // src/replay.ts
394
+ var replay_exports = {};
395
+ __export(replay_exports, {
396
+ replay: () => replay
397
+ });
398
+ function deserializeInputs(spanData) {
399
+ const inputMeta = spanData.input_meta;
400
+ const rawInput = spanData.input;
401
+ if (inputMeta !== void 0 && inputMeta !== null) {
402
+ const deserialized = deserializeValue({ json: rawInput, meta: inputMeta });
403
+ if (Array.isArray(deserialized)) {
404
+ return deserialized;
405
+ }
406
+ return deserialized !== void 0 && deserialized !== null ? [deserialized] : [];
407
+ }
408
+ if (Array.isArray(rawInput)) {
409
+ return rawInput;
410
+ }
411
+ return rawInput !== void 0 && rawInput !== null ? [rawInput] : [];
412
+ }
413
+ function deserializeOutput(spanData) {
414
+ const outputMeta = spanData.output_meta;
415
+ const rawOutput = spanData.output;
416
+ if (outputMeta !== void 0 && outputMeta !== null) {
417
+ return deserializeValue({ json: rawOutput, meta: outputMeta });
418
+ }
419
+ return rawOutput;
420
+ }
421
+ async function processItem(httpClient, serverItem, fn, testRunId) {
422
+ const span = await httpClient.getExternalSpan(serverItem.externalSpanId);
423
+ const spanData = span.rawData?.span_data ?? {};
424
+ const inputs = deserializeInputs(spanData);
425
+ const originalOutput = deserializeOutput(spanData);
426
+ let result;
427
+ let error = null;
428
+ try {
429
+ const maybePromise = runWithReplayContext(
430
+ { testRunId, inputSourceSpanId: span.id },
431
+ () => fn(...inputs)
432
+ );
433
+ result = maybePromise instanceof Promise ? await maybePromise : maybePromise;
434
+ } catch (e) {
435
+ error = e instanceof Error ? e.message : String(e);
436
+ }
437
+ return { input: inputs, result, originalOutput, error };
438
+ }
439
+ async function mapWithConcurrency(tasks, maxConcurrency) {
440
+ const results = new Array(tasks.length);
441
+ let nextIndex = 0;
442
+ async function worker() {
443
+ while (nextIndex < tasks.length) {
444
+ const index = nextIndex++;
445
+ results[index] = await tasks[index]();
446
+ }
447
+ }
448
+ const workers = Array.from(
449
+ { length: Math.min(maxConcurrency, tasks.length) },
450
+ () => worker()
451
+ );
452
+ await Promise.all(workers);
453
+ return results;
454
+ }
455
+ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options) {
456
+ await replayContextReady;
457
+ const {
458
+ testRunId,
459
+ testRunUrl,
460
+ items: serverItems
461
+ } = await httpClient.startReplay(
462
+ traceFunctionKey,
463
+ options?.limit ?? 5,
464
+ options?.traceIds
465
+ );
466
+ const maxConcurrency = options?.maxConcurrency ?? 10;
467
+ const tasks = serverItems.map(
468
+ (serverItem) => () => processItem(httpClient, serverItem, fn, testRunId)
469
+ );
470
+ const resultItems = await mapWithConcurrency(tasks, maxConcurrency);
471
+ await flushTraces();
472
+ try {
473
+ await httpClient.completeReplay(testRunId);
474
+ } catch (e) {
475
+ try {
476
+ console.error("Bitfab: Failed to complete replay:", e);
477
+ } catch {
478
+ }
479
+ }
480
+ return {
481
+ items: resultItems,
482
+ testRunId,
483
+ testRunUrl: `${serviceUrl}${testRunUrl}`
484
+ };
485
+ }
486
+ var init_replay = __esm({
487
+ "src/replay.ts"() {
488
+ "use strict";
489
+ init_http();
490
+ init_replayContext();
491
+ init_serialize();
492
+ }
493
+ });
494
+
495
+ // src/index.ts
496
+ var index_exports = {};
497
+ __export(index_exports, {
498
+ Bitfab: () => Bitfab,
499
+ BitfabError: () => BitfabError,
500
+ BitfabFunction: () => BitfabFunction,
501
+ BitfabOpenAITracingProcessor: () => BitfabOpenAITracingProcessor,
502
+ DEFAULT_SERVICE_URL: () => DEFAULT_SERVICE_URL,
503
+ __version__: () => __version__,
504
+ flushTraces: () => flushTraces,
505
+ getCurrentSpan: () => getCurrentSpan,
506
+ getCurrentTrace: () => getCurrentTrace
507
+ });
508
+ module.exports = __toCommonJS(index_exports);
509
+
510
+ // src/client.ts
511
+ init_asyncStorage();
512
+
513
+ // src/baml.ts
514
+ var cachedBaml = null;
515
+ async function loadBaml() {
516
+ if (cachedBaml) {
517
+ return cachedBaml;
518
+ }
519
+ try {
520
+ cachedBaml = await import("@boundaryml/baml");
521
+ return cachedBaml;
522
+ } catch {
523
+ throw new Error(
524
+ "@boundaryml/baml is required for Bitfab.call(). Install it with: npm install @boundaryml/baml"
525
+ );
526
+ }
527
+ }
528
+ function capitalize(str) {
529
+ return str.charAt(0).toUpperCase() + str.slice(1);
530
+ }
531
+ function formatProvider(provider) {
532
+ const providerMap = {
533
+ openai: "OpenAI",
534
+ anthropic: "Anthropic",
535
+ google: "Google"
536
+ };
537
+ return providerMap[provider] ?? capitalize(provider);
538
+ }
539
+ function formatModel(model) {
540
+ return model.replace(/^gpt-/, "GPT").replace(/\./g, "_").replace(/-/g, "_");
541
+ }
542
+ function getClientName(provider, model) {
543
+ return `${formatProvider(provider)}_${formatModel(model)}`;
544
+ }
545
+ function generateClientDefinitions(providers) {
546
+ const definitions = [];
547
+ for (const providerDef of providers) {
548
+ for (const model of providerDef.models) {
549
+ const clientName = getClientName(providerDef.provider, model.model);
550
+ definitions.push(`client<llm> ${clientName} {
551
+ provider ${providerDef.provider}
552
+ options {
553
+ model "${model.model}"
554
+ api_key env.${providerDef.apiKeyEnv}
555
+ }
556
+ }`);
557
+ }
558
+ }
559
+ return definitions.join("\n\n");
560
+ }
561
+ function withDefaultClients(bamlSource, providers) {
562
+ const hasDefaultClient = bamlSource.includes("client<llm> OpenAI_");
563
+ if (hasDefaultClient) {
564
+ return bamlSource;
565
+ }
566
+ const defaultClients = generateClientDefinitions(providers);
567
+ return `${defaultClients}
568
+
569
+ ${bamlSource}`;
570
+ }
571
+ function extractFunctionName(bamlSource) {
572
+ const match = bamlSource.match(/function\s+(\w+)\s*\(/);
573
+ return match?.[1] ?? null;
574
+ }
575
+ function extractFunctionParameters(bamlSource) {
576
+ const functionMatch = bamlSource.match(/function\s+\w+\s*\(([^)]*)\)\s*->/);
577
+ if (!functionMatch) {
578
+ return [];
579
+ }
580
+ const paramsString = functionMatch[1].trim();
581
+ if (!paramsString) {
582
+ return [];
583
+ }
584
+ const params = [];
585
+ const paramParts = splitParameters(paramsString);
586
+ for (const part of paramParts) {
587
+ const trimmed = part.trim();
588
+ if (!trimmed) {
589
+ continue;
590
+ }
591
+ const paramMatch = trimmed.match(/^(\w+)\s*:\s*(.+)$/);
592
+ if (paramMatch) {
593
+ const name = paramMatch[1];
594
+ let type = paramMatch[2].trim();
595
+ const isOptional = type.endsWith("?");
596
+ if (isOptional) {
597
+ type = type.slice(0, -1);
598
+ }
599
+ params.push({ name, type, isOptional });
600
+ }
601
+ }
602
+ return params;
603
+ }
604
+ function splitParameters(paramsString) {
605
+ const parts = [];
606
+ let current = "";
607
+ let depth = 0;
608
+ for (const char of paramsString) {
609
+ if (char === "<") {
610
+ depth++;
611
+ current += char;
612
+ } else if (char === ">") {
613
+ depth--;
614
+ current += char;
615
+ } else if (char === "," && depth === 0) {
616
+ parts.push(current);
617
+ current = "";
618
+ } else {
619
+ current += char;
620
+ }
621
+ }
622
+ if (current.trim()) {
623
+ parts.push(current);
624
+ }
625
+ return parts;
626
+ }
627
+ function coerceToType(value, expectedType) {
628
+ if (expectedType === "string") {
629
+ return value;
630
+ }
631
+ if (expectedType === "int") {
632
+ const parsed = Number.parseInt(value, 10);
633
+ if (!Number.isNaN(parsed)) {
634
+ return parsed;
635
+ }
636
+ return value;
637
+ }
638
+ if (expectedType === "float") {
639
+ const parsed = Number.parseFloat(value);
640
+ if (!Number.isNaN(parsed)) {
641
+ return parsed;
642
+ }
643
+ return value;
644
+ }
645
+ if (expectedType === "bool") {
646
+ const lower = value.toLowerCase();
647
+ if (lower === "true") {
648
+ return true;
649
+ }
650
+ if (lower === "false") {
651
+ return false;
652
+ }
653
+ return value;
654
+ }
655
+ if (expectedType.endsWith("[]")) {
656
+ try {
657
+ const parsed = JSON.parse(value);
658
+ if (Array.isArray(parsed)) {
659
+ return parsed;
660
+ }
661
+ } catch {
662
+ }
663
+ return value;
664
+ }
665
+ try {
666
+ return JSON.parse(value);
667
+ } catch {
668
+ return value;
669
+ }
670
+ }
671
+ function coerceInputs(inputs, expectedTypes) {
672
+ const coerced = {};
673
+ for (const [key, value] of Object.entries(inputs)) {
674
+ if (typeof value === "string") {
675
+ const expectedType = expectedTypes.get(key);
676
+ if (expectedType) {
677
+ coerced[key] = coerceToType(value, expectedType);
678
+ } else {
679
+ coerced[key] = value;
680
+ }
681
+ } else {
682
+ coerced[key] = value;
683
+ }
684
+ }
685
+ return coerced;
686
+ }
687
+ function objToDict(obj, depth = 0, maxDepth = 5) {
688
+ if (depth > maxDepth) {
689
+ return `<max depth reached: ${typeof obj}>`;
690
+ }
691
+ if (obj === null || obj === void 0 || typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean") {
692
+ return obj;
693
+ }
694
+ if (Array.isArray(obj)) {
695
+ return obj.map((item) => objToDict(item, depth + 1, maxDepth));
696
+ }
697
+ if (typeof obj === "object") {
698
+ const result = {};
699
+ if (obj.constructor && obj.constructor.name !== "Object") {
700
+ result.__type__ = obj.constructor.name;
701
+ }
702
+ for (const key of Object.keys(obj)) {
703
+ if (key.startsWith("_")) {
704
+ continue;
705
+ }
706
+ try {
707
+ const value = obj[key];
708
+ if (typeof value === "function") {
709
+ continue;
710
+ }
711
+ result[key] = objToDict(value, depth + 1, maxDepth);
712
+ } catch (error) {
713
+ result[key] = `<error: ${error instanceof Error ? error.message : String(error)}>`;
714
+ }
715
+ }
716
+ try {
717
+ const proto = Object.getPrototypeOf(obj);
718
+ if (proto && proto !== Object.prototype) {
719
+ const descriptors = Object.getOwnPropertyDescriptors(proto);
720
+ for (const [key, descriptor] of Object.entries(descriptors)) {
721
+ if (key.startsWith("_") || key === "constructor" || key in result) {
722
+ continue;
723
+ }
724
+ if (descriptor.get) {
725
+ try {
726
+ const value = obj[key];
727
+ if (typeof value !== "function") {
728
+ result[key] = objToDict(value, depth + 1, maxDepth);
729
+ }
730
+ } catch {
731
+ }
732
+ }
733
+ }
734
+ }
735
+ } catch {
736
+ }
737
+ return result;
738
+ }
739
+ return String(obj);
740
+ }
741
+ function serializeCollector(collector) {
742
+ try {
743
+ return objToDict(collector, 0, 5);
744
+ } catch (_error) {
745
+ return null;
746
+ }
747
+ }
748
+ var ALLOWED_ENV_KEYS = ["OPENAI_API_KEY"];
749
+ function filterEnvVars(envVars) {
750
+ const filtered = {};
751
+ for (const key of ALLOWED_ENV_KEYS) {
752
+ const value = envVars[key];
753
+ if (value) {
754
+ filtered[key] = value;
755
+ }
756
+ }
757
+ return filtered;
758
+ }
759
+ async function runFunctionWithBaml(bamlSource, inputs, providers, envVars) {
760
+ const { BamlRuntime, Collector } = await loadBaml();
761
+ const functionName = extractFunctionName(bamlSource);
762
+ if (!functionName) {
763
+ throw new Error("No function found in BAML source");
764
+ }
765
+ const fullSource = withDefaultClients(bamlSource, providers);
766
+ const filteredEnvVars = filterEnvVars(envVars);
767
+ const runtime = BamlRuntime.fromFiles(
768
+ "/tmp/baml_runtime",
769
+ { "source.baml": fullSource },
770
+ filteredEnvVars
771
+ );
772
+ const ctx = runtime.createContextManager();
773
+ const collector = new Collector("bitfab-collector");
774
+ const params = extractFunctionParameters(bamlSource);
775
+ const expectedTypes = new Map(params.map((p) => [p.name, p.type]));
776
+ const args = coerceInputs(inputs, expectedTypes);
777
+ const functionResult = await runtime.callFunction(
778
+ functionName,
779
+ args,
780
+ ctx,
781
+ null,
782
+ // TypeBuilder
783
+ null,
784
+ // ClientRegistry
785
+ [collector],
786
+ // Collectors - capture execution data
787
+ {},
788
+ // Tags
789
+ filteredEnvVars
790
+ );
791
+ if (!functionResult.isOk()) {
792
+ throw new Error("BAML function execution failed");
793
+ }
794
+ const rawCollector = serializeCollector(collector);
795
+ return {
796
+ result: functionResult.parsed(false),
797
+ rawCollector
798
+ };
799
+ }
800
+
801
+ // src/client.ts
802
+ init_constants();
803
+ init_http();
804
+ init_replayContext();
805
+ init_serialize();
806
+
807
+ // src/tracing.ts
808
+ init_constants();
809
+ init_http();
810
+ var BitfabOpenAITracingProcessor = class {
811
+ /**
812
+ * Initialize the tracing processor.
813
+ *
814
+ * @param config - Configuration options
815
+ */
816
+ constructor(config) {
817
+ this.activeTraces = {};
818
+ this.activeSpanMappings = {};
819
+ this.httpClient = new HttpClient({
820
+ apiKey: config.apiKey,
821
+ serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
822
+ timeout: config.timeout ?? 1e4
823
+ });
824
+ this.getActiveSpanContext = config.getActiveSpanContext ?? null;
825
+ }
826
+ /**
827
+ * Called when a trace is started.
828
+ * If there's an active withSpan context, the trace ID is remapped to the
829
+ * outer trace and sent to pre-create the external_traces row on the server.
830
+ */
831
+ async onTraceStart(trace) {
832
+ this.activeTraces[trace.traceId] = trace;
833
+ const activeContext = this.getActiveSpanContext?.();
834
+ if (activeContext) {
835
+ this.activeSpanMappings[trace.traceId] = activeContext;
836
+ }
837
+ this.sendTrace(trace, activeContext ? { id: activeContext.traceId } : {});
838
+ }
839
+ /**
840
+ * Called when a trace is ended.
841
+ * If mapped to a withSpan trace, sends with remapped ID and completed=false
842
+ * since the parent withSpan handles completion.
843
+ */
844
+ async onTraceEnd(trace) {
845
+ const mapping = this.activeSpanMappings[trace.traceId];
846
+ this.sendTrace(
847
+ trace,
848
+ mapping ? { id: mapping.traceId } : { completed: true }
849
+ );
850
+ delete this.activeSpanMappings[trace.traceId];
851
+ delete this.activeTraces[trace.traceId];
852
+ }
853
+ /**
854
+ * Called when a span is started.
855
+ */
856
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
857
+ async onSpanStart(span) {
858
+ this.sendSpan(span);
859
+ }
860
+ /**
861
+ * Called when a span is ended.
862
+ *
863
+ * Send all spans to Bitfab for complete trace capture.
864
+ */
865
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
866
+ async onSpanEnd(span) {
867
+ this.sendSpan(span);
868
+ }
869
+ /**
870
+ * Called when a trace is being flushed.
871
+ */
872
+ async forceFlush() {
873
+ }
874
+ /**
875
+ * Called when the trace processor is shutting down.
876
+ */
877
+ async shutdown(_timeout) {
878
+ this.activeTraces = {};
879
+ this.activeSpanMappings = {};
880
+ }
881
+ /**
882
+ * Send trace to Bitfab API (fire-and-forget).
883
+ * When traceIdOverride is provided, the trace ID is remapped to link
884
+ * the OpenAI trace into an outer withSpan trace.
885
+ */
886
+ sendTrace(trace, overrides = {}) {
887
+ try {
888
+ const { completed, ...traceOverrides } = overrides;
889
+ const traceData = trace.toJSON();
890
+ Object.assign(traceData, traceOverrides);
891
+ this.httpClient.sendExternalTrace({
892
+ type: "openai",
893
+ source: "typescript-sdk-openai-tracing",
894
+ externalTrace: traceData,
895
+ completed: completed ?? false
896
+ });
897
+ } catch {
898
+ }
899
+ }
900
+ /**
901
+ * Export span to JSON object, collecting any errors.
902
+ */
903
+ exportSpan(span) {
904
+ const errors = [];
905
+ let serializedSpan;
906
+ try {
907
+ const jsonResult = span.toJSON();
908
+ if (typeof jsonResult !== "object" || jsonResult === null) {
909
+ errors.push({
910
+ step: "span.toJSON()",
911
+ error: `Returned unexpected type: ${typeof jsonResult}`
912
+ });
913
+ serializedSpan = {};
914
+ } else {
915
+ serializedSpan = jsonResult;
916
+ }
917
+ } catch (error) {
918
+ errors.push({
919
+ step: "span.toJSON()",
920
+ error: error instanceof Error ? error.message : String(error)
921
+ });
922
+ serializedSpan = {};
923
+ }
924
+ if (!serializedSpan.span_data) {
925
+ serializedSpan.span_data = {};
926
+ }
927
+ return [serializedSpan, errors];
928
+ }
929
+ /**
930
+ * Extract and add input/response to serialized span, updating errors list.
931
+ */
932
+ extractSpanInputResponse(span, serializedSpan, errors) {
933
+ const spanData = serializedSpan.span_data;
934
+ try {
935
+ spanData.input = span.spanData?._input || [];
936
+ } catch (error) {
937
+ errors.push({
938
+ step: "access_input",
939
+ error: error instanceof Error ? error.message : String(error)
940
+ });
941
+ }
942
+ try {
943
+ spanData.response = span.spanData?._response || null;
944
+ } catch (error) {
945
+ errors.push({
946
+ step: "access_response",
947
+ error: error instanceof Error ? error.message : String(error)
948
+ });
949
+ }
950
+ }
951
+ /**
952
+ * If the span's trace is mapped to a withSpan trace, rewrite trace_id and parent_id.
953
+ */
954
+ applySpanOverrides(serializedSpan, traceId) {
955
+ const mapping = this.activeSpanMappings[traceId];
956
+ if (mapping) {
957
+ serializedSpan.trace_id = mapping.traceId;
958
+ if (!serializedSpan.parent_id) {
959
+ serializedSpan.parent_id = mapping.spanId;
960
+ }
961
+ }
962
+ }
963
+ /**
964
+ * Build span payload for the external spans API.
965
+ */
966
+ buildSpanPayload(serializedSpan, errors) {
967
+ const payload = {
968
+ type: "openai",
969
+ source: "typescript-sdk-openai-tracing",
970
+ sourceTraceId: serializedSpan.trace_id ?? "unknown",
971
+ rawSpan: serializedSpan
972
+ };
973
+ if (errors.length > 0) {
974
+ payload.errors = errors;
975
+ }
976
+ return payload;
977
+ }
978
+ /**
979
+ * Send span to Bitfab API (fire-and-forget).
980
+ * If the span belongs to a trace mapped to a withSpan trace, the trace_id
981
+ * and parent_id are rewritten to link the span into the withSpan tree.
982
+ */
983
+ sendSpan(span) {
984
+ const errors = [];
985
+ const [serializedSpan, exportErrors] = this.exportSpan(span);
986
+ errors.push(...exportErrors);
987
+ this.extractSpanInputResponse(span, serializedSpan, errors);
988
+ this.applySpanOverrides(serializedSpan, span.traceId ?? "");
989
+ const payload = this.buildSpanPayload(serializedSpan, errors);
990
+ this.httpClient.sendExternalSpan(payload);
991
+ }
992
+ };
993
+
994
+ // src/client.ts
995
+ var activeTraceStates = /* @__PURE__ */ new Map();
996
+ var pendingSpanPromises = /* @__PURE__ */ new Map();
997
+ var asyncLocalStorage = null;
998
+ var asyncLocalStorageReady = asyncStorageReady.then(() => {
999
+ asyncLocalStorage = createAsyncLocalStorage();
1000
+ });
1001
+ var browserSpanStack = [];
1002
+ function getSpanStack() {
1003
+ if (asyncLocalStorage) {
1004
+ return asyncLocalStorage.getStore() ?? [];
1005
+ }
1006
+ return browserSpanStack;
1007
+ }
1008
+ function runWithSpanStack(stack, fn) {
1009
+ if (asyncLocalStorage) {
1010
+ return asyncLocalStorage.run(stack, fn);
1011
+ }
1012
+ const previousStack = browserSpanStack;
1013
+ browserSpanStack = stack;
1014
+ try {
1015
+ const result = fn();
1016
+ if (result instanceof Promise) {
1017
+ return result.finally(() => {
1018
+ browserSpanStack = previousStack;
1019
+ });
1020
+ }
1021
+ browserSpanStack = previousStack;
1022
+ return result;
1023
+ } catch (error) {
1024
+ browserSpanStack = previousStack;
1025
+ throw error;
1026
+ }
1027
+ }
1028
+ var cachedCollectorClass;
1029
+ async function loadCollectorClass() {
1030
+ if (cachedCollectorClass !== void 0) {
1031
+ return cachedCollectorClass;
1032
+ }
1033
+ try {
1034
+ const baml = await import("@boundaryml/baml");
1035
+ cachedCollectorClass = baml.Collector;
1036
+ return cachedCollectorClass;
1037
+ } catch {
1038
+ cachedCollectorClass = null;
1039
+ return null;
1040
+ }
1041
+ }
1042
+ function extractPromptFromCollector(collector) {
1043
+ try {
1044
+ const c = collector;
1045
+ const calls = c?.last?.calls ?? [];
1046
+ const selectedCall = calls.find((call) => call.selected) ?? calls[0];
1047
+ if (!selectedCall?.httpRequest?.body) {
1048
+ return null;
1049
+ }
1050
+ const body = selectedCall.httpRequest.body.json();
1051
+ if (!body || typeof body !== "object") {
1052
+ return null;
1053
+ }
1054
+ const messages = body.messages;
1055
+ if (!Array.isArray(messages) || messages.length === 0) {
1056
+ return null;
1057
+ }
1058
+ const rendered = messages.filter(
1059
+ (msg) => typeof msg === "object" && msg !== null && "role" in msg && typeof msg.role === "string"
1060
+ ).map((msg) => ({
1061
+ role: msg.role,
1062
+ content: typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)
1063
+ }));
1064
+ if (rendered.length > 0) {
1065
+ return JSON.stringify(rendered);
1066
+ }
1067
+ return null;
1068
+ } catch {
1069
+ return null;
1070
+ }
1071
+ }
1072
+ function extractContextFromCollector(collector) {
1073
+ try {
1074
+ const c = collector;
1075
+ const calls = c?.last?.calls ?? [];
1076
+ const selectedCall = calls.find((call) => call.selected) ?? calls[0];
1077
+ const usage = c?.usage;
1078
+ const context = {};
1079
+ if (selectedCall?.provider) {
1080
+ context.provider = selectedCall.provider;
1081
+ }
1082
+ const body = selectedCall?.httpRequest?.body?.json();
1083
+ if (body && typeof body === "object" && typeof body.model === "string") {
1084
+ context.model = body.model;
1085
+ } else {
1086
+ const url = selectedCall?.httpRequest?.url;
1087
+ if (url) {
1088
+ const match = url.match(/\/models\/([^/:]+)/);
1089
+ if (match?.[1]) {
1090
+ context.model = match[1];
1091
+ }
1092
+ }
1093
+ }
1094
+ const inputTokens = usage?.inputTokens ?? selectedCall?.usage?.inputTokens ?? null;
1095
+ const outputTokens = usage?.outputTokens ?? selectedCall?.usage?.outputTokens ?? null;
1096
+ if (inputTokens !== null) {
1097
+ context.inputTokens = inputTokens;
1098
+ }
1099
+ if (outputTokens !== null) {
1100
+ context.outputTokens = outputTokens;
1101
+ }
1102
+ const durationMs = c?.last?.timing?.durationMs ?? null;
1103
+ if (durationMs !== null) {
1104
+ context.durationMs = durationMs;
1105
+ }
1106
+ return Object.keys(context).length > 0 ? context : null;
1107
+ } catch {
1108
+ return null;
1109
+ }
1110
+ }
1111
+ var noOpSpan = {
1112
+ traceId: "",
1113
+ addContext() {
1114
+ },
1115
+ setPrompt() {
1116
+ }
1117
+ };
1118
+ var noOpTrace = {
1119
+ setSessionId() {
1120
+ },
1121
+ setMetadata() {
1122
+ },
1123
+ addContext() {
1124
+ }
1125
+ };
1126
+ function getCurrentSpan() {
1127
+ const stack = getSpanStack();
1128
+ const current = stack[stack.length - 1];
1129
+ if (!current) {
1130
+ return noOpSpan;
1131
+ }
1132
+ return {
1133
+ traceId: current.traceId,
1134
+ addContext(context) {
1135
+ try {
1136
+ if (typeof context !== "object" || context === null) {
1137
+ return;
1138
+ }
1139
+ current.contexts.push(context);
1140
+ } catch {
1141
+ }
1142
+ },
1143
+ setPrompt(prompt) {
1144
+ try {
1145
+ if (typeof prompt !== "string") {
1146
+ return;
1147
+ }
1148
+ current.prompt = prompt;
1149
+ } catch {
1150
+ }
1151
+ }
1152
+ };
1153
+ }
1154
+ function getCurrentTrace() {
1155
+ const stack = getSpanStack();
1156
+ const current = stack[stack.length - 1];
1157
+ if (!current) {
1158
+ return noOpTrace;
1159
+ }
1160
+ const traceId = current.traceId;
1161
+ const getOrCreateTraceState = () => {
1162
+ let traceState = activeTraceStates.get(traceId);
1163
+ if (!traceState) {
1164
+ traceState = {
1165
+ traceId,
1166
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1167
+ contexts: []
1168
+ };
1169
+ activeTraceStates.set(traceId, traceState);
1170
+ }
1171
+ return traceState;
1172
+ };
1173
+ return {
1174
+ setSessionId(sessionId) {
1175
+ try {
1176
+ const traceState = getOrCreateTraceState();
1177
+ traceState.sessionId = sessionId;
1178
+ } catch {
1179
+ }
1180
+ },
1181
+ setMetadata(metadata) {
1182
+ try {
1183
+ if (typeof metadata !== "object" || metadata === null) {
1184
+ return;
1185
+ }
1186
+ const traceState = getOrCreateTraceState();
1187
+ traceState.metadata = { ...traceState.metadata, ...metadata };
1188
+ } catch {
1189
+ }
1190
+ },
1191
+ addContext(context) {
1192
+ try {
1193
+ if (typeof context !== "object" || context === null) {
1194
+ return;
1195
+ }
1196
+ const traceState = getOrCreateTraceState();
1197
+ traceState.contexts.push(context);
1198
+ } catch {
1199
+ }
1200
+ }
1201
+ };
1202
+ }
1203
+ var Bitfab = class {
1204
+ /**
1205
+ * Initialize the Bitfab client.
1206
+ *
1207
+ * @param config - Configuration options for the client
1208
+ */
1209
+ constructor(config) {
1210
+ this.apiKey = config.apiKey;
1211
+ this.serviceUrl = config.serviceUrl ?? DEFAULT_SERVICE_URL;
1212
+ this.timeout = config.timeout ?? 12e4;
1213
+ this.envVars = config.envVars ?? {};
1214
+ const enabled = config.enabled ?? true;
1215
+ if (enabled && (!config.apiKey || config.apiKey.trim() === "")) {
1216
+ console.warn(
1217
+ "Bitfab: apiKey is empty \u2014 tracing is disabled. Provide a valid API key to enable tracing."
1218
+ );
1219
+ this.enabled = false;
1220
+ } else {
1221
+ this.enabled = enabled;
1222
+ }
1223
+ this.bamlClient = config.bamlClient ?? null;
1224
+ this.httpClient = new HttpClient({
1225
+ apiKey: this.apiKey,
1226
+ serviceUrl: this.serviceUrl,
1227
+ timeout: this.timeout
1228
+ });
1229
+ }
1230
+ /**
1231
+ * Fetch the function with its current version and BAML prompt from the server.
1232
+ *
1233
+ * @param methodName - The name of the method to fetch
1234
+ * @returns The function with current version, BAML prompt, and provider definitions
1235
+ * @throws {BitfabError} If the function is not found or an error occurs
1236
+ */
1237
+ async fetchFunctionVersion(methodName) {
1238
+ const result = await this.httpClient.lookupFunction(methodName);
1239
+ if (result.id === null) {
1240
+ throw new BitfabError(
1241
+ `Function "${methodName}" not found. Create it at: ${this.serviceUrl}/functions`,
1242
+ "/functions"
1243
+ );
1244
+ }
1245
+ if (!result.prompt) {
1246
+ throw new BitfabError(
1247
+ `Function "${methodName}" has no prompt configured. Add one at: ${this.serviceUrl}/functions/${result.id}`,
1248
+ `/functions/${result.id}`
1249
+ );
1250
+ }
1251
+ return result;
1252
+ }
1253
+ /**
1254
+ * Call a method with the given named arguments via BAML execution.
1255
+ *
1256
+ * @param methodName - The name of the method to call
1257
+ * @param inputs - Named arguments to pass to the method
1258
+ * @returns The result of the BAML function execution
1259
+ * @throws {BitfabError} If service_url is not set, or if an error occurs
1260
+ */
1261
+ async call(methodName, inputs = {}) {
1262
+ try {
1263
+ const functionVersion = await this.fetchFunctionVersion(methodName);
1264
+ const executionResult = await runFunctionWithBaml(
1265
+ functionVersion.prompt,
1266
+ inputs,
1267
+ functionVersion.providers,
1268
+ this.envVars
1269
+ );
1270
+ const resultStr = typeof executionResult.result === "string" ? executionResult.result : JSON.stringify(executionResult.result);
1271
+ this.httpClient.sendInternalTrace(functionVersion.id, {
1272
+ result: resultStr,
1273
+ source: "typescript-sdk",
1274
+ ...Object.keys(inputs).length > 0 && { inputs },
1275
+ ...executionResult.rawCollector != null && {
1276
+ rawCollector: executionResult.rawCollector
1277
+ }
1278
+ });
1279
+ return executionResult.result;
1280
+ } catch (error) {
1281
+ if (error instanceof BitfabError) {
1282
+ throw error;
1283
+ }
1284
+ if (error instanceof Error) {
1285
+ throw new BitfabError(error.message);
1286
+ }
1287
+ throw new BitfabError("Unknown error occurred during local execution");
1288
+ }
1289
+ }
1290
+ /**
1291
+ * Get a tracing processor for OpenAI Agents SDK integration.
1292
+ *
1293
+ * This processor automatically captures traces and spans from the OpenAI Agents SDK
1294
+ * and sends them to Bitfab for monitoring and analysis.
1295
+ *
1296
+ * Example usage:
1297
+ * ```typescript
1298
+ * import { addTraceProcessor } from '@openai/agents';
1299
+ *
1300
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
1301
+ * const processor = client.getOpenAiTracingProcessor();
1302
+ * addTraceProcessor(processor);
1303
+ * ```
1304
+ *
1305
+ * @returns A BitfabOpenAITracingProcessor instance configured for this client
1306
+ */
1307
+ getOpenAiTracingProcessor() {
1308
+ return new BitfabOpenAITracingProcessor({
1309
+ apiKey: this.apiKey,
1310
+ serviceUrl: this.serviceUrl,
1311
+ getActiveSpanContext: () => {
1312
+ const stack = getSpanStack();
1313
+ return stack[stack.length - 1] ?? null;
1314
+ }
1315
+ });
1316
+ }
1317
+ /**
1318
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
1319
+ *
1320
+ * Creates a BAML Collector, calls the method through a tracked client,
1321
+ * then extracts rendered messages and token usage — calling setPrompt()
1322
+ * and addContext() on the current span automatically.
1323
+ *
1324
+ * The BAML client can be provided in the constructor or passed explicitly:
1325
+ *
1326
+ * ```typescript
1327
+ * // Option 1: bamlClient in constructor (use wrapBAML with just the method)
1328
+ * const client = new Bitfab({ apiKey: 'your-api-key', bamlClient: b });
1329
+ * const traced = client.withSpan('classify', { type: 'llm' },
1330
+ * client.wrapBAML(b.ClassifyText)
1331
+ * );
1332
+ *
1333
+ * // Option 2: pass bamlClient at call site
1334
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
1335
+ * const traced = client.withSpan('classify', { type: 'llm' },
1336
+ * client.wrapBAML(b, b.ClassifyText)
1337
+ * );
1338
+ * ```
1339
+ *
1340
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
1341
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
1342
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
1343
+ * @returns An async function with the same signature that instruments the BAML call
1344
+ */
1345
+ wrapBAML(methodOrClient, maybeMethodOrOptions, maybeOptions) {
1346
+ let bamlClient;
1347
+ let method;
1348
+ let options;
1349
+ if (typeof maybeMethodOrOptions === "function") {
1350
+ bamlClient = methodOrClient;
1351
+ method = maybeMethodOrOptions;
1352
+ options = maybeOptions;
1353
+ } else {
1354
+ bamlClient = this.bamlClient;
1355
+ method = methodOrClient;
1356
+ options = maybeMethodOrOptions;
1357
+ if (!bamlClient) {
1358
+ throw new BitfabError(
1359
+ "bamlClient is required for wrapBAML. Pass it in the constructor or as the first argument."
1360
+ );
1361
+ }
1362
+ }
1363
+ const methodName = method.name;
1364
+ if (!methodName) {
1365
+ throw new BitfabError(
1366
+ "wrapBAML requires a named function (e.g., b.ClassifyText)."
1367
+ );
1368
+ }
1369
+ loadCollectorClass();
1370
+ const wrappedFn = async (...args) => {
1371
+ const CollectorClass = await loadCollectorClass();
1372
+ if (!CollectorClass) {
1373
+ wrappedFn.collector = null;
1374
+ return await bamlClient[methodName](...args);
1375
+ }
1376
+ const collector = new CollectorClass("bitfab-baml-tracing");
1377
+ const trackedClient = bamlClient.withOptions({ collector });
1378
+ const trackedMethod = trackedClient[methodName];
1379
+ const result = await trackedMethod.bind(
1380
+ trackedClient
1381
+ )(...args);
1382
+ wrappedFn.collector = collector;
1383
+ try {
1384
+ const prompt = extractPromptFromCollector(collector);
1385
+ if (prompt) {
1386
+ getCurrentSpan().setPrompt(prompt);
1387
+ }
1388
+ const metadata = extractContextFromCollector(collector);
1389
+ if (metadata) {
1390
+ getCurrentSpan().addContext(metadata);
1391
+ }
1392
+ } catch {
1393
+ }
1394
+ try {
1395
+ options?.onCollector?.(collector);
1396
+ } catch {
1397
+ }
1398
+ return result;
1399
+ };
1400
+ wrappedFn.collector = null;
1401
+ return wrappedFn;
1402
+ }
1403
+ /**
1404
+ * Wrap a function to automatically create a span for its inputs and outputs.
1405
+ *
1406
+ * The wrapped function behaves identically to the original, but sends
1407
+ * span data to Bitfab in the background after each call.
1408
+ *
1409
+ * Example usage:
1410
+ * ```typescript
1411
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
1412
+ *
1413
+ * async function processOrder(orderId: string, items: string[]): Promise<{ total: number }> {
1414
+ * // ... process order
1415
+ * return { total: 100 };
1416
+ * }
1417
+ *
1418
+ * // Basic usage (defaults to "custom" span type)
1419
+ * const tracedProcessOrder = client.withSpan('order-processing', processOrder);
1420
+ *
1421
+ * // With explicit span type
1422
+ * const tracedProcessOrder = client.withSpan('order-processing', { type: 'function' }, processOrder);
1423
+ *
1424
+ * // Call the wrapped function normally
1425
+ * const result = await tracedProcessOrder('order-123', ['item-1', 'item-2']);
1426
+ * // Span is automatically sent to Bitfab
1427
+ * ```
1428
+ *
1429
+ * @param traceFunctionKey - A string identifier for grouping spans (e.g., 'order-processing', 'user-auth')
1430
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
1431
+ * @param maybeFn - The function to wrap if options were provided
1432
+ * @returns A wrapped function with the same signature that creates spans for inputs and outputs
1433
+ */
1434
+ withSpan(traceFunctionKey, optionsOrFn, maybeFn) {
1435
+ if (!this.enabled) {
1436
+ const fn2 = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
1437
+ return fn2;
1438
+ }
1439
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
1440
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
1441
+ const self = this;
1442
+ const wrappedFn = function(...args) {
1443
+ if (!asyncLocalStorage && !isAsyncStorageInitDone()) {
1444
+ return asyncLocalStorageReady.then(
1445
+ () => wrappedFn.apply(this, args)
1446
+ );
1447
+ }
1448
+ const currentStack = getSpanStack();
1449
+ const parentContext = currentStack[currentStack.length - 1];
1450
+ const traceId = parentContext?.traceId ?? crypto.randomUUID();
1451
+ const spanId = crypto.randomUUID();
1452
+ const parentSpanId = parentContext?.spanId ?? null;
1453
+ const isRootSpan = parentSpanId === null;
1454
+ const newContext = { traceId, spanId, contexts: [] };
1455
+ const newStack = [...currentStack, newContext];
1456
+ const inputs = args;
1457
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
1458
+ if (isRootSpan && !activeTraceStates.has(traceId)) {
1459
+ activeTraceStates.set(traceId, {
1460
+ traceId,
1461
+ startedAt,
1462
+ contexts: []
1463
+ });
1464
+ pendingSpanPromises.set(traceId, []);
1465
+ }
1466
+ const functionName = fn.name !== "" ? fn.name : void 0;
1467
+ const baseSpanParams = {
1468
+ traceFunctionKey,
1469
+ functionName,
1470
+ spanName: options.name ?? functionName ?? traceFunctionKey,
1471
+ traceId,
1472
+ spanId,
1473
+ parentSpanId,
1474
+ inputs,
1475
+ startedAt,
1476
+ spanType: options.type ?? "custom"
1477
+ };
1478
+ const sendSpan = async (params) => {
1479
+ try {
1480
+ const endedAt = (/* @__PURE__ */ new Date()).toISOString();
1481
+ const replayCtx = getReplayContext();
1482
+ const spanPromise = self.sendWrapperSpan({
1483
+ ...baseSpanParams,
1484
+ ...params,
1485
+ contexts: newContext.contexts,
1486
+ prompt: newContext.prompt,
1487
+ endedAt,
1488
+ ...replayCtx?.testRunId && { testRunId: replayCtx.testRunId },
1489
+ ...replayCtx?.inputSourceSpanId && {
1490
+ inputSourceSpanId: replayCtx.inputSourceSpanId
1491
+ }
1492
+ });
1493
+ if (isRootSpan) {
1494
+ const pending = pendingSpanPromises.get(traceId) ?? [];
1495
+ pending.push(spanPromise);
1496
+ await Promise.race([
1497
+ Promise.allSettled(pending),
1498
+ new Promise((resolve) => setTimeout(resolve, 5e3))
1499
+ ]);
1500
+ pendingSpanPromises.delete(traceId);
1501
+ const traceState = activeTraceStates.get(traceId);
1502
+ self.sendTraceCompletion({
1503
+ traceFunctionKey,
1504
+ traceId,
1505
+ startedAt: traceState?.startedAt ?? startedAt,
1506
+ endedAt,
1507
+ sessionId: traceState?.sessionId,
1508
+ metadata: traceState?.metadata,
1509
+ contexts: traceState?.contexts ?? []
1510
+ });
1511
+ activeTraceStates.delete(traceId);
1512
+ } else {
1513
+ const pending = pendingSpanPromises.get(traceId);
1514
+ if (pending) {
1515
+ pending.push(spanPromise);
1516
+ } else {
1517
+ pendingSpanPromises.set(traceId, [spanPromise]);
1518
+ }
1519
+ }
1520
+ } catch {
1521
+ }
1522
+ };
1523
+ const executeWithContext = () => {
1524
+ const result = fn(...args);
1525
+ if (result instanceof Promise) {
1526
+ return result.then((resolvedResult) => {
1527
+ void sendSpan({ result: resolvedResult });
1528
+ return resolvedResult;
1529
+ }).catch((error) => {
1530
+ void sendSpan({
1531
+ result: void 0,
1532
+ error: error instanceof Error ? error.message : String(error)
1533
+ });
1534
+ throw error;
1535
+ });
1536
+ }
1537
+ void sendSpan({ result });
1538
+ return result;
1539
+ };
1540
+ return runWithSpanStack(newStack, executeWithContext);
1541
+ };
1542
+ return wrappedFn;
1543
+ }
1544
+ /**
1545
+ * Get a function wrapper for a specific trace function key.
1546
+ *
1547
+ * This provides a fluent API alternative to calling withSpan directly,
1548
+ * allowing you to bind the traceFunctionKey once and wrap multiple functions.
1549
+ *
1550
+ * Example usage:
1551
+ * ```typescript
1552
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
1553
+ *
1554
+ * const orderFunc = client.getFunction('order-processing');
1555
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
1556
+ * const tracedValidateOrder = orderFunc.withSpan(validateOrder);
1557
+ * ```
1558
+ *
1559
+ * @param traceFunctionKey - A string identifier for grouping spans
1560
+ * @returns A BitfabFunction instance for wrapping functions
1561
+ */
1562
+ getFunction(traceFunctionKey) {
1563
+ return new BitfabFunction(this, traceFunctionKey);
1564
+ }
1565
+ /**
1566
+ * Send trace completion when a root span ends.
1567
+ * Internal method to record trace completion with end time.
1568
+ * Fire-and-forget - sends to externalTraces endpoint via httpClient.
1569
+ */
1570
+ sendTraceCompletion(params) {
1571
+ const rawTrace = {
1572
+ id: params.traceId,
1573
+ started_at: params.startedAt,
1574
+ ended_at: params.endedAt,
1575
+ workflow_name: params.traceFunctionKey
1576
+ };
1577
+ if (params.metadata && Object.keys(params.metadata).length > 0) {
1578
+ rawTrace.metadata = params.metadata;
1579
+ }
1580
+ if (params.contexts && params.contexts.length > 0) {
1581
+ rawTrace.contexts = params.contexts;
1582
+ }
1583
+ this.httpClient.sendExternalTrace({
1584
+ type: "sdk-function",
1585
+ source: "typescript-sdk-function",
1586
+ traceFunctionKey: params.traceFunctionKey,
1587
+ externalTrace: rawTrace,
1588
+ completed: true,
1589
+ ...params.sessionId && { sessionId: params.sessionId }
1590
+ });
1591
+ }
1592
+ /**
1593
+ * Send a wrapper span from function execution.
1594
+ * Internal method to record spans when using withSpan.
1595
+ * Fire-and-forget - sends to externalSpans endpoint via httpClient.
1596
+ */
1597
+ sendWrapperSpan(params) {
1598
+ const serializedInputs = serializeValue(params.inputs);
1599
+ const serializedResult = serializeValue(params.result);
1600
+ const externalSpan = {
1601
+ id: params.spanId,
1602
+ trace_id: params.traceId,
1603
+ started_at: params.startedAt,
1604
+ ended_at: params.endedAt,
1605
+ span_data: {
1606
+ name: params.spanName,
1607
+ type: params.spanType,
1608
+ input: serializedInputs.json,
1609
+ output: serializedResult.json,
1610
+ // Include superjson meta for type preservation
1611
+ ...serializedInputs.meta !== void 0 && {
1612
+ input_meta: serializedInputs.meta
1613
+ },
1614
+ ...serializedResult.meta !== void 0 && {
1615
+ output_meta: serializedResult.meta
1616
+ },
1617
+ ...params.functionName !== void 0 && {
1618
+ function_name: params.functionName
1619
+ },
1620
+ ...params.error !== void 0 && { error: params.error },
1621
+ ...params.contexts && params.contexts.length > 0 && {
1622
+ contexts: params.contexts
1623
+ },
1624
+ ...params.prompt !== void 0 && { prompt: params.prompt }
1625
+ }
1626
+ };
1627
+ if (params.parentSpanId) {
1628
+ externalSpan.parent_id = params.parentSpanId;
1629
+ }
1630
+ if (params.inputSourceSpanId) {
1631
+ externalSpan.input_source_span_id = params.inputSourceSpanId;
1632
+ }
1633
+ return this.httpClient.sendExternalSpan({
1634
+ type: "sdk-function",
1635
+ source: "typescript-sdk-function",
1636
+ sourceTraceId: params.traceId,
1637
+ traceFunctionKey: params.traceFunctionKey,
1638
+ rawSpan: externalSpan,
1639
+ ...params.testRunId && { testRunId: params.testRunId }
1640
+ });
1641
+ }
1642
+ /**
1643
+ * Replay historical traces through a function and create a test run.
1644
+ *
1645
+ * Fetches the last N traces for the given trace function key, re-runs each
1646
+ * through the provided function, and returns comparison data.
1647
+ *
1648
+ * The function must have been wrapped with `withSpan` — replay injects
1649
+ * `testRunId` via async context so new spans are linked to the test run.
1650
+ *
1651
+ * @param traceFunctionKey - The trace function key to replay
1652
+ * @param fn - The function to replay (must be the return value of `withSpan`)
1653
+ * @param options - Optional replay options (limit, traceIds)
1654
+ * @returns ReplayResult with items, testRunId, and testRunUrl
1655
+ */
1656
+ async replay(traceFunctionKey, fn, options) {
1657
+ const { replay: doReplay } = await Promise.resolve().then(() => (init_replay(), replay_exports));
1658
+ return doReplay(
1659
+ this.httpClient,
1660
+ this.serviceUrl,
1661
+ traceFunctionKey,
1662
+ fn,
1663
+ options
1664
+ );
1665
+ }
1666
+ };
1667
+ var BitfabFunction = class {
1668
+ constructor(client, traceFunctionKey) {
1669
+ this.client = client;
1670
+ this.traceFunctionKey = traceFunctionKey;
1671
+ }
1672
+ /**
1673
+ * Wrap a function to automatically create a span for its inputs and outputs.
1674
+ *
1675
+ * The wrapped function behaves identically to the original, but sends
1676
+ * span data to Bitfab in the background after each call.
1677
+ *
1678
+ * Example usage:
1679
+ * ```typescript
1680
+ * const orderFunc = client.getFunction('order-processing');
1681
+ *
1682
+ * // Basic usage (defaults to "custom" span type)
1683
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
1684
+ *
1685
+ * // With explicit span type
1686
+ * const tracedProcessOrder = orderFunc.withSpan({ type: 'function' }, processOrder);
1687
+ * ```
1688
+ *
1689
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
1690
+ * @param maybeFn - The function to wrap if options were provided
1691
+ * @returns A wrapped function with the same signature that creates spans
1692
+ */
1693
+ withSpan(optionsOrFn, maybeFn) {
1694
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
1695
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
1696
+ return this.client.withSpan(this.traceFunctionKey, options, fn);
1697
+ }
1698
+ /**
1699
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
1700
+ * Delegates to the parent client's wrapBAML method.
1701
+ *
1702
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
1703
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
1704
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
1705
+ * @returns An async function with the same signature that instruments the BAML call
1706
+ */
1707
+ wrapBAML(methodOrClient, maybeMethodOrOptions, maybeOptions) {
1708
+ return this.client.wrapBAML(
1709
+ methodOrClient,
1710
+ maybeMethodOrOptions,
1711
+ maybeOptions
1712
+ );
1713
+ }
1714
+ };
1715
+
1716
+ // src/index.ts
1717
+ init_constants();
1718
+ init_http();
1719
+ // Annotate the CommonJS export names for ESM import in node:
1720
+ 0 && (module.exports = {
1721
+ Bitfab,
1722
+ BitfabError,
1723
+ BitfabFunction,
1724
+ BitfabOpenAITracingProcessor,
1725
+ DEFAULT_SERVICE_URL,
1726
+ __version__,
1727
+ flushTraces,
1728
+ getCurrentSpan,
1729
+ getCurrentTrace
1730
+ });
1731
+ //# sourceMappingURL=index.cjs.map