@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,888 @@
1
+ import { Trace, Span } from '@openai/agents';
2
+
3
+ /**
4
+ * BAML execution utilities for the Bitfab TypeScript SDK.
5
+ * This module provides functions to execute BAML prompts dynamically on the client side.
6
+ */
7
+ /**
8
+ * Provider definition from the server.
9
+ */
10
+ interface ProviderDefinition {
11
+ provider: string;
12
+ apiKeyEnv: string;
13
+ models: Array<{
14
+ model: string;
15
+ description: string;
16
+ }>;
17
+ }
18
+ /**
19
+ * Result of a BAML function execution with raw collector data.
20
+ */
21
+ interface BamlExecutionResult {
22
+ /** The parsed result of the function */
23
+ result: unknown;
24
+ /** Raw collector data for the server to parse */
25
+ rawCollector: Record<string, unknown> | null;
26
+ }
27
+ /**
28
+ * Type for allowed environment variables.
29
+ * Only OPENAI_API_KEY is currently supported.
30
+ */
31
+ type AllowedEnvVars = {
32
+ OPENAI_API_KEY?: string;
33
+ };
34
+
35
+ /**
36
+ * Claude Agent SDK handler for Bitfab tracing.
37
+ *
38
+ * Hooks into the Claude Agent SDK's lifecycle to capture LLM turns,
39
+ * tool invocations, and subagent execution as Bitfab spans.
40
+ *
41
+ * Uses two integration surfaces:
42
+ * 1. SDK hooks (PreToolUse, PostToolUse, etc.) for tool/subagent lifecycle
43
+ * 2. Stream wrapping for LLM turn capture from the message stream
44
+ */
45
+ interface ActiveSpanContext$2 {
46
+ traceId: string;
47
+ spanId: string;
48
+ }
49
+ /**
50
+ * Claude Agent SDK handler that sends traces to Bitfab.
51
+ *
52
+ * Captures LLM turns, tool invocations, and subagent execution as
53
+ * Bitfab spans with proper parent-child hierarchy.
54
+ *
55
+ * ```typescript
56
+ * import { Bitfab } from "bitfab";
57
+ * import { ClaudeSDKClient } from "@anthropic-ai/claude-agent-sdk";
58
+ *
59
+ * const bitfab = new Bitfab({ apiKey: "..." });
60
+ * const handler = bitfab.getClaudeAgentHandler("my-agent");
61
+ *
62
+ * const options = handler.instrumentOptions({
63
+ * model: "claude-sonnet-4-5-...",
64
+ * });
65
+ *
66
+ * const client = new ClaudeSDKClient(options);
67
+ * await client.connect();
68
+ * await client.query("Do something");
69
+ *
70
+ * for await (const message of handler.wrapResponse(client.receiveResponse())) {
71
+ * // process messages normally
72
+ * }
73
+ * ```
74
+ */
75
+ declare class BitfabClaudeAgentHandler {
76
+ private readonly httpClient;
77
+ private readonly traceFunctionKey;
78
+ private readonly getActiveSpanContext;
79
+ private runToSpan;
80
+ private traceId;
81
+ private rootSpanId;
82
+ private activeContext;
83
+ private traceStartedAt;
84
+ private conversationHistory;
85
+ private pendingMessages;
86
+ private currentLlmSpanId;
87
+ private currentLlmMessageId;
88
+ private currentLlmContent;
89
+ private currentLlmModel;
90
+ private currentLlmUsage;
91
+ private currentLlmStartedAt;
92
+ private currentLlmHistorySnapshot;
93
+ private activeSubagentSpans;
94
+ constructor(config: {
95
+ apiKey?: string;
96
+ traceFunctionKey: string;
97
+ serviceUrl?: string;
98
+ timeout?: number;
99
+ getActiveSpanContext?: () => ActiveSpanContext$2 | null;
100
+ });
101
+ private ensureTrace;
102
+ private getParentId;
103
+ private startSpan;
104
+ private completeSpan;
105
+ private sendSpan;
106
+ private sendTraceCompletion;
107
+ private preToolUseHook;
108
+ private postToolUseHook;
109
+ private postToolUseFailureHook;
110
+ private subagentStartHook;
111
+ private subagentStopHook;
112
+ /**
113
+ * Inject Bitfab tracing hooks into Claude Agent SDK options.
114
+ *
115
+ * Modifies the options object and returns it for convenience.
116
+ * The SDK's `HookMatcher` is constructed as a plain object
117
+ * (`{ matcher: null, hooks: [callback] }`) to avoid requiring
118
+ * `@anthropic-ai/claude-agent-sdk` as a dependency.
119
+ *
120
+ * @param options - Options object with a `hooks` property
121
+ * @returns The modified options object with Bitfab hooks injected
122
+ */
123
+ instrumentOptions<T extends Record<string, unknown>>(options: T): T;
124
+ /**
125
+ * Wrap a `ClaudeSDKClient.receiveResponse()` stream to capture LLM turns.
126
+ *
127
+ * Yields every message unchanged while capturing AssistantMessage
128
+ * content as LLM turn spans.
129
+ */
130
+ wrapResponse(stream: AsyncIterable<unknown>): AsyncIterable<unknown>;
131
+ /**
132
+ * Wrap a `query()` async iterator to capture LLM turns.
133
+ *
134
+ * Same as `wrapResponse` but for the simpler `query()` API
135
+ * which does not support hooks (no tool/subagent spans).
136
+ */
137
+ wrapQuery(stream: AsyncIterable<unknown>): AsyncIterable<unknown>;
138
+ private processStream;
139
+ private processMessage;
140
+ private handleAssistantMessage;
141
+ private handleUserMessage;
142
+ private handleResultMessage;
143
+ private flushLlmTurn;
144
+ private resetState;
145
+ }
146
+
147
+ /**
148
+ * HTTP client utilities for Bitfab API requests.
149
+ *
150
+ * This module provides:
151
+ * - HttpClient class for making API requests
152
+ * - awaitOnExit helper for fire-and-forget operations that must complete before process exit
153
+ */
154
+ /**
155
+ * Error class for Bitfab API errors.
156
+ */
157
+ declare class BitfabError extends Error {
158
+ readonly url?: string | undefined;
159
+ constructor(message: string, url?: string | undefined);
160
+ }
161
+ /**
162
+ * Wait for all pending fire-and-forget operations (spans, traces) to complete.
163
+ * Useful in tests and scripts to ensure all data has been sent before asserting or exiting.
164
+ *
165
+ * @param timeoutMs - Maximum time to wait in milliseconds (default: 5000)
166
+ */
167
+ declare function flushTraces(timeoutMs?: number): Promise<void>;
168
+ interface TokenUsage {
169
+ input: number | null;
170
+ output: number | null;
171
+ cached: number | null;
172
+ total: number | null;
173
+ }
174
+ /**
175
+ * Describes a single file edited as part of a code change.
176
+ *
177
+ * - `path`: file path (relative to the repo root, or any consistent root)
178
+ * - `before`: file contents before the change ("" for newly created files)
179
+ * - `after`: file contents after the change ("" for deleted files)
180
+ */
181
+ interface CodeChangeFile {
182
+ path: string;
183
+ before: string;
184
+ after: string;
185
+ }
186
+
187
+ /**
188
+ * LangGraph/LangChain callback handler for Bitfab tracing.
189
+ *
190
+ * Hooks into LangGraph's callback system to capture graph node execution,
191
+ * LLM calls, and tool invocations as Bitfab spans — without requiring users
192
+ * to wrap their functions with withSpan (which fails on non-serializable args).
193
+ *
194
+ * Duck-typed to match LangChain.js's BaseCallbackHandler interface.
195
+ * No @langchain/core dependency required.
196
+ */
197
+ interface ActiveSpanContext$1 {
198
+ traceId: string;
199
+ spanId: string;
200
+ }
201
+ /**
202
+ * LangChain/LangGraph callback handler that sends traces to Bitfab.
203
+ *
204
+ * Duck-typed to match LangChain.js's BaseCallbackHandler — no
205
+ * `@langchain/core` dependency required. Pass as a callback:
206
+ *
207
+ * ```typescript
208
+ * const handler = bitfab.getLangGraphCallbackHandler("my-agent");
209
+ * const result = await agent.invoke(
210
+ * { messages: [...] },
211
+ * { callbacks: [handler] },
212
+ * );
213
+ * ```
214
+ */
215
+ declare class BitfabLangGraphCallbackHandler {
216
+ name: string;
217
+ ignoreRetriever: boolean;
218
+ ignoreRetry: boolean;
219
+ ignoreCustomEvent: boolean;
220
+ private readonly httpClient;
221
+ private readonly traceFunctionKey;
222
+ private readonly getActiveSpanContext;
223
+ private runToSpan;
224
+ private invocations;
225
+ constructor(config: {
226
+ apiKey?: string;
227
+ traceFunctionKey: string;
228
+ serviceUrl?: string;
229
+ timeout?: number;
230
+ getActiveSpanContext?: () => ActiveSpanContext$1 | null;
231
+ });
232
+ private startSpan;
233
+ private completeSpan;
234
+ private sendSpan;
235
+ private sendTraceCompletion;
236
+ handleChainStart(chain: Record<string, unknown>, inputs: Record<string, unknown>, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>): Promise<void>;
237
+ handleChainEnd(outputs: Record<string, unknown>, runId: string): Promise<void>;
238
+ handleChainError(error: unknown, runId: string): Promise<void>;
239
+ handleChatModelStart(llm: Record<string, unknown>, messages: unknown[][], runId: string, parentRunId?: string, _extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>): Promise<void>;
240
+ handleLLMStart(llm: Record<string, unknown>, prompts: string[], runId: string, parentRunId?: string, _extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>): Promise<void>;
241
+ handleLLMEnd(output: Record<string, unknown>, runId: string): Promise<void>;
242
+ handleLLMError(error: unknown, runId: string): Promise<void>;
243
+ handleLLMNewToken(): Promise<void>;
244
+ handleToolStart(tool: Record<string, unknown>, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>): Promise<void>;
245
+ handleToolEnd(output: unknown, runId: string): Promise<void>;
246
+ handleToolError(error: unknown, runId: string): Promise<void>;
247
+ handleRetrieverStart(retriever: Record<string, unknown>, query: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>): Promise<void>;
248
+ handleRetrieverEnd(documents: unknown, runId: string): Promise<void>;
249
+ handleRetrieverError(error: unknown, runId: string): Promise<void>;
250
+ }
251
+
252
+ /**
253
+ * Replay historical traces through a function and create a test run.
254
+ *
255
+ * The replay flow has three phases:
256
+ * 1. Start — fetches historical traces from the server and creates a test run
257
+ * 2. Execute — re-runs each trace's inputs through the provided function locally
258
+ * 3. Complete — marks the test run as completed on the server
259
+ */
260
+
261
+ type MockStrategy = "none" | "all" | "marked";
262
+ interface ReplayOptions {
263
+ /** Maximum number of traces to replay (1–100, default 5). */
264
+ limit?: number;
265
+ /** Optional list of specific trace IDs to replay. */
266
+ traceIds?: string[];
267
+ /** Maximum number of items to process in parallel. Set to 1 for sequential. Default 10. */
268
+ maxConcurrency?: number;
269
+ /**
270
+ * Description of the code change being tested in this replay. Stored on
271
+ * the resulting experiment so the change can be reviewed alongside results.
272
+ */
273
+ codeChangeDescription?: string;
274
+ /**
275
+ * Files edited as part of this code change. Each entry holds the file path
276
+ * and the full `before`/`after` contents — the agent reads each file before
277
+ * and after editing and passes the two strings. Use `""` for newly created
278
+ * files (`before`) or deleted files (`after`).
279
+ */
280
+ codeChangeFiles?: CodeChangeFile[];
281
+ /**
282
+ * Mock strategy for child spans during replay.
283
+ * - "none": everything runs real code (default)
284
+ * - "all": every child withSpan returns historical output
285
+ * - "marked": only spans tagged with { mockOnReplay: true } in SpanOptions are mocked
286
+ */
287
+ mock?: MockStrategy;
288
+ }
289
+ interface ReplayItem<T> {
290
+ /** Deserialized inputs from the original trace. */
291
+ input: unknown[];
292
+ /** The result returned by the function during replay, or undefined on error. */
293
+ result: T | undefined;
294
+ /** The original output from the historical trace. */
295
+ originalOutput: unknown;
296
+ /** Error message if the function threw, or null on success. */
297
+ error: string | null;
298
+ /** Original trace duration in milliseconds, or null if timestamps are missing. */
299
+ durationMs: number | null;
300
+ /** Token usage from the original trace, or null if not captured. */
301
+ tokens: TokenUsage | null;
302
+ /** Model name from the original trace, or null if not captured. */
303
+ model: string | null;
304
+ }
305
+
306
+ interface ReplayResult<T> {
307
+ /** Individual replay items with inputs, results, and comparison data. */
308
+ items: ReplayItem<T>[];
309
+ /** The test run ID created on the server. */
310
+ testRunId: string;
311
+ /** Full URL to view the test run in the dashboard. */
312
+ testRunUrl: string;
313
+ }
314
+
315
+ /**
316
+ * Tracing utilities for external trace submission to Bitfab.
317
+ *
318
+ * This module provides utilities for sending external traces (e.g., from OpenAI API calls)
319
+ * to Bitfab for monitoring and analysis.
320
+ */
321
+
322
+ interface TraceResponse {
323
+ traceId: string;
324
+ status: "success";
325
+ }
326
+ interface ActiveSpanContext {
327
+ traceId: string;
328
+ spanId: string;
329
+ }
330
+ /**
331
+ * TracingProcessor interface from OpenAI Agents SDK v0.3.7
332
+ */
333
+ interface TracingProcessor {
334
+ onTraceStart(trace: Trace): Promise<void>;
335
+ onTraceEnd(trace: Trace): Promise<void>;
336
+ onSpanStart(span: Span<any>): Promise<void>;
337
+ onSpanEnd(span: Span<any>): Promise<void>;
338
+ forceFlush(): Promise<void>;
339
+ shutdown(timeout?: number): Promise<void>;
340
+ }
341
+ /**
342
+ * Tracing processor for OpenAI Agents SDK integration.
343
+ *
344
+ * Implements the TracingProcessor interface from the OpenAI Agents SDK to
345
+ * automatically capture traces and spans and send them to Bitfab for
346
+ * monitoring and analysis.
347
+ *
348
+ * Example usage:
349
+ * ```typescript
350
+ * import { Bitfab } from 'bitfab';
351
+ * import { addTraceProcessor } from '@openai/agents';
352
+ *
353
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
354
+ * const processor = client.getOpenAiTracingProcessor();
355
+ * addTraceProcessor(processor);
356
+ * ```
357
+ */
358
+ declare class BitfabOpenAITracingProcessor implements TracingProcessor {
359
+ private readonly httpClient;
360
+ private activeTraces;
361
+ private readonly getActiveSpanContext;
362
+ private activeSpanMappings;
363
+ /**
364
+ * Initialize the tracing processor.
365
+ *
366
+ * @param config - Configuration options
367
+ */
368
+ constructor(config: {
369
+ apiKey?: string;
370
+ serviceUrl?: string;
371
+ timeout?: number;
372
+ getActiveSpanContext?: () => ActiveSpanContext | null;
373
+ });
374
+ /**
375
+ * Called when a trace is started.
376
+ * If there's an active withSpan context, the trace ID is remapped to the
377
+ * outer trace and sent to pre-create the external_traces row on the server.
378
+ */
379
+ onTraceStart(trace: Trace): Promise<void>;
380
+ /**
381
+ * Called when a trace is ended.
382
+ * If mapped to a withSpan trace, sends with remapped ID and completed=false
383
+ * since the parent withSpan handles completion.
384
+ */
385
+ onTraceEnd(trace: Trace): Promise<void>;
386
+ /**
387
+ * Called when a span is started.
388
+ */
389
+ onSpanStart(span: Span<any>): Promise<void>;
390
+ /**
391
+ * Called when a span is ended.
392
+ *
393
+ * Send all spans to Bitfab for complete trace capture.
394
+ */
395
+ onSpanEnd(span: Span<any>): Promise<void>;
396
+ /**
397
+ * Called when a trace is being flushed.
398
+ */
399
+ forceFlush(): Promise<void>;
400
+ /**
401
+ * Called when the trace processor is shutting down.
402
+ */
403
+ shutdown(_timeout?: number): Promise<void>;
404
+ /**
405
+ * Send trace to Bitfab API (fire-and-forget).
406
+ * When traceIdOverride is provided, the trace ID is remapped to link
407
+ * the OpenAI trace into an outer withSpan trace.
408
+ */
409
+ private sendTrace;
410
+ /**
411
+ * Export span to JSON object, collecting any errors.
412
+ */
413
+ private exportSpan;
414
+ /**
415
+ * Extract and add input/response to serialized span, updating errors list.
416
+ */
417
+ private extractSpanInputResponse;
418
+ /**
419
+ * If the span's trace is mapped to a withSpan trace, rewrite trace_id and parent_id.
420
+ */
421
+ private applySpanOverrides;
422
+ /**
423
+ * Build span payload for the external spans API.
424
+ */
425
+ private buildSpanPayload;
426
+ /**
427
+ * Send span to Bitfab API (fire-and-forget).
428
+ * If the span belongs to a trace mapped to a withSpan trace, the trace_id
429
+ * and parent_id are rewritten to link the span into the withSpan tree.
430
+ */
431
+ private sendSpan;
432
+ }
433
+
434
+ /**
435
+ * Bitfab client for provider-based API calls.
436
+ */
437
+
438
+ /**
439
+ * Options for wrapBAML.
440
+ */
441
+ interface WrapBAMLOptions {
442
+ /** Called after each BAML invocation with the Collector instance. */
443
+ onCollector?: (collector: unknown) => void;
444
+ }
445
+ /**
446
+ * A function returned by wrapBAML that exposes the BAML collector from the last call.
447
+ */
448
+ interface WrappedBamlFn<TArgs extends unknown[], TReturn> {
449
+ (...args: TArgs): Promise<TReturn>;
450
+ /** The BAML Collector instance from the most recent call. `null` before the first call or if @boundaryml/baml is unavailable. */
451
+ collector: unknown | null;
452
+ }
453
+ /**
454
+ * A handle to the current active span, allowing context to be added.
455
+ */
456
+ interface CurrentSpan {
457
+ /** The trace ID for the current span. */
458
+ readonly traceId: string;
459
+ /**
460
+ * Add a context entry to this span. Each call appends to the contexts array.
461
+ * Context entries are stored in span_data.contexts as [{key, value}, ...].
462
+ */
463
+ addContext(context: Record<string, unknown>): void;
464
+ /**
465
+ * Set the prompt for this span. Stored in span_data.prompt.
466
+ * Calling multiple times overwrites the previous value.
467
+ */
468
+ setPrompt(prompt: string): void;
469
+ }
470
+ /**
471
+ * A detached handle to a previously-created trace, looked up by its
472
+ * caller-supplied id (the same id passed when the trace was started).
473
+ *
474
+ * Unlike `getCurrentTrace()`, this handle is not tied to AsyncLocalStorage —
475
+ * each method sends to the server immediately. Useful for adding context
476
+ * to a trace from a different process, request, or thread (e.g. a forked
477
+ * agent that wants to annotate the original conversation's trace).
478
+ */
479
+ interface DetachedTrace {
480
+ /** The caller-supplied trace id this handle resolves. */
481
+ readonly traceId: string;
482
+ /**
483
+ * Append a context entry to this trace. Each call adds one entry to the
484
+ * server-side contexts array; existing entries are preserved.
485
+ *
486
+ * Returns a promise that the caller may await for confirmation, or ignore
487
+ * to fire-and-forget. The pending request is tracked so `flushTraces()`
488
+ * waits for it.
489
+ */
490
+ addContext(context: Record<string, unknown>): Promise<unknown>;
491
+ /**
492
+ * Merge metadata into this trace. Server-side shallow-merges the new keys
493
+ * into the existing metadata object; existing keys are preserved unless
494
+ * overwritten by the new values.
495
+ */
496
+ setMetadata(metadata: Record<string, unknown>): Promise<unknown>;
497
+ /**
498
+ * Set the sessionId for this trace. Replaces any existing sessionId.
499
+ */
500
+ setSessionId(sessionId: string): Promise<unknown>;
501
+ }
502
+ /**
503
+ * A handle to the current active trace, allowing trace-level context to be set.
504
+ */
505
+ interface CurrentTrace {
506
+ /**
507
+ * Set the session ID for this trace. Stored in the database session_id column.
508
+ */
509
+ setSessionId(sessionId: string): void;
510
+ /**
511
+ * Set metadata for this trace. Stored in rawData.metadata.
512
+ * Subsequent calls merge with existing metadata, with later values taking precedence.
513
+ */
514
+ setMetadata(metadata: Record<string, unknown>): void;
515
+ /**
516
+ * Add a context entry to this trace. Each call appends to the contexts array.
517
+ * Context entries are stored in rawData.contexts as [{key, value}, ...].
518
+ */
519
+ addContext(context: Record<string, unknown>): void;
520
+ }
521
+ /**
522
+ * Get a handle to the current active span.
523
+ *
524
+ * Call this from inside a traced function (wrapped with `withSpan`) to get
525
+ * a span handle that allows adding context at runtime.
526
+ *
527
+ * Returns a no-op object if called outside of a span context (methods do nothing).
528
+ */
529
+ declare function getCurrentSpan(): CurrentSpan;
530
+ /**
531
+ * Get a handle to the current active trace.
532
+ *
533
+ * Call this from inside a traced function (wrapped with `withSpan`) to get
534
+ * a trace handle that allows setting trace-level context at runtime.
535
+ *
536
+ * Returns a no-op object if called outside of a span context (methods do nothing).
537
+ */
538
+ declare function getCurrentTrace(): CurrentTrace;
539
+ interface BitfabConfig {
540
+ /** The API key for Bitfab API authentication. When undefined or empty, tracing is disabled. */
541
+ apiKey?: string;
542
+ /** The base URL for the Bitfab API (default: https://bitfab.ai) */
543
+ serviceUrl?: string;
544
+ /** Request timeout in milliseconds (default: 120000) */
545
+ timeout?: number;
546
+ /** Environment variables for LLM provider API keys (only OPENAI_API_KEY is supported) */
547
+ envVars?: AllowedEnvVars;
548
+ /** Whether the client is enabled. Defaults to true. When false, withSpan returns the original function unwrapped. */
549
+ enabled?: boolean;
550
+ /** The generated BAML client instance (e.g., `b` from your baml_client). Used by wrapBAML() when no explicit client is passed. */
551
+ bamlClient?: unknown;
552
+ }
553
+ /**
554
+ * Span types matching the backend enum.
555
+ * - llm: LLM API calls
556
+ * - agent: Autonomous orchestrators
557
+ * - function: Tool implementations
558
+ * - guardrail: Safety/validation checks
559
+ * - handoff: Agent-to-agent transfers
560
+ * - custom: Application-specific tracing (default)
561
+ */
562
+ type SpanType = "llm" | "agent" | "function" | "guardrail" | "handoff" | "custom";
563
+ /**
564
+ * Options for configuring span behavior.
565
+ */
566
+ interface SpanOptions {
567
+ /**
568
+ * The name of the span. Defaults to the function name if available,
569
+ * otherwise falls back to the trace function key.
570
+ */
571
+ name?: string;
572
+ /**
573
+ * The type of span. Defaults to "custom" if not specified.
574
+ */
575
+ type?: SpanType;
576
+ /**
577
+ * When true, replay will reuse this span's historical output instead of
578
+ * executing the wrapped function. Read by the "marked" replay strategy;
579
+ * ignored outside replay and under the "all"/"none" strategies.
580
+ *
581
+ * Use this for child spans that are expensive (paid LLM/API calls),
582
+ * slow, or non-deterministic — the root function still runs real code,
583
+ * only the marked descendants return their recorded output.
584
+ */
585
+ mockOnReplay?: boolean;
586
+ }
587
+
588
+ /**
589
+ * Client for making provider-based API calls via BAML.
590
+ */
591
+ declare class Bitfab {
592
+ private readonly apiKey;
593
+ private readonly serviceUrl;
594
+ private readonly timeout;
595
+ private readonly envVars;
596
+ private readonly enabled;
597
+ private readonly httpClient;
598
+ private readonly bamlClient;
599
+ /**
600
+ * Initialize the Bitfab client.
601
+ *
602
+ * @param config - Configuration options for the client
603
+ */
604
+ constructor(config: BitfabConfig);
605
+ /**
606
+ * Fetch the function with its current version and BAML prompt from the server.
607
+ *
608
+ * @param methodName - The name of the method to fetch
609
+ * @returns The function with current version, BAML prompt, and provider definitions
610
+ * @throws {BitfabError} If the function is not found or an error occurs
611
+ */
612
+ private fetchFunctionVersion;
613
+ /**
614
+ * Call a method with the given named arguments via BAML execution.
615
+ *
616
+ * @param methodName - The name of the method to call
617
+ * @param inputs - Named arguments to pass to the method
618
+ * @returns The result of the BAML function execution
619
+ * @throws {BitfabError} If service_url is not set, or if an error occurs
620
+ */
621
+ call<T = unknown>(methodName: string, inputs?: Record<string, unknown>): Promise<T>;
622
+ /**
623
+ * Get a tracing processor for OpenAI Agents SDK integration.
624
+ *
625
+ * This processor automatically captures traces and spans from the OpenAI Agents SDK
626
+ * and sends them to Bitfab for monitoring and analysis.
627
+ *
628
+ * Example usage:
629
+ * ```typescript
630
+ * import { addTraceProcessor } from '@openai/agents';
631
+ *
632
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
633
+ * const processor = client.getOpenAiTracingProcessor();
634
+ * addTraceProcessor(processor);
635
+ * ```
636
+ *
637
+ * @returns A BitfabOpenAITracingProcessor instance configured for this client
638
+ */
639
+ getOpenAiTracingProcessor(): BitfabOpenAITracingProcessor;
640
+ /**
641
+ * Get a LangGraph/LangChain callback handler for tracing.
642
+ *
643
+ * The handler captures graph node execution, LLM calls, and tool
644
+ * invocations as Bitfab spans with proper parent-child hierarchy.
645
+ *
646
+ * ```typescript
647
+ * const handler = client.getLangGraphCallbackHandler("my-agent");
648
+ * const result = await agent.invoke(
649
+ * { messages: [...] },
650
+ * { callbacks: [handler] },
651
+ * );
652
+ * ```
653
+ *
654
+ * @param traceFunctionKey - Groups traces under this key in Bitfab
655
+ * @returns A BitfabLangGraphCallbackHandler configured for this client
656
+ */
657
+ getLangGraphCallbackHandler(traceFunctionKey: string): BitfabLangGraphCallbackHandler;
658
+ /**
659
+ * Get a Claude Agent SDK handler for tracing.
660
+ *
661
+ * The handler captures LLM turns, tool invocations, and subagent
662
+ * execution as Bitfab spans with proper parent-child hierarchy.
663
+ *
664
+ * ```typescript
665
+ * const handler = client.getClaudeAgentHandler("my-agent");
666
+ * const options = handler.instrumentOptions({
667
+ * model: "claude-sonnet-4-5-...",
668
+ * });
669
+ * const sdkClient = new ClaudeSDKClient(options);
670
+ * await sdkClient.connect();
671
+ * await sdkClient.query("Do something");
672
+ * for await (const msg of handler.wrapResponse(sdkClient.receiveResponse())) {
673
+ * // process messages
674
+ * }
675
+ * ```
676
+ *
677
+ * @param traceFunctionKey - Groups traces under this key in Bitfab
678
+ * @returns A BitfabClaudeAgentHandler configured for this client
679
+ */
680
+ getClaudeAgentHandler(traceFunctionKey: string): BitfabClaudeAgentHandler;
681
+ /**
682
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
683
+ *
684
+ * Creates a BAML Collector, calls the method through a tracked client,
685
+ * then extracts rendered messages and token usage — calling setPrompt()
686
+ * and addContext() on the current span automatically.
687
+ *
688
+ * The BAML client can be provided in the constructor or passed explicitly:
689
+ *
690
+ * ```typescript
691
+ * // Option 1: bamlClient in constructor (use wrapBAML with just the method)
692
+ * const client = new Bitfab({ apiKey: 'your-api-key', bamlClient: b });
693
+ * const traced = client.withSpan('classify', { type: 'llm' },
694
+ * client.wrapBAML(b.ClassifyText)
695
+ * );
696
+ *
697
+ * // Option 2: pass bamlClient at call site
698
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
699
+ * const traced = client.withSpan('classify', { type: 'llm' },
700
+ * client.wrapBAML(b, b.ClassifyText)
701
+ * );
702
+ * ```
703
+ *
704
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
705
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
706
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
707
+ * @returns An async function with the same signature that instruments the BAML call
708
+ */
709
+ wrapBAML<TArgs extends unknown[], TReturn>(methodOrClient: unknown, maybeMethodOrOptions?: ((...args: TArgs) => Promise<TReturn>) | WrapBAMLOptions, maybeOptions?: WrapBAMLOptions): WrappedBamlFn<TArgs, TReturn>;
710
+ /**
711
+ * Wrap a function to automatically create a span for its inputs and outputs.
712
+ *
713
+ * The wrapped function behaves identically to the original, but sends
714
+ * span data to Bitfab in the background after each call.
715
+ *
716
+ * Example usage:
717
+ * ```typescript
718
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
719
+ *
720
+ * async function processOrder(orderId: string, items: string[]): Promise<{ total: number }> {
721
+ * // ... process order
722
+ * return { total: 100 };
723
+ * }
724
+ *
725
+ * // Basic usage (defaults to "custom" span type)
726
+ * const tracedProcessOrder = client.withSpan('order-processing', processOrder);
727
+ *
728
+ * // With explicit span type
729
+ * const tracedProcessOrder = client.withSpan('order-processing', { type: 'function' }, processOrder);
730
+ *
731
+ * // Call the wrapped function normally
732
+ * const result = await tracedProcessOrder('order-123', ['item-1', 'item-2']);
733
+ * // Span is automatically sent to Bitfab
734
+ * ```
735
+ *
736
+ * @param traceFunctionKey - A string identifier for grouping spans (e.g., 'order-processing', 'user-auth')
737
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
738
+ * @param maybeFn - The function to wrap if options were provided
739
+ * @returns A wrapped function with the same signature that creates spans for inputs and outputs
740
+ */
741
+ withSpan<TArgs extends unknown[], TReturn>(traceFunctionKey: string, optionsOrFn: SpanOptions | ((...args: TArgs) => TReturn), maybeFn?: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
742
+ /**
743
+ * Get a detached handle to a previously-created trace, looked up by the
744
+ * caller-supplied id (the same id passed at trace creation).
745
+ *
746
+ * The returned handle is not tied to AsyncLocalStorage — each method sends
747
+ * to the server immediately. Useful for adding context to a trace from a
748
+ * different process or thread than the one that created it.
749
+ *
750
+ * Throws synchronously if `traceId` is malformed (empty, too long, or
751
+ * contains characters outside `[a-zA-Z0-9_\-.:]`). Server returns 404 if
752
+ * no trace exists with that id in the org; the failure surfaces as a
753
+ * logged warning (fire-and-forget) or via the awaited promise.
754
+ *
755
+ * Example:
756
+ * ```typescript
757
+ * const trace = client.getTrace("order_abc_123");
758
+ * await trace.addContext({ refund_status: "approved" });
759
+ * await trace.setMetadata({ region: "us-west" });
760
+ * ```
761
+ */
762
+ getTrace(traceId: string): DetachedTrace;
763
+ /**
764
+ * Get a function wrapper for a specific trace function key.
765
+ *
766
+ * This provides a fluent API alternative to calling withSpan directly,
767
+ * allowing you to bind the traceFunctionKey once and wrap multiple functions.
768
+ *
769
+ * Example usage:
770
+ * ```typescript
771
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
772
+ *
773
+ * const orderFunc = client.getFunction('order-processing');
774
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
775
+ * const tracedValidateOrder = orderFunc.withSpan(validateOrder);
776
+ * ```
777
+ *
778
+ * @param traceFunctionKey - A string identifier for grouping spans
779
+ * @returns A BitfabFunction instance for wrapping functions
780
+ */
781
+ getFunction(traceFunctionKey: string): BitfabFunction;
782
+ /**
783
+ * Send trace completion when a root span ends.
784
+ * Internal method to record trace completion with end time.
785
+ * Fire-and-forget - sends to externalTraces endpoint via httpClient.
786
+ */
787
+ private sendTraceCompletion;
788
+ /**
789
+ * Send a wrapper span from function execution.
790
+ * Internal method to record spans when using withSpan.
791
+ * Fire-and-forget - sends to externalSpans endpoint via httpClient.
792
+ */
793
+ private sendWrapperSpan;
794
+ /**
795
+ * Replay historical traces through a function and create a test run.
796
+ *
797
+ * Fetches the last N traces for the given trace function key, re-runs each
798
+ * through the provided function, and returns comparison data.
799
+ *
800
+ * The function must have been wrapped with `withSpan` — replay injects
801
+ * `testRunId` via async context so new spans are linked to the test run.
802
+ *
803
+ * @param traceFunctionKey - The trace function key to replay
804
+ * @param fn - The function to replay (must be the return value of `withSpan`)
805
+ * @param options - Optional replay options (limit, traceIds)
806
+ * @returns ReplayResult with items, testRunId, and testRunUrl
807
+ */
808
+ replay<TReturn>(traceFunctionKey: string, fn: (...args: any[]) => TReturn | Promise<TReturn>, options?: {
809
+ limit?: number;
810
+ traceIds?: string[];
811
+ maxConcurrency?: number;
812
+ codeChangeDescription?: string;
813
+ codeChangeFiles?: CodeChangeFile[];
814
+ mock?: "none" | "all" | "marked";
815
+ }): Promise<ReplayResult<TReturn>>;
816
+ }
817
+ /**
818
+ * Represents a Bitfab function that can wrap user functions for tracing.
819
+ *
820
+ * This provides a fluent API for binding a traceFunctionKey once and
821
+ * then wrapping multiple functions with that key.
822
+ *
823
+ * Example usage:
824
+ * ```typescript
825
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
826
+ *
827
+ * const orderFunc = client.getFunction('order-processing');
828
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
829
+ * const tracedValidateOrder = orderFunc.withSpan(validateOrder);
830
+ * ```
831
+ */
832
+ declare class BitfabFunction {
833
+ private readonly client;
834
+ private readonly traceFunctionKey;
835
+ constructor(client: Bitfab, traceFunctionKey: string);
836
+ /**
837
+ * Wrap a function to automatically create a span for its inputs and outputs.
838
+ *
839
+ * The wrapped function behaves identically to the original, but sends
840
+ * span data to Bitfab in the background after each call.
841
+ *
842
+ * Example usage:
843
+ * ```typescript
844
+ * const orderFunc = client.getFunction('order-processing');
845
+ *
846
+ * // Basic usage (defaults to "custom" span type)
847
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
848
+ *
849
+ * // With explicit span type
850
+ * const tracedProcessOrder = orderFunc.withSpan({ type: 'function' }, processOrder);
851
+ * ```
852
+ *
853
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
854
+ * @param maybeFn - The function to wrap if options were provided
855
+ * @returns A wrapped function with the same signature that creates spans
856
+ */
857
+ withSpan<TArgs extends unknown[], TReturn>(optionsOrFn: SpanOptions | ((...args: TArgs) => TReturn), maybeFn?: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
858
+ /**
859
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
860
+ * Delegates to the parent client's wrapBAML method.
861
+ *
862
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
863
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
864
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
865
+ * @returns An async function with the same signature that instruments the BAML call
866
+ */
867
+ wrapBAML<TArgs extends unknown[], TReturn>(methodOrClient: unknown, maybeMethodOrOptions?: ((...args: TArgs) => Promise<TReturn>) | WrapBAMLOptions, maybeOptions?: WrapBAMLOptions): WrappedBamlFn<TArgs, TReturn>;
868
+ }
869
+
870
+ /**
871
+ * Auto-generated version file.
872
+ * This file is generated by scripts/generate-version.ts during build.
873
+ * DO NOT EDIT MANUALLY.
874
+ */
875
+ /**
876
+ * SDK version from package.json (injected at build time)
877
+ */
878
+ declare const __version__ = "0.13.0";
879
+
880
+ /**
881
+ * Constants for the Bitfab SDK.
882
+ */
883
+ /**
884
+ * Default service URL for Bitfab API.
885
+ */
886
+ declare const DEFAULT_SERVICE_URL = "https://bitfab.ai";
887
+
888
+ export { type ActiveSpanContext, type AllowedEnvVars, type BamlExecutionResult, Bitfab, BitfabClaudeAgentHandler, type BitfabConfig, BitfabError, BitfabFunction, BitfabLangGraphCallbackHandler, BitfabOpenAITracingProcessor, type CodeChangeFile, type CurrentSpan, type CurrentTrace, DEFAULT_SERVICE_URL, type DetachedTrace, type MockStrategy, type ProviderDefinition, type ReplayItem, type ReplayOptions, type ReplayResult, type SpanOptions, type SpanType, type TokenUsage, type TraceResponse, type TracingProcessor, type WrapBAMLOptions, type WrappedBamlFn, __version__, flushTraces, getCurrentSpan, getCurrentTrace };