bitfab 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,568 @@
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
+ * HTTP client utilities for Bitfab API requests.
37
+ *
38
+ * This module provides:
39
+ * - HttpClient class for making API requests
40
+ * - awaitOnExit helper for fire-and-forget operations that must complete before process exit
41
+ */
42
+ /**
43
+ * Error class for Bitfab API errors.
44
+ */
45
+ declare class BitfabError extends Error {
46
+ readonly url?: string | undefined;
47
+ constructor(message: string, url?: string | undefined);
48
+ }
49
+ /**
50
+ * Wait for all pending fire-and-forget operations (spans, traces) to complete.
51
+ * Useful in tests and scripts to ensure all data has been sent before asserting or exiting.
52
+ *
53
+ * @param timeoutMs - Maximum time to wait in milliseconds (default: 5000)
54
+ */
55
+ declare function flushTraces(timeoutMs?: number): Promise<void>;
56
+
57
+ /**
58
+ * Tracing utilities for external trace submission to Bitfab.
59
+ *
60
+ * This module provides utilities for sending external traces (e.g., from OpenAI API calls)
61
+ * to Bitfab for monitoring and analysis.
62
+ */
63
+
64
+ interface TraceResponse {
65
+ traceId: string;
66
+ status: "success";
67
+ }
68
+ interface ActiveSpanContext {
69
+ traceId: string;
70
+ spanId: string;
71
+ }
72
+ /**
73
+ * TracingProcessor interface from OpenAI Agents SDK v0.3.7
74
+ */
75
+ interface TracingProcessor {
76
+ onTraceStart(trace: Trace): Promise<void>;
77
+ onTraceEnd(trace: Trace): Promise<void>;
78
+ onSpanStart(span: Span<any>): Promise<void>;
79
+ onSpanEnd(span: Span<any>): Promise<void>;
80
+ forceFlush(): Promise<void>;
81
+ shutdown(timeout?: number): Promise<void>;
82
+ }
83
+ /**
84
+ * Tracing processor for OpenAI Agents SDK integration.
85
+ *
86
+ * Implements the TracingProcessor interface from the OpenAI Agents SDK to
87
+ * automatically capture traces and spans and send them to Bitfab for
88
+ * monitoring and analysis.
89
+ *
90
+ * Example usage:
91
+ * ```typescript
92
+ * import { Bitfab } from '@goharvest/bitfab';
93
+ * import { addTraceProcessor } from '@openai/agents';
94
+ *
95
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
96
+ * const processor = client.getOpenAiTracingProcessor();
97
+ * addTraceProcessor(processor);
98
+ * ```
99
+ */
100
+ declare class BitfabOpenAITracingProcessor implements TracingProcessor {
101
+ private readonly httpClient;
102
+ private activeTraces;
103
+ private readonly getActiveSpanContext;
104
+ private activeSpanMappings;
105
+ /**
106
+ * Initialize the tracing processor.
107
+ *
108
+ * @param config - Configuration options
109
+ */
110
+ constructor(config: {
111
+ apiKey?: string;
112
+ serviceUrl?: string;
113
+ timeout?: number;
114
+ getActiveSpanContext?: () => ActiveSpanContext | null;
115
+ });
116
+ /**
117
+ * Called when a trace is started.
118
+ * If there's an active withSpan context, the trace ID is remapped to the
119
+ * outer trace and sent to pre-create the external_traces row on the server.
120
+ */
121
+ onTraceStart(trace: Trace): Promise<void>;
122
+ /**
123
+ * Called when a trace is ended.
124
+ * If mapped to a withSpan trace, sends with remapped ID and completed=false
125
+ * since the parent withSpan handles completion.
126
+ */
127
+ onTraceEnd(trace: Trace): Promise<void>;
128
+ /**
129
+ * Called when a span is started.
130
+ */
131
+ onSpanStart(span: Span<any>): Promise<void>;
132
+ /**
133
+ * Called when a span is ended.
134
+ *
135
+ * Send all spans to Bitfab for complete trace capture.
136
+ */
137
+ onSpanEnd(span: Span<any>): Promise<void>;
138
+ /**
139
+ * Called when a trace is being flushed.
140
+ */
141
+ forceFlush(): Promise<void>;
142
+ /**
143
+ * Called when the trace processor is shutting down.
144
+ */
145
+ shutdown(_timeout?: number): Promise<void>;
146
+ /**
147
+ * Send trace to Bitfab API (fire-and-forget).
148
+ * When traceIdOverride is provided, the trace ID is remapped to link
149
+ * the OpenAI trace into an outer withSpan trace.
150
+ */
151
+ private sendTrace;
152
+ /**
153
+ * Export span to JSON object, collecting any errors.
154
+ */
155
+ private exportSpan;
156
+ /**
157
+ * Extract and add input/response to serialized span, updating errors list.
158
+ */
159
+ private extractSpanInputResponse;
160
+ /**
161
+ * If the span's trace is mapped to a withSpan trace, rewrite trace_id and parent_id.
162
+ */
163
+ private applySpanOverrides;
164
+ /**
165
+ * Build span payload for the external spans API.
166
+ */
167
+ private buildSpanPayload;
168
+ /**
169
+ * Send span to Bitfab API (fire-and-forget).
170
+ * If the span belongs to a trace mapped to a withSpan trace, the trace_id
171
+ * and parent_id are rewritten to link the span into the withSpan tree.
172
+ */
173
+ private sendSpan;
174
+ }
175
+
176
+ /**
177
+ * Bitfab client for provider-based API calls.
178
+ */
179
+
180
+ /**
181
+ * Options for wrapBAML.
182
+ */
183
+ interface WrapBAMLOptions {
184
+ /** Called after each BAML invocation with the Collector instance. */
185
+ onCollector?: (collector: unknown) => void;
186
+ }
187
+ /**
188
+ * A function returned by wrapBAML that exposes the BAML collector from the last call.
189
+ */
190
+ interface WrappedBamlFn<TArgs extends unknown[], TReturn> {
191
+ (...args: TArgs): Promise<TReturn>;
192
+ /** The BAML Collector instance from the most recent call. `null` before the first call or if @boundaryml/baml is unavailable. */
193
+ collector: unknown | null;
194
+ }
195
+ /**
196
+ * A handle to the current active span, allowing context to be added.
197
+ */
198
+ interface CurrentSpan {
199
+ /** The trace ID for the current span. */
200
+ readonly traceId: string;
201
+ /**
202
+ * Add a context entry to this span. Each call appends to the contexts array.
203
+ * Context entries are stored in span_data.contexts as [{key, value}, ...].
204
+ */
205
+ addContext(context: Record<string, unknown>): void;
206
+ /**
207
+ * Set the prompt for this span. Stored in span_data.prompt.
208
+ * Calling multiple times overwrites the previous value.
209
+ */
210
+ setPrompt(prompt: string): void;
211
+ }
212
+ /**
213
+ * A handle to the current active trace, allowing trace-level context to be set.
214
+ */
215
+ interface CurrentTrace {
216
+ /**
217
+ * Set the session ID for this trace. Stored in the database session_id column.
218
+ */
219
+ setSessionId(sessionId: string): void;
220
+ /**
221
+ * Set metadata for this trace. Stored in rawData.metadata.
222
+ * Subsequent calls merge with existing metadata, with later values taking precedence.
223
+ */
224
+ setMetadata(metadata: Record<string, unknown>): void;
225
+ /**
226
+ * Add a context entry to this trace. Each call appends to the contexts array.
227
+ * Context entries are stored in rawData.contexts as [{key, value}, ...].
228
+ */
229
+ addContext(context: Record<string, unknown>): void;
230
+ }
231
+ /**
232
+ * Get a handle to the current active span.
233
+ *
234
+ * Call this from inside a traced function (wrapped with `withSpan`) to get
235
+ * a span handle that allows adding context at runtime.
236
+ *
237
+ * Returns a no-op object if called outside of a span context (methods do nothing).
238
+ */
239
+ declare function getCurrentSpan(): CurrentSpan;
240
+ /**
241
+ * Get a handle to the current active trace.
242
+ *
243
+ * Call this from inside a traced function (wrapped with `withSpan`) to get
244
+ * a trace handle that allows setting trace-level context at runtime.
245
+ *
246
+ * Returns a no-op object if called outside of a span context (methods do nothing).
247
+ */
248
+ declare function getCurrentTrace(): CurrentTrace;
249
+ interface BitfabConfig {
250
+ /** The API key for Bitfab API authentication. When undefined or empty, tracing is disabled. */
251
+ apiKey?: string;
252
+ /** The base URL for the Bitfab API (default: https://bitfab.ai) */
253
+ serviceUrl?: string;
254
+ /** Request timeout in milliseconds (default: 120000) */
255
+ timeout?: number;
256
+ /** Environment variables for LLM provider API keys (only OPENAI_API_KEY is supported) */
257
+ envVars?: AllowedEnvVars;
258
+ /** Whether the client is enabled. Defaults to true. When false, withSpan returns the original function unwrapped. */
259
+ enabled?: boolean;
260
+ /** The generated BAML client instance (e.g., `b` from your baml_client). Used by wrapBAML() when no explicit client is passed. */
261
+ bamlClient?: unknown;
262
+ }
263
+ /**
264
+ * Span types matching the backend enum.
265
+ * - llm: LLM API calls
266
+ * - agent: Autonomous orchestrators
267
+ * - function: Tool implementations
268
+ * - guardrail: Safety/validation checks
269
+ * - handoff: Agent-to-agent transfers
270
+ * - custom: Application-specific tracing (default)
271
+ */
272
+ type SpanType = "llm" | "agent" | "function" | "guardrail" | "handoff" | "custom";
273
+ /**
274
+ * Options for configuring span behavior.
275
+ */
276
+ interface SpanOptions {
277
+ /**
278
+ * The name of the span. Defaults to the function name if available,
279
+ * otherwise falls back to the trace function key.
280
+ */
281
+ name?: string;
282
+ /**
283
+ * The type of span. Defaults to "custom" if not specified.
284
+ */
285
+ type?: SpanType;
286
+ }
287
+
288
+ /**
289
+ * Client for making provider-based API calls via BAML.
290
+ */
291
+ declare class Bitfab {
292
+ private readonly apiKey;
293
+ private readonly serviceUrl;
294
+ private readonly timeout;
295
+ private readonly envVars;
296
+ private readonly enabled;
297
+ private readonly httpClient;
298
+ private readonly bamlClient;
299
+ /**
300
+ * Initialize the Bitfab client.
301
+ *
302
+ * @param config - Configuration options for the client
303
+ */
304
+ constructor(config: BitfabConfig);
305
+ /**
306
+ * Fetch the function with its current version and BAML prompt from the server.
307
+ *
308
+ * @param methodName - The name of the method to fetch
309
+ * @returns The function with current version, BAML prompt, and provider definitions
310
+ * @throws {BitfabError} If the function is not found or an error occurs
311
+ */
312
+ private fetchFunctionVersion;
313
+ /**
314
+ * Call a method with the given named arguments via BAML execution.
315
+ *
316
+ * @param methodName - The name of the method to call
317
+ * @param inputs - Named arguments to pass to the method
318
+ * @returns The result of the BAML function execution
319
+ * @throws {BitfabError} If service_url is not set, or if an error occurs
320
+ */
321
+ call<T = unknown>(methodName: string, inputs?: Record<string, unknown>): Promise<T>;
322
+ /**
323
+ * Get a tracing processor for OpenAI Agents SDK integration.
324
+ *
325
+ * This processor automatically captures traces and spans from the OpenAI Agents SDK
326
+ * and sends them to Bitfab for monitoring and analysis.
327
+ *
328
+ * Example usage:
329
+ * ```typescript
330
+ * import { addTraceProcessor } from '@openai/agents';
331
+ *
332
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
333
+ * const processor = client.getOpenAiTracingProcessor();
334
+ * addTraceProcessor(processor);
335
+ * ```
336
+ *
337
+ * @returns A BitfabOpenAITracingProcessor instance configured for this client
338
+ */
339
+ getOpenAiTracingProcessor(): BitfabOpenAITracingProcessor;
340
+ /**
341
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
342
+ *
343
+ * Creates a BAML Collector, calls the method through a tracked client,
344
+ * then extracts rendered messages and token usage — calling setPrompt()
345
+ * and addContext() on the current span automatically.
346
+ *
347
+ * The BAML client can be provided in the constructor or passed explicitly:
348
+ *
349
+ * ```typescript
350
+ * // Option 1: bamlClient in constructor (use wrapBAML with just the method)
351
+ * const client = new Bitfab({ apiKey: 'your-api-key', bamlClient: b });
352
+ * const traced = client.withSpan('classify', { type: 'llm' },
353
+ * client.wrapBAML(b.ClassifyText)
354
+ * );
355
+ *
356
+ * // Option 2: pass bamlClient at call site
357
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
358
+ * const traced = client.withSpan('classify', { type: 'llm' },
359
+ * client.wrapBAML(b, b.ClassifyText)
360
+ * );
361
+ * ```
362
+ *
363
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
364
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
365
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
366
+ * @returns An async function with the same signature that instruments the BAML call
367
+ */
368
+ wrapBAML<TArgs extends unknown[], TReturn>(methodOrClient: unknown, maybeMethodOrOptions?: ((...args: TArgs) => Promise<TReturn>) | WrapBAMLOptions, maybeOptions?: WrapBAMLOptions): WrappedBamlFn<TArgs, TReturn>;
369
+ /**
370
+ * Wrap a function to automatically create a span for its inputs and outputs.
371
+ *
372
+ * The wrapped function behaves identically to the original, but sends
373
+ * span data to Bitfab in the background after each call.
374
+ *
375
+ * Example usage:
376
+ * ```typescript
377
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
378
+ *
379
+ * async function processOrder(orderId: string, items: string[]): Promise<{ total: number }> {
380
+ * // ... process order
381
+ * return { total: 100 };
382
+ * }
383
+ *
384
+ * // Basic usage (defaults to "custom" span type)
385
+ * const tracedProcessOrder = client.withSpan('order-processing', processOrder);
386
+ *
387
+ * // With explicit span type
388
+ * const tracedProcessOrder = client.withSpan('order-processing', { type: 'function' }, processOrder);
389
+ *
390
+ * // Call the wrapped function normally
391
+ * const result = await tracedProcessOrder('order-123', ['item-1', 'item-2']);
392
+ * // Span is automatically sent to Bitfab
393
+ * ```
394
+ *
395
+ * @param traceFunctionKey - A string identifier for grouping spans (e.g., 'order-processing', 'user-auth')
396
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
397
+ * @param maybeFn - The function to wrap if options were provided
398
+ * @returns A wrapped function with the same signature that creates spans for inputs and outputs
399
+ */
400
+ withSpan<TArgs extends unknown[], TReturn>(traceFunctionKey: string, optionsOrFn: SpanOptions | ((...args: TArgs) => TReturn), maybeFn?: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
401
+ /**
402
+ * Get a function wrapper for a specific trace function key.
403
+ *
404
+ * This provides a fluent API alternative to calling withSpan directly,
405
+ * allowing you to bind the traceFunctionKey once and wrap multiple functions.
406
+ *
407
+ * Example usage:
408
+ * ```typescript
409
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
410
+ *
411
+ * const orderFunc = client.getFunction('order-processing');
412
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
413
+ * const tracedValidateOrder = orderFunc.withSpan(validateOrder);
414
+ * ```
415
+ *
416
+ * @param traceFunctionKey - A string identifier for grouping spans
417
+ * @returns A BitfabFunction instance for wrapping functions
418
+ */
419
+ getFunction(traceFunctionKey: string): BitfabFunction;
420
+ /**
421
+ * Send trace completion when a root span ends.
422
+ * Internal method to record trace completion with end time.
423
+ * Fire-and-forget - sends to externalTraces endpoint via httpClient.
424
+ */
425
+ private sendTraceCompletion;
426
+ /**
427
+ * Send a wrapper span from function execution.
428
+ * Internal method to record spans when using withSpan.
429
+ * Fire-and-forget - sends to externalSpans endpoint via httpClient.
430
+ */
431
+ private sendWrapperSpan;
432
+ /**
433
+ * Replay historical traces through a function and create a test run.
434
+ *
435
+ * Fetches the last N traces for the given trace function key, re-runs each
436
+ * through the provided function, and returns comparison data.
437
+ *
438
+ * The function must have been wrapped with `withSpan` — replay injects
439
+ * `testRunId` via async context so new spans are linked to the test run.
440
+ *
441
+ * @param traceFunctionKey - The trace function key to replay
442
+ * @param fn - The function to replay (must be the return value of `withSpan`)
443
+ * @param options - Optional replay options (limit, traceIds)
444
+ * @returns ReplayResult with items, testRunId, and testRunUrl
445
+ */
446
+ replay<TReturn>(traceFunctionKey: string, fn: (...args: any[]) => TReturn | Promise<TReturn>, options?: {
447
+ limit?: number;
448
+ traceIds?: string[];
449
+ maxConcurrency?: number;
450
+ }): Promise<{
451
+ items: Array<{
452
+ input: unknown[];
453
+ result: TReturn | undefined;
454
+ originalOutput: unknown;
455
+ error: string | null;
456
+ }>;
457
+ testRunId: string;
458
+ testRunUrl: string;
459
+ }>;
460
+ }
461
+ /**
462
+ * Represents a Bitfab function that can wrap user functions for tracing.
463
+ *
464
+ * This provides a fluent API for binding a traceFunctionKey once and
465
+ * then wrapping multiple functions with that key.
466
+ *
467
+ * Example usage:
468
+ * ```typescript
469
+ * const client = new Bitfab({ apiKey: 'your-api-key' });
470
+ *
471
+ * const orderFunc = client.getFunction('order-processing');
472
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
473
+ * const tracedValidateOrder = orderFunc.withSpan(validateOrder);
474
+ * ```
475
+ */
476
+ declare class BitfabFunction {
477
+ private readonly client;
478
+ private readonly traceFunctionKey;
479
+ constructor(client: Bitfab, traceFunctionKey: string);
480
+ /**
481
+ * Wrap a function to automatically create a span for its inputs and outputs.
482
+ *
483
+ * The wrapped function behaves identically to the original, but sends
484
+ * span data to Bitfab in the background after each call.
485
+ *
486
+ * Example usage:
487
+ * ```typescript
488
+ * const orderFunc = client.getFunction('order-processing');
489
+ *
490
+ * // Basic usage (defaults to "custom" span type)
491
+ * const tracedProcessOrder = orderFunc.withSpan(processOrder);
492
+ *
493
+ * // With explicit span type
494
+ * const tracedProcessOrder = orderFunc.withSpan({ type: 'function' }, processOrder);
495
+ * ```
496
+ *
497
+ * @param optionsOrFn - Either SpanOptions or the function to wrap
498
+ * @param maybeFn - The function to wrap if options were provided
499
+ * @returns A wrapped function with the same signature that creates spans
500
+ */
501
+ withSpan<TArgs extends unknown[], TReturn>(optionsOrFn: SpanOptions | ((...args: TArgs) => TReturn), maybeFn?: (...args: TArgs) => TReturn): (...args: TArgs) => TReturn;
502
+ /**
503
+ * Wrap a BAML client method to automatically capture prompt and LLM metadata.
504
+ * Delegates to the parent client's wrapBAML method.
505
+ *
506
+ * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance
507
+ * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method
508
+ * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form
509
+ * @returns An async function with the same signature that instruments the BAML call
510
+ */
511
+ wrapBAML<TArgs extends unknown[], TReturn>(methodOrClient: unknown, maybeMethodOrOptions?: ((...args: TArgs) => Promise<TReturn>) | WrapBAMLOptions, maybeOptions?: WrapBAMLOptions): WrappedBamlFn<TArgs, TReturn>;
512
+ }
513
+
514
+ /**
515
+ * Auto-generated version file.
516
+ * This file is generated by scripts/generate-version.ts during build.
517
+ * DO NOT EDIT MANUALLY.
518
+ */
519
+ /**
520
+ * SDK version from package.json (injected at build time)
521
+ */
522
+ declare const __version__ = "0.9.2";
523
+
524
+ /**
525
+ * Constants for the Bitfab SDK.
526
+ */
527
+ /**
528
+ * Default service URL for Bitfab API.
529
+ */
530
+ declare const DEFAULT_SERVICE_URL = "https://bitfab.ai";
531
+
532
+ /**
533
+ * Replay historical traces through a function and create a test run.
534
+ *
535
+ * The replay flow has three phases:
536
+ * 1. Start — fetches historical traces from the server and creates a test run
537
+ * 2. Execute — re-runs each trace's inputs through the provided function locally
538
+ * 3. Complete — marks the test run as completed on the server
539
+ */
540
+
541
+ interface ReplayOptions {
542
+ /** Maximum number of traces to replay (1–100, default 5). */
543
+ limit?: number;
544
+ /** Optional list of specific trace IDs to replay. */
545
+ traceIds?: string[];
546
+ /** Maximum number of items to process in parallel. Set to 1 for sequential. Default 10. */
547
+ maxConcurrency?: number;
548
+ }
549
+ interface ReplayItem<T> {
550
+ /** Deserialized inputs from the original trace. */
551
+ input: unknown[];
552
+ /** The result returned by the function during replay, or undefined on error. */
553
+ result: T | undefined;
554
+ /** The original output from the historical trace. */
555
+ originalOutput: unknown;
556
+ /** Error message if the function threw, or null on success. */
557
+ error: string | null;
558
+ }
559
+ interface ReplayResult<T> {
560
+ /** Individual replay items with inputs, results, and comparison data. */
561
+ items: ReplayItem<T>[];
562
+ /** The test run ID created on the server. */
563
+ testRunId: string;
564
+ /** Full URL to view the test run in the dashboard. */
565
+ testRunUrl: string;
566
+ }
567
+
568
+ export { type ActiveSpanContext, type AllowedEnvVars, type BamlExecutionResult, Bitfab, type BitfabConfig, BitfabError, BitfabFunction, BitfabOpenAITracingProcessor, type CurrentSpan, type CurrentTrace, DEFAULT_SERVICE_URL, type ProviderDefinition, type ReplayItem, type ReplayOptions, type ReplayResult, type SpanOptions, type SpanType, type TraceResponse, type TracingProcessor, type WrapBAMLOptions, type WrappedBamlFn, __version__, flushTraces, getCurrentSpan, getCurrentTrace };