@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.
@@ -0,0 +1,2408 @@
1
+ import {
2
+ BitfabError,
3
+ DEFAULT_SERVICE_URL,
4
+ HttpClient,
5
+ asyncStorageReady,
6
+ createAsyncLocalStorage,
7
+ deserializeValue,
8
+ getReplayContext,
9
+ isAsyncStorageInitDone,
10
+ serializeValue
11
+ } from "./chunk-QLVXAFGP.js";
12
+
13
+ // src/claudeAgentSdk.ts
14
+ function nowIso() {
15
+ return (/* @__PURE__ */ new Date()).toISOString();
16
+ }
17
+ function safeSerialize(value) {
18
+ if (value === null || value === void 0) {
19
+ return value;
20
+ }
21
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
22
+ return value;
23
+ }
24
+ if (Array.isArray(value)) {
25
+ return value.map(safeSerialize);
26
+ }
27
+ if (typeof value === "object") {
28
+ if (typeof value.toJSON === "function") {
29
+ return value.toJSON();
30
+ }
31
+ const result = {};
32
+ for (const [k, v] of Object.entries(value)) {
33
+ if (!k.startsWith("_")) {
34
+ result[k] = safeSerialize(v);
35
+ }
36
+ }
37
+ return result;
38
+ }
39
+ return String(value);
40
+ }
41
+ function extractContentBlocks(content) {
42
+ if (!Array.isArray(content)) {
43
+ return [];
44
+ }
45
+ return content.map((block) => safeSerialize(block));
46
+ }
47
+ function extractUsage(message) {
48
+ const usageInfo = {};
49
+ const usage = message.usage;
50
+ if (!usage) {
51
+ return usageInfo;
52
+ }
53
+ const mapping = {
54
+ input_tokens: "inputTokens",
55
+ output_tokens: "outputTokens",
56
+ cache_read_input_tokens: "cacheReadTokens",
57
+ cache_creation_input_tokens: "cacheCreationTokens"
58
+ };
59
+ for (const [srcKey, dstKey] of Object.entries(mapping)) {
60
+ const val = usage[srcKey];
61
+ if (val !== void 0 && val !== null) {
62
+ usageInfo[dstKey] = val;
63
+ }
64
+ }
65
+ return usageInfo;
66
+ }
67
+ var BitfabClaudeAgentHandler = class {
68
+ constructor(config) {
69
+ // Span tracking
70
+ this.runToSpan = /* @__PURE__ */ new Map();
71
+ this.traceId = null;
72
+ this.rootSpanId = null;
73
+ this.activeContext = null;
74
+ this.traceStartedAt = null;
75
+ // LLM turn tracking
76
+ this.conversationHistory = [];
77
+ this.pendingMessages = [];
78
+ this.currentLlmSpanId = null;
79
+ this.currentLlmMessageId = null;
80
+ this.currentLlmContent = [];
81
+ this.currentLlmModel = null;
82
+ this.currentLlmUsage = {};
83
+ this.currentLlmStartedAt = null;
84
+ this.currentLlmHistorySnapshot = [];
85
+ // Subagent tracking
86
+ this.activeSubagentSpans = /* @__PURE__ */ new Map();
87
+ this.httpClient = new HttpClient({
88
+ apiKey: config.apiKey,
89
+ serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
90
+ timeout: config.timeout ?? 1e4
91
+ });
92
+ this.traceFunctionKey = config.traceFunctionKey;
93
+ this.getActiveSpanContext = config.getActiveSpanContext ?? null;
94
+ this.preToolUseHook = this.preToolUseHook.bind(this);
95
+ this.postToolUseHook = this.postToolUseHook.bind(this);
96
+ this.postToolUseFailureHook = this.postToolUseFailureHook.bind(this);
97
+ this.subagentStartHook = this.subagentStartHook.bind(this);
98
+ this.subagentStopHook = this.subagentStopHook.bind(this);
99
+ }
100
+ // ── trace lifecycle ──────────────────────────────────────────
101
+ ensureTrace() {
102
+ if (this.traceId !== null) {
103
+ return this.traceId;
104
+ }
105
+ this.activeContext = this.getActiveSpanContext?.() ?? null;
106
+ if (this.activeContext) {
107
+ this.traceId = this.activeContext.traceId;
108
+ } else {
109
+ this.traceId = crypto.randomUUID();
110
+ }
111
+ this.traceStartedAt = nowIso();
112
+ return this.traceId;
113
+ }
114
+ getParentId(agentId) {
115
+ if (agentId) {
116
+ const subagentSpanId = this.activeSubagentSpans.get(agentId);
117
+ if (subagentSpanId) {
118
+ return subagentSpanId;
119
+ }
120
+ }
121
+ return this.activeContext?.spanId ?? this.rootSpanId ?? null;
122
+ }
123
+ // ── span helpers ─────────────────────────────────────────────
124
+ startSpan(spanId, name, spanType, inputData, parentId) {
125
+ const traceId = this.ensureTrace();
126
+ const spanInfo = {
127
+ spanId,
128
+ traceId,
129
+ parentId: parentId ?? null,
130
+ startedAt: nowIso(),
131
+ name,
132
+ type: spanType,
133
+ input: safeSerialize(inputData),
134
+ contexts: []
135
+ };
136
+ this.runToSpan.set(spanId, spanInfo);
137
+ return spanInfo;
138
+ }
139
+ completeSpan(spanId, output, error, extraContexts) {
140
+ const spanInfo = this.runToSpan.get(spanId);
141
+ if (!spanInfo) {
142
+ return;
143
+ }
144
+ this.runToSpan.delete(spanId);
145
+ spanInfo.endedAt = nowIso();
146
+ spanInfo.output = safeSerialize(output);
147
+ if (error !== void 0) {
148
+ spanInfo.error = error;
149
+ }
150
+ if (extraContexts) {
151
+ spanInfo.contexts.push(extraContexts);
152
+ }
153
+ this.sendSpan(spanInfo);
154
+ }
155
+ sendSpan(spanInfo) {
156
+ const spanData = {
157
+ name: spanInfo.name,
158
+ type: spanInfo.type
159
+ };
160
+ if (spanInfo.input !== void 0) {
161
+ spanData.input = spanInfo.input;
162
+ }
163
+ if (spanInfo.output !== void 0) {
164
+ spanData.output = spanInfo.output;
165
+ }
166
+ if (spanInfo.error !== void 0) {
167
+ spanData.error = spanInfo.error;
168
+ }
169
+ if (spanInfo.contexts.length > 0) {
170
+ spanData.contexts = spanInfo.contexts;
171
+ }
172
+ const rawSpan = {
173
+ id: spanInfo.spanId,
174
+ trace_id: spanInfo.traceId,
175
+ started_at: spanInfo.startedAt,
176
+ ended_at: spanInfo.endedAt ?? nowIso(),
177
+ span_data: spanData
178
+ };
179
+ if (spanInfo.parentId !== null) {
180
+ rawSpan.parent_id = spanInfo.parentId;
181
+ }
182
+ const payload = {
183
+ type: "sdk-function",
184
+ source: "typescript-sdk-claude-agent-sdk",
185
+ traceFunctionKey: this.traceFunctionKey,
186
+ sourceTraceId: spanInfo.traceId,
187
+ rawSpan
188
+ };
189
+ try {
190
+ this.httpClient.sendExternalSpan(payload);
191
+ } catch {
192
+ }
193
+ }
194
+ sendTraceCompletion(endedAt, metadata) {
195
+ if (this.traceId === null) {
196
+ return;
197
+ }
198
+ const completed = this.activeContext === null;
199
+ const traceId = this.traceId;
200
+ this.traceId = null;
201
+ const externalTrace = {
202
+ id: traceId,
203
+ started_at: this.traceStartedAt ?? nowIso(),
204
+ ended_at: endedAt ?? nowIso(),
205
+ workflow_name: this.traceFunctionKey
206
+ };
207
+ if (metadata) {
208
+ externalTrace.metadata = metadata;
209
+ }
210
+ const traceData = {
211
+ type: "sdk-function",
212
+ source: "typescript-sdk-claude-agent-sdk",
213
+ traceFunctionKey: this.traceFunctionKey,
214
+ externalTrace,
215
+ completed
216
+ };
217
+ try {
218
+ this.httpClient.sendExternalTrace(traceData);
219
+ } catch {
220
+ }
221
+ }
222
+ // ── hook callbacks ───────────────────────────────────────────
223
+ async preToolUseHook(inputData, toolUseId, _context) {
224
+ try {
225
+ const sid = inputData.tool_use_id ?? toolUseId ?? crypto.randomUUID();
226
+ const toolName = inputData.tool_name ?? "tool";
227
+ const toolInput = inputData.tool_input ?? {};
228
+ const agentId = inputData.agent_id;
229
+ const parentId = this.getParentId(agentId);
230
+ this.startSpan(sid, toolName, "function", toolInput, parentId);
231
+ } catch {
232
+ }
233
+ return {};
234
+ }
235
+ async postToolUseHook(inputData, toolUseId, _context) {
236
+ try {
237
+ const sid = inputData.tool_use_id ?? toolUseId ?? "";
238
+ const toolResponse = inputData.tool_response;
239
+ this.completeSpan(sid, toolResponse);
240
+ } catch {
241
+ }
242
+ return {};
243
+ }
244
+ async postToolUseFailureHook(inputData, toolUseId, _context) {
245
+ try {
246
+ const sid = inputData.tool_use_id ?? toolUseId ?? "";
247
+ const error = String(inputData.error ?? "Unknown error");
248
+ this.completeSpan(sid, void 0, error);
249
+ } catch {
250
+ }
251
+ return {};
252
+ }
253
+ async subagentStartHook(inputData, _toolUseId, _context) {
254
+ try {
255
+ const agentId = inputData.agent_id ?? crypto.randomUUID();
256
+ const agentType = inputData.agent_type ?? "subagent";
257
+ const parentId = this.getParentId();
258
+ const spanId = crypto.randomUUID();
259
+ this.activeSubagentSpans.set(agentId, spanId);
260
+ this.startSpan(
261
+ spanId,
262
+ `Agent: ${agentType}`,
263
+ "agent",
264
+ void 0,
265
+ parentId
266
+ );
267
+ } catch {
268
+ }
269
+ return {};
270
+ }
271
+ async subagentStopHook(inputData, _toolUseId, _context) {
272
+ try {
273
+ const agentId = inputData.agent_id ?? "";
274
+ const spanId = this.activeSubagentSpans.get(agentId);
275
+ if (spanId) {
276
+ this.activeSubagentSpans.delete(agentId);
277
+ this.completeSpan(spanId);
278
+ }
279
+ } catch {
280
+ }
281
+ return {};
282
+ }
283
+ // ── public API ───────────────────────────────────────────────
284
+ /**
285
+ * Inject Bitfab tracing hooks into Claude Agent SDK options.
286
+ *
287
+ * Modifies the options object and returns it for convenience.
288
+ * The SDK's `HookMatcher` is constructed as a plain object
289
+ * (`{ matcher: null, hooks: [callback] }`) to avoid requiring
290
+ * `@anthropic-ai/claude-agent-sdk` as a dependency.
291
+ *
292
+ * @param options - Options object with a `hooks` property
293
+ * @returns The modified options object with Bitfab hooks injected
294
+ */
295
+ instrumentOptions(options) {
296
+ const hooks = options.hooks ?? {};
297
+ if (!options.hooks) {
298
+ ;
299
+ options.hooks = hooks;
300
+ }
301
+ const hookConfig = [
302
+ ["PreToolUse", this.preToolUseHook],
303
+ ["PostToolUse", this.postToolUseHook],
304
+ ["PostToolUseFailure", this.postToolUseFailureHook],
305
+ ["SubagentStart", this.subagentStartHook],
306
+ ["SubagentStop", this.subagentStopHook]
307
+ ];
308
+ for (const [event, callback] of hookConfig) {
309
+ if (!hooks[event]) {
310
+ hooks[event] = [];
311
+ }
312
+ hooks[event].push({ matcher: null, hooks: [callback] });
313
+ }
314
+ return options;
315
+ }
316
+ /**
317
+ * Wrap a `ClaudeSDKClient.receiveResponse()` stream to capture LLM turns.
318
+ *
319
+ * Yields every message unchanged while capturing AssistantMessage
320
+ * content as LLM turn spans.
321
+ */
322
+ async *wrapResponse(stream) {
323
+ yield* this.processStream(stream);
324
+ }
325
+ /**
326
+ * Wrap a `query()` async iterator to capture LLM turns.
327
+ *
328
+ * Same as `wrapResponse` but for the simpler `query()` API
329
+ * which does not support hooks (no tool/subagent spans).
330
+ */
331
+ async *wrapQuery(stream) {
332
+ yield* this.processStream(stream);
333
+ }
334
+ // ── stream processing ────────────────────────────────────────
335
+ async *processStream(stream) {
336
+ try {
337
+ for await (const message of stream) {
338
+ try {
339
+ this.processMessage(message);
340
+ } catch {
341
+ }
342
+ yield message;
343
+ }
344
+ } finally {
345
+ try {
346
+ this.flushLlmTurn();
347
+ this.sendTraceCompletion();
348
+ } catch {
349
+ }
350
+ this.resetState();
351
+ }
352
+ }
353
+ processMessage(message) {
354
+ const typeName = message.constructor?.name ?? "";
355
+ if (typeName === "AssistantMessage") {
356
+ this.handleAssistantMessage(message);
357
+ } else if (typeName === "UserMessage") {
358
+ this.handleUserMessage(message);
359
+ } else if (typeName === "ResultMessage") {
360
+ this.handleResultMessage(message);
361
+ }
362
+ }
363
+ handleAssistantMessage(message) {
364
+ this.ensureTrace();
365
+ const messageId = message.message_id;
366
+ if (messageId !== this.currentLlmMessageId) {
367
+ this.flushLlmTurn();
368
+ this.conversationHistory.push(...this.pendingMessages);
369
+ this.pendingMessages = [];
370
+ this.currentLlmSpanId = crypto.randomUUID();
371
+ this.currentLlmMessageId = messageId ?? null;
372
+ this.currentLlmContent = [];
373
+ this.currentLlmModel = message.model ?? null;
374
+ this.currentLlmUsage = {};
375
+ this.currentLlmStartedAt = nowIso();
376
+ this.currentLlmHistorySnapshot = [...this.conversationHistory];
377
+ }
378
+ const content = message.content;
379
+ if (Array.isArray(content)) {
380
+ this.currentLlmContent.push(...extractContentBlocks(content));
381
+ }
382
+ const usage = extractUsage(message);
383
+ if (Object.keys(usage).length > 0) {
384
+ Object.assign(this.currentLlmUsage, usage);
385
+ }
386
+ const model = message.model;
387
+ if (model) {
388
+ this.currentLlmModel = model;
389
+ }
390
+ }
391
+ handleUserMessage(message) {
392
+ const content = message.content;
393
+ const toolUseResult = message.tool_use_result;
394
+ if (toolUseResult !== void 0) {
395
+ this.pendingMessages.push({
396
+ role: "tool",
397
+ content: safeSerialize(content),
398
+ tool_result: safeSerialize(toolUseResult)
399
+ });
400
+ } else {
401
+ this.pendingMessages.push({
402
+ role: "user",
403
+ content: safeSerialize(content)
404
+ });
405
+ }
406
+ }
407
+ handleResultMessage(message) {
408
+ this.flushLlmTurn();
409
+ const metadata = {};
410
+ for (const attr of [
411
+ "num_turns",
412
+ "total_cost_usd",
413
+ "duration_ms",
414
+ "duration_api_ms",
415
+ "session_id"
416
+ ]) {
417
+ const val = message[attr];
418
+ if (val !== void 0 && val !== null) {
419
+ metadata[attr] = val;
420
+ }
421
+ }
422
+ const usage = message.usage;
423
+ if (usage && typeof usage === "object") {
424
+ metadata.usage = safeSerialize(usage);
425
+ }
426
+ this.sendTraceCompletion(
427
+ void 0,
428
+ Object.keys(metadata).length > 0 ? metadata : void 0
429
+ );
430
+ }
431
+ flushLlmTurn() {
432
+ if (this.currentLlmSpanId === null) {
433
+ return;
434
+ }
435
+ const spanId = this.currentLlmSpanId;
436
+ const traceId = this.ensureTrace();
437
+ const parentId = this.getParentId();
438
+ const llmContext = {};
439
+ if (this.currentLlmModel) {
440
+ llmContext.model = this.currentLlmModel;
441
+ }
442
+ Object.assign(llmContext, this.currentLlmUsage);
443
+ const spanInfo = {
444
+ spanId,
445
+ traceId,
446
+ parentId,
447
+ startedAt: this.currentLlmStartedAt ?? nowIso(),
448
+ endedAt: nowIso(),
449
+ name: this.currentLlmModel ?? "llm",
450
+ type: "llm",
451
+ input: this.currentLlmHistorySnapshot,
452
+ output: this.currentLlmContent,
453
+ contexts: Object.keys(llmContext).length > 0 ? [llmContext] : []
454
+ };
455
+ this.sendSpan(spanInfo);
456
+ this.conversationHistory.push({
457
+ role: "assistant",
458
+ content: this.currentLlmContent
459
+ });
460
+ this.currentLlmSpanId = null;
461
+ this.currentLlmMessageId = null;
462
+ this.currentLlmContent = [];
463
+ this.currentLlmModel = null;
464
+ this.currentLlmUsage = {};
465
+ this.currentLlmStartedAt = null;
466
+ this.currentLlmHistorySnapshot = [];
467
+ }
468
+ resetState() {
469
+ this.runToSpan.clear();
470
+ this.traceId = null;
471
+ this.rootSpanId = null;
472
+ this.activeContext = null;
473
+ this.traceStartedAt = null;
474
+ this.conversationHistory = [];
475
+ this.pendingMessages = [];
476
+ this.currentLlmSpanId = null;
477
+ this.currentLlmMessageId = null;
478
+ this.currentLlmContent = [];
479
+ this.currentLlmModel = null;
480
+ this.currentLlmUsage = {};
481
+ this.currentLlmStartedAt = null;
482
+ this.currentLlmHistorySnapshot = [];
483
+ this.activeSubagentSpans.clear();
484
+ }
485
+ };
486
+
487
+ // src/baml.ts
488
+ var cachedBaml = null;
489
+ async function loadBaml() {
490
+ if (cachedBaml) {
491
+ return cachedBaml;
492
+ }
493
+ try {
494
+ cachedBaml = await import("@boundaryml/baml");
495
+ return cachedBaml;
496
+ } catch {
497
+ throw new Error(
498
+ "@boundaryml/baml is required for Bitfab.call(). Install it with: npm install @boundaryml/baml"
499
+ );
500
+ }
501
+ }
502
+ function capitalize(str) {
503
+ return str.charAt(0).toUpperCase() + str.slice(1);
504
+ }
505
+ function formatProvider(provider) {
506
+ const providerMap = {
507
+ openai: "OpenAI",
508
+ anthropic: "Anthropic",
509
+ google: "Google"
510
+ };
511
+ return providerMap[provider] ?? capitalize(provider);
512
+ }
513
+ function formatModel(model) {
514
+ return model.replace(/^gpt-/, "GPT").replace(/\./g, "_").replace(/-/g, "_");
515
+ }
516
+ function getClientName(provider, model) {
517
+ return `${formatProvider(provider)}_${formatModel(model)}`;
518
+ }
519
+ function generateClientDefinitions(providers) {
520
+ const definitions = [];
521
+ for (const providerDef of providers) {
522
+ for (const model of providerDef.models) {
523
+ const clientName = getClientName(providerDef.provider, model.model);
524
+ definitions.push(`client<llm> ${clientName} {
525
+ provider ${providerDef.provider}
526
+ options {
527
+ model "${model.model}"
528
+ api_key env.${providerDef.apiKeyEnv}
529
+ }
530
+ }`);
531
+ }
532
+ }
533
+ return definitions.join("\n\n");
534
+ }
535
+ function withDefaultClients(bamlSource, providers) {
536
+ const hasDefaultClient = bamlSource.includes("client<llm> OpenAI_");
537
+ if (hasDefaultClient) {
538
+ return bamlSource;
539
+ }
540
+ const defaultClients = generateClientDefinitions(providers);
541
+ return `${defaultClients}
542
+
543
+ ${bamlSource}`;
544
+ }
545
+ function extractFunctionName(bamlSource) {
546
+ const match = bamlSource.match(/function\s+(\w+)\s*\(/);
547
+ return match?.[1] ?? null;
548
+ }
549
+ function extractFunctionParameters(bamlSource) {
550
+ const functionMatch = bamlSource.match(/function\s+\w+\s*\(([^)]*)\)\s*->/);
551
+ if (!functionMatch) {
552
+ return [];
553
+ }
554
+ const paramsString = functionMatch[1].trim();
555
+ if (!paramsString) {
556
+ return [];
557
+ }
558
+ const params = [];
559
+ const paramParts = splitParameters(paramsString);
560
+ for (const part of paramParts) {
561
+ const trimmed = part.trim();
562
+ if (!trimmed) {
563
+ continue;
564
+ }
565
+ const paramMatch = trimmed.match(/^(\w+)\s*:\s*(.+)$/);
566
+ if (paramMatch) {
567
+ const name = paramMatch[1];
568
+ let type = paramMatch[2].trim();
569
+ const isOptional = type.endsWith("?");
570
+ if (isOptional) {
571
+ type = type.slice(0, -1);
572
+ }
573
+ params.push({ name, type, isOptional });
574
+ }
575
+ }
576
+ return params;
577
+ }
578
+ function splitParameters(paramsString) {
579
+ const parts = [];
580
+ let current = "";
581
+ let depth = 0;
582
+ for (const char of paramsString) {
583
+ if (char === "<") {
584
+ depth++;
585
+ current += char;
586
+ } else if (char === ">") {
587
+ depth--;
588
+ current += char;
589
+ } else if (char === "," && depth === 0) {
590
+ parts.push(current);
591
+ current = "";
592
+ } else {
593
+ current += char;
594
+ }
595
+ }
596
+ if (current.trim()) {
597
+ parts.push(current);
598
+ }
599
+ return parts;
600
+ }
601
+ function coerceToType(value, expectedType) {
602
+ if (expectedType === "string") {
603
+ return value;
604
+ }
605
+ if (expectedType === "int") {
606
+ const parsed = Number.parseInt(value, 10);
607
+ if (!Number.isNaN(parsed)) {
608
+ return parsed;
609
+ }
610
+ return value;
611
+ }
612
+ if (expectedType === "float") {
613
+ const parsed = Number.parseFloat(value);
614
+ if (!Number.isNaN(parsed)) {
615
+ return parsed;
616
+ }
617
+ return value;
618
+ }
619
+ if (expectedType === "bool") {
620
+ const lower = value.toLowerCase();
621
+ if (lower === "true") {
622
+ return true;
623
+ }
624
+ if (lower === "false") {
625
+ return false;
626
+ }
627
+ return value;
628
+ }
629
+ if (expectedType.endsWith("[]")) {
630
+ try {
631
+ const parsed = JSON.parse(value);
632
+ if (Array.isArray(parsed)) {
633
+ return parsed;
634
+ }
635
+ } catch {
636
+ }
637
+ return value;
638
+ }
639
+ try {
640
+ return JSON.parse(value);
641
+ } catch {
642
+ return value;
643
+ }
644
+ }
645
+ function coerceInputs(inputs, expectedTypes) {
646
+ const coerced = {};
647
+ for (const [key, value] of Object.entries(inputs)) {
648
+ if (typeof value === "string") {
649
+ const expectedType = expectedTypes.get(key);
650
+ if (expectedType) {
651
+ coerced[key] = coerceToType(value, expectedType);
652
+ } else {
653
+ coerced[key] = value;
654
+ }
655
+ } else {
656
+ coerced[key] = value;
657
+ }
658
+ }
659
+ return coerced;
660
+ }
661
+ function objToDict(obj, depth = 0, maxDepth = 5) {
662
+ if (depth > maxDepth) {
663
+ return `<max depth reached: ${typeof obj}>`;
664
+ }
665
+ if (obj === null || obj === void 0 || typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean") {
666
+ return obj;
667
+ }
668
+ if (Array.isArray(obj)) {
669
+ return obj.map((item) => objToDict(item, depth + 1, maxDepth));
670
+ }
671
+ if (typeof obj === "object") {
672
+ const result = {};
673
+ if (obj.constructor && obj.constructor.name !== "Object") {
674
+ result.__type__ = obj.constructor.name;
675
+ }
676
+ for (const key of Object.keys(obj)) {
677
+ if (key.startsWith("_")) {
678
+ continue;
679
+ }
680
+ try {
681
+ const value = obj[key];
682
+ if (typeof value === "function") {
683
+ continue;
684
+ }
685
+ result[key] = objToDict(value, depth + 1, maxDepth);
686
+ } catch (error) {
687
+ result[key] = `<error: ${error instanceof Error ? error.message : String(error)}>`;
688
+ }
689
+ }
690
+ try {
691
+ const proto = Object.getPrototypeOf(obj);
692
+ if (proto && proto !== Object.prototype) {
693
+ const descriptors = Object.getOwnPropertyDescriptors(proto);
694
+ for (const [key, descriptor] of Object.entries(descriptors)) {
695
+ if (key.startsWith("_") || key === "constructor" || key in result) {
696
+ continue;
697
+ }
698
+ if (descriptor.get) {
699
+ try {
700
+ const value = obj[key];
701
+ if (typeof value !== "function") {
702
+ result[key] = objToDict(value, depth + 1, maxDepth);
703
+ }
704
+ } catch {
705
+ }
706
+ }
707
+ }
708
+ }
709
+ } catch {
710
+ }
711
+ return result;
712
+ }
713
+ return String(obj);
714
+ }
715
+ function serializeCollector(collector) {
716
+ try {
717
+ return objToDict(collector, 0, 5);
718
+ } catch (_error) {
719
+ return null;
720
+ }
721
+ }
722
+ var ALLOWED_ENV_KEYS = ["OPENAI_API_KEY"];
723
+ function filterEnvVars(envVars) {
724
+ const filtered = {};
725
+ for (const key of ALLOWED_ENV_KEYS) {
726
+ const value = envVars[key];
727
+ if (value) {
728
+ filtered[key] = value;
729
+ }
730
+ }
731
+ return filtered;
732
+ }
733
+ async function runFunctionWithBaml(bamlSource, inputs, providers, envVars) {
734
+ const { BamlRuntime, Collector } = await loadBaml();
735
+ const functionName = extractFunctionName(bamlSource);
736
+ if (!functionName) {
737
+ throw new Error("No function found in BAML source");
738
+ }
739
+ const fullSource = withDefaultClients(bamlSource, providers);
740
+ const filteredEnvVars = filterEnvVars(envVars);
741
+ const runtime = BamlRuntime.fromFiles(
742
+ "/tmp/baml_runtime",
743
+ { "source.baml": fullSource },
744
+ filteredEnvVars
745
+ );
746
+ const ctx = runtime.createContextManager();
747
+ const collector = new Collector("bitfab-collector");
748
+ const params = extractFunctionParameters(bamlSource);
749
+ const expectedTypes = new Map(params.map((p) => [p.name, p.type]));
750
+ const args = coerceInputs(inputs, expectedTypes);
751
+ const functionResult = await runtime.callFunction(
752
+ functionName,
753
+ args,
754
+ ctx,
755
+ null,
756
+ // TypeBuilder
757
+ null,
758
+ // ClientRegistry
759
+ [collector],
760
+ // Collectors - capture execution data
761
+ {},
762
+ // Tags
763
+ filteredEnvVars
764
+ );
765
+ if (!functionResult.isOk()) {
766
+ throw new Error("BAML function execution failed");
767
+ }
768
+ const rawCollector = serializeCollector(collector);
769
+ return {
770
+ result: functionResult.parsed(false),
771
+ rawCollector
772
+ };
773
+ }
774
+
775
+ // src/langgraph.ts
776
+ var LANGSMITH_HIDDEN_TAG = "langsmith:hidden";
777
+ var LANGGRAPH_METADATA_KEYS = [
778
+ "langgraph_step",
779
+ "langgraph_node",
780
+ "langgraph_triggers",
781
+ "langgraph_path",
782
+ "langgraph_checkpoint_ns"
783
+ ];
784
+ function nowIso2() {
785
+ return (/* @__PURE__ */ new Date()).toISOString();
786
+ }
787
+ var MAX_SERIALIZE_DEPTH = 6;
788
+ function safeSerialize2(value) {
789
+ return safeSerializeInner(value, 0, /* @__PURE__ */ new WeakSet());
790
+ }
791
+ function safeSerializeInner(value, depth, seen) {
792
+ if (value === null || value === void 0) {
793
+ return value;
794
+ }
795
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
796
+ return value;
797
+ }
798
+ const className = value?.constructor?.name ?? typeof value;
799
+ if (depth > MAX_SERIALIZE_DEPTH) {
800
+ return `<${className}>`;
801
+ }
802
+ if (typeof value === "object") {
803
+ if (seen.has(value)) {
804
+ return `<cycle ${className}>`;
805
+ }
806
+ seen.add(value);
807
+ }
808
+ if (Array.isArray(value)) {
809
+ return value.map((item) => safeSerializeInner(item, depth + 1, seen));
810
+ }
811
+ if (typeof value === "object") {
812
+ if (typeof value.toJSON === "function") {
813
+ try {
814
+ return value.toJSON();
815
+ } catch {
816
+ return `<${className}>`;
817
+ }
818
+ }
819
+ try {
820
+ const result = {};
821
+ for (const [k, v] of Object.entries(value)) {
822
+ if (!k.startsWith("_")) {
823
+ result[k] = safeSerializeInner(v, depth + 1, seen);
824
+ }
825
+ }
826
+ return result;
827
+ } catch {
828
+ return `<${className}>`;
829
+ }
830
+ }
831
+ try {
832
+ return String(value);
833
+ } catch {
834
+ return `<${className}>`;
835
+ }
836
+ }
837
+ function convertMessage(message) {
838
+ if (typeof message !== "object" || message === null) {
839
+ return { role: "unknown", content: String(message) };
840
+ }
841
+ const msg = message;
842
+ if (typeof msg.toDict === "function") {
843
+ return msg.toDict();
844
+ }
845
+ const typeToRole = {
846
+ human: "user",
847
+ ai: "assistant",
848
+ system: "system",
849
+ tool: "tool",
850
+ function: "function"
851
+ };
852
+ const result = {};
853
+ const msgType = msg._getType ? String(msg._getType()) : msg.type;
854
+ result.role = (msgType ? typeToRole[msgType] : void 0) ?? msg.role ?? "unknown";
855
+ result.content = msg.content ?? "";
856
+ if (msg.tool_calls) {
857
+ result.tool_calls = msg.tool_calls;
858
+ }
859
+ if (msg.tool_call_id) {
860
+ result.tool_call_id = msg.tool_call_id;
861
+ }
862
+ if (msg.name) {
863
+ result.name = msg.name;
864
+ }
865
+ return result;
866
+ }
867
+ function extractModelName(serialized, metadata) {
868
+ if (serialized) {
869
+ const kwargs = serialized.kwargs;
870
+ if (kwargs) {
871
+ const model = kwargs.model_name ?? kwargs.model ?? kwargs.model_id;
872
+ if (model) {
873
+ return String(model);
874
+ }
875
+ }
876
+ }
877
+ if (metadata) {
878
+ const lsModel = metadata.ls_model_name;
879
+ if (lsModel) {
880
+ return String(lsModel);
881
+ }
882
+ }
883
+ return void 0;
884
+ }
885
+ function extractUsage2(output) {
886
+ const usage = {};
887
+ const llmOutput = output.llmOutput;
888
+ const tokenUsage = llmOutput?.tokenUsage ?? llmOutput?.token_usage ?? llmOutput?.usage ?? {};
889
+ const inputTokens = tokenUsage.promptTokens ?? tokenUsage.prompt_tokens ?? tokenUsage.input_tokens;
890
+ const outputTokens = tokenUsage.completionTokens ?? tokenUsage.completion_tokens ?? tokenUsage.output_tokens;
891
+ const totalTokens = tokenUsage.totalTokens ?? tokenUsage.total_tokens;
892
+ if (inputTokens !== void 0 && inputTokens !== null) {
893
+ usage.inputTokens = inputTokens;
894
+ }
895
+ if (outputTokens !== void 0 && outputTokens !== null) {
896
+ usage.outputTokens = outputTokens;
897
+ }
898
+ if (totalTokens !== void 0 && totalTokens !== null) {
899
+ usage.totalTokens = totalTokens;
900
+ }
901
+ return usage;
902
+ }
903
+ function extractLangGraphMetadata(metadata) {
904
+ if (!metadata) {
905
+ return {};
906
+ }
907
+ const result = {};
908
+ for (const key of LANGGRAPH_METADATA_KEYS) {
909
+ if (key in metadata) {
910
+ result[key] = metadata[key];
911
+ }
912
+ }
913
+ return result;
914
+ }
915
+ var BitfabLangGraphCallbackHandler = class {
916
+ constructor(config) {
917
+ this.name = "BitfabLangGraphCallbackHandler";
918
+ this.ignoreRetriever = true;
919
+ this.ignoreRetry = true;
920
+ this.ignoreCustomEvent = true;
921
+ this.runToSpan = /* @__PURE__ */ new Map();
922
+ this.invocations = /* @__PURE__ */ new Map();
923
+ this.httpClient = new HttpClient({
924
+ apiKey: config.apiKey,
925
+ serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
926
+ timeout: config.timeout ?? 1e4
927
+ });
928
+ this.traceFunctionKey = config.traceFunctionKey;
929
+ this.getActiveSpanContext = config.getActiveSpanContext ?? null;
930
+ }
931
+ // ── lifecycle helpers ──────────────────────────────────────────
932
+ startSpan(runId, parentRunId, name, spanType, inputData, metadata, tags) {
933
+ const parentSpan = parentRunId ? this.runToSpan.get(parentRunId) : void 0;
934
+ const willHide = tags?.includes(LANGSMITH_HIDDEN_TAG) === true;
935
+ let invocation;
936
+ let effectiveParentId;
937
+ if (parentSpan) {
938
+ const existing = this.invocations.get(parentSpan.rootRunId);
939
+ if (existing) {
940
+ invocation = existing;
941
+ } else {
942
+ invocation = {
943
+ traceId: parentSpan.traceId,
944
+ activeContext: null,
945
+ rootRunId: parentSpan.rootRunId
946
+ };
947
+ this.invocations.set(invocation.rootRunId, invocation);
948
+ }
949
+ if (!willHide) {
950
+ let resolved = parentSpan;
951
+ while (resolved?.hidden === true) {
952
+ resolved = resolved.parentId ? this.runToSpan.get(resolved.parentId) : void 0;
953
+ }
954
+ effectiveParentId = resolved ? resolved.spanId : invocation.activeContext?.spanId ?? null;
955
+ } else {
956
+ effectiveParentId = parentRunId ?? null;
957
+ }
958
+ } else {
959
+ const activeContext = this.getActiveSpanContext?.() ?? null;
960
+ invocation = {
961
+ traceId: activeContext ? activeContext.traceId : crypto.randomUUID(),
962
+ activeContext,
963
+ rootRunId: runId
964
+ };
965
+ this.invocations.set(runId, invocation);
966
+ effectiveParentId = activeContext?.spanId ?? null;
967
+ }
968
+ const lgMetadata = extractLangGraphMetadata(metadata);
969
+ const contexts = Object.keys(lgMetadata).length > 0 ? [lgMetadata] : [];
970
+ const spanInfo = {
971
+ spanId: runId,
972
+ traceId: invocation.traceId,
973
+ rootRunId: invocation.rootRunId,
974
+ parentId: effectiveParentId,
975
+ startedAt: nowIso2(),
976
+ name,
977
+ type: spanType,
978
+ input: safeSerialize2(inputData),
979
+ contexts
980
+ };
981
+ if (willHide) {
982
+ spanInfo.hidden = true;
983
+ }
984
+ this.runToSpan.set(runId, spanInfo);
985
+ return spanInfo;
986
+ }
987
+ completeSpan(runId, output, error, extraContexts) {
988
+ const spanInfo = this.runToSpan.get(runId);
989
+ if (!spanInfo) {
990
+ return;
991
+ }
992
+ this.runToSpan.delete(runId);
993
+ spanInfo.endedAt = nowIso2();
994
+ spanInfo.output = safeSerialize2(output);
995
+ if (error !== void 0) {
996
+ spanInfo.error = error;
997
+ }
998
+ if (extraContexts && Object.keys(extraContexts).length > 0) {
999
+ spanInfo.contexts.push(extraContexts);
1000
+ }
1001
+ this.sendSpan(spanInfo);
1002
+ if (runId === spanInfo.rootRunId) {
1003
+ const invocation = this.invocations.get(runId);
1004
+ this.sendTraceCompletion(spanInfo, invocation?.activeContext ?? null);
1005
+ this.invocations.delete(runId);
1006
+ }
1007
+ }
1008
+ sendSpan(spanInfo) {
1009
+ const spanData = {
1010
+ name: spanInfo.name,
1011
+ type: spanInfo.type
1012
+ };
1013
+ if (spanInfo.input !== void 0) {
1014
+ spanData.input = spanInfo.input;
1015
+ }
1016
+ if (spanInfo.output !== void 0) {
1017
+ spanData.output = spanInfo.output;
1018
+ }
1019
+ if (spanInfo.error !== void 0) {
1020
+ spanData.error = spanInfo.error;
1021
+ }
1022
+ if (spanInfo.contexts.length > 0) {
1023
+ spanData.contexts = spanInfo.contexts;
1024
+ }
1025
+ if (spanInfo.hidden) {
1026
+ spanData.hidden = true;
1027
+ }
1028
+ const rawSpan = {
1029
+ id: spanInfo.spanId,
1030
+ trace_id: spanInfo.traceId,
1031
+ started_at: spanInfo.startedAt,
1032
+ ended_at: spanInfo.endedAt ?? nowIso2(),
1033
+ span_data: spanData
1034
+ };
1035
+ if (spanInfo.parentId !== null) {
1036
+ rawSpan.parent_id = spanInfo.parentId;
1037
+ }
1038
+ const payload = {
1039
+ type: "sdk-function",
1040
+ source: "typescript-sdk-langgraph",
1041
+ traceFunctionKey: this.traceFunctionKey,
1042
+ sourceTraceId: spanInfo.traceId,
1043
+ rawSpan
1044
+ };
1045
+ try {
1046
+ this.httpClient.sendExternalSpan(payload);
1047
+ } catch {
1048
+ }
1049
+ }
1050
+ sendTraceCompletion(rootSpan, activeContext) {
1051
+ const completed = activeContext === null;
1052
+ const traceData = {
1053
+ type: "sdk-function",
1054
+ source: "typescript-sdk-langgraph",
1055
+ traceFunctionKey: this.traceFunctionKey,
1056
+ externalTrace: {
1057
+ id: rootSpan.traceId,
1058
+ started_at: rootSpan.startedAt,
1059
+ ended_at: rootSpan.endedAt ?? nowIso2(),
1060
+ workflow_name: this.traceFunctionKey
1061
+ },
1062
+ completed
1063
+ };
1064
+ try {
1065
+ this.httpClient.sendExternalTrace(traceData);
1066
+ } catch {
1067
+ }
1068
+ }
1069
+ // ── chain callbacks (graph nodes) ─────────────────────────────
1070
+ async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata) {
1071
+ try {
1072
+ const idArr = chain.id;
1073
+ const name = chain.name ?? idArr?.[idArr.length - 1] ?? "chain";
1074
+ this.startSpan(
1075
+ runId,
1076
+ parentRunId,
1077
+ String(name),
1078
+ "agent",
1079
+ inputs,
1080
+ metadata,
1081
+ tags
1082
+ );
1083
+ } catch {
1084
+ }
1085
+ }
1086
+ async handleChainEnd(outputs, runId) {
1087
+ try {
1088
+ this.completeSpan(runId, outputs);
1089
+ } catch {
1090
+ }
1091
+ }
1092
+ async handleChainError(error, runId) {
1093
+ try {
1094
+ const errorObj = error;
1095
+ if (errorObj?.constructor?.name === "GraphBubbleUp") {
1096
+ this.completeSpan(runId, void 0, void 0);
1097
+ return;
1098
+ }
1099
+ this.completeSpan(
1100
+ runId,
1101
+ void 0,
1102
+ error instanceof Error ? error.message : String(error)
1103
+ );
1104
+ } catch {
1105
+ }
1106
+ }
1107
+ // ── LLM callbacks ─────────────────────────────────────────────
1108
+ async handleChatModelStart(llm, messages, runId, parentRunId, _extraParams, tags, metadata) {
1109
+ try {
1110
+ const model = extractModelName(llm, metadata);
1111
+ const idArr = llm.id;
1112
+ const name = model ?? idArr?.[idArr.length - 1] ?? "llm";
1113
+ const converted = messages.map((batch) => batch.map(convertMessage));
1114
+ const spanInfo = this.startSpan(
1115
+ runId,
1116
+ parentRunId,
1117
+ String(name),
1118
+ "llm",
1119
+ converted,
1120
+ metadata,
1121
+ tags
1122
+ );
1123
+ spanInfo.model = model;
1124
+ } catch {
1125
+ }
1126
+ }
1127
+ async handleLLMStart(llm, prompts, runId, parentRunId, _extraParams, tags, metadata) {
1128
+ try {
1129
+ const model = extractModelName(llm, metadata);
1130
+ const idArr = llm.id;
1131
+ const name = model ?? idArr?.[idArr.length - 1] ?? "llm";
1132
+ const spanInfo = this.startSpan(
1133
+ runId,
1134
+ parentRunId,
1135
+ String(name),
1136
+ "llm",
1137
+ prompts,
1138
+ metadata,
1139
+ tags
1140
+ );
1141
+ spanInfo.model = model;
1142
+ } catch {
1143
+ }
1144
+ }
1145
+ async handleLLMEnd(output, runId) {
1146
+ try {
1147
+ let llmOutput;
1148
+ const generations = output.generations;
1149
+ if (generations?.length && generations[generations.length - 1]?.length) {
1150
+ const gen = generations[generations.length - 1][generations[generations.length - 1].length - 1];
1151
+ const msg = gen.message;
1152
+ llmOutput = msg ? convertMessage(msg) : gen.text ?? String(gen);
1153
+ }
1154
+ const usage = extractUsage2(output);
1155
+ const spanInfo = this.runToSpan.get(runId);
1156
+ const model = spanInfo?.model;
1157
+ const llmContext = {};
1158
+ if (model) {
1159
+ llmContext.model = model;
1160
+ }
1161
+ Object.assign(llmContext, usage);
1162
+ this.completeSpan(
1163
+ runId,
1164
+ llmOutput,
1165
+ void 0,
1166
+ Object.keys(llmContext).length > 0 ? llmContext : void 0
1167
+ );
1168
+ } catch {
1169
+ }
1170
+ }
1171
+ async handleLLMError(error, runId) {
1172
+ try {
1173
+ this.completeSpan(
1174
+ runId,
1175
+ void 0,
1176
+ error instanceof Error ? error.message : String(error)
1177
+ );
1178
+ } catch {
1179
+ }
1180
+ }
1181
+ async handleLLMNewToken() {
1182
+ }
1183
+ // ── tool callbacks ────────────────────────────────────────────
1184
+ async handleToolStart(tool, input, runId, parentRunId, tags, metadata) {
1185
+ try {
1186
+ const name = tool.name ?? "tool";
1187
+ this.startSpan(
1188
+ runId,
1189
+ parentRunId,
1190
+ String(name),
1191
+ "function",
1192
+ input,
1193
+ metadata,
1194
+ tags
1195
+ );
1196
+ } catch {
1197
+ }
1198
+ }
1199
+ async handleToolEnd(output, runId) {
1200
+ try {
1201
+ this.completeSpan(runId, output);
1202
+ } catch {
1203
+ }
1204
+ }
1205
+ async handleToolError(error, runId) {
1206
+ try {
1207
+ this.completeSpan(
1208
+ runId,
1209
+ void 0,
1210
+ error instanceof Error ? error.message : String(error)
1211
+ );
1212
+ } catch {
1213
+ }
1214
+ }
1215
+ // ── retriever callbacks ───────────────────────────────────────
1216
+ async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata) {
1217
+ try {
1218
+ const name = retriever.name ?? "retriever";
1219
+ this.startSpan(
1220
+ runId,
1221
+ parentRunId,
1222
+ String(name),
1223
+ "function",
1224
+ query,
1225
+ metadata,
1226
+ tags
1227
+ );
1228
+ } catch {
1229
+ }
1230
+ }
1231
+ async handleRetrieverEnd(documents, runId) {
1232
+ try {
1233
+ this.completeSpan(runId, documents);
1234
+ } catch {
1235
+ }
1236
+ }
1237
+ async handleRetrieverError(error, runId) {
1238
+ try {
1239
+ this.completeSpan(
1240
+ runId,
1241
+ void 0,
1242
+ error instanceof Error ? error.message : String(error)
1243
+ );
1244
+ } catch {
1245
+ }
1246
+ }
1247
+ };
1248
+
1249
+ // src/tracing.ts
1250
+ var BitfabOpenAITracingProcessor = class {
1251
+ /**
1252
+ * Initialize the tracing processor.
1253
+ *
1254
+ * @param config - Configuration options
1255
+ */
1256
+ constructor(config) {
1257
+ this.activeTraces = {};
1258
+ this.activeSpanMappings = {};
1259
+ this.httpClient = new HttpClient({
1260
+ apiKey: config.apiKey,
1261
+ serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
1262
+ timeout: config.timeout ?? 1e4
1263
+ });
1264
+ this.getActiveSpanContext = config.getActiveSpanContext ?? null;
1265
+ }
1266
+ /**
1267
+ * Called when a trace is started.
1268
+ * If there's an active withSpan context, the trace ID is remapped to the
1269
+ * outer trace and sent to pre-create the external_traces row on the server.
1270
+ */
1271
+ async onTraceStart(trace) {
1272
+ this.activeTraces[trace.traceId] = trace;
1273
+ const activeContext = this.getActiveSpanContext?.();
1274
+ if (activeContext) {
1275
+ this.activeSpanMappings[trace.traceId] = activeContext;
1276
+ }
1277
+ this.sendTrace(trace, activeContext ? { id: activeContext.traceId } : {});
1278
+ }
1279
+ /**
1280
+ * Called when a trace is ended.
1281
+ * If mapped to a withSpan trace, sends with remapped ID and completed=false
1282
+ * since the parent withSpan handles completion.
1283
+ */
1284
+ async onTraceEnd(trace) {
1285
+ const mapping = this.activeSpanMappings[trace.traceId];
1286
+ this.sendTrace(
1287
+ trace,
1288
+ mapping ? { id: mapping.traceId } : { completed: true }
1289
+ );
1290
+ delete this.activeSpanMappings[trace.traceId];
1291
+ delete this.activeTraces[trace.traceId];
1292
+ }
1293
+ /**
1294
+ * Called when a span is started.
1295
+ */
1296
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
1297
+ async onSpanStart(span) {
1298
+ this.sendSpan(span);
1299
+ }
1300
+ /**
1301
+ * Called when a span is ended.
1302
+ *
1303
+ * Send all spans to Bitfab for complete trace capture.
1304
+ */
1305
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
1306
+ async onSpanEnd(span) {
1307
+ this.sendSpan(span);
1308
+ }
1309
+ /**
1310
+ * Called when a trace is being flushed.
1311
+ */
1312
+ async forceFlush() {
1313
+ }
1314
+ /**
1315
+ * Called when the trace processor is shutting down.
1316
+ */
1317
+ async shutdown(_timeout) {
1318
+ this.activeTraces = {};
1319
+ this.activeSpanMappings = {};
1320
+ }
1321
+ /**
1322
+ * Send trace to Bitfab API (fire-and-forget).
1323
+ * When traceIdOverride is provided, the trace ID is remapped to link
1324
+ * the OpenAI trace into an outer withSpan trace.
1325
+ */
1326
+ sendTrace(trace, overrides = {}) {
1327
+ try {
1328
+ const { completed, ...traceOverrides } = overrides;
1329
+ const traceData = trace.toJSON();
1330
+ Object.assign(traceData, traceOverrides);
1331
+ this.httpClient.sendExternalTrace({
1332
+ type: "openai",
1333
+ source: "typescript-sdk-openai-tracing",
1334
+ externalTrace: traceData,
1335
+ completed: completed ?? false
1336
+ });
1337
+ } catch {
1338
+ }
1339
+ }
1340
+ /**
1341
+ * Export span to JSON object, collecting any errors.
1342
+ */
1343
+ exportSpan(span) {
1344
+ const errors = [];
1345
+ let serializedSpan;
1346
+ try {
1347
+ const jsonResult = span.toJSON();
1348
+ if (typeof jsonResult !== "object" || jsonResult === null) {
1349
+ errors.push({
1350
+ step: "span.toJSON()",
1351
+ error: `Returned unexpected type: ${typeof jsonResult}`
1352
+ });
1353
+ serializedSpan = {};
1354
+ } else {
1355
+ serializedSpan = jsonResult;
1356
+ }
1357
+ } catch (error) {
1358
+ errors.push({
1359
+ step: "span.toJSON()",
1360
+ error: error instanceof Error ? error.message : String(error)
1361
+ });
1362
+ serializedSpan = {};
1363
+ }
1364
+ if (!serializedSpan.span_data) {
1365
+ serializedSpan.span_data = {};
1366
+ }
1367
+ return [serializedSpan, errors];
1368
+ }
1369
+ /**
1370
+ * Extract and add input/response to serialized span, updating errors list.
1371
+ */
1372
+ extractSpanInputResponse(span, serializedSpan, errors) {
1373
+ const spanData = serializedSpan.span_data;
1374
+ try {
1375
+ spanData.input = span.spanData?._input || [];
1376
+ } catch (error) {
1377
+ errors.push({
1378
+ step: "access_input",
1379
+ error: error instanceof Error ? error.message : String(error)
1380
+ });
1381
+ }
1382
+ try {
1383
+ spanData.response = span.spanData?._response || null;
1384
+ } catch (error) {
1385
+ errors.push({
1386
+ step: "access_response",
1387
+ error: error instanceof Error ? error.message : String(error)
1388
+ });
1389
+ }
1390
+ }
1391
+ /**
1392
+ * If the span's trace is mapped to a withSpan trace, rewrite trace_id and parent_id.
1393
+ */
1394
+ applySpanOverrides(serializedSpan, traceId) {
1395
+ const mapping = this.activeSpanMappings[traceId];
1396
+ if (mapping) {
1397
+ serializedSpan.trace_id = mapping.traceId;
1398
+ if (!serializedSpan.parent_id) {
1399
+ serializedSpan.parent_id = mapping.spanId;
1400
+ }
1401
+ }
1402
+ }
1403
+ /**
1404
+ * Build span payload for the external spans API.
1405
+ */
1406
+ buildSpanPayload(serializedSpan, errors) {
1407
+ const payload = {
1408
+ type: "openai",
1409
+ source: "typescript-sdk-openai-tracing",
1410
+ sourceTraceId: serializedSpan.trace_id ?? "unknown",
1411
+ rawSpan: serializedSpan
1412
+ };
1413
+ if (errors.length > 0) {
1414
+ payload.errors = errors;
1415
+ }
1416
+ return payload;
1417
+ }
1418
+ /**
1419
+ * Send span to Bitfab API (fire-and-forget).
1420
+ * If the span belongs to a trace mapped to a withSpan trace, the trace_id
1421
+ * and parent_id are rewritten to link the span into the withSpan tree.
1422
+ */
1423
+ sendSpan(span) {
1424
+ const errors = [];
1425
+ const [serializedSpan, exportErrors] = this.exportSpan(span);
1426
+ errors.push(...exportErrors);
1427
+ this.extractSpanInputResponse(span, serializedSpan, errors);
1428
+ this.applySpanOverrides(serializedSpan, span.traceId ?? "");
1429
+ const payload = this.buildSpanPayload(serializedSpan, errors);
1430
+ this.httpClient.sendExternalSpan(payload);
1431
+ }
1432
+ };
1433
+
1434
+ // src/client.ts
1435
+ var activeTraceStates = /* @__PURE__ */ new Map();
1436
+ var pendingSpanPromises = /* @__PURE__ */ new Map();
1437
+ var asyncLocalStorage = null;
1438
+ var asyncLocalStorageReady = asyncStorageReady.then(() => {
1439
+ asyncLocalStorage = createAsyncLocalStorage();
1440
+ });
1441
+ var browserSpanStack = [];
1442
+ function getSpanStack() {
1443
+ if (asyncLocalStorage) {
1444
+ return asyncLocalStorage.getStore() ?? [];
1445
+ }
1446
+ return browserSpanStack;
1447
+ }
1448
+ function runWithSpanStack(stack, fn) {
1449
+ if (asyncLocalStorage) {
1450
+ return asyncLocalStorage.run(stack, fn);
1451
+ }
1452
+ const previousStack = browserSpanStack;
1453
+ browserSpanStack = stack;
1454
+ try {
1455
+ const result = fn();
1456
+ if (result instanceof Promise) {
1457
+ return result.finally(() => {
1458
+ browserSpanStack = previousStack;
1459
+ });
1460
+ }
1461
+ browserSpanStack = previousStack;
1462
+ return result;
1463
+ } catch (error) {
1464
+ browserSpanStack = previousStack;
1465
+ throw error;
1466
+ }
1467
+ }
1468
+ function isAsyncGenerator(value) {
1469
+ if (value === null || typeof value !== "object") {
1470
+ return false;
1471
+ }
1472
+ const candidate = value;
1473
+ return typeof candidate.next === "function" && typeof candidate.return === "function" && typeof candidate.throw === "function" && typeof candidate[Symbol.asyncIterator] === "function";
1474
+ }
1475
+ function wrapAsyncGenerator(source, spanStack, sendSpan) {
1476
+ const yielded = [];
1477
+ let returnValue;
1478
+ let finalized = false;
1479
+ const finalize = (errorMsg) => {
1480
+ if (finalized) {
1481
+ return;
1482
+ }
1483
+ finalized = true;
1484
+ void sendSpan({
1485
+ result: { yielded, return: returnValue },
1486
+ ...errorMsg && { error: errorMsg }
1487
+ });
1488
+ };
1489
+ const step = (method, arg) => runWithSpanStack(spanStack, () => {
1490
+ const op = source[method];
1491
+ return op.call(source, arg);
1492
+ });
1493
+ const handle = async (method, arg) => {
1494
+ try {
1495
+ const result = await step(method, arg);
1496
+ if (result.done) {
1497
+ returnValue = result.value;
1498
+ finalize();
1499
+ } else {
1500
+ yielded.push(result.value);
1501
+ }
1502
+ return result;
1503
+ } catch (error) {
1504
+ finalize(error instanceof Error ? error.message : String(error));
1505
+ throw error;
1506
+ }
1507
+ };
1508
+ const wrapped = {
1509
+ next(arg) {
1510
+ return handle("next", arg);
1511
+ },
1512
+ return(value) {
1513
+ return handle("return", value);
1514
+ },
1515
+ throw(err) {
1516
+ return handle("throw", err);
1517
+ },
1518
+ [Symbol.asyncIterator]() {
1519
+ return wrapped;
1520
+ },
1521
+ [Symbol.asyncDispose]() {
1522
+ return handle("return", void 0).then(() => void 0);
1523
+ }
1524
+ };
1525
+ return wrapped;
1526
+ }
1527
+ var cachedCollectorClass;
1528
+ async function loadCollectorClass() {
1529
+ if (cachedCollectorClass !== void 0) {
1530
+ return cachedCollectorClass;
1531
+ }
1532
+ try {
1533
+ const baml = await import("@boundaryml/baml");
1534
+ cachedCollectorClass = baml.Collector;
1535
+ return cachedCollectorClass;
1536
+ } catch {
1537
+ cachedCollectorClass = null;
1538
+ return null;
1539
+ }
1540
+ }
1541
+ function extractPromptFromCollector(collector) {
1542
+ try {
1543
+ const c = collector;
1544
+ const calls = c?.last?.calls ?? [];
1545
+ const selectedCall = calls.find((call) => call.selected) ?? calls[0];
1546
+ if (!selectedCall?.httpRequest?.body) {
1547
+ return null;
1548
+ }
1549
+ const body = selectedCall.httpRequest.body.json();
1550
+ if (!body || typeof body !== "object") {
1551
+ return null;
1552
+ }
1553
+ const messages = body.messages;
1554
+ if (!Array.isArray(messages) || messages.length === 0) {
1555
+ return null;
1556
+ }
1557
+ const rendered = messages.filter(
1558
+ (msg) => typeof msg === "object" && msg !== null && "role" in msg && typeof msg.role === "string"
1559
+ ).map((msg) => ({
1560
+ role: msg.role,
1561
+ content: typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)
1562
+ }));
1563
+ if (rendered.length > 0) {
1564
+ return JSON.stringify(rendered);
1565
+ }
1566
+ return null;
1567
+ } catch {
1568
+ return null;
1569
+ }
1570
+ }
1571
+ function extractContextFromCollector(collector) {
1572
+ try {
1573
+ const c = collector;
1574
+ const calls = c?.last?.calls ?? [];
1575
+ const selectedCall = calls.find((call) => call.selected) ?? calls[0];
1576
+ const usage = c?.usage;
1577
+ const context = {};
1578
+ if (selectedCall?.provider) {
1579
+ context.provider = selectedCall.provider;
1580
+ }
1581
+ const body = selectedCall?.httpRequest?.body?.json();
1582
+ if (body && typeof body === "object" && typeof body.model === "string") {
1583
+ context.model = body.model;
1584
+ } else {
1585
+ const url = selectedCall?.httpRequest?.url;
1586
+ if (url) {
1587
+ const match = url.match(/\/models\/([^/:]+)/);
1588
+ if (match?.[1]) {
1589
+ context.model = match[1];
1590
+ }
1591
+ }
1592
+ }
1593
+ const inputTokens = usage?.inputTokens ?? selectedCall?.usage?.inputTokens ?? null;
1594
+ const outputTokens = usage?.outputTokens ?? selectedCall?.usage?.outputTokens ?? null;
1595
+ if (inputTokens !== null) {
1596
+ context.inputTokens = inputTokens;
1597
+ }
1598
+ if (outputTokens !== null) {
1599
+ context.outputTokens = outputTokens;
1600
+ }
1601
+ const durationMs = c?.last?.timing?.durationMs ?? null;
1602
+ if (durationMs !== null) {
1603
+ context.durationMs = durationMs;
1604
+ }
1605
+ return Object.keys(context).length > 0 ? context : null;
1606
+ } catch {
1607
+ return null;
1608
+ }
1609
+ }
1610
+ var TRACE_ID_PATTERN = /^[a-zA-Z0-9_\-.:]+$/;
1611
+ var TRACE_ID_MAX_LENGTH = 256;
1612
+ function validateTraceId(traceId) {
1613
+ if (typeof traceId !== "string" || traceId.length === 0) {
1614
+ throw new BitfabError("traceId is required and must be a non-empty string");
1615
+ }
1616
+ if (traceId.length > TRACE_ID_MAX_LENGTH) {
1617
+ throw new BitfabError(
1618
+ `traceId must be ${TRACE_ID_MAX_LENGTH} characters or fewer`
1619
+ );
1620
+ }
1621
+ if (!TRACE_ID_PATTERN.test(traceId)) {
1622
+ throw new BitfabError(
1623
+ `traceId may only contain letters, digits, "_", "-", ".", ":"`
1624
+ );
1625
+ }
1626
+ }
1627
+ var noOpSpan = {
1628
+ traceId: "",
1629
+ addContext() {
1630
+ },
1631
+ setPrompt() {
1632
+ }
1633
+ };
1634
+ var noOpTrace = {
1635
+ setSessionId() {
1636
+ },
1637
+ setMetadata() {
1638
+ },
1639
+ addContext() {
1640
+ }
1641
+ };
1642
+ function getCurrentSpan() {
1643
+ const stack = getSpanStack();
1644
+ const current = stack[stack.length - 1];
1645
+ if (!current) {
1646
+ return noOpSpan;
1647
+ }
1648
+ return {
1649
+ traceId: current.traceId,
1650
+ addContext(context) {
1651
+ try {
1652
+ if (typeof context !== "object" || context === null) {
1653
+ return;
1654
+ }
1655
+ current.contexts.push(context);
1656
+ } catch {
1657
+ }
1658
+ },
1659
+ setPrompt(prompt) {
1660
+ try {
1661
+ if (typeof prompt !== "string") {
1662
+ return;
1663
+ }
1664
+ current.prompt = prompt;
1665
+ } catch {
1666
+ }
1667
+ }
1668
+ };
1669
+ }
1670
+ function getCurrentTrace() {
1671
+ const stack = getSpanStack();
1672
+ const current = stack[stack.length - 1];
1673
+ if (!current) {
1674
+ return noOpTrace;
1675
+ }
1676
+ const traceId = current.traceId;
1677
+ const getOrCreateTraceState = () => {
1678
+ let traceState = activeTraceStates.get(traceId);
1679
+ if (!traceState) {
1680
+ traceState = {
1681
+ traceId,
1682
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1683
+ contexts: []
1684
+ };
1685
+ activeTraceStates.set(traceId, traceState);
1686
+ }
1687
+ return traceState;
1688
+ };
1689
+ return {
1690
+ setSessionId(sessionId) {
1691
+ try {
1692
+ const traceState = getOrCreateTraceState();
1693
+ traceState.sessionId = sessionId;
1694
+ } catch {
1695
+ }
1696
+ },
1697
+ setMetadata(metadata) {
1698
+ try {
1699
+ if (typeof metadata !== "object" || metadata === null) {
1700
+ return;
1701
+ }
1702
+ const traceState = getOrCreateTraceState();
1703
+ traceState.metadata = { ...traceState.metadata, ...metadata };
1704
+ } catch {
1705
+ }
1706
+ },
1707
+ addContext(context) {
1708
+ try {
1709
+ if (typeof context !== "object" || context === null) {
1710
+ return;
1711
+ }
1712
+ const traceState = getOrCreateTraceState();
1713
+ traceState.contexts.push(context);
1714
+ } catch {
1715
+ }
1716
+ }
1717
+ };
1718
+ }
1719
+ var Bitfab = class {
1720
+ /**
1721
+ * Initialize the Bitfab client.
1722
+ *
1723
+ * @param config - Configuration options for the client
1724
+ */
1725
+ constructor(config) {
1726
+ this.apiKey = config.apiKey;
1727
+ this.serviceUrl = config.serviceUrl ?? DEFAULT_SERVICE_URL;
1728
+ this.timeout = config.timeout ?? 12e4;
1729
+ this.envVars = config.envVars ?? {};
1730
+ const enabled = config.enabled ?? true;
1731
+ if (enabled && (!config.apiKey || config.apiKey.trim() === "")) {
1732
+ console.warn(
1733
+ "Bitfab: apiKey is empty \u2014 tracing is disabled. Provide a valid API key to enable tracing."
1734
+ );
1735
+ this.enabled = false;
1736
+ } else {
1737
+ this.enabled = enabled;
1738
+ }
1739
+ this.bamlClient = config.bamlClient ?? null;
1740
+ this.httpClient = new HttpClient({
1741
+ apiKey: this.apiKey,
1742
+ serviceUrl: this.serviceUrl,
1743
+ timeout: this.timeout
1744
+ });
1745
+ }
1746
+ /**
1747
+ * Fetch the function with its current version and BAML prompt from the server.
1748
+ *
1749
+ * @param methodName - The name of the method to fetch
1750
+ * @returns The function with current version, BAML prompt, and provider definitions
1751
+ * @throws {BitfabError} If the function is not found or an error occurs
1752
+ */
1753
+ async fetchFunctionVersion(methodName) {
1754
+ const result = await this.httpClient.lookupFunction(methodName);
1755
+ if (result.id === null) {
1756
+ throw new BitfabError(
1757
+ `Function "${methodName}" not found. Create it at: ${this.serviceUrl}/functions`,
1758
+ "/functions"
1759
+ );
1760
+ }
1761
+ if (!result.prompt) {
1762
+ throw new BitfabError(
1763
+ `Function "${methodName}" has no prompt configured. Add one at: ${this.serviceUrl}/functions/${result.id}`,
1764
+ `/functions/${result.id}`
1765
+ );
1766
+ }
1767
+ return result;
1768
+ }
1769
+ /**
1770
+ * Call a method with the given named arguments via BAML execution.
1771
+ *
1772
+ * @param methodName - The name of the method to call
1773
+ * @param inputs - Named arguments to pass to the method
1774
+ * @returns The result of the BAML function execution
1775
+ * @throws {BitfabError} If service_url is not set, or if an error occurs
1776
+ */
1777
+ async call(methodName, inputs = {}) {
1778
+ try {
1779
+ const functionVersion = await this.fetchFunctionVersion(methodName);
1780
+ const executionResult = await runFunctionWithBaml(
1781
+ functionVersion.prompt,
1782
+ inputs,
1783
+ functionVersion.providers,
1784
+ this.envVars
1785
+ );
1786
+ const resultStr = typeof executionResult.result === "string" ? executionResult.result : JSON.stringify(executionResult.result);
1787
+ this.httpClient.sendInternalTrace(functionVersion.id, {
1788
+ result: resultStr,
1789
+ source: "typescript-sdk",
1790
+ ...Object.keys(inputs).length > 0 && { inputs },
1791
+ ...executionResult.rawCollector != null && {
1792
+ rawCollector: executionResult.rawCollector
1793
+ }
1794
+ });
1795
+ return executionResult.result;
1796
+ } catch (error) {
1797
+ if (error instanceof BitfabError) {
1798
+ throw error;
1799
+ }
1800
+ if (error instanceof Error) {
1801
+ throw new BitfabError(error.message);
1802
+ }
1803
+ throw new BitfabError("Unknown error occurred during local execution");
1804
+ }
1805
+ }
1806
+ /**
1807
+ * Get a tracing processor for OpenAI Agents SDK integration.
1808
+ *
1809
+ * This processor automatically captures traces and spans from the OpenAI Agents SDK
1810
+ * and sends them to Bitfab for monitoring and analysis.
1811
+ *
1812
+ * Example usage:
1813
+ * ```typescript
1814
+ * import { addTraceProcessor } from '@openai/agents';
1815
+ *
1816
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
1817
+ * const processor = client.getOpenAiTracingProcessor();
1818
+ * addTraceProcessor(processor);
1819
+ * ```
1820
+ *
1821
+ * @returns A BitfabOpenAITracingProcessor instance configured for this client
1822
+ */
1823
+ getOpenAiTracingProcessor() {
1824
+ return new BitfabOpenAITracingProcessor({
1825
+ apiKey: this.apiKey,
1826
+ serviceUrl: this.serviceUrl,
1827
+ getActiveSpanContext: () => {
1828
+ const stack = getSpanStack();
1829
+ return stack[stack.length - 1] ?? null;
1830
+ }
1831
+ });
1832
+ }
1833
+ /**
1834
+ * Get a LangGraph/LangChain callback handler for tracing.
1835
+ *
1836
+ * The handler captures graph node execution, LLM calls, and tool
1837
+ * invocations as Bitfab spans with proper parent-child hierarchy.
1838
+ *
1839
+ * ```typescript
1840
+ * const handler = client.getLangGraphCallbackHandler("my-agent");
1841
+ * const result = await agent.invoke(
1842
+ * { messages: [...] },
1843
+ * { callbacks: [handler] },
1844
+ * );
1845
+ * ```
1846
+ *
1847
+ * @param traceFunctionKey - Groups traces under this key in Bitfab
1848
+ * @returns A BitfabLangGraphCallbackHandler configured for this client
1849
+ */
1850
+ getLangGraphCallbackHandler(traceFunctionKey) {
1851
+ return new BitfabLangGraphCallbackHandler({
1852
+ apiKey: this.apiKey,
1853
+ traceFunctionKey,
1854
+ serviceUrl: this.serviceUrl,
1855
+ getActiveSpanContext: () => {
1856
+ const stack = getSpanStack();
1857
+ return stack[stack.length - 1] ?? null;
1858
+ }
1859
+ });
1860
+ }
1861
+ /**
1862
+ * Get a Claude Agent SDK handler for tracing.
1863
+ *
1864
+ * The handler captures LLM turns, tool invocations, and subagent
1865
+ * execution as Bitfab spans with proper parent-child hierarchy.
1866
+ *
1867
+ * ```typescript
1868
+ * const handler = client.getClaudeAgentHandler("my-agent");
1869
+ * const options = handler.instrumentOptions({
1870
+ * model: "claude-sonnet-4-5-...",
1871
+ * });
1872
+ * const sdkClient = new ClaudeSDKClient(options);
1873
+ * await sdkClient.connect();
1874
+ * await sdkClient.query("Do something");
1875
+ * for await (const msg of handler.wrapResponse(sdkClient.receiveResponse())) {
1876
+ * // process messages
1877
+ * }
1878
+ * ```
1879
+ *
1880
+ * @param traceFunctionKey - Groups traces under this key in Bitfab
1881
+ * @returns A BitfabClaudeAgentHandler configured for this client
1882
+ */
1883
+ getClaudeAgentHandler(traceFunctionKey) {
1884
+ return new BitfabClaudeAgentHandler({
1885
+ apiKey: this.apiKey,
1886
+ traceFunctionKey,
1887
+ serviceUrl: this.serviceUrl,
1888
+ getActiveSpanContext: () => {
1889
+ const stack = getSpanStack();
1890
+ return stack[stack.length - 1] ?? null;
1891
+ }
1892
+ });
1893
+ }
1894
+ /**
1895
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
1896
+ *
1897
+ * Creates a BAML Collector, calls the method through a tracked client,
1898
+ * then extracts rendered messages and token usage — calling setPrompt()
1899
+ * and addContext() on the current span automatically.
1900
+ *
1901
+ * The BAML client can be provided in the constructor or passed explicitly:
1902
+ *
1903
+ * ```typescript
1904
+ * // Option 1: bamlClient in constructor (use wrapBAML with just the method)
1905
+ * const client = new Bitfab({ apiKey: 'your-api-key', bamlClient: b });
1906
+ * const traced = client.withSpan('classify', { type: 'llm' },
1907
+ * client.wrapBAML(b.ClassifyText)
1908
+ * );
1909
+ *
1910
+ * // Option 2: pass bamlClient at call site
1911
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
1912
+ * const traced = client.withSpan('classify', { type: 'llm' },
1913
+ * client.wrapBAML(b, b.ClassifyText)
1914
+ * );
1915
+ * ```
1916
+ *
1917
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
1918
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
1919
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
1920
+ * @returns An async function with the same signature that instruments the BAML call
1921
+ */
1922
+ wrapBAML(methodOrClient, maybeMethodOrOptions, maybeOptions) {
1923
+ let bamlClient;
1924
+ let method;
1925
+ let options;
1926
+ if (typeof maybeMethodOrOptions === "function") {
1927
+ bamlClient = methodOrClient;
1928
+ method = maybeMethodOrOptions;
1929
+ options = maybeOptions;
1930
+ } else {
1931
+ bamlClient = this.bamlClient;
1932
+ method = methodOrClient;
1933
+ options = maybeMethodOrOptions;
1934
+ if (!bamlClient) {
1935
+ throw new BitfabError(
1936
+ "bamlClient is required for wrapBAML. Pass it in the constructor or as the first argument."
1937
+ );
1938
+ }
1939
+ }
1940
+ const methodName = method.name;
1941
+ if (!methodName) {
1942
+ throw new BitfabError(
1943
+ "wrapBAML requires a named function (e.g., b.ClassifyText)."
1944
+ );
1945
+ }
1946
+ loadCollectorClass();
1947
+ const wrappedFn = async (...args) => {
1948
+ const CollectorClass = await loadCollectorClass();
1949
+ if (!CollectorClass) {
1950
+ wrappedFn.collector = null;
1951
+ return await bamlClient[methodName](...args);
1952
+ }
1953
+ const collector = new CollectorClass("bitfab-baml-tracing");
1954
+ const trackedClient = bamlClient.withOptions({ collector });
1955
+ const trackedMethod = trackedClient[methodName];
1956
+ const result = await trackedMethod.bind(
1957
+ trackedClient
1958
+ )(...args);
1959
+ wrappedFn.collector = collector;
1960
+ try {
1961
+ const prompt = extractPromptFromCollector(collector);
1962
+ if (prompt) {
1963
+ getCurrentSpan().setPrompt(prompt);
1964
+ }
1965
+ const metadata = extractContextFromCollector(collector);
1966
+ if (metadata) {
1967
+ getCurrentSpan().addContext(metadata);
1968
+ }
1969
+ } catch {
1970
+ }
1971
+ try {
1972
+ options?.onCollector?.(collector);
1973
+ } catch {
1974
+ }
1975
+ return result;
1976
+ };
1977
+ wrappedFn.collector = null;
1978
+ return wrappedFn;
1979
+ }
1980
+ /**
1981
+ * Wrap a function to automatically create a span for its inputs and outputs.
1982
+ *
1983
+ * The wrapped function behaves identically to the original, but sends
1984
+ * span data to Bitfab in the background after each call.
1985
+ *
1986
+ * Example usage:
1987
+ * ```typescript
1988
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
1989
+ *
1990
+ * async function processOrder(orderId: string, items: string[]): Promise<{ total: number }> {
1991
+ * // ... process order
1992
+ * return { total: 100 };
1993
+ * }
1994
+ *
1995
+ * // Basic usage (defaults to "custom" span type)
1996
+ * const tracedProcessOrder = client.withSpan('order-processing', processOrder);
1997
+ *
1998
+ * // With explicit span type
1999
+ * const tracedProcessOrder = client.withSpan('order-processing', { type: 'function' }, processOrder);
2000
+ *
2001
+ * // Call the wrapped function normally
2002
+ * const result = await tracedProcessOrder('order-123', ['item-1', 'item-2']);
2003
+ * // Span is automatically sent to Bitfab
2004
+ * ```
2005
+ *
2006
+ * @param traceFunctionKey - A string identifier for grouping spans (e.g., 'order-processing', 'user-auth')
2007
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
2008
+ * @param maybeFn - The function to wrap if options were provided
2009
+ * @returns A wrapped function with the same signature that creates spans for inputs and outputs
2010
+ */
2011
+ withSpan(traceFunctionKey, optionsOrFn, maybeFn) {
2012
+ if (!this.enabled) {
2013
+ const fn2 = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
2014
+ return fn2;
2015
+ }
2016
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
2017
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
2018
+ const self = this;
2019
+ const fnIsAsyncFunction = fn.constructor.name === "AsyncFunction";
2020
+ const fnReturnsPromise = fnIsAsyncFunction || (() => {
2021
+ try {
2022
+ const src = fn.toString();
2023
+ return /\b(?:Promise|await)\b/.test(src);
2024
+ } catch {
2025
+ return false;
2026
+ }
2027
+ })();
2028
+ const wrappedFn = function(...args) {
2029
+ if (!asyncLocalStorage && !isAsyncStorageInitDone()) {
2030
+ return asyncLocalStorageReady.then(
2031
+ () => wrappedFn.apply(this, args)
2032
+ );
2033
+ }
2034
+ const currentStack = getSpanStack();
2035
+ const parentContext = currentStack[currentStack.length - 1];
2036
+ const traceId = parentContext?.traceId ?? crypto.randomUUID();
2037
+ const spanId = crypto.randomUUID();
2038
+ const parentSpanId = parentContext?.spanId ?? null;
2039
+ const isRootSpan = parentSpanId === null;
2040
+ const newContext = { traceId, spanId, contexts: [] };
2041
+ const newStack = [...currentStack, newContext];
2042
+ const inputs = args;
2043
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2044
+ if (isRootSpan && !activeTraceStates.has(traceId)) {
2045
+ const replayCtxAtRoot = getReplayContext();
2046
+ activeTraceStates.set(traceId, {
2047
+ traceId,
2048
+ startedAt,
2049
+ contexts: [],
2050
+ ...replayCtxAtRoot?.testRunId && {
2051
+ testRunId: replayCtxAtRoot.testRunId
2052
+ },
2053
+ ...replayCtxAtRoot?.inputSourceTraceId && {
2054
+ inputSourceTraceId: replayCtxAtRoot.inputSourceTraceId
2055
+ }
2056
+ });
2057
+ pendingSpanPromises.set(traceId, []);
2058
+ }
2059
+ const functionName = fn.name !== "" ? fn.name : void 0;
2060
+ const baseSpanParams = {
2061
+ traceFunctionKey,
2062
+ functionName,
2063
+ spanName: options.name ?? functionName ?? traceFunctionKey,
2064
+ traceId,
2065
+ spanId,
2066
+ parentSpanId,
2067
+ inputs,
2068
+ startedAt,
2069
+ spanType: options.type ?? "custom"
2070
+ };
2071
+ const sendSpan = async (params) => {
2072
+ try {
2073
+ const endedAt = (/* @__PURE__ */ new Date()).toISOString();
2074
+ const replayCtx = getReplayContext();
2075
+ const spanPromise = self.sendWrapperSpan({
2076
+ ...baseSpanParams,
2077
+ ...params,
2078
+ contexts: newContext.contexts,
2079
+ prompt: newContext.prompt,
2080
+ endedAt,
2081
+ ...replayCtx?.testRunId && { testRunId: replayCtx.testRunId },
2082
+ ...replayCtx?.inputSourceSpanId && {
2083
+ inputSourceSpanId: replayCtx.inputSourceSpanId
2084
+ }
2085
+ });
2086
+ if (isRootSpan) {
2087
+ const pending = pendingSpanPromises.get(traceId) ?? [];
2088
+ pending.push(spanPromise);
2089
+ await Promise.race([
2090
+ Promise.allSettled(pending),
2091
+ new Promise((resolve) => setTimeout(resolve, 5e3))
2092
+ ]);
2093
+ pendingSpanPromises.delete(traceId);
2094
+ const traceState = activeTraceStates.get(traceId);
2095
+ self.sendTraceCompletion({
2096
+ traceFunctionKey,
2097
+ traceId,
2098
+ startedAt: traceState?.startedAt ?? startedAt,
2099
+ endedAt,
2100
+ sessionId: traceState?.sessionId,
2101
+ metadata: traceState?.metadata,
2102
+ contexts: traceState?.contexts ?? [],
2103
+ testRunId: traceState?.testRunId,
2104
+ inputSourceTraceId: traceState?.inputSourceTraceId
2105
+ });
2106
+ activeTraceStates.delete(traceId);
2107
+ } else {
2108
+ const pending = pendingSpanPromises.get(traceId);
2109
+ if (pending) {
2110
+ pending.push(spanPromise);
2111
+ } else {
2112
+ pendingSpanPromises.set(traceId, [spanPromise]);
2113
+ }
2114
+ }
2115
+ } catch {
2116
+ }
2117
+ };
2118
+ const replayCtxForMock = getReplayContext();
2119
+ if (replayCtxForMock?.mockTree && !isRootSpan) {
2120
+ const counters = replayCtxForMock.callCounters;
2121
+ const counterKey = `${traceFunctionKey}:${baseSpanParams.spanName}`;
2122
+ const callIndex = counters.get(counterKey) ?? 0;
2123
+ counters.set(counterKey, callIndex + 1);
2124
+ const shouldMock = replayCtxForMock.mockStrategy === "all" || replayCtxForMock.mockStrategy === "marked" && options.mockOnReplay === true;
2125
+ if (shouldMock) {
2126
+ const mockKey = `${counterKey}:${callIndex}`;
2127
+ const mockSpan = replayCtxForMock.mockTree.spans.get(mockKey);
2128
+ if (mockSpan) {
2129
+ let output = mockSpan.output;
2130
+ if (mockSpan.outputMeta !== void 0 && mockSpan.outputMeta !== null) {
2131
+ output = deserializeValue({
2132
+ json: mockSpan.output,
2133
+ meta: mockSpan.outputMeta
2134
+ });
2135
+ }
2136
+ void sendSpan({ result: output });
2137
+ if (fnReturnsPromise) {
2138
+ return Promise.resolve(output);
2139
+ }
2140
+ return output;
2141
+ }
2142
+ }
2143
+ }
2144
+ const executeWithContext = () => {
2145
+ const result = fn(...args);
2146
+ if (result instanceof Promise) {
2147
+ return result.then((resolvedResult) => {
2148
+ void sendSpan({ result: resolvedResult });
2149
+ return resolvedResult;
2150
+ }).catch((error) => {
2151
+ void sendSpan({
2152
+ result: void 0,
2153
+ error: error instanceof Error ? error.message : String(error)
2154
+ });
2155
+ throw error;
2156
+ });
2157
+ }
2158
+ if (isAsyncGenerator(result)) {
2159
+ return wrapAsyncGenerator(result, newStack, sendSpan);
2160
+ }
2161
+ void sendSpan({ result });
2162
+ return result;
2163
+ };
2164
+ return runWithSpanStack(newStack, executeWithContext);
2165
+ };
2166
+ return wrappedFn;
2167
+ }
2168
+ /**
2169
+ * Get a detached handle to a previously-created trace, looked up by the
2170
+ * caller-supplied id (the same id passed at trace creation).
2171
+ *
2172
+ * The returned handle is not tied to AsyncLocalStorage — each method sends
2173
+ * to the server immediately. Useful for adding context to a trace from a
2174
+ * different process or thread than the one that created it.
2175
+ *
2176
+ * Throws synchronously if `traceId` is malformed (empty, too long, or
2177
+ * contains characters outside `[a-zA-Z0-9_\-.:]`). Server returns 404 if
2178
+ * no trace exists with that id in the org; the failure surfaces as a
2179
+ * logged warning (fire-and-forget) or via the awaited promise.
2180
+ *
2181
+ * Example:
2182
+ * ```typescript
2183
+ * const trace = client.getTrace("order_abc_123");
2184
+ * await trace.addContext({ refund_status: "approved" });
2185
+ * await trace.setMetadata({ region: "us-west" });
2186
+ * ```
2187
+ */
2188
+ getTrace(traceId) {
2189
+ validateTraceId(traceId);
2190
+ return {
2191
+ traceId,
2192
+ addContext: (context) => {
2193
+ if (!this.enabled) {
2194
+ return Promise.resolve();
2195
+ }
2196
+ if (typeof context !== "object" || context === null) {
2197
+ return Promise.resolve();
2198
+ }
2199
+ return this.httpClient.patchTrace(traceId, {
2200
+ appendContexts: [context]
2201
+ });
2202
+ },
2203
+ setMetadata: (metadata) => {
2204
+ if (!this.enabled) {
2205
+ return Promise.resolve();
2206
+ }
2207
+ if (typeof metadata !== "object" || metadata === null) {
2208
+ return Promise.resolve();
2209
+ }
2210
+ return this.httpClient.patchTrace(traceId, { mergeMetadata: metadata });
2211
+ },
2212
+ setSessionId: (sessionId) => {
2213
+ if (!this.enabled) {
2214
+ return Promise.resolve();
2215
+ }
2216
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
2217
+ return Promise.resolve();
2218
+ }
2219
+ return this.httpClient.patchTrace(traceId, { setSessionId: sessionId });
2220
+ }
2221
+ };
2222
+ }
2223
+ /**
2224
+ * Get a function wrapper for a specific trace function key.
2225
+ *
2226
+ * This provides a fluent API alternative to calling withSpan directly,
2227
+ * allowing you to bind the traceFunctionKey once and wrap multiple functions.
2228
+ *
2229
+ * Example usage:
2230
+ * ```typescript
2231
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
2232
+ *
2233
+ * const orderFunc = client.getFunction('order-processing');
2234
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
2235
+ * const tracedValidateOrder = orderFunc.withSpan(validateOrder);
2236
+ * ```
2237
+ *
2238
+ * @param traceFunctionKey - A string identifier for grouping spans
2239
+ * @returns A BitfabFunction instance for wrapping functions
2240
+ */
2241
+ getFunction(traceFunctionKey) {
2242
+ return new BitfabFunction(this, traceFunctionKey);
2243
+ }
2244
+ /**
2245
+ * Send trace completion when a root span ends.
2246
+ * Internal method to record trace completion with end time.
2247
+ * Fire-and-forget - sends to externalTraces endpoint via httpClient.
2248
+ */
2249
+ sendTraceCompletion(params) {
2250
+ const rawTrace = {
2251
+ id: params.traceId,
2252
+ started_at: params.startedAt,
2253
+ ended_at: params.endedAt,
2254
+ workflow_name: params.traceFunctionKey
2255
+ };
2256
+ if (params.metadata && Object.keys(params.metadata).length > 0) {
2257
+ rawTrace.metadata = params.metadata;
2258
+ }
2259
+ if (params.contexts && params.contexts.length > 0) {
2260
+ rawTrace.contexts = params.contexts;
2261
+ }
2262
+ if (params.inputSourceTraceId) {
2263
+ rawTrace.input_source_trace_id = params.inputSourceTraceId;
2264
+ }
2265
+ this.httpClient.sendExternalTrace({
2266
+ type: "sdk-function",
2267
+ source: "typescript-sdk-function",
2268
+ traceFunctionKey: params.traceFunctionKey,
2269
+ externalTrace: rawTrace,
2270
+ completed: true,
2271
+ ...params.sessionId && { sessionId: params.sessionId },
2272
+ ...params.testRunId && { testRunId: params.testRunId }
2273
+ });
2274
+ }
2275
+ /**
2276
+ * Send a wrapper span from function execution.
2277
+ * Internal method to record spans when using withSpan.
2278
+ * Fire-and-forget - sends to externalSpans endpoint via httpClient.
2279
+ */
2280
+ sendWrapperSpan(params) {
2281
+ const serializedInputs = serializeValue(params.inputs);
2282
+ const serializedResult = serializeValue(params.result);
2283
+ const externalSpan = {
2284
+ id: params.spanId,
2285
+ trace_id: params.traceId,
2286
+ started_at: params.startedAt,
2287
+ ended_at: params.endedAt,
2288
+ span_data: {
2289
+ name: params.spanName,
2290
+ type: params.spanType,
2291
+ input: serializedInputs.json,
2292
+ output: serializedResult.json,
2293
+ // Include superjson meta for type preservation
2294
+ ...serializedInputs.meta !== void 0 && {
2295
+ input_meta: serializedInputs.meta
2296
+ },
2297
+ ...serializedResult.meta !== void 0 && {
2298
+ output_meta: serializedResult.meta
2299
+ },
2300
+ ...params.functionName !== void 0 && {
2301
+ function_name: params.functionName
2302
+ },
2303
+ ...params.error !== void 0 && { error: params.error },
2304
+ ...params.contexts && params.contexts.length > 0 && {
2305
+ contexts: params.contexts
2306
+ },
2307
+ ...params.prompt !== void 0 && { prompt: params.prompt }
2308
+ }
2309
+ };
2310
+ if (params.parentSpanId) {
2311
+ externalSpan.parent_id = params.parentSpanId;
2312
+ }
2313
+ if (params.inputSourceSpanId) {
2314
+ externalSpan.input_source_span_id = params.inputSourceSpanId;
2315
+ }
2316
+ return this.httpClient.sendExternalSpan({
2317
+ type: "sdk-function",
2318
+ source: "typescript-sdk-function",
2319
+ sourceTraceId: params.traceId,
2320
+ traceFunctionKey: params.traceFunctionKey,
2321
+ rawSpan: externalSpan,
2322
+ ...params.testRunId && { testRunId: params.testRunId }
2323
+ });
2324
+ }
2325
+ /**
2326
+ * Replay historical traces through a function and create a test run.
2327
+ *
2328
+ * Fetches the last N traces for the given trace function key, re-runs each
2329
+ * through the provided function, and returns comparison data.
2330
+ *
2331
+ * The function must have been wrapped with `withSpan` — replay injects
2332
+ * `testRunId` via async context so new spans are linked to the test run.
2333
+ *
2334
+ * @param traceFunctionKey - The trace function key to replay
2335
+ * @param fn - The function to replay (must be the return value of `withSpan`)
2336
+ * @param options - Optional replay options (limit, traceIds)
2337
+ * @returns ReplayResult with items, testRunId, and testRunUrl
2338
+ */
2339
+ async replay(traceFunctionKey, fn, options) {
2340
+ const { replay: doReplay } = await import("./replay-SIWSK66F.js");
2341
+ return doReplay(
2342
+ this.httpClient,
2343
+ this.serviceUrl,
2344
+ traceFunctionKey,
2345
+ fn,
2346
+ options
2347
+ );
2348
+ }
2349
+ };
2350
+ var BitfabFunction = class {
2351
+ constructor(client, traceFunctionKey) {
2352
+ this.client = client;
2353
+ this.traceFunctionKey = traceFunctionKey;
2354
+ }
2355
+ /**
2356
+ * Wrap a function to automatically create a span for its inputs and outputs.
2357
+ *
2358
+ * The wrapped function behaves identically to the original, but sends
2359
+ * span data to Bitfab in the background after each call.
2360
+ *
2361
+ * Example usage:
2362
+ * ```typescript
2363
+ * const orderFunc = client.getFunction('order-processing');
2364
+ *
2365
+ * // Basic usage (defaults to "custom" span type)
2366
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
2367
+ *
2368
+ * // With explicit span type
2369
+ * const tracedProcessOrder = orderFunc.withSpan({ type: 'function' }, processOrder);
2370
+ * ```
2371
+ *
2372
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
2373
+ * @param maybeFn - The function to wrap if options were provided
2374
+ * @returns A wrapped function with the same signature that creates spans
2375
+ */
2376
+ withSpan(optionsOrFn, maybeFn) {
2377
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
2378
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
2379
+ return this.client.withSpan(this.traceFunctionKey, options, fn);
2380
+ }
2381
+ /**
2382
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
2383
+ * Delegates to the parent client's wrapBAML method.
2384
+ *
2385
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
2386
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
2387
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
2388
+ * @returns An async function with the same signature that instruments the BAML call
2389
+ */
2390
+ wrapBAML(methodOrClient, maybeMethodOrOptions, maybeOptions) {
2391
+ return this.client.wrapBAML(
2392
+ methodOrClient,
2393
+ maybeMethodOrOptions,
2394
+ maybeOptions
2395
+ );
2396
+ }
2397
+ };
2398
+
2399
+ export {
2400
+ BitfabClaudeAgentHandler,
2401
+ BitfabLangGraphCallbackHandler,
2402
+ BitfabOpenAITracingProcessor,
2403
+ getCurrentSpan,
2404
+ getCurrentTrace,
2405
+ Bitfab,
2406
+ BitfabFunction
2407
+ };
2408
+ //# sourceMappingURL=chunk-62NGOY7Q.js.map