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