@bitfab/sdk 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.cjs ADDED
@@ -0,0 +1,3058 @@
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.13.0";
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 request to the Bitfab API. Defaults to POST; pass
155
+ * `options.method` to use a different verb (e.g. "PATCH").
156
+ *
157
+ * @param endpoint - The API endpoint (without base URL)
158
+ * @param payload - The request body
159
+ * @param options - Optional request options
160
+ * @returns The parsed JSON response
161
+ * @throws {BitfabError} If the request fails
162
+ */
163
+ async request(endpoint, payload, options) {
164
+ const url = `${this.serviceUrl}${endpoint}`;
165
+ const timeout = options?.timeout ?? this.timeout;
166
+ const method = options?.method ?? "POST";
167
+ const controller = new AbortController();
168
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
169
+ let body;
170
+ let serializationError;
171
+ try {
172
+ body = JSON.stringify(payload);
173
+ } catch (error) {
174
+ serializationError = error instanceof Error ? error.message : String(error);
175
+ body = JSON.stringify({
176
+ ...Object.fromEntries(
177
+ Object.entries(payload).filter(
178
+ ([, v]) => typeof v === "string" || typeof v === "number"
179
+ )
180
+ ),
181
+ rawSpan: {},
182
+ errors: [{ step: "json_serialize", error: serializationError }]
183
+ });
184
+ }
185
+ try {
186
+ const response = await fetch(url, {
187
+ method,
188
+ headers: {
189
+ "Content-Type": "application/json",
190
+ Authorization: `Bearer ${this.apiKey}`
191
+ },
192
+ body,
193
+ signal: controller.signal
194
+ });
195
+ if (!response.ok) {
196
+ const errorText = await response.text();
197
+ throw new BitfabError(
198
+ `HTTP ${response.status}: ${errorText.slice(0, 500)}`
199
+ );
200
+ }
201
+ const result = await response.json();
202
+ if (result.error) {
203
+ if (result.url) {
204
+ throw new BitfabError(
205
+ `${result.error} Configure it at: ${this.serviceUrl}${result.url}`,
206
+ result.url
207
+ );
208
+ }
209
+ throw new BitfabError(result.error);
210
+ }
211
+ return result;
212
+ } catch (error) {
213
+ if (error instanceof BitfabError) {
214
+ throw error;
215
+ }
216
+ if (error instanceof Error) {
217
+ if (error.name === "AbortError") {
218
+ throw new BitfabError(`Request timed out after ${timeout}ms`);
219
+ }
220
+ throw new BitfabError(error.message);
221
+ }
222
+ throw new BitfabError("Unknown error occurred");
223
+ } finally {
224
+ clearTimeout(timeoutId);
225
+ }
226
+ }
227
+ /**
228
+ * Look up a function by name.
229
+ * Blocks until complete - needed for function execution.
230
+ */
231
+ async lookupFunction(name) {
232
+ return this.request("/api/sdk/functions/lookup", { name });
233
+ }
234
+ /**
235
+ * Send an internal trace (from BAML execution).
236
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
237
+ */
238
+ sendInternalTrace(functionId, payload) {
239
+ void awaitOnExit(
240
+ this.request(`/api/sdk/functions/${functionId}/traces`, {
241
+ ...payload,
242
+ sdkVersion: __version__
243
+ })
244
+ ).catch((error) => {
245
+ try {
246
+ console.error("Bitfab: Failed to create trace:", error);
247
+ } catch {
248
+ }
249
+ });
250
+ }
251
+ /**
252
+ * Send an external span (from withSpan wrapper or OpenAI tracing).
253
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
254
+ * Returns the tracked promise so callers can optionally await it.
255
+ */
256
+ sendExternalSpan(payload) {
257
+ return awaitOnExit(
258
+ this.request("/api/sdk/externalSpans", {
259
+ ...payload,
260
+ sdkVersion: __version__
261
+ })
262
+ ).catch((error) => {
263
+ try {
264
+ console.error("Bitfab: Failed to create external span:", error);
265
+ } catch {
266
+ }
267
+ });
268
+ }
269
+ /**
270
+ * Send an external trace (from OpenAI tracing).
271
+ * Fire-and-forget with awaitOnExit - doesn't block the caller.
272
+ */
273
+ sendExternalTrace(payload) {
274
+ void awaitOnExit(
275
+ this.request("/api/sdk/externalTraces", {
276
+ ...payload,
277
+ sdkVersion: __version__
278
+ })
279
+ ).catch((error) => {
280
+ try {
281
+ console.error("Bitfab: Failed to create external trace:", error);
282
+ } catch {
283
+ }
284
+ });
285
+ }
286
+ /**
287
+ * Partial update of an existing external trace identified by sourceTraceId.
288
+ * Used by the detached `client.getTrace(id)` handle. Fire-and-forget;
289
+ * returns a tracked promise that callers may optionally await.
290
+ */
291
+ patchTrace(sourceTraceId, payload) {
292
+ const endpoint = `/api/sdk/externalTraces/${encodeURIComponent(sourceTraceId)}`;
293
+ return awaitOnExit(
294
+ this.request(endpoint, payload, { method: "PATCH" })
295
+ ).catch((error) => {
296
+ try {
297
+ console.error("Bitfab: Failed to patch trace:", error);
298
+ } catch {
299
+ }
300
+ });
301
+ }
302
+ /**
303
+ * Start a replay session by fetching historical traces.
304
+ * Blocking call — creates a test run and returns lightweight item references.
305
+ */
306
+ async startReplay(traceFunctionKey, limit, traceIds, codeChangeDescription, codeChangeFiles) {
307
+ const payload = { traceFunctionKey, limit };
308
+ if (traceIds) {
309
+ payload.traceIds = traceIds;
310
+ }
311
+ if (codeChangeDescription !== void 0) {
312
+ payload.codeChangeDescription = codeChangeDescription;
313
+ }
314
+ if (codeChangeFiles !== void 0) {
315
+ payload.codeChangeFiles = codeChangeFiles;
316
+ }
317
+ return this.request("/api/sdk/replay/start", payload, {
318
+ timeout: 3e4
319
+ });
320
+ }
321
+ /**
322
+ * Fetch an external span by ID.
323
+ * Blocking GET request.
324
+ */
325
+ async getExternalSpan(spanId) {
326
+ const url = `${this.serviceUrl}/api/sdk/externalSpans/${spanId}`;
327
+ const controller = new AbortController();
328
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
329
+ try {
330
+ const response = await fetch(url, {
331
+ method: "GET",
332
+ headers: { Authorization: `Bearer ${this.apiKey}` },
333
+ signal: controller.signal
334
+ });
335
+ if (!response.ok) {
336
+ const errorText = await response.text();
337
+ throw new BitfabError(
338
+ `HTTP ${response.status}: ${errorText.slice(0, 500)}`
339
+ );
340
+ }
341
+ return await response.json();
342
+ } catch (error) {
343
+ if (error instanceof BitfabError) {
344
+ throw error;
345
+ }
346
+ if (error instanceof Error) {
347
+ if (error.name === "AbortError") {
348
+ throw new BitfabError("Request timed out after 30000ms");
349
+ }
350
+ throw new BitfabError(error.message);
351
+ }
352
+ throw new BitfabError("Unknown error occurred");
353
+ } finally {
354
+ clearTimeout(timeoutId);
355
+ }
356
+ }
357
+ /**
358
+ * Fetch the span tree for a root span.
359
+ * Blocking GET request.
360
+ */
361
+ async getSpanTree(externalSpanId) {
362
+ const url = `${this.serviceUrl}/api/sdk/replay/spanTree/${externalSpanId}`;
363
+ const controller = new AbortController();
364
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
365
+ try {
366
+ const response = await fetch(url, {
367
+ method: "GET",
368
+ headers: { Authorization: `Bearer ${this.apiKey}` },
369
+ signal: controller.signal
370
+ });
371
+ if (!response.ok) {
372
+ const errorText = await response.text();
373
+ throw new BitfabError(
374
+ `HTTP ${response.status}: ${errorText.slice(0, 500)}`
375
+ );
376
+ }
377
+ return await response.json();
378
+ } catch (error) {
379
+ if (error instanceof BitfabError) {
380
+ throw error;
381
+ }
382
+ if (error instanceof Error) {
383
+ if (error.name === "AbortError") {
384
+ throw new BitfabError("Request timed out after 30000ms");
385
+ }
386
+ throw new BitfabError(error.message);
387
+ }
388
+ throw new BitfabError("Unknown error occurred");
389
+ } finally {
390
+ clearTimeout(timeoutId);
391
+ }
392
+ }
393
+ /**
394
+ * Mark a replay test run as completed.
395
+ * Blocking call.
396
+ */
397
+ async completeReplay(testRunId) {
398
+ return this.request(
399
+ "/api/sdk/replay/complete",
400
+ { testRunId },
401
+ { timeout: 3e4 }
402
+ );
403
+ }
404
+ };
405
+ }
406
+ });
407
+
408
+ // src/replayContext.ts
409
+ function getReplayContext() {
410
+ return replayContextStorage?.getStore() ?? null;
411
+ }
412
+ function runWithReplayContext(ctx, fn) {
413
+ if (replayContextStorage) {
414
+ return replayContextStorage.run(ctx, fn);
415
+ }
416
+ return fn();
417
+ }
418
+ var replayContextStorage, replayContextReady;
419
+ var init_replayContext = __esm({
420
+ "src/replayContext.ts"() {
421
+ "use strict";
422
+ init_asyncStorage();
423
+ replayContextStorage = null;
424
+ replayContextReady = asyncStorageReady.then(() => {
425
+ replayContextStorage = createAsyncLocalStorage();
426
+ });
427
+ }
428
+ });
429
+
430
+ // src/serialize.ts
431
+ function serializeValue(value) {
432
+ try {
433
+ const { json, meta } = import_superjson.default.serialize(value);
434
+ return meta ? { json, meta } : { json };
435
+ } catch {
436
+ try {
437
+ return { json: JSON.parse(JSON.stringify(value)) };
438
+ } catch {
439
+ return { json: String(value) };
440
+ }
441
+ }
442
+ }
443
+ function deserializeValue(serialized) {
444
+ if (serialized.meta === void 0) {
445
+ return serialized.json;
446
+ }
447
+ return import_superjson.default.deserialize({
448
+ json: serialized.json,
449
+ meta: serialized.meta
450
+ });
451
+ }
452
+ var import_superjson;
453
+ var init_serialize = __esm({
454
+ "src/serialize.ts"() {
455
+ "use strict";
456
+ import_superjson = __toESM(require("superjson"), 1);
457
+ }
458
+ });
459
+
460
+ // src/replay.ts
461
+ var replay_exports = {};
462
+ __export(replay_exports, {
463
+ replay: () => replay
464
+ });
465
+ function deserializeInputs(spanData) {
466
+ const inputMeta = spanData.input_meta;
467
+ const rawInput = spanData.input;
468
+ if (inputMeta !== void 0 && inputMeta !== null) {
469
+ const deserialized = deserializeValue({ json: rawInput, meta: inputMeta });
470
+ if (Array.isArray(deserialized)) {
471
+ return deserialized;
472
+ }
473
+ return deserialized !== void 0 && deserialized !== null ? [deserialized] : [];
474
+ }
475
+ if (Array.isArray(rawInput)) {
476
+ return rawInput;
477
+ }
478
+ return rawInput !== void 0 && rawInput !== null ? [rawInput] : [];
479
+ }
480
+ function deserializeOutput(spanData) {
481
+ const outputMeta = spanData.output_meta;
482
+ const rawOutput = spanData.output;
483
+ if (outputMeta !== void 0 && outputMeta !== null) {
484
+ return deserializeValue({ json: rawOutput, meta: outputMeta });
485
+ }
486
+ return rawOutput;
487
+ }
488
+ function buildMockTree(rootNode) {
489
+ const spans = /* @__PURE__ */ new Map();
490
+ const counters = /* @__PURE__ */ new Map();
491
+ function walk(node) {
492
+ const key = node.traceFunctionKey;
493
+ if (key) {
494
+ const name = node.spanName;
495
+ const counterKey = `${key}:${name}`;
496
+ const index = counters.get(counterKey) ?? 0;
497
+ counters.set(counterKey, index + 1);
498
+ spans.set(`${counterKey}:${index}`, {
499
+ sourceSpanId: node.sourceSpanId,
500
+ output: node.output,
501
+ outputMeta: node.outputMeta
502
+ });
503
+ }
504
+ for (const child of node.children) {
505
+ walk(child);
506
+ }
507
+ }
508
+ for (const child of rootNode.children) {
509
+ walk(child);
510
+ }
511
+ return { spans };
512
+ }
513
+ async function processItem(httpClient, serverItem, fn, testRunId, mockStrategy) {
514
+ const span = await httpClient.getExternalSpan(serverItem.externalSpanId);
515
+ const spanData = span.rawData?.span_data ?? {};
516
+ const inputs = deserializeInputs(spanData);
517
+ const originalOutput = deserializeOutput(spanData);
518
+ let mockTree;
519
+ if (mockStrategy === "all" || mockStrategy === "marked") {
520
+ const treeResponse = await httpClient.getSpanTree(serverItem.externalSpanId);
521
+ mockTree = buildMockTree(treeResponse.root);
522
+ }
523
+ let result;
524
+ let error = null;
525
+ try {
526
+ const maybePromise = runWithReplayContext(
527
+ {
528
+ testRunId,
529
+ inputSourceSpanId: span.id,
530
+ inputSourceTraceId: span.externalTraceId,
531
+ mockTree,
532
+ callCounters: mockTree ? /* @__PURE__ */ new Map() : void 0,
533
+ mockStrategy
534
+ },
535
+ () => fn(...inputs)
536
+ );
537
+ result = maybePromise instanceof Promise ? await maybePromise : maybePromise;
538
+ } catch (e) {
539
+ error = e instanceof Error ? e.message : String(e);
540
+ }
541
+ return {
542
+ input: inputs,
543
+ result,
544
+ originalOutput,
545
+ error,
546
+ durationMs: serverItem.durationMs ?? null,
547
+ tokens: serverItem.tokens ?? null,
548
+ model: serverItem.model ?? null
549
+ };
550
+ }
551
+ async function mapWithConcurrency(tasks, maxConcurrency) {
552
+ const results = new Array(tasks.length);
553
+ let nextIndex = 0;
554
+ async function worker() {
555
+ while (nextIndex < tasks.length) {
556
+ const index = nextIndex++;
557
+ results[index] = await tasks[index]();
558
+ }
559
+ }
560
+ const workers = Array.from(
561
+ { length: Math.min(maxConcurrency, tasks.length) },
562
+ () => worker()
563
+ );
564
+ await Promise.all(workers);
565
+ return results;
566
+ }
567
+ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options) {
568
+ await replayContextReady;
569
+ const {
570
+ testRunId,
571
+ testRunUrl,
572
+ items: serverItems
573
+ } = await httpClient.startReplay(
574
+ traceFunctionKey,
575
+ options?.limit ?? 5,
576
+ options?.traceIds,
577
+ options?.codeChangeDescription,
578
+ options?.codeChangeFiles
579
+ );
580
+ const mockStrategy = options?.mock ?? "none";
581
+ const maxConcurrency = options?.maxConcurrency ?? 10;
582
+ const tasks = serverItems.map(
583
+ (serverItem) => () => processItem(httpClient, serverItem, fn, testRunId, mockStrategy)
584
+ );
585
+ const resultItems = await mapWithConcurrency(tasks, maxConcurrency);
586
+ await flushTraces();
587
+ try {
588
+ await httpClient.completeReplay(testRunId);
589
+ } catch (e) {
590
+ try {
591
+ console.error("Bitfab: Failed to complete replay:", e);
592
+ } catch {
593
+ }
594
+ }
595
+ return {
596
+ items: resultItems,
597
+ testRunId,
598
+ testRunUrl: `${serviceUrl}${testRunUrl}`
599
+ };
600
+ }
601
+ var init_replay = __esm({
602
+ "src/replay.ts"() {
603
+ "use strict";
604
+ init_http();
605
+ init_replayContext();
606
+ init_serialize();
607
+ }
608
+ });
609
+
610
+ // src/node.ts
611
+ var node_exports = {};
612
+ __export(node_exports, {
613
+ Bitfab: () => Bitfab,
614
+ BitfabClaudeAgentHandler: () => BitfabClaudeAgentHandler,
615
+ BitfabError: () => BitfabError,
616
+ BitfabFunction: () => BitfabFunction,
617
+ BitfabLangGraphCallbackHandler: () => BitfabLangGraphCallbackHandler,
618
+ BitfabOpenAITracingProcessor: () => BitfabOpenAITracingProcessor,
619
+ DEFAULT_SERVICE_URL: () => DEFAULT_SERVICE_URL,
620
+ __version__: () => __version__,
621
+ flushTraces: () => flushTraces,
622
+ getCurrentSpan: () => getCurrentSpan,
623
+ getCurrentTrace: () => getCurrentTrace
624
+ });
625
+ module.exports = __toCommonJS(node_exports);
626
+
627
+ // src/asyncStorageNode.ts
628
+ var import_node_async_hooks = require("async_hooks");
629
+ init_asyncStorage();
630
+ registerAsyncLocalStorageClass(
631
+ import_node_async_hooks.AsyncLocalStorage
632
+ );
633
+
634
+ // src/claudeAgentSdk.ts
635
+ init_constants();
636
+ init_http();
637
+ function nowIso() {
638
+ return (/* @__PURE__ */ new Date()).toISOString();
639
+ }
640
+ function safeSerialize(value) {
641
+ if (value === null || value === void 0) {
642
+ return value;
643
+ }
644
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
645
+ return value;
646
+ }
647
+ if (Array.isArray(value)) {
648
+ return value.map(safeSerialize);
649
+ }
650
+ if (typeof value === "object") {
651
+ if (typeof value.toJSON === "function") {
652
+ return value.toJSON();
653
+ }
654
+ const result = {};
655
+ for (const [k, v] of Object.entries(value)) {
656
+ if (!k.startsWith("_")) {
657
+ result[k] = safeSerialize(v);
658
+ }
659
+ }
660
+ return result;
661
+ }
662
+ return String(value);
663
+ }
664
+ function extractContentBlocks(content) {
665
+ if (!Array.isArray(content)) {
666
+ return [];
667
+ }
668
+ return content.map((block) => safeSerialize(block));
669
+ }
670
+ function extractUsage(message) {
671
+ const usageInfo = {};
672
+ const usage = message.usage;
673
+ if (!usage) {
674
+ return usageInfo;
675
+ }
676
+ const mapping = {
677
+ input_tokens: "inputTokens",
678
+ output_tokens: "outputTokens",
679
+ cache_read_input_tokens: "cacheReadTokens",
680
+ cache_creation_input_tokens: "cacheCreationTokens"
681
+ };
682
+ for (const [srcKey, dstKey] of Object.entries(mapping)) {
683
+ const val = usage[srcKey];
684
+ if (val !== void 0 && val !== null) {
685
+ usageInfo[dstKey] = val;
686
+ }
687
+ }
688
+ return usageInfo;
689
+ }
690
+ var BitfabClaudeAgentHandler = class {
691
+ constructor(config) {
692
+ // Span tracking
693
+ this.runToSpan = /* @__PURE__ */ new Map();
694
+ this.traceId = null;
695
+ this.rootSpanId = null;
696
+ this.activeContext = null;
697
+ this.traceStartedAt = null;
698
+ // LLM turn tracking
699
+ this.conversationHistory = [];
700
+ this.pendingMessages = [];
701
+ this.currentLlmSpanId = null;
702
+ this.currentLlmMessageId = null;
703
+ this.currentLlmContent = [];
704
+ this.currentLlmModel = null;
705
+ this.currentLlmUsage = {};
706
+ this.currentLlmStartedAt = null;
707
+ this.currentLlmHistorySnapshot = [];
708
+ // Subagent tracking
709
+ this.activeSubagentSpans = /* @__PURE__ */ new Map();
710
+ this.httpClient = new HttpClient({
711
+ apiKey: config.apiKey,
712
+ serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
713
+ timeout: config.timeout ?? 1e4
714
+ });
715
+ this.traceFunctionKey = config.traceFunctionKey;
716
+ this.getActiveSpanContext = config.getActiveSpanContext ?? null;
717
+ this.preToolUseHook = this.preToolUseHook.bind(this);
718
+ this.postToolUseHook = this.postToolUseHook.bind(this);
719
+ this.postToolUseFailureHook = this.postToolUseFailureHook.bind(this);
720
+ this.subagentStartHook = this.subagentStartHook.bind(this);
721
+ this.subagentStopHook = this.subagentStopHook.bind(this);
722
+ }
723
+ // ── trace lifecycle ──────────────────────────────────────────
724
+ ensureTrace() {
725
+ if (this.traceId !== null) {
726
+ return this.traceId;
727
+ }
728
+ this.activeContext = this.getActiveSpanContext?.() ?? null;
729
+ if (this.activeContext) {
730
+ this.traceId = this.activeContext.traceId;
731
+ } else {
732
+ this.traceId = crypto.randomUUID();
733
+ }
734
+ this.traceStartedAt = nowIso();
735
+ return this.traceId;
736
+ }
737
+ getParentId(agentId) {
738
+ if (agentId) {
739
+ const subagentSpanId = this.activeSubagentSpans.get(agentId);
740
+ if (subagentSpanId) {
741
+ return subagentSpanId;
742
+ }
743
+ }
744
+ return this.activeContext?.spanId ?? this.rootSpanId ?? null;
745
+ }
746
+ // ── span helpers ─────────────────────────────────────────────
747
+ startSpan(spanId, name, spanType, inputData, parentId) {
748
+ const traceId = this.ensureTrace();
749
+ const spanInfo = {
750
+ spanId,
751
+ traceId,
752
+ parentId: parentId ?? null,
753
+ startedAt: nowIso(),
754
+ name,
755
+ type: spanType,
756
+ input: safeSerialize(inputData),
757
+ contexts: []
758
+ };
759
+ this.runToSpan.set(spanId, spanInfo);
760
+ return spanInfo;
761
+ }
762
+ completeSpan(spanId, output, error, extraContexts) {
763
+ const spanInfo = this.runToSpan.get(spanId);
764
+ if (!spanInfo) {
765
+ return;
766
+ }
767
+ this.runToSpan.delete(spanId);
768
+ spanInfo.endedAt = nowIso();
769
+ spanInfo.output = safeSerialize(output);
770
+ if (error !== void 0) {
771
+ spanInfo.error = error;
772
+ }
773
+ if (extraContexts) {
774
+ spanInfo.contexts.push(extraContexts);
775
+ }
776
+ this.sendSpan(spanInfo);
777
+ }
778
+ sendSpan(spanInfo) {
779
+ const spanData = {
780
+ name: spanInfo.name,
781
+ type: spanInfo.type
782
+ };
783
+ if (spanInfo.input !== void 0) {
784
+ spanData.input = spanInfo.input;
785
+ }
786
+ if (spanInfo.output !== void 0) {
787
+ spanData.output = spanInfo.output;
788
+ }
789
+ if (spanInfo.error !== void 0) {
790
+ spanData.error = spanInfo.error;
791
+ }
792
+ if (spanInfo.contexts.length > 0) {
793
+ spanData.contexts = spanInfo.contexts;
794
+ }
795
+ const rawSpan = {
796
+ id: spanInfo.spanId,
797
+ trace_id: spanInfo.traceId,
798
+ started_at: spanInfo.startedAt,
799
+ ended_at: spanInfo.endedAt ?? nowIso(),
800
+ span_data: spanData
801
+ };
802
+ if (spanInfo.parentId !== null) {
803
+ rawSpan.parent_id = spanInfo.parentId;
804
+ }
805
+ const payload = {
806
+ type: "sdk-function",
807
+ source: "typescript-sdk-claude-agent-sdk",
808
+ traceFunctionKey: this.traceFunctionKey,
809
+ sourceTraceId: spanInfo.traceId,
810
+ rawSpan
811
+ };
812
+ try {
813
+ this.httpClient.sendExternalSpan(payload);
814
+ } catch {
815
+ }
816
+ }
817
+ sendTraceCompletion(endedAt, metadata) {
818
+ if (this.traceId === null) {
819
+ return;
820
+ }
821
+ const completed = this.activeContext === null;
822
+ const traceId = this.traceId;
823
+ this.traceId = null;
824
+ const externalTrace = {
825
+ id: traceId,
826
+ started_at: this.traceStartedAt ?? nowIso(),
827
+ ended_at: endedAt ?? nowIso(),
828
+ workflow_name: this.traceFunctionKey
829
+ };
830
+ if (metadata) {
831
+ externalTrace.metadata = metadata;
832
+ }
833
+ const traceData = {
834
+ type: "sdk-function",
835
+ source: "typescript-sdk-claude-agent-sdk",
836
+ traceFunctionKey: this.traceFunctionKey,
837
+ externalTrace,
838
+ completed
839
+ };
840
+ try {
841
+ this.httpClient.sendExternalTrace(traceData);
842
+ } catch {
843
+ }
844
+ }
845
+ // ── hook callbacks ───────────────────────────────────────────
846
+ async preToolUseHook(inputData, toolUseId, _context) {
847
+ try {
848
+ const sid = inputData.tool_use_id ?? toolUseId ?? crypto.randomUUID();
849
+ const toolName = inputData.tool_name ?? "tool";
850
+ const toolInput = inputData.tool_input ?? {};
851
+ const agentId = inputData.agent_id;
852
+ const parentId = this.getParentId(agentId);
853
+ this.startSpan(sid, toolName, "function", toolInput, parentId);
854
+ } catch {
855
+ }
856
+ return {};
857
+ }
858
+ async postToolUseHook(inputData, toolUseId, _context) {
859
+ try {
860
+ const sid = inputData.tool_use_id ?? toolUseId ?? "";
861
+ const toolResponse = inputData.tool_response;
862
+ this.completeSpan(sid, toolResponse);
863
+ } catch {
864
+ }
865
+ return {};
866
+ }
867
+ async postToolUseFailureHook(inputData, toolUseId, _context) {
868
+ try {
869
+ const sid = inputData.tool_use_id ?? toolUseId ?? "";
870
+ const error = String(inputData.error ?? "Unknown error");
871
+ this.completeSpan(sid, void 0, error);
872
+ } catch {
873
+ }
874
+ return {};
875
+ }
876
+ async subagentStartHook(inputData, _toolUseId, _context) {
877
+ try {
878
+ const agentId = inputData.agent_id ?? crypto.randomUUID();
879
+ const agentType = inputData.agent_type ?? "subagent";
880
+ const parentId = this.getParentId();
881
+ const spanId = crypto.randomUUID();
882
+ this.activeSubagentSpans.set(agentId, spanId);
883
+ this.startSpan(
884
+ spanId,
885
+ `Agent: ${agentType}`,
886
+ "agent",
887
+ void 0,
888
+ parentId
889
+ );
890
+ } catch {
891
+ }
892
+ return {};
893
+ }
894
+ async subagentStopHook(inputData, _toolUseId, _context) {
895
+ try {
896
+ const agentId = inputData.agent_id ?? "";
897
+ const spanId = this.activeSubagentSpans.get(agentId);
898
+ if (spanId) {
899
+ this.activeSubagentSpans.delete(agentId);
900
+ this.completeSpan(spanId);
901
+ }
902
+ } catch {
903
+ }
904
+ return {};
905
+ }
906
+ // ── public API ───────────────────────────────────────────────
907
+ /**
908
+ * Inject Bitfab tracing hooks into Claude Agent SDK options.
909
+ *
910
+ * Modifies the options object and returns it for convenience.
911
+ * The SDK's `HookMatcher` is constructed as a plain object
912
+ * (`{ matcher: null, hooks: [callback] }`) to avoid requiring
913
+ * `@anthropic-ai/claude-agent-sdk` as a dependency.
914
+ *
915
+ * @param options - Options object with a `hooks` property
916
+ * @returns The modified options object with Bitfab hooks injected
917
+ */
918
+ instrumentOptions(options) {
919
+ const hooks = options.hooks ?? {};
920
+ if (!options.hooks) {
921
+ ;
922
+ options.hooks = hooks;
923
+ }
924
+ const hookConfig = [
925
+ ["PreToolUse", this.preToolUseHook],
926
+ ["PostToolUse", this.postToolUseHook],
927
+ ["PostToolUseFailure", this.postToolUseFailureHook],
928
+ ["SubagentStart", this.subagentStartHook],
929
+ ["SubagentStop", this.subagentStopHook]
930
+ ];
931
+ for (const [event, callback] of hookConfig) {
932
+ if (!hooks[event]) {
933
+ hooks[event] = [];
934
+ }
935
+ hooks[event].push({ matcher: null, hooks: [callback] });
936
+ }
937
+ return options;
938
+ }
939
+ /**
940
+ * Wrap a `ClaudeSDKClient.receiveResponse()` stream to capture LLM turns.
941
+ *
942
+ * Yields every message unchanged while capturing AssistantMessage
943
+ * content as LLM turn spans.
944
+ */
945
+ async *wrapResponse(stream) {
946
+ yield* this.processStream(stream);
947
+ }
948
+ /**
949
+ * Wrap a `query()` async iterator to capture LLM turns.
950
+ *
951
+ * Same as `wrapResponse` but for the simpler `query()` API
952
+ * which does not support hooks (no tool/subagent spans).
953
+ */
954
+ async *wrapQuery(stream) {
955
+ yield* this.processStream(stream);
956
+ }
957
+ // ── stream processing ────────────────────────────────────────
958
+ async *processStream(stream) {
959
+ try {
960
+ for await (const message of stream) {
961
+ try {
962
+ this.processMessage(message);
963
+ } catch {
964
+ }
965
+ yield message;
966
+ }
967
+ } finally {
968
+ try {
969
+ this.flushLlmTurn();
970
+ this.sendTraceCompletion();
971
+ } catch {
972
+ }
973
+ this.resetState();
974
+ }
975
+ }
976
+ processMessage(message) {
977
+ const typeName = message.constructor?.name ?? "";
978
+ if (typeName === "AssistantMessage") {
979
+ this.handleAssistantMessage(message);
980
+ } else if (typeName === "UserMessage") {
981
+ this.handleUserMessage(message);
982
+ } else if (typeName === "ResultMessage") {
983
+ this.handleResultMessage(message);
984
+ }
985
+ }
986
+ handleAssistantMessage(message) {
987
+ this.ensureTrace();
988
+ const messageId = message.message_id;
989
+ if (messageId !== this.currentLlmMessageId) {
990
+ this.flushLlmTurn();
991
+ this.conversationHistory.push(...this.pendingMessages);
992
+ this.pendingMessages = [];
993
+ this.currentLlmSpanId = crypto.randomUUID();
994
+ this.currentLlmMessageId = messageId ?? null;
995
+ this.currentLlmContent = [];
996
+ this.currentLlmModel = message.model ?? null;
997
+ this.currentLlmUsage = {};
998
+ this.currentLlmStartedAt = nowIso();
999
+ this.currentLlmHistorySnapshot = [...this.conversationHistory];
1000
+ }
1001
+ const content = message.content;
1002
+ if (Array.isArray(content)) {
1003
+ this.currentLlmContent.push(...extractContentBlocks(content));
1004
+ }
1005
+ const usage = extractUsage(message);
1006
+ if (Object.keys(usage).length > 0) {
1007
+ Object.assign(this.currentLlmUsage, usage);
1008
+ }
1009
+ const model = message.model;
1010
+ if (model) {
1011
+ this.currentLlmModel = model;
1012
+ }
1013
+ }
1014
+ handleUserMessage(message) {
1015
+ const content = message.content;
1016
+ const toolUseResult = message.tool_use_result;
1017
+ if (toolUseResult !== void 0) {
1018
+ this.pendingMessages.push({
1019
+ role: "tool",
1020
+ content: safeSerialize(content),
1021
+ tool_result: safeSerialize(toolUseResult)
1022
+ });
1023
+ } else {
1024
+ this.pendingMessages.push({
1025
+ role: "user",
1026
+ content: safeSerialize(content)
1027
+ });
1028
+ }
1029
+ }
1030
+ handleResultMessage(message) {
1031
+ this.flushLlmTurn();
1032
+ const metadata = {};
1033
+ for (const attr of [
1034
+ "num_turns",
1035
+ "total_cost_usd",
1036
+ "duration_ms",
1037
+ "duration_api_ms",
1038
+ "session_id"
1039
+ ]) {
1040
+ const val = message[attr];
1041
+ if (val !== void 0 && val !== null) {
1042
+ metadata[attr] = val;
1043
+ }
1044
+ }
1045
+ const usage = message.usage;
1046
+ if (usage && typeof usage === "object") {
1047
+ metadata.usage = safeSerialize(usage);
1048
+ }
1049
+ this.sendTraceCompletion(
1050
+ void 0,
1051
+ Object.keys(metadata).length > 0 ? metadata : void 0
1052
+ );
1053
+ }
1054
+ flushLlmTurn() {
1055
+ if (this.currentLlmSpanId === null) {
1056
+ return;
1057
+ }
1058
+ const spanId = this.currentLlmSpanId;
1059
+ const traceId = this.ensureTrace();
1060
+ const parentId = this.getParentId();
1061
+ const llmContext = {};
1062
+ if (this.currentLlmModel) {
1063
+ llmContext.model = this.currentLlmModel;
1064
+ }
1065
+ Object.assign(llmContext, this.currentLlmUsage);
1066
+ const spanInfo = {
1067
+ spanId,
1068
+ traceId,
1069
+ parentId,
1070
+ startedAt: this.currentLlmStartedAt ?? nowIso(),
1071
+ endedAt: nowIso(),
1072
+ name: this.currentLlmModel ?? "llm",
1073
+ type: "llm",
1074
+ input: this.currentLlmHistorySnapshot,
1075
+ output: this.currentLlmContent,
1076
+ contexts: Object.keys(llmContext).length > 0 ? [llmContext] : []
1077
+ };
1078
+ this.sendSpan(spanInfo);
1079
+ this.conversationHistory.push({
1080
+ role: "assistant",
1081
+ content: this.currentLlmContent
1082
+ });
1083
+ this.currentLlmSpanId = null;
1084
+ this.currentLlmMessageId = null;
1085
+ this.currentLlmContent = [];
1086
+ this.currentLlmModel = null;
1087
+ this.currentLlmUsage = {};
1088
+ this.currentLlmStartedAt = null;
1089
+ this.currentLlmHistorySnapshot = [];
1090
+ }
1091
+ resetState() {
1092
+ this.runToSpan.clear();
1093
+ this.traceId = null;
1094
+ this.rootSpanId = null;
1095
+ this.activeContext = null;
1096
+ this.traceStartedAt = null;
1097
+ this.conversationHistory = [];
1098
+ this.pendingMessages = [];
1099
+ this.currentLlmSpanId = null;
1100
+ this.currentLlmMessageId = null;
1101
+ this.currentLlmContent = [];
1102
+ this.currentLlmModel = null;
1103
+ this.currentLlmUsage = {};
1104
+ this.currentLlmStartedAt = null;
1105
+ this.currentLlmHistorySnapshot = [];
1106
+ this.activeSubagentSpans.clear();
1107
+ }
1108
+ };
1109
+
1110
+ // src/client.ts
1111
+ init_asyncStorage();
1112
+
1113
+ // src/baml.ts
1114
+ var cachedBaml = null;
1115
+ async function loadBaml() {
1116
+ if (cachedBaml) {
1117
+ return cachedBaml;
1118
+ }
1119
+ try {
1120
+ cachedBaml = await import("@boundaryml/baml");
1121
+ return cachedBaml;
1122
+ } catch {
1123
+ throw new Error(
1124
+ "@boundaryml/baml is required for Bitfab.call(). Install it with: npm install @boundaryml/baml"
1125
+ );
1126
+ }
1127
+ }
1128
+ function capitalize(str) {
1129
+ return str.charAt(0).toUpperCase() + str.slice(1);
1130
+ }
1131
+ function formatProvider(provider) {
1132
+ const providerMap = {
1133
+ openai: "OpenAI",
1134
+ anthropic: "Anthropic",
1135
+ google: "Google"
1136
+ };
1137
+ return providerMap[provider] ?? capitalize(provider);
1138
+ }
1139
+ function formatModel(model) {
1140
+ return model.replace(/^gpt-/, "GPT").replace(/\./g, "_").replace(/-/g, "_");
1141
+ }
1142
+ function getClientName(provider, model) {
1143
+ return `${formatProvider(provider)}_${formatModel(model)}`;
1144
+ }
1145
+ function generateClientDefinitions(providers) {
1146
+ const definitions = [];
1147
+ for (const providerDef of providers) {
1148
+ for (const model of providerDef.models) {
1149
+ const clientName = getClientName(providerDef.provider, model.model);
1150
+ definitions.push(`client<llm> ${clientName} {
1151
+ provider ${providerDef.provider}
1152
+ options {
1153
+ model "${model.model}"
1154
+ api_key env.${providerDef.apiKeyEnv}
1155
+ }
1156
+ }`);
1157
+ }
1158
+ }
1159
+ return definitions.join("\n\n");
1160
+ }
1161
+ function withDefaultClients(bamlSource, providers) {
1162
+ const hasDefaultClient = bamlSource.includes("client<llm> OpenAI_");
1163
+ if (hasDefaultClient) {
1164
+ return bamlSource;
1165
+ }
1166
+ const defaultClients = generateClientDefinitions(providers);
1167
+ return `${defaultClients}
1168
+
1169
+ ${bamlSource}`;
1170
+ }
1171
+ function extractFunctionName(bamlSource) {
1172
+ const match = bamlSource.match(/function\s+(\w+)\s*\(/);
1173
+ return match?.[1] ?? null;
1174
+ }
1175
+ function extractFunctionParameters(bamlSource) {
1176
+ const functionMatch = bamlSource.match(/function\s+\w+\s*\(([^)]*)\)\s*->/);
1177
+ if (!functionMatch) {
1178
+ return [];
1179
+ }
1180
+ const paramsString = functionMatch[1].trim();
1181
+ if (!paramsString) {
1182
+ return [];
1183
+ }
1184
+ const params = [];
1185
+ const paramParts = splitParameters(paramsString);
1186
+ for (const part of paramParts) {
1187
+ const trimmed = part.trim();
1188
+ if (!trimmed) {
1189
+ continue;
1190
+ }
1191
+ const paramMatch = trimmed.match(/^(\w+)\s*:\s*(.+)$/);
1192
+ if (paramMatch) {
1193
+ const name = paramMatch[1];
1194
+ let type = paramMatch[2].trim();
1195
+ const isOptional = type.endsWith("?");
1196
+ if (isOptional) {
1197
+ type = type.slice(0, -1);
1198
+ }
1199
+ params.push({ name, type, isOptional });
1200
+ }
1201
+ }
1202
+ return params;
1203
+ }
1204
+ function splitParameters(paramsString) {
1205
+ const parts = [];
1206
+ let current = "";
1207
+ let depth = 0;
1208
+ for (const char of paramsString) {
1209
+ if (char === "<") {
1210
+ depth++;
1211
+ current += char;
1212
+ } else if (char === ">") {
1213
+ depth--;
1214
+ current += char;
1215
+ } else if (char === "," && depth === 0) {
1216
+ parts.push(current);
1217
+ current = "";
1218
+ } else {
1219
+ current += char;
1220
+ }
1221
+ }
1222
+ if (current.trim()) {
1223
+ parts.push(current);
1224
+ }
1225
+ return parts;
1226
+ }
1227
+ function coerceToType(value, expectedType) {
1228
+ if (expectedType === "string") {
1229
+ return value;
1230
+ }
1231
+ if (expectedType === "int") {
1232
+ const parsed = Number.parseInt(value, 10);
1233
+ if (!Number.isNaN(parsed)) {
1234
+ return parsed;
1235
+ }
1236
+ return value;
1237
+ }
1238
+ if (expectedType === "float") {
1239
+ const parsed = Number.parseFloat(value);
1240
+ if (!Number.isNaN(parsed)) {
1241
+ return parsed;
1242
+ }
1243
+ return value;
1244
+ }
1245
+ if (expectedType === "bool") {
1246
+ const lower = value.toLowerCase();
1247
+ if (lower === "true") {
1248
+ return true;
1249
+ }
1250
+ if (lower === "false") {
1251
+ return false;
1252
+ }
1253
+ return value;
1254
+ }
1255
+ if (expectedType.endsWith("[]")) {
1256
+ try {
1257
+ const parsed = JSON.parse(value);
1258
+ if (Array.isArray(parsed)) {
1259
+ return parsed;
1260
+ }
1261
+ } catch {
1262
+ }
1263
+ return value;
1264
+ }
1265
+ try {
1266
+ return JSON.parse(value);
1267
+ } catch {
1268
+ return value;
1269
+ }
1270
+ }
1271
+ function coerceInputs(inputs, expectedTypes) {
1272
+ const coerced = {};
1273
+ for (const [key, value] of Object.entries(inputs)) {
1274
+ if (typeof value === "string") {
1275
+ const expectedType = expectedTypes.get(key);
1276
+ if (expectedType) {
1277
+ coerced[key] = coerceToType(value, expectedType);
1278
+ } else {
1279
+ coerced[key] = value;
1280
+ }
1281
+ } else {
1282
+ coerced[key] = value;
1283
+ }
1284
+ }
1285
+ return coerced;
1286
+ }
1287
+ function objToDict(obj, depth = 0, maxDepth = 5) {
1288
+ if (depth > maxDepth) {
1289
+ return `<max depth reached: ${typeof obj}>`;
1290
+ }
1291
+ if (obj === null || obj === void 0 || typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean") {
1292
+ return obj;
1293
+ }
1294
+ if (Array.isArray(obj)) {
1295
+ return obj.map((item) => objToDict(item, depth + 1, maxDepth));
1296
+ }
1297
+ if (typeof obj === "object") {
1298
+ const result = {};
1299
+ if (obj.constructor && obj.constructor.name !== "Object") {
1300
+ result.__type__ = obj.constructor.name;
1301
+ }
1302
+ for (const key of Object.keys(obj)) {
1303
+ if (key.startsWith("_")) {
1304
+ continue;
1305
+ }
1306
+ try {
1307
+ const value = obj[key];
1308
+ if (typeof value === "function") {
1309
+ continue;
1310
+ }
1311
+ result[key] = objToDict(value, depth + 1, maxDepth);
1312
+ } catch (error) {
1313
+ result[key] = `<error: ${error instanceof Error ? error.message : String(error)}>`;
1314
+ }
1315
+ }
1316
+ try {
1317
+ const proto = Object.getPrototypeOf(obj);
1318
+ if (proto && proto !== Object.prototype) {
1319
+ const descriptors = Object.getOwnPropertyDescriptors(proto);
1320
+ for (const [key, descriptor] of Object.entries(descriptors)) {
1321
+ if (key.startsWith("_") || key === "constructor" || key in result) {
1322
+ continue;
1323
+ }
1324
+ if (descriptor.get) {
1325
+ try {
1326
+ const value = obj[key];
1327
+ if (typeof value !== "function") {
1328
+ result[key] = objToDict(value, depth + 1, maxDepth);
1329
+ }
1330
+ } catch {
1331
+ }
1332
+ }
1333
+ }
1334
+ }
1335
+ } catch {
1336
+ }
1337
+ return result;
1338
+ }
1339
+ return String(obj);
1340
+ }
1341
+ function serializeCollector(collector) {
1342
+ try {
1343
+ return objToDict(collector, 0, 5);
1344
+ } catch (_error) {
1345
+ return null;
1346
+ }
1347
+ }
1348
+ var ALLOWED_ENV_KEYS = ["OPENAI_API_KEY"];
1349
+ function filterEnvVars(envVars) {
1350
+ const filtered = {};
1351
+ for (const key of ALLOWED_ENV_KEYS) {
1352
+ const value = envVars[key];
1353
+ if (value) {
1354
+ filtered[key] = value;
1355
+ }
1356
+ }
1357
+ return filtered;
1358
+ }
1359
+ async function runFunctionWithBaml(bamlSource, inputs, providers, envVars) {
1360
+ const { BamlRuntime, Collector } = await loadBaml();
1361
+ const functionName = extractFunctionName(bamlSource);
1362
+ if (!functionName) {
1363
+ throw new Error("No function found in BAML source");
1364
+ }
1365
+ const fullSource = withDefaultClients(bamlSource, providers);
1366
+ const filteredEnvVars = filterEnvVars(envVars);
1367
+ const runtime = BamlRuntime.fromFiles(
1368
+ "/tmp/baml_runtime",
1369
+ { "source.baml": fullSource },
1370
+ filteredEnvVars
1371
+ );
1372
+ const ctx = runtime.createContextManager();
1373
+ const collector = new Collector("bitfab-collector");
1374
+ const params = extractFunctionParameters(bamlSource);
1375
+ const expectedTypes = new Map(params.map((p) => [p.name, p.type]));
1376
+ const args = coerceInputs(inputs, expectedTypes);
1377
+ const functionResult = await runtime.callFunction(
1378
+ functionName,
1379
+ args,
1380
+ ctx,
1381
+ null,
1382
+ // TypeBuilder
1383
+ null,
1384
+ // ClientRegistry
1385
+ [collector],
1386
+ // Collectors - capture execution data
1387
+ {},
1388
+ // Tags
1389
+ filteredEnvVars
1390
+ );
1391
+ if (!functionResult.isOk()) {
1392
+ throw new Error("BAML function execution failed");
1393
+ }
1394
+ const rawCollector = serializeCollector(collector);
1395
+ return {
1396
+ result: functionResult.parsed(false),
1397
+ rawCollector
1398
+ };
1399
+ }
1400
+
1401
+ // src/client.ts
1402
+ init_constants();
1403
+ init_http();
1404
+
1405
+ // src/langgraph.ts
1406
+ init_constants();
1407
+ init_http();
1408
+ var LANGSMITH_HIDDEN_TAG = "langsmith:hidden";
1409
+ var LANGGRAPH_METADATA_KEYS = [
1410
+ "langgraph_step",
1411
+ "langgraph_node",
1412
+ "langgraph_triggers",
1413
+ "langgraph_path",
1414
+ "langgraph_checkpoint_ns"
1415
+ ];
1416
+ function nowIso2() {
1417
+ return (/* @__PURE__ */ new Date()).toISOString();
1418
+ }
1419
+ var MAX_SERIALIZE_DEPTH = 6;
1420
+ function safeSerialize2(value) {
1421
+ return safeSerializeInner(value, 0, /* @__PURE__ */ new WeakSet());
1422
+ }
1423
+ function safeSerializeInner(value, depth, seen) {
1424
+ if (value === null || value === void 0) {
1425
+ return value;
1426
+ }
1427
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1428
+ return value;
1429
+ }
1430
+ const className = value?.constructor?.name ?? typeof value;
1431
+ if (depth > MAX_SERIALIZE_DEPTH) {
1432
+ return `<${className}>`;
1433
+ }
1434
+ if (typeof value === "object") {
1435
+ if (seen.has(value)) {
1436
+ return `<cycle ${className}>`;
1437
+ }
1438
+ seen.add(value);
1439
+ }
1440
+ if (Array.isArray(value)) {
1441
+ return value.map((item) => safeSerializeInner(item, depth + 1, seen));
1442
+ }
1443
+ if (typeof value === "object") {
1444
+ if (typeof value.toJSON === "function") {
1445
+ try {
1446
+ return value.toJSON();
1447
+ } catch {
1448
+ return `<${className}>`;
1449
+ }
1450
+ }
1451
+ try {
1452
+ const result = {};
1453
+ for (const [k, v] of Object.entries(value)) {
1454
+ if (!k.startsWith("_")) {
1455
+ result[k] = safeSerializeInner(v, depth + 1, seen);
1456
+ }
1457
+ }
1458
+ return result;
1459
+ } catch {
1460
+ return `<${className}>`;
1461
+ }
1462
+ }
1463
+ try {
1464
+ return String(value);
1465
+ } catch {
1466
+ return `<${className}>`;
1467
+ }
1468
+ }
1469
+ function convertMessage(message) {
1470
+ if (typeof message !== "object" || message === null) {
1471
+ return { role: "unknown", content: String(message) };
1472
+ }
1473
+ const msg = message;
1474
+ if (typeof msg.toDict === "function") {
1475
+ return msg.toDict();
1476
+ }
1477
+ const typeToRole = {
1478
+ human: "user",
1479
+ ai: "assistant",
1480
+ system: "system",
1481
+ tool: "tool",
1482
+ function: "function"
1483
+ };
1484
+ const result = {};
1485
+ const msgType = msg._getType ? String(msg._getType()) : msg.type;
1486
+ result.role = (msgType ? typeToRole[msgType] : void 0) ?? msg.role ?? "unknown";
1487
+ result.content = msg.content ?? "";
1488
+ if (msg.tool_calls) {
1489
+ result.tool_calls = msg.tool_calls;
1490
+ }
1491
+ if (msg.tool_call_id) {
1492
+ result.tool_call_id = msg.tool_call_id;
1493
+ }
1494
+ if (msg.name) {
1495
+ result.name = msg.name;
1496
+ }
1497
+ return result;
1498
+ }
1499
+ function extractModelName(serialized, metadata) {
1500
+ if (serialized) {
1501
+ const kwargs = serialized.kwargs;
1502
+ if (kwargs) {
1503
+ const model = kwargs.model_name ?? kwargs.model ?? kwargs.model_id;
1504
+ if (model) {
1505
+ return String(model);
1506
+ }
1507
+ }
1508
+ }
1509
+ if (metadata) {
1510
+ const lsModel = metadata.ls_model_name;
1511
+ if (lsModel) {
1512
+ return String(lsModel);
1513
+ }
1514
+ }
1515
+ return void 0;
1516
+ }
1517
+ function extractUsage2(output) {
1518
+ const usage = {};
1519
+ const llmOutput = output.llmOutput;
1520
+ const tokenUsage = llmOutput?.tokenUsage ?? llmOutput?.token_usage ?? llmOutput?.usage ?? {};
1521
+ const inputTokens = tokenUsage.promptTokens ?? tokenUsage.prompt_tokens ?? tokenUsage.input_tokens;
1522
+ const outputTokens = tokenUsage.completionTokens ?? tokenUsage.completion_tokens ?? tokenUsage.output_tokens;
1523
+ const totalTokens = tokenUsage.totalTokens ?? tokenUsage.total_tokens;
1524
+ if (inputTokens !== void 0 && inputTokens !== null) {
1525
+ usage.inputTokens = inputTokens;
1526
+ }
1527
+ if (outputTokens !== void 0 && outputTokens !== null) {
1528
+ usage.outputTokens = outputTokens;
1529
+ }
1530
+ if (totalTokens !== void 0 && totalTokens !== null) {
1531
+ usage.totalTokens = totalTokens;
1532
+ }
1533
+ return usage;
1534
+ }
1535
+ function extractLangGraphMetadata(metadata) {
1536
+ if (!metadata) {
1537
+ return {};
1538
+ }
1539
+ const result = {};
1540
+ for (const key of LANGGRAPH_METADATA_KEYS) {
1541
+ if (key in metadata) {
1542
+ result[key] = metadata[key];
1543
+ }
1544
+ }
1545
+ return result;
1546
+ }
1547
+ var BitfabLangGraphCallbackHandler = class {
1548
+ constructor(config) {
1549
+ this.name = "BitfabLangGraphCallbackHandler";
1550
+ this.ignoreRetriever = true;
1551
+ this.ignoreRetry = true;
1552
+ this.ignoreCustomEvent = true;
1553
+ this.runToSpan = /* @__PURE__ */ new Map();
1554
+ this.invocations = /* @__PURE__ */ new Map();
1555
+ this.httpClient = new HttpClient({
1556
+ apiKey: config.apiKey,
1557
+ serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
1558
+ timeout: config.timeout ?? 1e4
1559
+ });
1560
+ this.traceFunctionKey = config.traceFunctionKey;
1561
+ this.getActiveSpanContext = config.getActiveSpanContext ?? null;
1562
+ }
1563
+ // ── lifecycle helpers ──────────────────────────────────────────
1564
+ startSpan(runId, parentRunId, name, spanType, inputData, metadata, tags) {
1565
+ const parentSpan = parentRunId ? this.runToSpan.get(parentRunId) : void 0;
1566
+ const willHide = tags?.includes(LANGSMITH_HIDDEN_TAG) === true;
1567
+ let invocation;
1568
+ let effectiveParentId;
1569
+ if (parentSpan) {
1570
+ const existing = this.invocations.get(parentSpan.rootRunId);
1571
+ if (existing) {
1572
+ invocation = existing;
1573
+ } else {
1574
+ invocation = {
1575
+ traceId: parentSpan.traceId,
1576
+ activeContext: null,
1577
+ rootRunId: parentSpan.rootRunId
1578
+ };
1579
+ this.invocations.set(invocation.rootRunId, invocation);
1580
+ }
1581
+ if (!willHide) {
1582
+ let resolved = parentSpan;
1583
+ while (resolved?.hidden === true) {
1584
+ resolved = resolved.parentId ? this.runToSpan.get(resolved.parentId) : void 0;
1585
+ }
1586
+ effectiveParentId = resolved ? resolved.spanId : invocation.activeContext?.spanId ?? null;
1587
+ } else {
1588
+ effectiveParentId = parentRunId ?? null;
1589
+ }
1590
+ } else {
1591
+ const activeContext = this.getActiveSpanContext?.() ?? null;
1592
+ invocation = {
1593
+ traceId: activeContext ? activeContext.traceId : crypto.randomUUID(),
1594
+ activeContext,
1595
+ rootRunId: runId
1596
+ };
1597
+ this.invocations.set(runId, invocation);
1598
+ effectiveParentId = activeContext?.spanId ?? null;
1599
+ }
1600
+ const lgMetadata = extractLangGraphMetadata(metadata);
1601
+ const contexts = Object.keys(lgMetadata).length > 0 ? [lgMetadata] : [];
1602
+ const spanInfo = {
1603
+ spanId: runId,
1604
+ traceId: invocation.traceId,
1605
+ rootRunId: invocation.rootRunId,
1606
+ parentId: effectiveParentId,
1607
+ startedAt: nowIso2(),
1608
+ name,
1609
+ type: spanType,
1610
+ input: safeSerialize2(inputData),
1611
+ contexts
1612
+ };
1613
+ if (willHide) {
1614
+ spanInfo.hidden = true;
1615
+ }
1616
+ this.runToSpan.set(runId, spanInfo);
1617
+ return spanInfo;
1618
+ }
1619
+ completeSpan(runId, output, error, extraContexts) {
1620
+ const spanInfo = this.runToSpan.get(runId);
1621
+ if (!spanInfo) {
1622
+ return;
1623
+ }
1624
+ this.runToSpan.delete(runId);
1625
+ spanInfo.endedAt = nowIso2();
1626
+ spanInfo.output = safeSerialize2(output);
1627
+ if (error !== void 0) {
1628
+ spanInfo.error = error;
1629
+ }
1630
+ if (extraContexts && Object.keys(extraContexts).length > 0) {
1631
+ spanInfo.contexts.push(extraContexts);
1632
+ }
1633
+ this.sendSpan(spanInfo);
1634
+ if (runId === spanInfo.rootRunId) {
1635
+ const invocation = this.invocations.get(runId);
1636
+ this.sendTraceCompletion(spanInfo, invocation?.activeContext ?? null);
1637
+ this.invocations.delete(runId);
1638
+ }
1639
+ }
1640
+ sendSpan(spanInfo) {
1641
+ const spanData = {
1642
+ name: spanInfo.name,
1643
+ type: spanInfo.type
1644
+ };
1645
+ if (spanInfo.input !== void 0) {
1646
+ spanData.input = spanInfo.input;
1647
+ }
1648
+ if (spanInfo.output !== void 0) {
1649
+ spanData.output = spanInfo.output;
1650
+ }
1651
+ if (spanInfo.error !== void 0) {
1652
+ spanData.error = spanInfo.error;
1653
+ }
1654
+ if (spanInfo.contexts.length > 0) {
1655
+ spanData.contexts = spanInfo.contexts;
1656
+ }
1657
+ if (spanInfo.hidden) {
1658
+ spanData.hidden = true;
1659
+ }
1660
+ const rawSpan = {
1661
+ id: spanInfo.spanId,
1662
+ trace_id: spanInfo.traceId,
1663
+ started_at: spanInfo.startedAt,
1664
+ ended_at: spanInfo.endedAt ?? nowIso2(),
1665
+ span_data: spanData
1666
+ };
1667
+ if (spanInfo.parentId !== null) {
1668
+ rawSpan.parent_id = spanInfo.parentId;
1669
+ }
1670
+ const payload = {
1671
+ type: "sdk-function",
1672
+ source: "typescript-sdk-langgraph",
1673
+ traceFunctionKey: this.traceFunctionKey,
1674
+ sourceTraceId: spanInfo.traceId,
1675
+ rawSpan
1676
+ };
1677
+ try {
1678
+ this.httpClient.sendExternalSpan(payload);
1679
+ } catch {
1680
+ }
1681
+ }
1682
+ sendTraceCompletion(rootSpan, activeContext) {
1683
+ const completed = activeContext === null;
1684
+ const traceData = {
1685
+ type: "sdk-function",
1686
+ source: "typescript-sdk-langgraph",
1687
+ traceFunctionKey: this.traceFunctionKey,
1688
+ externalTrace: {
1689
+ id: rootSpan.traceId,
1690
+ started_at: rootSpan.startedAt,
1691
+ ended_at: rootSpan.endedAt ?? nowIso2(),
1692
+ workflow_name: this.traceFunctionKey
1693
+ },
1694
+ completed
1695
+ };
1696
+ try {
1697
+ this.httpClient.sendExternalTrace(traceData);
1698
+ } catch {
1699
+ }
1700
+ }
1701
+ // ── chain callbacks (graph nodes) ─────────────────────────────
1702
+ async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata) {
1703
+ try {
1704
+ const idArr = chain.id;
1705
+ const name = chain.name ?? idArr?.[idArr.length - 1] ?? "chain";
1706
+ this.startSpan(
1707
+ runId,
1708
+ parentRunId,
1709
+ String(name),
1710
+ "agent",
1711
+ inputs,
1712
+ metadata,
1713
+ tags
1714
+ );
1715
+ } catch {
1716
+ }
1717
+ }
1718
+ async handleChainEnd(outputs, runId) {
1719
+ try {
1720
+ this.completeSpan(runId, outputs);
1721
+ } catch {
1722
+ }
1723
+ }
1724
+ async handleChainError(error, runId) {
1725
+ try {
1726
+ const errorObj = error;
1727
+ if (errorObj?.constructor?.name === "GraphBubbleUp") {
1728
+ this.completeSpan(runId, void 0, void 0);
1729
+ return;
1730
+ }
1731
+ this.completeSpan(
1732
+ runId,
1733
+ void 0,
1734
+ error instanceof Error ? error.message : String(error)
1735
+ );
1736
+ } catch {
1737
+ }
1738
+ }
1739
+ // ── LLM callbacks ─────────────────────────────────────────────
1740
+ async handleChatModelStart(llm, messages, runId, parentRunId, _extraParams, tags, metadata) {
1741
+ try {
1742
+ const model = extractModelName(llm, metadata);
1743
+ const idArr = llm.id;
1744
+ const name = model ?? idArr?.[idArr.length - 1] ?? "llm";
1745
+ const converted = messages.map((batch) => batch.map(convertMessage));
1746
+ const spanInfo = this.startSpan(
1747
+ runId,
1748
+ parentRunId,
1749
+ String(name),
1750
+ "llm",
1751
+ converted,
1752
+ metadata,
1753
+ tags
1754
+ );
1755
+ spanInfo.model = model;
1756
+ } catch {
1757
+ }
1758
+ }
1759
+ async handleLLMStart(llm, prompts, runId, parentRunId, _extraParams, tags, metadata) {
1760
+ try {
1761
+ const model = extractModelName(llm, metadata);
1762
+ const idArr = llm.id;
1763
+ const name = model ?? idArr?.[idArr.length - 1] ?? "llm";
1764
+ const spanInfo = this.startSpan(
1765
+ runId,
1766
+ parentRunId,
1767
+ String(name),
1768
+ "llm",
1769
+ prompts,
1770
+ metadata,
1771
+ tags
1772
+ );
1773
+ spanInfo.model = model;
1774
+ } catch {
1775
+ }
1776
+ }
1777
+ async handleLLMEnd(output, runId) {
1778
+ try {
1779
+ let llmOutput;
1780
+ const generations = output.generations;
1781
+ if (generations?.length && generations[generations.length - 1]?.length) {
1782
+ const gen = generations[generations.length - 1][generations[generations.length - 1].length - 1];
1783
+ const msg = gen.message;
1784
+ llmOutput = msg ? convertMessage(msg) : gen.text ?? String(gen);
1785
+ }
1786
+ const usage = extractUsage2(output);
1787
+ const spanInfo = this.runToSpan.get(runId);
1788
+ const model = spanInfo?.model;
1789
+ const llmContext = {};
1790
+ if (model) {
1791
+ llmContext.model = model;
1792
+ }
1793
+ Object.assign(llmContext, usage);
1794
+ this.completeSpan(
1795
+ runId,
1796
+ llmOutput,
1797
+ void 0,
1798
+ Object.keys(llmContext).length > 0 ? llmContext : void 0
1799
+ );
1800
+ } catch {
1801
+ }
1802
+ }
1803
+ async handleLLMError(error, runId) {
1804
+ try {
1805
+ this.completeSpan(
1806
+ runId,
1807
+ void 0,
1808
+ error instanceof Error ? error.message : String(error)
1809
+ );
1810
+ } catch {
1811
+ }
1812
+ }
1813
+ async handleLLMNewToken() {
1814
+ }
1815
+ // ── tool callbacks ────────────────────────────────────────────
1816
+ async handleToolStart(tool, input, runId, parentRunId, tags, metadata) {
1817
+ try {
1818
+ const name = tool.name ?? "tool";
1819
+ this.startSpan(
1820
+ runId,
1821
+ parentRunId,
1822
+ String(name),
1823
+ "function",
1824
+ input,
1825
+ metadata,
1826
+ tags
1827
+ );
1828
+ } catch {
1829
+ }
1830
+ }
1831
+ async handleToolEnd(output, runId) {
1832
+ try {
1833
+ this.completeSpan(runId, output);
1834
+ } catch {
1835
+ }
1836
+ }
1837
+ async handleToolError(error, runId) {
1838
+ try {
1839
+ this.completeSpan(
1840
+ runId,
1841
+ void 0,
1842
+ error instanceof Error ? error.message : String(error)
1843
+ );
1844
+ } catch {
1845
+ }
1846
+ }
1847
+ // ── retriever callbacks ───────────────────────────────────────
1848
+ async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata) {
1849
+ try {
1850
+ const name = retriever.name ?? "retriever";
1851
+ this.startSpan(
1852
+ runId,
1853
+ parentRunId,
1854
+ String(name),
1855
+ "function",
1856
+ query,
1857
+ metadata,
1858
+ tags
1859
+ );
1860
+ } catch {
1861
+ }
1862
+ }
1863
+ async handleRetrieverEnd(documents, runId) {
1864
+ try {
1865
+ this.completeSpan(runId, documents);
1866
+ } catch {
1867
+ }
1868
+ }
1869
+ async handleRetrieverError(error, runId) {
1870
+ try {
1871
+ this.completeSpan(
1872
+ runId,
1873
+ void 0,
1874
+ error instanceof Error ? error.message : String(error)
1875
+ );
1876
+ } catch {
1877
+ }
1878
+ }
1879
+ };
1880
+
1881
+ // src/client.ts
1882
+ init_replayContext();
1883
+ init_serialize();
1884
+
1885
+ // src/tracing.ts
1886
+ init_constants();
1887
+ init_http();
1888
+ var BitfabOpenAITracingProcessor = class {
1889
+ /**
1890
+ * Initialize the tracing processor.
1891
+ *
1892
+ * @param config - Configuration options
1893
+ */
1894
+ constructor(config) {
1895
+ this.activeTraces = {};
1896
+ this.activeSpanMappings = {};
1897
+ this.httpClient = new HttpClient({
1898
+ apiKey: config.apiKey,
1899
+ serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
1900
+ timeout: config.timeout ?? 1e4
1901
+ });
1902
+ this.getActiveSpanContext = config.getActiveSpanContext ?? null;
1903
+ }
1904
+ /**
1905
+ * Called when a trace is started.
1906
+ * If there's an active withSpan context, the trace ID is remapped to the
1907
+ * outer trace and sent to pre-create the external_traces row on the server.
1908
+ */
1909
+ async onTraceStart(trace) {
1910
+ this.activeTraces[trace.traceId] = trace;
1911
+ const activeContext = this.getActiveSpanContext?.();
1912
+ if (activeContext) {
1913
+ this.activeSpanMappings[trace.traceId] = activeContext;
1914
+ }
1915
+ this.sendTrace(trace, activeContext ? { id: activeContext.traceId } : {});
1916
+ }
1917
+ /**
1918
+ * Called when a trace is ended.
1919
+ * If mapped to a withSpan trace, sends with remapped ID and completed=false
1920
+ * since the parent withSpan handles completion.
1921
+ */
1922
+ async onTraceEnd(trace) {
1923
+ const mapping = this.activeSpanMappings[trace.traceId];
1924
+ this.sendTrace(
1925
+ trace,
1926
+ mapping ? { id: mapping.traceId } : { completed: true }
1927
+ );
1928
+ delete this.activeSpanMappings[trace.traceId];
1929
+ delete this.activeTraces[trace.traceId];
1930
+ }
1931
+ /**
1932
+ * Called when a span is started.
1933
+ */
1934
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
1935
+ async onSpanStart(span) {
1936
+ this.sendSpan(span);
1937
+ }
1938
+ /**
1939
+ * Called when a span is ended.
1940
+ *
1941
+ * Send all spans to Bitfab for complete trace capture.
1942
+ */
1943
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
1944
+ async onSpanEnd(span) {
1945
+ this.sendSpan(span);
1946
+ }
1947
+ /**
1948
+ * Called when a trace is being flushed.
1949
+ */
1950
+ async forceFlush() {
1951
+ }
1952
+ /**
1953
+ * Called when the trace processor is shutting down.
1954
+ */
1955
+ async shutdown(_timeout) {
1956
+ this.activeTraces = {};
1957
+ this.activeSpanMappings = {};
1958
+ }
1959
+ /**
1960
+ * Send trace to Bitfab API (fire-and-forget).
1961
+ * When traceIdOverride is provided, the trace ID is remapped to link
1962
+ * the OpenAI trace into an outer withSpan trace.
1963
+ */
1964
+ sendTrace(trace, overrides = {}) {
1965
+ try {
1966
+ const { completed, ...traceOverrides } = overrides;
1967
+ const traceData = trace.toJSON();
1968
+ Object.assign(traceData, traceOverrides);
1969
+ this.httpClient.sendExternalTrace({
1970
+ type: "openai",
1971
+ source: "typescript-sdk-openai-tracing",
1972
+ externalTrace: traceData,
1973
+ completed: completed ?? false
1974
+ });
1975
+ } catch {
1976
+ }
1977
+ }
1978
+ /**
1979
+ * Export span to JSON object, collecting any errors.
1980
+ */
1981
+ exportSpan(span) {
1982
+ const errors = [];
1983
+ let serializedSpan;
1984
+ try {
1985
+ const jsonResult = span.toJSON();
1986
+ if (typeof jsonResult !== "object" || jsonResult === null) {
1987
+ errors.push({
1988
+ step: "span.toJSON()",
1989
+ error: `Returned unexpected type: ${typeof jsonResult}`
1990
+ });
1991
+ serializedSpan = {};
1992
+ } else {
1993
+ serializedSpan = jsonResult;
1994
+ }
1995
+ } catch (error) {
1996
+ errors.push({
1997
+ step: "span.toJSON()",
1998
+ error: error instanceof Error ? error.message : String(error)
1999
+ });
2000
+ serializedSpan = {};
2001
+ }
2002
+ if (!serializedSpan.span_data) {
2003
+ serializedSpan.span_data = {};
2004
+ }
2005
+ return [serializedSpan, errors];
2006
+ }
2007
+ /**
2008
+ * Extract and add input/response to serialized span, updating errors list.
2009
+ */
2010
+ extractSpanInputResponse(span, serializedSpan, errors) {
2011
+ const spanData = serializedSpan.span_data;
2012
+ try {
2013
+ spanData.input = span.spanData?._input || [];
2014
+ } catch (error) {
2015
+ errors.push({
2016
+ step: "access_input",
2017
+ error: error instanceof Error ? error.message : String(error)
2018
+ });
2019
+ }
2020
+ try {
2021
+ spanData.response = span.spanData?._response || null;
2022
+ } catch (error) {
2023
+ errors.push({
2024
+ step: "access_response",
2025
+ error: error instanceof Error ? error.message : String(error)
2026
+ });
2027
+ }
2028
+ }
2029
+ /**
2030
+ * If the span's trace is mapped to a withSpan trace, rewrite trace_id and parent_id.
2031
+ */
2032
+ applySpanOverrides(serializedSpan, traceId) {
2033
+ const mapping = this.activeSpanMappings[traceId];
2034
+ if (mapping) {
2035
+ serializedSpan.trace_id = mapping.traceId;
2036
+ if (!serializedSpan.parent_id) {
2037
+ serializedSpan.parent_id = mapping.spanId;
2038
+ }
2039
+ }
2040
+ }
2041
+ /**
2042
+ * Build span payload for the external spans API.
2043
+ */
2044
+ buildSpanPayload(serializedSpan, errors) {
2045
+ const payload = {
2046
+ type: "openai",
2047
+ source: "typescript-sdk-openai-tracing",
2048
+ sourceTraceId: serializedSpan.trace_id ?? "unknown",
2049
+ rawSpan: serializedSpan
2050
+ };
2051
+ if (errors.length > 0) {
2052
+ payload.errors = errors;
2053
+ }
2054
+ return payload;
2055
+ }
2056
+ /**
2057
+ * Send span to Bitfab API (fire-and-forget).
2058
+ * If the span belongs to a trace mapped to a withSpan trace, the trace_id
2059
+ * and parent_id are rewritten to link the span into the withSpan tree.
2060
+ */
2061
+ sendSpan(span) {
2062
+ const errors = [];
2063
+ const [serializedSpan, exportErrors] = this.exportSpan(span);
2064
+ errors.push(...exportErrors);
2065
+ this.extractSpanInputResponse(span, serializedSpan, errors);
2066
+ this.applySpanOverrides(serializedSpan, span.traceId ?? "");
2067
+ const payload = this.buildSpanPayload(serializedSpan, errors);
2068
+ this.httpClient.sendExternalSpan(payload);
2069
+ }
2070
+ };
2071
+
2072
+ // src/client.ts
2073
+ var activeTraceStates = /* @__PURE__ */ new Map();
2074
+ var pendingSpanPromises = /* @__PURE__ */ new Map();
2075
+ var asyncLocalStorage = null;
2076
+ var asyncLocalStorageReady = asyncStorageReady.then(() => {
2077
+ asyncLocalStorage = createAsyncLocalStorage();
2078
+ });
2079
+ var browserSpanStack = [];
2080
+ function getSpanStack() {
2081
+ if (asyncLocalStorage) {
2082
+ return asyncLocalStorage.getStore() ?? [];
2083
+ }
2084
+ return browserSpanStack;
2085
+ }
2086
+ function runWithSpanStack(stack, fn) {
2087
+ if (asyncLocalStorage) {
2088
+ return asyncLocalStorage.run(stack, fn);
2089
+ }
2090
+ const previousStack = browserSpanStack;
2091
+ browserSpanStack = stack;
2092
+ try {
2093
+ const result = fn();
2094
+ if (result instanceof Promise) {
2095
+ return result.finally(() => {
2096
+ browserSpanStack = previousStack;
2097
+ });
2098
+ }
2099
+ browserSpanStack = previousStack;
2100
+ return result;
2101
+ } catch (error) {
2102
+ browserSpanStack = previousStack;
2103
+ throw error;
2104
+ }
2105
+ }
2106
+ function isAsyncGenerator(value) {
2107
+ if (value === null || typeof value !== "object") {
2108
+ return false;
2109
+ }
2110
+ const candidate = value;
2111
+ return typeof candidate.next === "function" && typeof candidate.return === "function" && typeof candidate.throw === "function" && typeof candidate[Symbol.asyncIterator] === "function";
2112
+ }
2113
+ function wrapAsyncGenerator(source, spanStack, sendSpan) {
2114
+ const yielded = [];
2115
+ let returnValue;
2116
+ let finalized = false;
2117
+ const finalize = (errorMsg) => {
2118
+ if (finalized) {
2119
+ return;
2120
+ }
2121
+ finalized = true;
2122
+ void sendSpan({
2123
+ result: { yielded, return: returnValue },
2124
+ ...errorMsg && { error: errorMsg }
2125
+ });
2126
+ };
2127
+ const step = (method, arg) => runWithSpanStack(spanStack, () => {
2128
+ const op = source[method];
2129
+ return op.call(source, arg);
2130
+ });
2131
+ const handle = async (method, arg) => {
2132
+ try {
2133
+ const result = await step(method, arg);
2134
+ if (result.done) {
2135
+ returnValue = result.value;
2136
+ finalize();
2137
+ } else {
2138
+ yielded.push(result.value);
2139
+ }
2140
+ return result;
2141
+ } catch (error) {
2142
+ finalize(error instanceof Error ? error.message : String(error));
2143
+ throw error;
2144
+ }
2145
+ };
2146
+ const wrapped = {
2147
+ next(arg) {
2148
+ return handle("next", arg);
2149
+ },
2150
+ return(value) {
2151
+ return handle("return", value);
2152
+ },
2153
+ throw(err) {
2154
+ return handle("throw", err);
2155
+ },
2156
+ [Symbol.asyncIterator]() {
2157
+ return wrapped;
2158
+ },
2159
+ [Symbol.asyncDispose]() {
2160
+ return handle("return", void 0).then(() => void 0);
2161
+ }
2162
+ };
2163
+ return wrapped;
2164
+ }
2165
+ var cachedCollectorClass;
2166
+ async function loadCollectorClass() {
2167
+ if (cachedCollectorClass !== void 0) {
2168
+ return cachedCollectorClass;
2169
+ }
2170
+ try {
2171
+ const baml = await import("@boundaryml/baml");
2172
+ cachedCollectorClass = baml.Collector;
2173
+ return cachedCollectorClass;
2174
+ } catch {
2175
+ cachedCollectorClass = null;
2176
+ return null;
2177
+ }
2178
+ }
2179
+ function extractPromptFromCollector(collector) {
2180
+ try {
2181
+ const c = collector;
2182
+ const calls = c?.last?.calls ?? [];
2183
+ const selectedCall = calls.find((call) => call.selected) ?? calls[0];
2184
+ if (!selectedCall?.httpRequest?.body) {
2185
+ return null;
2186
+ }
2187
+ const body = selectedCall.httpRequest.body.json();
2188
+ if (!body || typeof body !== "object") {
2189
+ return null;
2190
+ }
2191
+ const messages = body.messages;
2192
+ if (!Array.isArray(messages) || messages.length === 0) {
2193
+ return null;
2194
+ }
2195
+ const rendered = messages.filter(
2196
+ (msg) => typeof msg === "object" && msg !== null && "role" in msg && typeof msg.role === "string"
2197
+ ).map((msg) => ({
2198
+ role: msg.role,
2199
+ content: typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)
2200
+ }));
2201
+ if (rendered.length > 0) {
2202
+ return JSON.stringify(rendered);
2203
+ }
2204
+ return null;
2205
+ } catch {
2206
+ return null;
2207
+ }
2208
+ }
2209
+ function extractContextFromCollector(collector) {
2210
+ try {
2211
+ const c = collector;
2212
+ const calls = c?.last?.calls ?? [];
2213
+ const selectedCall = calls.find((call) => call.selected) ?? calls[0];
2214
+ const usage = c?.usage;
2215
+ const context = {};
2216
+ if (selectedCall?.provider) {
2217
+ context.provider = selectedCall.provider;
2218
+ }
2219
+ const body = selectedCall?.httpRequest?.body?.json();
2220
+ if (body && typeof body === "object" && typeof body.model === "string") {
2221
+ context.model = body.model;
2222
+ } else {
2223
+ const url = selectedCall?.httpRequest?.url;
2224
+ if (url) {
2225
+ const match = url.match(/\/models\/([^/:]+)/);
2226
+ if (match?.[1]) {
2227
+ context.model = match[1];
2228
+ }
2229
+ }
2230
+ }
2231
+ const inputTokens = usage?.inputTokens ?? selectedCall?.usage?.inputTokens ?? null;
2232
+ const outputTokens = usage?.outputTokens ?? selectedCall?.usage?.outputTokens ?? null;
2233
+ if (inputTokens !== null) {
2234
+ context.inputTokens = inputTokens;
2235
+ }
2236
+ if (outputTokens !== null) {
2237
+ context.outputTokens = outputTokens;
2238
+ }
2239
+ const durationMs = c?.last?.timing?.durationMs ?? null;
2240
+ if (durationMs !== null) {
2241
+ context.durationMs = durationMs;
2242
+ }
2243
+ return Object.keys(context).length > 0 ? context : null;
2244
+ } catch {
2245
+ return null;
2246
+ }
2247
+ }
2248
+ var TRACE_ID_PATTERN = /^[a-zA-Z0-9_\-.:]+$/;
2249
+ var TRACE_ID_MAX_LENGTH = 256;
2250
+ function validateTraceId(traceId) {
2251
+ if (typeof traceId !== "string" || traceId.length === 0) {
2252
+ throw new BitfabError("traceId is required and must be a non-empty string");
2253
+ }
2254
+ if (traceId.length > TRACE_ID_MAX_LENGTH) {
2255
+ throw new BitfabError(
2256
+ `traceId must be ${TRACE_ID_MAX_LENGTH} characters or fewer`
2257
+ );
2258
+ }
2259
+ if (!TRACE_ID_PATTERN.test(traceId)) {
2260
+ throw new BitfabError(
2261
+ `traceId may only contain letters, digits, "_", "-", ".", ":"`
2262
+ );
2263
+ }
2264
+ }
2265
+ var noOpSpan = {
2266
+ traceId: "",
2267
+ addContext() {
2268
+ },
2269
+ setPrompt() {
2270
+ }
2271
+ };
2272
+ var noOpTrace = {
2273
+ setSessionId() {
2274
+ },
2275
+ setMetadata() {
2276
+ },
2277
+ addContext() {
2278
+ }
2279
+ };
2280
+ function getCurrentSpan() {
2281
+ const stack = getSpanStack();
2282
+ const current = stack[stack.length - 1];
2283
+ if (!current) {
2284
+ return noOpSpan;
2285
+ }
2286
+ return {
2287
+ traceId: current.traceId,
2288
+ addContext(context) {
2289
+ try {
2290
+ if (typeof context !== "object" || context === null) {
2291
+ return;
2292
+ }
2293
+ current.contexts.push(context);
2294
+ } catch {
2295
+ }
2296
+ },
2297
+ setPrompt(prompt) {
2298
+ try {
2299
+ if (typeof prompt !== "string") {
2300
+ return;
2301
+ }
2302
+ current.prompt = prompt;
2303
+ } catch {
2304
+ }
2305
+ }
2306
+ };
2307
+ }
2308
+ function getCurrentTrace() {
2309
+ const stack = getSpanStack();
2310
+ const current = stack[stack.length - 1];
2311
+ if (!current) {
2312
+ return noOpTrace;
2313
+ }
2314
+ const traceId = current.traceId;
2315
+ const getOrCreateTraceState = () => {
2316
+ let traceState = activeTraceStates.get(traceId);
2317
+ if (!traceState) {
2318
+ traceState = {
2319
+ traceId,
2320
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2321
+ contexts: []
2322
+ };
2323
+ activeTraceStates.set(traceId, traceState);
2324
+ }
2325
+ return traceState;
2326
+ };
2327
+ return {
2328
+ setSessionId(sessionId) {
2329
+ try {
2330
+ const traceState = getOrCreateTraceState();
2331
+ traceState.sessionId = sessionId;
2332
+ } catch {
2333
+ }
2334
+ },
2335
+ setMetadata(metadata) {
2336
+ try {
2337
+ if (typeof metadata !== "object" || metadata === null) {
2338
+ return;
2339
+ }
2340
+ const traceState = getOrCreateTraceState();
2341
+ traceState.metadata = { ...traceState.metadata, ...metadata };
2342
+ } catch {
2343
+ }
2344
+ },
2345
+ addContext(context) {
2346
+ try {
2347
+ if (typeof context !== "object" || context === null) {
2348
+ return;
2349
+ }
2350
+ const traceState = getOrCreateTraceState();
2351
+ traceState.contexts.push(context);
2352
+ } catch {
2353
+ }
2354
+ }
2355
+ };
2356
+ }
2357
+ var Bitfab = class {
2358
+ /**
2359
+ * Initialize the Bitfab client.
2360
+ *
2361
+ * @param config - Configuration options for the client
2362
+ */
2363
+ constructor(config) {
2364
+ this.apiKey = config.apiKey;
2365
+ this.serviceUrl = config.serviceUrl ?? DEFAULT_SERVICE_URL;
2366
+ this.timeout = config.timeout ?? 12e4;
2367
+ this.envVars = config.envVars ?? {};
2368
+ const enabled = config.enabled ?? true;
2369
+ if (enabled && (!config.apiKey || config.apiKey.trim() === "")) {
2370
+ console.warn(
2371
+ "Bitfab: apiKey is empty \u2014 tracing is disabled. Provide a valid API key to enable tracing."
2372
+ );
2373
+ this.enabled = false;
2374
+ } else {
2375
+ this.enabled = enabled;
2376
+ }
2377
+ this.bamlClient = config.bamlClient ?? null;
2378
+ this.httpClient = new HttpClient({
2379
+ apiKey: this.apiKey,
2380
+ serviceUrl: this.serviceUrl,
2381
+ timeout: this.timeout
2382
+ });
2383
+ }
2384
+ /**
2385
+ * Fetch the function with its current version and BAML prompt from the server.
2386
+ *
2387
+ * @param methodName - The name of the method to fetch
2388
+ * @returns The function with current version, BAML prompt, and provider definitions
2389
+ * @throws {BitfabError} If the function is not found or an error occurs
2390
+ */
2391
+ async fetchFunctionVersion(methodName) {
2392
+ const result = await this.httpClient.lookupFunction(methodName);
2393
+ if (result.id === null) {
2394
+ throw new BitfabError(
2395
+ `Function "${methodName}" not found. Create it at: ${this.serviceUrl}/functions`,
2396
+ "/functions"
2397
+ );
2398
+ }
2399
+ if (!result.prompt) {
2400
+ throw new BitfabError(
2401
+ `Function "${methodName}" has no prompt configured. Add one at: ${this.serviceUrl}/functions/${result.id}`,
2402
+ `/functions/${result.id}`
2403
+ );
2404
+ }
2405
+ return result;
2406
+ }
2407
+ /**
2408
+ * Call a method with the given named arguments via BAML execution.
2409
+ *
2410
+ * @param methodName - The name of the method to call
2411
+ * @param inputs - Named arguments to pass to the method
2412
+ * @returns The result of the BAML function execution
2413
+ * @throws {BitfabError} If service_url is not set, or if an error occurs
2414
+ */
2415
+ async call(methodName, inputs = {}) {
2416
+ try {
2417
+ const functionVersion = await this.fetchFunctionVersion(methodName);
2418
+ const executionResult = await runFunctionWithBaml(
2419
+ functionVersion.prompt,
2420
+ inputs,
2421
+ functionVersion.providers,
2422
+ this.envVars
2423
+ );
2424
+ const resultStr = typeof executionResult.result === "string" ? executionResult.result : JSON.stringify(executionResult.result);
2425
+ this.httpClient.sendInternalTrace(functionVersion.id, {
2426
+ result: resultStr,
2427
+ source: "typescript-sdk",
2428
+ ...Object.keys(inputs).length > 0 && { inputs },
2429
+ ...executionResult.rawCollector != null && {
2430
+ rawCollector: executionResult.rawCollector
2431
+ }
2432
+ });
2433
+ return executionResult.result;
2434
+ } catch (error) {
2435
+ if (error instanceof BitfabError) {
2436
+ throw error;
2437
+ }
2438
+ if (error instanceof Error) {
2439
+ throw new BitfabError(error.message);
2440
+ }
2441
+ throw new BitfabError("Unknown error occurred during local execution");
2442
+ }
2443
+ }
2444
+ /**
2445
+ * Get a tracing processor for OpenAI Agents SDK integration.
2446
+ *
2447
+ * This processor automatically captures traces and spans from the OpenAI Agents SDK
2448
+ * and sends them to Bitfab for monitoring and analysis.
2449
+ *
2450
+ * Example usage:
2451
+ * ```typescript
2452
+ * import { addTraceProcessor } from '@openai/agents';
2453
+ *
2454
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
2455
+ * const processor = client.getOpenAiTracingProcessor();
2456
+ * addTraceProcessor(processor);
2457
+ * ```
2458
+ *
2459
+ * @returns A BitfabOpenAITracingProcessor instance configured for this client
2460
+ */
2461
+ getOpenAiTracingProcessor() {
2462
+ return new BitfabOpenAITracingProcessor({
2463
+ apiKey: this.apiKey,
2464
+ serviceUrl: this.serviceUrl,
2465
+ getActiveSpanContext: () => {
2466
+ const stack = getSpanStack();
2467
+ return stack[stack.length - 1] ?? null;
2468
+ }
2469
+ });
2470
+ }
2471
+ /**
2472
+ * Get a LangGraph/LangChain callback handler for tracing.
2473
+ *
2474
+ * The handler captures graph node execution, LLM calls, and tool
2475
+ * invocations as Bitfab spans with proper parent-child hierarchy.
2476
+ *
2477
+ * ```typescript
2478
+ * const handler = client.getLangGraphCallbackHandler("my-agent");
2479
+ * const result = await agent.invoke(
2480
+ * { messages: [...] },
2481
+ * { callbacks: [handler] },
2482
+ * );
2483
+ * ```
2484
+ *
2485
+ * @param traceFunctionKey - Groups traces under this key in Bitfab
2486
+ * @returns A BitfabLangGraphCallbackHandler configured for this client
2487
+ */
2488
+ getLangGraphCallbackHandler(traceFunctionKey) {
2489
+ return new BitfabLangGraphCallbackHandler({
2490
+ apiKey: this.apiKey,
2491
+ traceFunctionKey,
2492
+ serviceUrl: this.serviceUrl,
2493
+ getActiveSpanContext: () => {
2494
+ const stack = getSpanStack();
2495
+ return stack[stack.length - 1] ?? null;
2496
+ }
2497
+ });
2498
+ }
2499
+ /**
2500
+ * Get a Claude Agent SDK handler for tracing.
2501
+ *
2502
+ * The handler captures LLM turns, tool invocations, and subagent
2503
+ * execution as Bitfab spans with proper parent-child hierarchy.
2504
+ *
2505
+ * ```typescript
2506
+ * const handler = client.getClaudeAgentHandler("my-agent");
2507
+ * const options = handler.instrumentOptions({
2508
+ * model: "claude-sonnet-4-5-...",
2509
+ * });
2510
+ * const sdkClient = new ClaudeSDKClient(options);
2511
+ * await sdkClient.connect();
2512
+ * await sdkClient.query("Do something");
2513
+ * for await (const msg of handler.wrapResponse(sdkClient.receiveResponse())) {
2514
+ * // process messages
2515
+ * }
2516
+ * ```
2517
+ *
2518
+ * @param traceFunctionKey - Groups traces under this key in Bitfab
2519
+ * @returns A BitfabClaudeAgentHandler configured for this client
2520
+ */
2521
+ getClaudeAgentHandler(traceFunctionKey) {
2522
+ return new BitfabClaudeAgentHandler({
2523
+ apiKey: this.apiKey,
2524
+ traceFunctionKey,
2525
+ serviceUrl: this.serviceUrl,
2526
+ getActiveSpanContext: () => {
2527
+ const stack = getSpanStack();
2528
+ return stack[stack.length - 1] ?? null;
2529
+ }
2530
+ });
2531
+ }
2532
+ /**
2533
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
2534
+ *
2535
+ * Creates a BAML Collector, calls the method through a tracked client,
2536
+ * then extracts rendered messages and token usage — calling setPrompt()
2537
+ * and addContext() on the current span automatically.
2538
+ *
2539
+ * The BAML client can be provided in the constructor or passed explicitly:
2540
+ *
2541
+ * ```typescript
2542
+ * // Option 1: bamlClient in constructor (use wrapBAML with just the method)
2543
+ * const client = new Bitfab({ apiKey: 'your-api-key', bamlClient: b });
2544
+ * const traced = client.withSpan('classify', { type: 'llm' },
2545
+ * client.wrapBAML(b.ClassifyText)
2546
+ * );
2547
+ *
2548
+ * // Option 2: pass bamlClient at call site
2549
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
2550
+ * const traced = client.withSpan('classify', { type: 'llm' },
2551
+ * client.wrapBAML(b, b.ClassifyText)
2552
+ * );
2553
+ * ```
2554
+ *
2555
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
2556
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
2557
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
2558
+ * @returns An async function with the same signature that instruments the BAML call
2559
+ */
2560
+ wrapBAML(methodOrClient, maybeMethodOrOptions, maybeOptions) {
2561
+ let bamlClient;
2562
+ let method;
2563
+ let options;
2564
+ if (typeof maybeMethodOrOptions === "function") {
2565
+ bamlClient = methodOrClient;
2566
+ method = maybeMethodOrOptions;
2567
+ options = maybeOptions;
2568
+ } else {
2569
+ bamlClient = this.bamlClient;
2570
+ method = methodOrClient;
2571
+ options = maybeMethodOrOptions;
2572
+ if (!bamlClient) {
2573
+ throw new BitfabError(
2574
+ "bamlClient is required for wrapBAML. Pass it in the constructor or as the first argument."
2575
+ );
2576
+ }
2577
+ }
2578
+ const methodName = method.name;
2579
+ if (!methodName) {
2580
+ throw new BitfabError(
2581
+ "wrapBAML requires a named function (e.g., b.ClassifyText)."
2582
+ );
2583
+ }
2584
+ loadCollectorClass();
2585
+ const wrappedFn = async (...args) => {
2586
+ const CollectorClass = await loadCollectorClass();
2587
+ if (!CollectorClass) {
2588
+ wrappedFn.collector = null;
2589
+ return await bamlClient[methodName](...args);
2590
+ }
2591
+ const collector = new CollectorClass("bitfab-baml-tracing");
2592
+ const trackedClient = bamlClient.withOptions({ collector });
2593
+ const trackedMethod = trackedClient[methodName];
2594
+ const result = await trackedMethod.bind(
2595
+ trackedClient
2596
+ )(...args);
2597
+ wrappedFn.collector = collector;
2598
+ try {
2599
+ const prompt = extractPromptFromCollector(collector);
2600
+ if (prompt) {
2601
+ getCurrentSpan().setPrompt(prompt);
2602
+ }
2603
+ const metadata = extractContextFromCollector(collector);
2604
+ if (metadata) {
2605
+ getCurrentSpan().addContext(metadata);
2606
+ }
2607
+ } catch {
2608
+ }
2609
+ try {
2610
+ options?.onCollector?.(collector);
2611
+ } catch {
2612
+ }
2613
+ return result;
2614
+ };
2615
+ wrappedFn.collector = null;
2616
+ return wrappedFn;
2617
+ }
2618
+ /**
2619
+ * Wrap a function to automatically create a span for its inputs and outputs.
2620
+ *
2621
+ * The wrapped function behaves identically to the original, but sends
2622
+ * span data to Bitfab in the background after each call.
2623
+ *
2624
+ * Example usage:
2625
+ * ```typescript
2626
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
2627
+ *
2628
+ * async function processOrder(orderId: string, items: string[]): Promise<{ total: number }> {
2629
+ * // ... process order
2630
+ * return { total: 100 };
2631
+ * }
2632
+ *
2633
+ * // Basic usage (defaults to "custom" span type)
2634
+ * const tracedProcessOrder = client.withSpan('order-processing', processOrder);
2635
+ *
2636
+ * // With explicit span type
2637
+ * const tracedProcessOrder = client.withSpan('order-processing', { type: 'function' }, processOrder);
2638
+ *
2639
+ * // Call the wrapped function normally
2640
+ * const result = await tracedProcessOrder('order-123', ['item-1', 'item-2']);
2641
+ * // Span is automatically sent to Bitfab
2642
+ * ```
2643
+ *
2644
+ * @param traceFunctionKey - A string identifier for grouping spans (e.g., 'order-processing', 'user-auth')
2645
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
2646
+ * @param maybeFn - The function to wrap if options were provided
2647
+ * @returns A wrapped function with the same signature that creates spans for inputs and outputs
2648
+ */
2649
+ withSpan(traceFunctionKey, optionsOrFn, maybeFn) {
2650
+ if (!this.enabled) {
2651
+ const fn2 = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
2652
+ return fn2;
2653
+ }
2654
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
2655
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
2656
+ const self = this;
2657
+ const fnIsAsyncFunction = fn.constructor.name === "AsyncFunction";
2658
+ const fnReturnsPromise = fnIsAsyncFunction || (() => {
2659
+ try {
2660
+ const src = fn.toString();
2661
+ return /\b(?:Promise|await)\b/.test(src);
2662
+ } catch {
2663
+ return false;
2664
+ }
2665
+ })();
2666
+ const wrappedFn = function(...args) {
2667
+ if (!asyncLocalStorage && !isAsyncStorageInitDone()) {
2668
+ return asyncLocalStorageReady.then(
2669
+ () => wrappedFn.apply(this, args)
2670
+ );
2671
+ }
2672
+ const currentStack = getSpanStack();
2673
+ const parentContext = currentStack[currentStack.length - 1];
2674
+ const traceId = parentContext?.traceId ?? crypto.randomUUID();
2675
+ const spanId = crypto.randomUUID();
2676
+ const parentSpanId = parentContext?.spanId ?? null;
2677
+ const isRootSpan = parentSpanId === null;
2678
+ const newContext = { traceId, spanId, contexts: [] };
2679
+ const newStack = [...currentStack, newContext];
2680
+ const inputs = args;
2681
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2682
+ if (isRootSpan && !activeTraceStates.has(traceId)) {
2683
+ const replayCtxAtRoot = getReplayContext();
2684
+ activeTraceStates.set(traceId, {
2685
+ traceId,
2686
+ startedAt,
2687
+ contexts: [],
2688
+ ...replayCtxAtRoot?.testRunId && {
2689
+ testRunId: replayCtxAtRoot.testRunId
2690
+ },
2691
+ ...replayCtxAtRoot?.inputSourceTraceId && {
2692
+ inputSourceTraceId: replayCtxAtRoot.inputSourceTraceId
2693
+ }
2694
+ });
2695
+ pendingSpanPromises.set(traceId, []);
2696
+ }
2697
+ const functionName = fn.name !== "" ? fn.name : void 0;
2698
+ const baseSpanParams = {
2699
+ traceFunctionKey,
2700
+ functionName,
2701
+ spanName: options.name ?? functionName ?? traceFunctionKey,
2702
+ traceId,
2703
+ spanId,
2704
+ parentSpanId,
2705
+ inputs,
2706
+ startedAt,
2707
+ spanType: options.type ?? "custom"
2708
+ };
2709
+ const sendSpan = async (params) => {
2710
+ try {
2711
+ const endedAt = (/* @__PURE__ */ new Date()).toISOString();
2712
+ const replayCtx = getReplayContext();
2713
+ const spanPromise = self.sendWrapperSpan({
2714
+ ...baseSpanParams,
2715
+ ...params,
2716
+ contexts: newContext.contexts,
2717
+ prompt: newContext.prompt,
2718
+ endedAt,
2719
+ ...replayCtx?.testRunId && { testRunId: replayCtx.testRunId },
2720
+ ...replayCtx?.inputSourceSpanId && {
2721
+ inputSourceSpanId: replayCtx.inputSourceSpanId
2722
+ }
2723
+ });
2724
+ if (isRootSpan) {
2725
+ const pending = pendingSpanPromises.get(traceId) ?? [];
2726
+ pending.push(spanPromise);
2727
+ await Promise.race([
2728
+ Promise.allSettled(pending),
2729
+ new Promise((resolve) => setTimeout(resolve, 5e3))
2730
+ ]);
2731
+ pendingSpanPromises.delete(traceId);
2732
+ const traceState = activeTraceStates.get(traceId);
2733
+ self.sendTraceCompletion({
2734
+ traceFunctionKey,
2735
+ traceId,
2736
+ startedAt: traceState?.startedAt ?? startedAt,
2737
+ endedAt,
2738
+ sessionId: traceState?.sessionId,
2739
+ metadata: traceState?.metadata,
2740
+ contexts: traceState?.contexts ?? [],
2741
+ testRunId: traceState?.testRunId,
2742
+ inputSourceTraceId: traceState?.inputSourceTraceId
2743
+ });
2744
+ activeTraceStates.delete(traceId);
2745
+ } else {
2746
+ const pending = pendingSpanPromises.get(traceId);
2747
+ if (pending) {
2748
+ pending.push(spanPromise);
2749
+ } else {
2750
+ pendingSpanPromises.set(traceId, [spanPromise]);
2751
+ }
2752
+ }
2753
+ } catch {
2754
+ }
2755
+ };
2756
+ const replayCtxForMock = getReplayContext();
2757
+ if (replayCtxForMock?.mockTree && !isRootSpan) {
2758
+ const counters = replayCtxForMock.callCounters;
2759
+ const counterKey = `${traceFunctionKey}:${baseSpanParams.spanName}`;
2760
+ const callIndex = counters.get(counterKey) ?? 0;
2761
+ counters.set(counterKey, callIndex + 1);
2762
+ const shouldMock = replayCtxForMock.mockStrategy === "all" || replayCtxForMock.mockStrategy === "marked" && options.mockOnReplay === true;
2763
+ if (shouldMock) {
2764
+ const mockKey = `${counterKey}:${callIndex}`;
2765
+ const mockSpan = replayCtxForMock.mockTree.spans.get(mockKey);
2766
+ if (mockSpan) {
2767
+ let output = mockSpan.output;
2768
+ if (mockSpan.outputMeta !== void 0 && mockSpan.outputMeta !== null) {
2769
+ output = deserializeValue({
2770
+ json: mockSpan.output,
2771
+ meta: mockSpan.outputMeta
2772
+ });
2773
+ }
2774
+ void sendSpan({ result: output });
2775
+ if (fnReturnsPromise) {
2776
+ return Promise.resolve(output);
2777
+ }
2778
+ return output;
2779
+ }
2780
+ }
2781
+ }
2782
+ const executeWithContext = () => {
2783
+ const result = fn(...args);
2784
+ if (result instanceof Promise) {
2785
+ return result.then((resolvedResult) => {
2786
+ void sendSpan({ result: resolvedResult });
2787
+ return resolvedResult;
2788
+ }).catch((error) => {
2789
+ void sendSpan({
2790
+ result: void 0,
2791
+ error: error instanceof Error ? error.message : String(error)
2792
+ });
2793
+ throw error;
2794
+ });
2795
+ }
2796
+ if (isAsyncGenerator(result)) {
2797
+ return wrapAsyncGenerator(result, newStack, sendSpan);
2798
+ }
2799
+ void sendSpan({ result });
2800
+ return result;
2801
+ };
2802
+ return runWithSpanStack(newStack, executeWithContext);
2803
+ };
2804
+ return wrappedFn;
2805
+ }
2806
+ /**
2807
+ * Get a detached handle to a previously-created trace, looked up by the
2808
+ * caller-supplied id (the same id passed at trace creation).
2809
+ *
2810
+ * The returned handle is not tied to AsyncLocalStorage — each method sends
2811
+ * to the server immediately. Useful for adding context to a trace from a
2812
+ * different process or thread than the one that created it.
2813
+ *
2814
+ * Throws synchronously if `traceId` is malformed (empty, too long, or
2815
+ * contains characters outside `[a-zA-Z0-9_\-.:]`). Server returns 404 if
2816
+ * no trace exists with that id in the org; the failure surfaces as a
2817
+ * logged warning (fire-and-forget) or via the awaited promise.
2818
+ *
2819
+ * Example:
2820
+ * ```typescript
2821
+ * const trace = client.getTrace("order_abc_123");
2822
+ * await trace.addContext({ refund_status: "approved" });
2823
+ * await trace.setMetadata({ region: "us-west" });
2824
+ * ```
2825
+ */
2826
+ getTrace(traceId) {
2827
+ validateTraceId(traceId);
2828
+ return {
2829
+ traceId,
2830
+ addContext: (context) => {
2831
+ if (!this.enabled) {
2832
+ return Promise.resolve();
2833
+ }
2834
+ if (typeof context !== "object" || context === null) {
2835
+ return Promise.resolve();
2836
+ }
2837
+ return this.httpClient.patchTrace(traceId, {
2838
+ appendContexts: [context]
2839
+ });
2840
+ },
2841
+ setMetadata: (metadata) => {
2842
+ if (!this.enabled) {
2843
+ return Promise.resolve();
2844
+ }
2845
+ if (typeof metadata !== "object" || metadata === null) {
2846
+ return Promise.resolve();
2847
+ }
2848
+ return this.httpClient.patchTrace(traceId, { mergeMetadata: metadata });
2849
+ },
2850
+ setSessionId: (sessionId) => {
2851
+ if (!this.enabled) {
2852
+ return Promise.resolve();
2853
+ }
2854
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
2855
+ return Promise.resolve();
2856
+ }
2857
+ return this.httpClient.patchTrace(traceId, { setSessionId: sessionId });
2858
+ }
2859
+ };
2860
+ }
2861
+ /**
2862
+ * Get a function wrapper for a specific trace function key.
2863
+ *
2864
+ * This provides a fluent API alternative to calling withSpan directly,
2865
+ * allowing you to bind the traceFunctionKey once and wrap multiple functions.
2866
+ *
2867
+ * Example usage:
2868
+ * ```typescript
2869
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
2870
+ *
2871
+ * const orderFunc = client.getFunction('order-processing');
2872
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
2873
+ * const tracedValidateOrder = orderFunc.withSpan(validateOrder);
2874
+ * ```
2875
+ *
2876
+ * @param traceFunctionKey - A string identifier for grouping spans
2877
+ * @returns A BitfabFunction instance for wrapping functions
2878
+ */
2879
+ getFunction(traceFunctionKey) {
2880
+ return new BitfabFunction(this, traceFunctionKey);
2881
+ }
2882
+ /**
2883
+ * Send trace completion when a root span ends.
2884
+ * Internal method to record trace completion with end time.
2885
+ * Fire-and-forget - sends to externalTraces endpoint via httpClient.
2886
+ */
2887
+ sendTraceCompletion(params) {
2888
+ const rawTrace = {
2889
+ id: params.traceId,
2890
+ started_at: params.startedAt,
2891
+ ended_at: params.endedAt,
2892
+ workflow_name: params.traceFunctionKey
2893
+ };
2894
+ if (params.metadata && Object.keys(params.metadata).length > 0) {
2895
+ rawTrace.metadata = params.metadata;
2896
+ }
2897
+ if (params.contexts && params.contexts.length > 0) {
2898
+ rawTrace.contexts = params.contexts;
2899
+ }
2900
+ if (params.inputSourceTraceId) {
2901
+ rawTrace.input_source_trace_id = params.inputSourceTraceId;
2902
+ }
2903
+ this.httpClient.sendExternalTrace({
2904
+ type: "sdk-function",
2905
+ source: "typescript-sdk-function",
2906
+ traceFunctionKey: params.traceFunctionKey,
2907
+ externalTrace: rawTrace,
2908
+ completed: true,
2909
+ ...params.sessionId && { sessionId: params.sessionId },
2910
+ ...params.testRunId && { testRunId: params.testRunId }
2911
+ });
2912
+ }
2913
+ /**
2914
+ * Send a wrapper span from function execution.
2915
+ * Internal method to record spans when using withSpan.
2916
+ * Fire-and-forget - sends to externalSpans endpoint via httpClient.
2917
+ */
2918
+ sendWrapperSpan(params) {
2919
+ const serializedInputs = serializeValue(params.inputs);
2920
+ const serializedResult = serializeValue(params.result);
2921
+ const externalSpan = {
2922
+ id: params.spanId,
2923
+ trace_id: params.traceId,
2924
+ started_at: params.startedAt,
2925
+ ended_at: params.endedAt,
2926
+ span_data: {
2927
+ name: params.spanName,
2928
+ type: params.spanType,
2929
+ input: serializedInputs.json,
2930
+ output: serializedResult.json,
2931
+ // Include superjson meta for type preservation
2932
+ ...serializedInputs.meta !== void 0 && {
2933
+ input_meta: serializedInputs.meta
2934
+ },
2935
+ ...serializedResult.meta !== void 0 && {
2936
+ output_meta: serializedResult.meta
2937
+ },
2938
+ ...params.functionName !== void 0 && {
2939
+ function_name: params.functionName
2940
+ },
2941
+ ...params.error !== void 0 && { error: params.error },
2942
+ ...params.contexts && params.contexts.length > 0 && {
2943
+ contexts: params.contexts
2944
+ },
2945
+ ...params.prompt !== void 0 && { prompt: params.prompt }
2946
+ }
2947
+ };
2948
+ if (params.parentSpanId) {
2949
+ externalSpan.parent_id = params.parentSpanId;
2950
+ }
2951
+ if (params.inputSourceSpanId) {
2952
+ externalSpan.input_source_span_id = params.inputSourceSpanId;
2953
+ }
2954
+ return this.httpClient.sendExternalSpan({
2955
+ type: "sdk-function",
2956
+ source: "typescript-sdk-function",
2957
+ sourceTraceId: params.traceId,
2958
+ traceFunctionKey: params.traceFunctionKey,
2959
+ rawSpan: externalSpan,
2960
+ ...params.testRunId && { testRunId: params.testRunId }
2961
+ });
2962
+ }
2963
+ /**
2964
+ * Replay historical traces through a function and create a test run.
2965
+ *
2966
+ * Fetches the last N traces for the given trace function key, re-runs each
2967
+ * through the provided function, and returns comparison data.
2968
+ *
2969
+ * The function must have been wrapped with `withSpan` — replay injects
2970
+ * `testRunId` via async context so new spans are linked to the test run.
2971
+ *
2972
+ * @param traceFunctionKey - The trace function key to replay
2973
+ * @param fn - The function to replay (must be the return value of `withSpan`)
2974
+ * @param options - Optional replay options (limit, traceIds)
2975
+ * @returns ReplayResult with items, testRunId, and testRunUrl
2976
+ */
2977
+ async replay(traceFunctionKey, fn, options) {
2978
+ const { replay: doReplay } = await Promise.resolve().then(() => (init_replay(), replay_exports));
2979
+ return doReplay(
2980
+ this.httpClient,
2981
+ this.serviceUrl,
2982
+ traceFunctionKey,
2983
+ fn,
2984
+ options
2985
+ );
2986
+ }
2987
+ };
2988
+ var BitfabFunction = class {
2989
+ constructor(client, traceFunctionKey) {
2990
+ this.client = client;
2991
+ this.traceFunctionKey = traceFunctionKey;
2992
+ }
2993
+ /**
2994
+ * Wrap a function to automatically create a span for its inputs and outputs.
2995
+ *
2996
+ * The wrapped function behaves identically to the original, but sends
2997
+ * span data to Bitfab in the background after each call.
2998
+ *
2999
+ * Example usage:
3000
+ * ```typescript
3001
+ * const orderFunc = client.getFunction('order-processing');
3002
+ *
3003
+ * // Basic usage (defaults to "custom" span type)
3004
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
3005
+ *
3006
+ * // With explicit span type
3007
+ * const tracedProcessOrder = orderFunc.withSpan({ type: 'function' }, processOrder);
3008
+ * ```
3009
+ *
3010
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
3011
+ * @param maybeFn - The function to wrap if options were provided
3012
+ * @returns A wrapped function with the same signature that creates spans
3013
+ */
3014
+ withSpan(optionsOrFn, maybeFn) {
3015
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
3016
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
3017
+ return this.client.withSpan(this.traceFunctionKey, options, fn);
3018
+ }
3019
+ /**
3020
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
3021
+ * Delegates to the parent client's wrapBAML method.
3022
+ *
3023
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
3024
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
3025
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
3026
+ * @returns An async function with the same signature that instruments the BAML call
3027
+ */
3028
+ wrapBAML(methodOrClient, maybeMethodOrOptions, maybeOptions) {
3029
+ return this.client.wrapBAML(
3030
+ methodOrClient,
3031
+ maybeMethodOrOptions,
3032
+ maybeOptions
3033
+ );
3034
+ }
3035
+ };
3036
+
3037
+ // src/index.ts
3038
+ init_constants();
3039
+ init_http();
3040
+
3041
+ // src/node.ts
3042
+ init_asyncStorage();
3043
+ assertAsyncStorageRegistered();
3044
+ // Annotate the CommonJS export names for ESM import in node:
3045
+ 0 && (module.exports = {
3046
+ Bitfab,
3047
+ BitfabClaudeAgentHandler,
3048
+ BitfabError,
3049
+ BitfabFunction,
3050
+ BitfabLangGraphCallbackHandler,
3051
+ BitfabOpenAITracingProcessor,
3052
+ DEFAULT_SERVICE_URL,
3053
+ __version__,
3054
+ flushTraces,
3055
+ getCurrentSpan,
3056
+ getCurrentTrace
3057
+ });
3058
+ //# sourceMappingURL=node.cjs.map