@bitfab/sdk 0.44.1 → 0.45.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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/processorPayload.ts","../src/timestamp.ts","../src/claudeAgentSdk.ts","../src/optionalPeer.ts","../src/baml.ts","../src/captureSurface.ts","../src/datasets.ts","../src/dbSnapshot.ts","../src/langgraph.ts","../src/langgraphIntegration.ts","../src/openaiAgentSdk.ts","../src/replayBranch.ts","../src/seedContext.ts","../src/tracing.ts","../src/vercelAiSdk.ts","../src/client.ts","../src/finalizers.ts","../src/replayRegistry.ts"],"sourcesContent":["/**\n * Shared payload finalization for the framework tracing handlers.\n *\n * The OpenAI-Agents, LangGraph, and Claude Agent SDK handlers each build an\n * external span/trace payload that must be made JSON-safe before it is sent.\n *\n * Doing that silently with `toJsonSafe` hides a lossy capture. These helpers do\n * it in one place: sanitize via `toJsonSafeReport` and, when a value could only\n * be captured as a placeholder, mark the span (a `serialization_degraded`\n * error) or warn for the trace, so a degraded capture is surfaced as\n * non-replayable instead of being shipped silently. The HTTP boundary stays as\n * the final net. Mirrors the Python SDK's `processor_payload.py`.\n *\n * Note: this is only wired into the `toJsonSafe`-based framework surfaces. Core\n * `withSpan` / `@span` spans serialize via `serializeValue` (superjson, which\n * preserves the `meta` needed for typed replay); running this report serializer\n * there would strip that metadata, so the core path keeps its existing\n * http-layer sanitizer instead.\n */\n\nimport { toJsonSafeReport } from \"./serialize.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport const SERIALIZATION_DEGRADED_STEP = \"serialization_degraded\"\n\ninterface DegradedError {\n source: \"sdk\"\n step: string\n error: string\n}\n\nfunction degradedError(dropped: string[]): DegradedError {\n const names = [...new Set(dropped)].sort().join(\", \")\n return {\n source: \"sdk\",\n step: SERIALIZATION_DEGRADED_STEP,\n error: `non-replayable: could not faithfully capture ${names}`,\n }\n}\n\n// Plain control fields carried through when the whole payload collapses to a\n// placeholder. Mirror of the Python SDK's `_rebuild_envelope` (plus\n// `traceFunctionKey`, which the TS payloads also carry): without them a\n// pathological top-level value would strip the routing fields the server needs,\n// not just the body. `completed` is span-irrelevant but harmless to copy.\nconst ENVELOPE_FIELDS = [\n \"type\",\n \"source\",\n \"traceFunctionKey\",\n \"sourceTraceId\",\n \"completed\",\n] as const\n\nfunction rebuildEnvelope(\n payload: Record<string, unknown>,\n bodyKey: string,\n placeholder: unknown,\n): Record<string, unknown> {\n const rebuilt: Record<string, unknown> = {}\n for (const k of ENVELOPE_FIELDS) {\n if (k in payload) {\n rebuilt[k] = payload[k]\n }\n }\n rebuilt[bodyKey] = { serialized: placeholder }\n return rebuilt\n}\n\n/**\n * Return a JSON-safe span payload, marking a lossy capture on its errors.\n *\n * The span body is preserved (never gutted). When a value could only be\n * captured as a placeholder, a `serialization_degraded` error is appended to\n * `payload.errors` so the lossy capture is recorded rather than shipped\n * silently.\n *\n * `extraDropped` carries losses detected by an earlier sanitization pass - e.g.\n * input/output that a handler serialized at capture time to snapshot a mutable\n * value. Without it, those fields reach this point as plain placeholder strings\n * and their loss would go unreported.\n */\nexport function finalizeSpanPayload(\n payload: Record<string, unknown>,\n extraDropped?: string[],\n): Record<string, unknown> {\n const { safe, dropped } = toJsonSafeReport(payload)\n const allDropped = [...(extraDropped ?? []), ...dropped]\n\n // toJsonSafeReport collapses to a non-object only for a pathological\n // top-level value; rebuild an envelope (carrying control fields) so the span\n // still ships and stays routable.\n const collapsed =\n safe === null || typeof safe !== \"object\" || Array.isArray(safe)\n const result: Record<string, unknown> = collapsed\n ? rebuildEnvelope(payload, \"rawSpan\", safe)\n : (safe as Record<string, unknown>)\n\n if (allDropped.length > 0) {\n const existing = result.errors\n const errors = Array.isArray(existing) ? existing : []\n errors.push(degradedError(allDropped))\n result.errors = errors\n }\n return result\n}\n\n/**\n * Return a JSON-safe trace payload, warning when the capture was lossy.\n *\n * The trace is preserved (never dropped). A trace payload has no errors field,\n * so a lossy capture is surfaced via `warnOnce` instead.\n */\nexport function finalizeTracePayload(\n payload: Record<string, unknown>,\n): Record<string, unknown> {\n const { safe, dropped } = toJsonSafeReport(payload)\n const collapsed =\n safe === null || typeof safe !== \"object\" || Array.isArray(safe)\n const result: Record<string, unknown> = collapsed\n ? rebuildEnvelope(payload, \"externalTrace\", safe)\n : (safe as Record<string, unknown>)\n\n if (dropped.length > 0 || collapsed) {\n const names =\n dropped.length > 0 ? [...new Set(dropped)].sort().join(\", \") : \"trace\"\n warnOnce(\n `finalizeTrace:${names.replace(/\\d+/g, \"N\")}`,\n `a trace held non-serializable value(s) (${names}); they were captured as placeholders, so the trace may not be replayable.`,\n )\n }\n return result\n}\n","let lastTimestampMicros = 0\n\nexport function nowIsoTimestamp(): string {\n const wallClockMicros = Date.now() * 1_000\n lastTimestampMicros = Math.max(wallClockMicros, lastTimestampMicros + 1)\n const milliseconds = Math.floor(lastTimestampMicros / 1_000)\n const remainingMicros = lastTimestampMicros % 1_000\n return new Date(milliseconds)\n .toISOString()\n .replace(\"Z\", `${remainingMicros.toString().padStart(3, \"0\")}Z`)\n}\n","/**\n * Claude Agent SDK handler for Bitfab tracing.\n *\n * Hooks into the Claude Agent SDK's lifecycle to capture LLM turns,\n * tool invocations, and subagent execution as Bitfab spans.\n *\n * Uses two integration surfaces:\n * 1. SDK hooks (PreToolUse, PostToolUse, etc.) for tool/subagent lifecycle\n * 2. Stream wrapping for LLM turn capture from the message stream\n */\n\nimport { DEFAULT_SERVICE_URL } from \"./constants.js\"\nimport { type ApiKeyInput, HttpClient } from \"./http.js\"\nimport {\n finalizeSpanPayload,\n finalizeTracePayload,\n} from \"./processorPayload.js\"\nimport { randomUuid } from \"./randomUuid.js\"\nimport { toJsonSafe, toJsonSafeReport } from \"./serialize.js\"\nimport { nowIsoTimestamp } from \"./timestamp.js\"\n\nexport interface ActiveSpanContext {\n traceId: string\n spanId: string\n}\n\ninterface SpanInfo {\n id: string\n spanId: string\n traceId: string\n parentId: string | null\n startedAt: string\n endedAt?: string\n name: string\n type: string\n input?: unknown\n output?: unknown\n error?: string\n contexts: Array<Record<string, unknown>>\n // Type names of input/output values that could only be captured as\n // placeholders (serialized at capture time to snapshot a mutable value).\n // Carried to the send boundary so finalizeSpanPayload can mark the span.\n dropped?: string[]\n}\n\nfunction nowIso(): string {\n return nowIsoTimestamp()\n}\n\n// Delegates to the shared toJsonSafe so the recurse-the-dump logic lives in\n// exactly one place (see serialize.ts).\nconst safeSerialize = toJsonSafe\n\nfunction extractContentBlocks(\n content: unknown,\n): Array<Record<string, unknown>> {\n if (!Array.isArray(content)) {\n return []\n }\n return content.map((block) => safeSerialize(block) as Record<string, unknown>)\n}\n\nfunction asTokenCount(val: unknown): number | null {\n return typeof val === \"number\" && Number.isFinite(val) ? val : null\n}\n\nfunction extractUsage(\n message: Record<string, unknown>,\n): Record<string, unknown> {\n const usageInfo: Record<string, unknown> = {}\n const usage = message.usage as Record<string, unknown> | undefined\n if (!usage) {\n return usageInfo\n }\n\n // Anthropic reports `input_tokens` as the NON-cached prompt tokens, with\n // cache reads and cache writes counted separately. Bitfab's `inputTokens`\n // is the full prompt size (matching the LangGraph integration), so fold the\n // cache buckets in. `cacheReadTokens` stays the cached SUBSET, which the read\n // side uses to back out the uncached portion (`?tokenType=uncached`).\n const baseInput = asTokenCount(usage.input_tokens)\n const cacheRead = asTokenCount(usage.cache_read_input_tokens)\n const cacheCreation = asTokenCount(usage.cache_creation_input_tokens)\n if (baseInput !== null || cacheRead !== null || cacheCreation !== null) {\n usageInfo.inputTokens =\n (baseInput ?? 0) + (cacheRead ?? 0) + (cacheCreation ?? 0)\n }\n\n const output = asTokenCount(usage.output_tokens)\n if (output !== null) {\n usageInfo.outputTokens = output\n }\n if (cacheRead !== null) {\n usageInfo.cacheReadTokens = cacheRead\n }\n if (cacheCreation !== null) {\n usageInfo.cacheCreationTokens = cacheCreation\n }\n\n return usageInfo\n}\n\ntype HookCallback = (\n // biome-ignore lint/suspicious/noExplicitAny: Hook callback signatures from Claude Agent SDK use untyped dicts\n inputData: Record<string, any>,\n toolUseId: string | null,\n context: unknown,\n) => Promise<Record<string, unknown>>\n\n/**\n * Claude Agent SDK handler that sends traces to Bitfab.\n *\n * Captures LLM turns, tool invocations, and subagent execution as\n * Bitfab spans with proper parent-child hierarchy.\n *\n * The TypeScript Claude Agent SDK exposes a single `query()` entry point (there\n * is no `ClaudeSDKClient` class - that exists only in the Python SDK). Wrap the\n * `query()` async iterator with `wrapQuery`; tool and subagent spans come from\n * the hooks injected by `instrumentOptions`.\n *\n * ```typescript\n * import { Bitfab } from \"@bitfab/sdk\";\n * import { query } from \"@anthropic-ai/claude-agent-sdk\";\n *\n * const bitfab = new Bitfab({ apiKey: \"...\" });\n * const handler = bitfab.getClaudeAgentHandler(\"my-agent\");\n *\n * const options = handler.instrumentOptions({\n * model: \"claude-sonnet-4-5-...\",\n * });\n *\n * for await (const message of handler.wrapQuery(\n * query({ prompt: \"Do something\", options })\n * )) {\n * // process messages normally\n * }\n * ```\n */\nexport class BitfabClaudeAgentHandler {\n private readonly httpClient: HttpClient\n private readonly ownsHttpClient: boolean\n private readonly traceFunctionKey: string\n private readonly getActiveSpanContext: (() => ActiveSpanContext | null) | null\n\n // Span tracking\n private runToSpan: Map<string, SpanInfo> = new Map()\n private traceId: string | null = null\n private rootSpanId: string | null = null\n private activeContext: ActiveSpanContext | null = null\n private traceStartedAt: string | null = null\n\n // LLM turn tracking\n private conversationHistory: Array<Record<string, unknown>> = []\n private pendingMessages: Array<Record<string, unknown>> = []\n private currentLlmSpanId: string | null = null\n private currentLlmMessageId: string | null = null\n private currentLlmContent: Array<Record<string, unknown>> = []\n private currentLlmModel: string | null = null\n private currentLlmUsage: Record<string, unknown> = {}\n private currentLlmStartedAt: string | null = null\n private currentLlmHistorySnapshot: Array<Record<string, unknown>> = []\n\n // Subagent tracking\n private activeSubagentSpans: Map<string, string> = new Map()\n\n // Synthetic root span (handler-only replay). When an `input` is supplied to\n // wrapQuery/wrapResponse, the handler emits a root `agent` span carrying that\n // input, so a handler-instrumented run is replayable WITHOUT an enclosing\n // withSpan - matching the LangGraph handler, which records the graph input as\n // its root. The prompt is not present anywhere in the message stream, so it\n // must be handed in explicitly.\n private hasRootInput = false\n private rootInput: unknown\n private rootOutput: unknown\n\n constructor(config: {\n apiKey?: ApiKeyInput\n traceFunctionKey: string\n serviceUrl?: string\n timeout?: number\n getActiveSpanContext?: () => ActiveSpanContext | null\n /**\n * The owning `Bitfab` client's HTTP client. Supplied by\n * `getClaudeAgentHandler()` so this handler shares that client's single\n * span-transport worker instead of starting a second one.\n * @internal\n */\n _httpClient?: HttpClient\n }) {\n this.ownsHttpClient = config._httpClient === undefined\n this.httpClient =\n config._httpClient ??\n new HttpClient({\n apiKey: config.apiKey,\n serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,\n timeout: config.timeout ?? 10000,\n })\n this.traceFunctionKey = config.traceFunctionKey\n this.getActiveSpanContext = config.getActiveSpanContext ?? null\n\n // Bind hook callbacks so they can be passed as standalone functions\n this.preToolUseHook = this.preToolUseHook.bind(this)\n this.postToolUseHook = this.postToolUseHook.bind(this)\n this.postToolUseFailureHook = this.postToolUseFailureHook.bind(this)\n this.subagentStartHook = this.subagentStartHook.bind(this)\n this.subagentStopHook = this.subagentStopHook.bind(this)\n }\n\n /**\n * Flush and release the span transport this handler started. A no-op when\n * the handler borrowed a `Bitfab` client's HTTP client: that client's\n * `close()` owns the worker's lifetime.\n */\n async close(timeoutMs?: number): Promise<boolean> {\n return this.ownsHttpClient ? this.httpClient.close(timeoutMs) : true\n }\n\n // ── trace lifecycle ──────────────────────────────────────────\n\n private ensureTrace(): string {\n if (this.traceId !== null) {\n return this.traceId\n }\n\n this.activeContext = this.getActiveSpanContext?.() ?? null\n\n if (this.activeContext) {\n this.traceId = this.activeContext.traceId\n } else {\n this.traceId = randomUuid()\n }\n\n this.traceStartedAt = nowIso()\n return this.traceId\n }\n\n private getParentId(agentId?: string): string | null {\n if (agentId) {\n const subagentSpanId = this.activeSubagentSpans.get(agentId)\n if (subagentSpanId) {\n return subagentSpanId\n }\n }\n // Prefer the synthetic root (handler-only mode) so every span nests under\n // it; fall back to the enclosing withSpan context. The two are never both\n // set - the synthetic root is only created when there is no active context.\n return this.rootSpanId ?? this.activeContext?.spanId ?? null\n }\n\n // Emit the synthetic root `agent` span once, before any child spans. No-op\n // unless an `input` was supplied AND there is no enclosing withSpan (in which\n // case that outer span is already the replayable root).\n private maybeStartRootSpan(): void {\n if (!this.hasRootInput || this.rootSpanId !== null) {\n return\n }\n this.ensureTrace()\n if (this.activeContext !== null) {\n return\n }\n const spanId = randomUuid()\n this.startSpan(spanId, this.traceFunctionKey, \"agent\", this.rootInput, null)\n this.rootSpanId = spanId\n }\n\n private completeRootSpan(): void {\n if (this.rootSpanId === null) {\n return\n }\n const spanId = this.rootSpanId\n this.rootSpanId = null\n this.completeSpan(spanId, this.rootOutput)\n }\n\n // ── span helpers ─────────────────────────────────────────────\n\n private startSpan(\n spanId: string,\n name: string,\n spanType: string,\n inputData?: unknown,\n parentId?: string | null,\n ): SpanInfo {\n const traceId = this.ensureTrace()\n\n // Serialize input now to snapshot it (tool input can mutate between\n // PreToolUse and PostToolUse), but keep the report so a lossy input is\n // still marked non-replayable at the send boundary.\n const { safe: safeInput, dropped: inputDropped } =\n toJsonSafeReport(inputData)\n\n const spanInfo: SpanInfo = {\n id: randomUuid(),\n spanId,\n traceId,\n parentId: parentId ?? null,\n startedAt: nowIso(),\n name,\n type: spanType,\n input: safeInput,\n contexts: [],\n }\n if (inputDropped.length > 0) {\n spanInfo.dropped = [...inputDropped]\n }\n this.runToSpan.set(spanId, spanInfo)\n return spanInfo\n }\n\n private completeSpan(\n spanId: string,\n output?: unknown,\n error?: string,\n extraContexts?: Record<string, unknown>,\n ): void {\n const spanInfo = this.runToSpan.get(spanId)\n if (!spanInfo) {\n return\n }\n this.runToSpan.delete(spanId)\n\n spanInfo.endedAt = nowIso()\n const { safe: safeOutput, dropped: outputDropped } =\n toJsonSafeReport(output)\n spanInfo.output = safeOutput\n if (outputDropped.length > 0) {\n spanInfo.dropped = [...(spanInfo.dropped ?? []), ...outputDropped]\n }\n if (error !== undefined) {\n spanInfo.error = error\n }\n\n if (extraContexts) {\n spanInfo.contexts.push(extraContexts)\n }\n\n this.sendSpan(spanInfo)\n }\n\n private sendSpan(spanInfo: SpanInfo): void {\n const spanData: Record<string, unknown> = {\n name: spanInfo.name,\n type: spanInfo.type,\n }\n if (spanInfo.input !== undefined) {\n spanData.input = spanInfo.input\n }\n if (spanInfo.output !== undefined) {\n spanData.output = spanInfo.output\n }\n if (spanInfo.error !== undefined) {\n spanData.error = spanInfo.error\n }\n if (spanInfo.contexts.length > 0) {\n spanData.contexts = spanInfo.contexts\n }\n\n const rawSpan: Record<string, unknown> = {\n id: spanInfo.spanId,\n trace_id: spanInfo.traceId,\n started_at: spanInfo.startedAt,\n ended_at: spanInfo.endedAt ?? nowIso(),\n span_data: spanData,\n }\n if (spanInfo.parentId !== null) {\n rawSpan.parent_id = spanInfo.parentId\n }\n\n const payload: Record<string, unknown> = {\n id: spanInfo.id,\n traceId: spanInfo.traceId,\n type: \"sdk-function\",\n source: \"typescript-sdk-claude-agent-sdk\",\n traceFunctionKey: this.traceFunctionKey,\n sourceTraceId: spanInfo.traceId,\n rawSpan,\n }\n\n // Sanitize the whole span (a non-serializable value in any field is\n // dumped/stubbed, a lossy capture is marked) instead of shipping it raw.\n // spanInfo.dropped carries losses from the capture-time input/output\n // snapshot above.\n const finalized = finalizeSpanPayload(payload, spanInfo.dropped)\n\n try {\n this.httpClient.sendExternalSpan(finalized)\n } catch {\n // Silently ignore - never crash the host app\n }\n }\n\n private sendTraceCompletion(\n endedAt?: string,\n metadata?: Record<string, unknown>,\n ): void {\n if (this.traceId === null) {\n return\n }\n\n const completed = this.activeContext === null\n const traceId = this.traceId\n\n // Mark as sent so the finally block doesn't re-send\n this.traceId = null\n\n const externalTrace: Record<string, unknown> = {\n id: traceId,\n started_at: this.traceStartedAt ?? nowIso(),\n ended_at: endedAt ?? nowIso(),\n }\n\n if (metadata) {\n externalTrace.metadata = metadata\n }\n\n const traceData: Record<string, unknown> = {\n id: traceId,\n type: \"sdk-function\",\n source: \"typescript-sdk-claude-agent-sdk\",\n traceFunctionKey: this.traceFunctionKey,\n externalTrace,\n completed,\n }\n\n // Sanitize the whole trace (warning when the capture was lossy) instead of\n // shipping it raw and risking a wire-side JSON.stringify failure.\n const finalized = finalizeTracePayload(traceData)\n\n try {\n this.httpClient.sendExternalTrace(finalized)\n } catch {\n // Silently ignore - never crash the host app\n }\n }\n\n // ── hook callbacks ───────────────────────────────────────────\n\n private async preToolUseHook(\n // biome-ignore lint/suspicious/noExplicitAny: Hook input from Claude Agent SDK is untyped\n inputData: Record<string, any>,\n toolUseId: string | null,\n _context: unknown,\n ): Promise<Record<string, unknown>> {\n try {\n const sid = (inputData.tool_use_id as string) ?? toolUseId ?? randomUuid()\n const toolName = (inputData.tool_name as string) ?? \"tool\"\n const toolInput = inputData.tool_input ?? {}\n const agentId = inputData.agent_id as string | undefined\n const parentId = this.getParentId(agentId)\n\n this.startSpan(sid, toolName, \"function\", toolInput, parentId)\n } catch {\n // Never crash the host app\n }\n return {}\n }\n\n private async postToolUseHook(\n // biome-ignore lint/suspicious/noExplicitAny: Hook input from Claude Agent SDK is untyped\n inputData: Record<string, any>,\n toolUseId: string | null,\n _context: unknown,\n ): Promise<Record<string, unknown>> {\n try {\n const sid = (inputData.tool_use_id as string) ?? toolUseId ?? \"\"\n const toolResponse = inputData.tool_response\n this.completeSpan(sid, toolResponse)\n } catch {\n // Never crash the host app\n }\n return {}\n }\n\n private async postToolUseFailureHook(\n // biome-ignore lint/suspicious/noExplicitAny: Hook input from Claude Agent SDK is untyped\n inputData: Record<string, any>,\n toolUseId: string | null,\n _context: unknown,\n ): Promise<Record<string, unknown>> {\n try {\n const sid = (inputData.tool_use_id as string) ?? toolUseId ?? \"\"\n const error = String(inputData.error ?? \"Unknown error\")\n this.completeSpan(sid, undefined, error)\n } catch {\n // Never crash the host app\n }\n return {}\n }\n\n private async subagentStartHook(\n // biome-ignore lint/suspicious/noExplicitAny: Hook input from Claude Agent SDK is untyped\n inputData: Record<string, any>,\n _toolUseId: string | null,\n _context: unknown,\n ): Promise<Record<string, unknown>> {\n try {\n const agentId = (inputData.agent_id as string) ?? randomUuid()\n const agentType = (inputData.agent_type as string) ?? \"subagent\"\n const parentId = this.getParentId()\n\n const spanId = randomUuid()\n this.activeSubagentSpans.set(agentId, spanId)\n\n this.startSpan(\n spanId,\n `Agent: ${agentType}`,\n \"agent\",\n undefined,\n parentId,\n )\n } catch {\n // Never crash the host app\n }\n return {}\n }\n\n private async subagentStopHook(\n // biome-ignore lint/suspicious/noExplicitAny: Hook input from Claude Agent SDK is untyped\n inputData: Record<string, any>,\n _toolUseId: string | null,\n _context: unknown,\n ): Promise<Record<string, unknown>> {\n try {\n const agentId = (inputData.agent_id as string) ?? \"\"\n const spanId = this.activeSubagentSpans.get(agentId)\n if (spanId) {\n this.activeSubagentSpans.delete(agentId)\n this.completeSpan(spanId)\n }\n } catch {\n // Never crash the host app\n }\n return {}\n }\n\n // ── public API ───────────────────────────────────────────────\n\n /**\n * Inject Bitfab tracing hooks into Claude Agent SDK options.\n *\n * Modifies the options object and returns it for convenience.\n * The SDK's `HookMatcher` is constructed as a plain object\n * (`{ matcher: null, hooks: [callback] }`) to avoid requiring\n * `@anthropic-ai/claude-agent-sdk` as a dependency.\n *\n * @param options - Options object with a `hooks` property\n * @returns The modified options object with Bitfab hooks injected\n */\n instrumentOptions<T extends Record<string, unknown>>(options: T): T {\n type HookEntry = { matcher: null; hooks: HookCallback[] }\n type HooksDict = Record<string, HookEntry[]>\n\n const hooks: HooksDict = (options.hooks as HooksDict) ?? {}\n if (!options.hooks) {\n ;(options as Record<string, unknown>).hooks = hooks\n }\n\n const hookConfig: Array<[string, HookCallback]> = [\n [\"PreToolUse\", this.preToolUseHook],\n [\"PostToolUse\", this.postToolUseHook],\n [\"PostToolUseFailure\", this.postToolUseFailureHook],\n [\"SubagentStart\", this.subagentStartHook],\n [\"SubagentStop\", this.subagentStopHook],\n ]\n\n for (const [event, callback] of hookConfig) {\n if (!hooks[event]) {\n hooks[event] = []\n }\n hooks[event].push({ matcher: null, hooks: [callback] })\n }\n\n return options\n }\n\n /**\n * Wrap any Claude Agent SDK message stream to capture LLM turns.\n *\n * Yields every message unchanged while capturing assistant message\n * content as LLM turn spans. Kept for naming symmetry with the Python\n * SDK's `wrapResponse` (which wraps `ClaudeSDKClient.receiveResponse()`);\n * in TypeScript, prefer `wrapQuery` around `query()`.\n *\n * Pass `{ input }` (the prompt) to record a replayable root span - see\n * `wrapQuery`.\n */\n async *wrapResponse(\n stream: AsyncIterable<unknown>,\n opts?: { input?: unknown },\n ): AsyncIterable<unknown> {\n this.setRootInput(opts)\n yield* this.processStream(stream)\n }\n\n /**\n * Wrap a `query()` async iterator to capture LLM turns.\n *\n * Tool and subagent spans are captured separately via the hooks injected\n * by `instrumentOptions` into the `options` passed to `query()`.\n *\n * Pass `{ input }` - the prompt (or the serializable args that produced it)\n * - to make a handler-only run replayable: the handler records a root `agent`\n * span with that input, so `replay(key, fn)` can re-feed it. Omit it only\n * when an enclosing `withSpan` already supplies the replayable root.\n *\n * ```typescript\n * handler.wrapQuery(query({ prompt, options }), { input: prompt })\n * ```\n */\n async *wrapQuery(\n stream: AsyncIterable<unknown>,\n opts?: { input?: unknown },\n ): AsyncIterable<unknown> {\n this.setRootInput(opts)\n yield* this.processStream(stream)\n }\n\n private setRootInput(opts?: { input?: unknown }): void {\n // Set deterministically on every wrap call so a prior call's input can\n // never leak into a later input-less run on a reused handler (e.g. if the\n // earlier stream's iterator was abandoned mid-iteration, so resetState\n // never ran).\n if (opts && opts.input !== undefined) {\n this.hasRootInput = true\n this.rootInput = opts.input\n } else {\n this.hasRootInput = false\n this.rootInput = undefined\n }\n this.rootOutput = undefined\n }\n\n // ── stream processing ────────────────────────────────────────\n\n private async *processStream(\n stream: AsyncIterable<unknown>,\n ): AsyncIterable<unknown> {\n try {\n this.maybeStartRootSpan()\n for await (const message of stream) {\n try {\n this.processMessage(message as Record<string, unknown>)\n } catch {\n // Never crash the host app\n }\n yield message\n }\n } finally {\n try {\n this.flushLlmTurn()\n this.completeRootSpan()\n this.sendTraceCompletion()\n } catch {\n // Never crash the host app\n }\n this.resetState()\n }\n }\n\n private processMessage(message: Record<string, unknown>): void {\n // The TypeScript Claude Agent SDK streams plain wire objects discriminated\n // by a `type` field (`{ type: \"assistant\", message: <BetaMessage>, ... }`),\n // NOT class instances. (The Python SDK, by contrast, yields AssistantMessage\n // / UserMessage / ResultMessage dataclasses - hence the different field\n // access here vs. claude_agent_sdk.py.) Routing on `constructor.name` would\n // always see \"Object\" and silently capture nothing.\n const typeName = message.type\n\n if (typeName === \"assistant\") {\n this.handleAssistantMessage(message)\n } else if (typeName === \"user\") {\n this.handleUserMessage(message)\n } else if (typeName === \"result\") {\n this.handleResultMessage(message)\n }\n }\n\n private handleAssistantMessage(message: Record<string, unknown>): void {\n this.ensureTrace()\n\n // Content, model, id, and usage live on the nested BetaMessage, not the\n // top-level SDK wire wrapper.\n const inner = (message.message as Record<string, unknown> | undefined) ?? {}\n\n const messageId =\n (inner.id as string | undefined) ?? (message.uuid as string | undefined)\n\n if (messageId !== this.currentLlmMessageId) {\n this.flushLlmTurn()\n\n // Drain pending user/tool messages into history before snapshot\n this.conversationHistory.push(...this.pendingMessages)\n this.pendingMessages = []\n\n this.currentLlmSpanId = randomUuid()\n this.currentLlmMessageId = messageId ?? null\n this.currentLlmContent = []\n this.currentLlmModel = (inner.model as string) ?? null\n this.currentLlmUsage = {}\n this.currentLlmStartedAt = nowIso()\n this.currentLlmHistorySnapshot = [...this.conversationHistory]\n }\n\n const content = inner.content\n if (Array.isArray(content)) {\n this.currentLlmContent.push(...extractContentBlocks(content))\n }\n\n const usage = extractUsage(inner)\n if (Object.keys(usage).length > 0) {\n Object.assign(this.currentLlmUsage, usage)\n }\n\n const model = inner.model as string | undefined\n if (model) {\n this.currentLlmModel = model\n }\n }\n\n private handleUserMessage(message: Record<string, unknown>): void {\n // User content lives on the nested MessageParam; tool_use_result is a\n // top-level field on the SDK wire wrapper.\n const inner = (message.message as Record<string, unknown> | undefined) ?? {}\n const content = inner.content\n const toolUseResult = message.tool_use_result\n\n if (toolUseResult !== undefined) {\n this.pendingMessages.push({\n role: \"tool\",\n content: safeSerialize(content),\n tool_result: safeSerialize(toolUseResult),\n })\n } else {\n this.pendingMessages.push({\n role: \"user\",\n content: safeSerialize(content),\n })\n }\n }\n\n private handleResultMessage(message: Record<string, unknown>): void {\n this.flushLlmTurn()\n\n // The final result text is the synthetic root span's output.\n if (message.result !== undefined) {\n this.rootOutput = message.result\n }\n this.completeRootSpan()\n\n const metadata: Record<string, unknown> = {}\n for (const attr of [\n \"num_turns\",\n \"total_cost_usd\",\n \"duration_ms\",\n \"duration_api_ms\",\n \"session_id\",\n ]) {\n const val = message[attr]\n if (val !== undefined && val !== null) {\n metadata[attr] = val\n }\n }\n\n const usage = message.usage\n if (usage && typeof usage === \"object\") {\n metadata.usage = safeSerialize(usage)\n }\n\n this.sendTraceCompletion(\n undefined,\n Object.keys(metadata).length > 0 ? metadata : undefined,\n )\n }\n\n private flushLlmTurn(): void {\n if (this.currentLlmSpanId === null) {\n return\n }\n\n const spanId = this.currentLlmSpanId\n const traceId = this.ensureTrace()\n const parentId = this.getParentId()\n\n const llmContext: Record<string, unknown> = {}\n if (this.currentLlmModel) {\n llmContext.model = this.currentLlmModel\n }\n Object.assign(llmContext, this.currentLlmUsage)\n\n const spanInfo: SpanInfo = {\n id: randomUuid(),\n spanId,\n traceId,\n parentId,\n startedAt: this.currentLlmStartedAt ?? nowIso(),\n endedAt: nowIso(),\n name: this.currentLlmModel ?? \"llm\",\n type: \"llm\",\n input: this.currentLlmHistorySnapshot,\n output: this.currentLlmContent,\n contexts: Object.keys(llmContext).length > 0 ? [llmContext] : [],\n }\n\n this.sendSpan(spanInfo)\n\n this.conversationHistory.push({\n role: \"assistant\",\n content: this.currentLlmContent,\n })\n\n this.currentLlmSpanId = null\n this.currentLlmMessageId = null\n this.currentLlmContent = []\n this.currentLlmModel = null\n this.currentLlmUsage = {}\n this.currentLlmStartedAt = null\n this.currentLlmHistorySnapshot = []\n }\n\n private resetState(): void {\n this.runToSpan.clear()\n this.traceId = null\n this.rootSpanId = null\n this.hasRootInput = false\n this.rootInput = undefined\n this.rootOutput = undefined\n this.activeContext = null\n this.traceStartedAt = null\n this.conversationHistory = []\n this.pendingMessages = []\n this.currentLlmSpanId = null\n this.currentLlmMessageId = null\n this.currentLlmContent = []\n this.currentLlmModel = null\n this.currentLlmUsage = {}\n this.currentLlmStartedAt = null\n this.currentLlmHistorySnapshot = []\n this.activeSubagentSpans.clear()\n }\n}\n","/**\n * Import an OPTIONAL peer dependency without breaking a consumer's bundler.\n *\n * Optional peers (declared in this package's `peerDependenciesMeta` with\n * `optional: true` - e.g. `@openai/agents`, `@boundaryml/baml`) are absent by\n * design for most consumers: someone who only uses the Vercel AI integration\n * never installs `@openai/agents`, and someone who never calls `Bitfab.call()`\n * never installs `@boundaryml/baml`.\n *\n * A plain `import(\"@openai/agents\")` leaves a static, literal specifier in the\n * built SDK. A consumer's bundler (webpack, Turbopack, Vite, Rollup, esbuild)\n * statically analyses that specifier and tries to resolve it at *build* time,\n * failing the whole build with \"Module not found: Can't resolve\n * '@openai/agents'\" even though that code path never runs for that consumer.\n * Wrapping the import in try/catch is not enough: only webpack >= 5.90.2 treats\n * that as optional, and Turbopack/Vite/older webpack do not.\n *\n * The robust, bundler-agnostic fix is to keep the specifier out of static\n * analysis entirely. The caller passes the specifier as parts that are joined\n * at runtime, so no bundler can see a literal module name to resolve. The\n * `webpackIgnore` / `@vite-ignore` magic comments are belt-and-suspenders for\n * bundlers that still inspect the (now non-literal) request. This mirrors the\n * technique already used for `node:async_hooks` in `asyncStorage.ts`.\n *\n * The import stays a native runtime `import()`: it resolves from `node_modules`\n * when the peer IS installed, and throws an ordinary module-not-found error\n * only when the feature is actually used without its peer installed - which is\n * the correct behaviour (the caller opted into an integration whose peer they\n * chose not to install).\n *\n * @param specifierParts - The package specifier split so it is reconstructed at\n * runtime, never appearing as a literal (e.g. `[\"@openai\", \"agents\"]` ->\n * `\"@openai/agents\"`).\n */\nexport function importOptionalPeer<T = unknown>(\n specifierParts: readonly string[],\n): Promise<T> {\n // Reconstructed at runtime so no bundler sees a literal specifier to resolve.\n const specifier = specifierParts.join(\"/\")\n return import(\n /* webpackIgnore: true */ /* @vite-ignore */ specifier\n ) as Promise<T>\n}\n","/**\n * BAML execution utilities for the Bitfab TypeScript SDK.\n * This module provides functions to execute BAML prompts dynamically on the client side.\n */\n\nimport { importOptionalPeer } from \"./optionalPeer.js\"\n\ntype BamlModule = typeof import(\"@boundaryml/baml\")\n\nlet cachedBaml: BamlModule | null = null\n\nasync function loadBaml(): Promise<BamlModule> {\n if (cachedBaml) {\n return cachedBaml\n }\n try {\n // Reconstructed specifier (see importOptionalPeer): keeps a consumer's\n // bundler from trying to resolve `@boundaryml/baml` at build time when it\n // is not installed (it is an optional peer, only needed for Bitfab.call()).\n cachedBaml = await importOptionalPeer<BamlModule>([\"@boundaryml\", \"baml\"])\n return cachedBaml\n } catch {\n throw new Error(\n \"@boundaryml/baml is required for Bitfab.call(). Install it with: npm install @boundaryml/baml\",\n )\n }\n}\n\n/**\n * Provider definition from the server.\n */\nexport interface ProviderDefinition {\n provider: string\n apiKeyEnv: string\n models: Array<{\n model: string\n description: string\n }>\n}\n\n/**\n * Result of a BAML function execution with raw collector data.\n */\nexport interface BamlExecutionResult {\n /** The parsed result of the function */\n result: unknown\n /** Raw collector data for the server to parse */\n rawCollector: Record<string, unknown> | null\n}\n\n/**\n * Capitalize first letter of a string.\n */\nfunction capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1)\n}\n\n/**\n * Convert provider name to PascalCase.\n * e.g., \"openai\" -> \"OpenAI\", \"anthropic\" -> \"Anthropic\"\n */\nfunction formatProvider(provider: string): string {\n const providerMap: Record<string, string> = {\n openai: \"OpenAI\",\n anthropic: \"Anthropic\",\n google: \"Google\",\n }\n return providerMap[provider] ?? capitalize(provider)\n}\n\n/**\n * Convert a model name to a valid BAML identifier part.\n * e.g., \"gpt-5-mini\" -> \"GPT5_mini\", \"gpt-4.1\" -> \"GPT4_1\"\n */\nfunction formatModel(model: string): string {\n return model\n .replace(/^gpt-/, \"GPT\") // gpt- prefix -> GPT\n .replace(/\\./g, \"_\") // dots -> underscore\n .replace(/-/g, \"_\") // hyphens -> underscore\n}\n\n/**\n * Generate the BAML client name from provider and model.\n * e.g., \"openai\" + \"gpt-4.1-mini\" -> \"OpenAI_GPT4_1_mini\"\n */\nexport function getClientName(provider: string, model: string): string {\n return `${formatProvider(provider)}_${formatModel(model)}`\n}\n\n/**\n * Generates BAML client definition strings.\n * BamlRuntime.fromFiles requires clients to be defined in source for parsing.\n */\nfunction generateClientDefinitions(providers: ProviderDefinition[]): string {\n const definitions: string[] = []\n\n for (const providerDef of providers) {\n for (const model of providerDef.models) {\n const clientName = getClientName(providerDef.provider, model.model)\n const temperatureOption = supportsTemperatureZero(\n providerDef.provider,\n model.model,\n )\n ? \"\\n temperature 0\"\n : \"\"\n definitions.push(`client<llm> ${clientName} {\n provider ${providerDef.provider}\n options {\n model \"${model.model}\"\n api_key env.${providerDef.apiKeyEnv}${temperatureOption}\n }\n}`)\n }\n }\n\n return definitions.join(\"\\n\\n\")\n}\n\nfunction supportsTemperatureZero(provider: string, model: string): boolean {\n return (\n provider === \"openai\" &&\n (model.startsWith(\"gpt-4.1\") || model.startsWith(\"gpt-4o\"))\n )\n}\n\n/**\n * Prepends the default client definitions to a BAML source if it doesn't already define them.\n */\nfunction withDefaultClients(\n bamlSource: string,\n providers: ProviderDefinition[],\n): string {\n const hasDefaultClient = bamlSource.includes(\"client<llm> OpenAI_\")\n if (hasDefaultClient) {\n return bamlSource\n }\n const defaultClients = generateClientDefinitions(providers)\n return `${defaultClients}\\n\\n${bamlSource}`\n}\n\n/**\n * Extracts the first function name from BAML source code.\n */\nfunction extractFunctionName(bamlSource: string): string | null {\n const match = bamlSource.match(/function\\s+(\\w+)\\s*\\(/)\n return match?.[1] ?? null\n}\n\n/**\n * Parameter type information extracted from BAML function signature.\n */\nexport interface BamlParameterType {\n name: string\n type: string\n isOptional: boolean\n}\n\n/**\n * Extracts function parameter names and types from BAML source code.\n * Used to properly coerce inputs based on expected types.\n */\nexport function extractFunctionParameters(\n bamlSource: string,\n): BamlParameterType[] {\n const functionMatch = bamlSource.match(/function\\s+\\w+\\s*\\(([^)]*)\\)\\s*->/)\n if (!functionMatch) {\n return []\n }\n\n const paramsString = functionMatch[1].trim()\n if (!paramsString) {\n return []\n }\n\n const params: BamlParameterType[] = []\n const paramParts = splitParameters(paramsString)\n\n for (const part of paramParts) {\n const trimmed = part.trim()\n if (!trimmed) {\n continue\n }\n\n const paramMatch = trimmed.match(/^(\\w+)\\s*:\\s*(.+)$/)\n if (paramMatch) {\n const name = paramMatch[1]\n let type = paramMatch[2].trim()\n const isOptional = type.endsWith(\"?\")\n if (isOptional) {\n type = type.slice(0, -1)\n }\n params.push({ name, type, isOptional })\n }\n }\n\n return params\n}\n\n/**\n * Split parameter string by commas, respecting nested angle brackets.\n */\nfunction splitParameters(paramsString: string): string[] {\n const parts: string[] = []\n let current = \"\"\n let depth = 0\n\n for (const char of paramsString) {\n if (char === \"<\") {\n depth++\n current += char\n } else if (char === \">\") {\n depth--\n current += char\n } else if (char === \",\" && depth === 0) {\n parts.push(current)\n current = \"\"\n } else {\n current += char\n }\n }\n\n if (current.trim()) {\n parts.push(current)\n }\n\n return parts\n}\n\n/**\n * Coerce a single string value to the expected BAML type.\n * Returns the coerced value, or the original string if coercion fails.\n */\nfunction coerceToType(value: string, expectedType: string): unknown {\n // String type - keep as is\n if (expectedType === \"string\") {\n return value\n }\n\n // Integer type\n if (expectedType === \"int\") {\n const parsed = Number.parseInt(value, 10)\n if (!Number.isNaN(parsed)) {\n return parsed\n }\n return value\n }\n\n // Float type\n if (expectedType === \"float\") {\n const parsed = Number.parseFloat(value)\n if (!Number.isNaN(parsed)) {\n return parsed\n }\n return value\n }\n\n // Boolean type\n if (expectedType === \"bool\") {\n const lower = value.toLowerCase()\n if (lower === \"true\") {\n return true\n }\n if (lower === \"false\") {\n return false\n }\n return value\n }\n\n // Array types (e.g., string[], int[])\n if (expectedType.endsWith(\"[]\")) {\n try {\n const parsed = JSON.parse(value)\n if (Array.isArray(parsed)) {\n return parsed\n }\n } catch {\n // Not valid JSON array\n }\n return value\n }\n\n // Complex types (objects, classes, maps) - try JSON parse\n try {\n return JSON.parse(value)\n } catch {\n return value\n }\n}\n\n/**\n * Coerces input values from strings to their appropriate types based on expected BAML types.\n * Actively coerces to the expected type (int, float, bool, etc.) rather than just avoiding\n * unintended conversions.\n */\nfunction coerceInputs(\n inputs: Record<string, unknown>,\n expectedTypes: Map<string, string>,\n): Record<string, unknown> {\n const coerced: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(inputs)) {\n if (typeof value === \"string\") {\n const expectedType = expectedTypes.get(key)\n\n if (expectedType) {\n coerced[key] = coerceToType(value, expectedType)\n } else {\n // No expected type info - keep as string\n coerced[key] = value\n }\n } else {\n coerced[key] = value\n }\n }\n\n return coerced\n}\n\n/**\n * Recursively convert an object to a JSON-serializable structure.\n * Similar to Python's _obj_to_dict function.\n */\nfunction objToDict(obj: unknown, depth = 0, maxDepth = 5): unknown {\n if (depth > maxDepth) {\n return `<max depth reached: ${typeof obj}>`\n }\n\n // Handle primitives\n if (\n obj === null ||\n obj === undefined ||\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\"\n ) {\n return obj\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => objToDict(item, depth + 1, maxDepth))\n }\n\n // Handle plain objects and class instances\n if (typeof obj === \"object\") {\n const result: Record<string, unknown> = {}\n\n // Add type information for non-plain objects\n if (obj.constructor && obj.constructor.name !== \"Object\") {\n result.__type__ = obj.constructor.name\n }\n\n // Extract all enumerable properties\n for (const key of Object.keys(obj)) {\n if (key.startsWith(\"_\")) {\n continue // Skip private properties\n }\n\n try {\n const value = (obj as Record<string, unknown>)[key]\n\n // Skip functions\n if (typeof value === \"function\") {\n continue\n }\n\n result[key] = objToDict(value, depth + 1, maxDepth)\n } catch (error) {\n result[key] =\n `<error: ${error instanceof Error ? error.message : String(error)}>`\n }\n }\n\n // Also try to get non-enumerable properties from the prototype\n // This helps capture getters and computed properties\n try {\n const proto = Object.getPrototypeOf(obj)\n if (proto && proto !== Object.prototype) {\n const descriptors = Object.getOwnPropertyDescriptors(proto)\n for (const [key, descriptor] of Object.entries(descriptors)) {\n if (key.startsWith(\"_\") || key === \"constructor\" || key in result) {\n continue\n }\n\n // Try to get the value if it has a getter\n if (descriptor.get) {\n try {\n const value = (obj as Record<string, unknown>)[key]\n if (typeof value !== \"function\") {\n result[key] = objToDict(value, depth + 1, maxDepth)\n }\n } catch {\n // Getter might throw or be inaccessible\n }\n }\n }\n }\n } catch {\n // Prototype inspection might fail\n }\n\n return result\n }\n\n // Fallback for other types\n return String(obj)\n}\n\n/**\n * Serialize the BAML Collector to a JSON-serializable structure.\n * Recursively extracts all properties from the Collector for server-side parsing.\n */\nfunction serializeCollector(\n collector: unknown,\n): Record<string, unknown> | null {\n try {\n return objToDict(collector, 0, 5) as Record<string, unknown>\n } catch (_error) {\n // Silently ignore serialization failures\n return null\n }\n}\n\n/**\n * Allowed environment variable keys for LLM providers.\n * Only these keys will be passed to the BAML runtime.\n */\nconst ALLOWED_ENV_KEYS = [\"OPENAI_API_KEY\"] as const\n\n/**\n * Type for allowed environment variables.\n * Only OPENAI_API_KEY is currently supported.\n */\nexport type AllowedEnvVars = {\n OPENAI_API_KEY?: string\n}\n\n/**\n * Filters environment variables to only include allowed keys.\n * This prevents accidentally passing sensitive environment variables to the BAML runtime.\n */\nfunction filterEnvVars(envVars: AllowedEnvVars): Record<string, string> {\n const filtered: Record<string, string> = {}\n for (const key of ALLOWED_ENV_KEYS) {\n const value = envVars[key]\n if (value) {\n filtered[key] = value\n }\n }\n return filtered\n}\n\n/**\n * Runs the BAML function with the given inputs using the BAML runtime directly.\n * No file generation or subprocess spawning needed.\n *\n * @param bamlSource - The BAML source code containing the function\n * @param inputs - Named arguments to pass to the function\n * @param providers - Available provider definitions\n * @param envVars - Environment variables for API keys (only OPENAI_API_KEY is allowed)\n * @returns The result and execution metadata of the BAML function call\n */\nexport async function runFunctionWithBaml(\n bamlSource: string,\n inputs: Record<string, unknown>,\n providers: ProviderDefinition[],\n envVars: AllowedEnvVars,\n): Promise<BamlExecutionResult> {\n const { BamlRuntime, Collector } = await loadBaml()\n\n // Extract function name from the BAML source\n const functionName = extractFunctionName(bamlSource)\n if (!functionName) {\n throw new Error(\"No function found in BAML source\")\n }\n\n // Add default client definitions (runtime needs them for parsing)\n const fullSource = withDefaultClients(bamlSource, providers)\n\n // Filter env vars to only allowed keys\n const filteredEnvVars = filterEnvVars(envVars)\n\n // Create runtime from source with env vars\n const runtime = BamlRuntime.fromFiles(\n \"/tmp/baml_runtime\",\n { \"source.baml\": fullSource },\n filteredEnvVars,\n )\n\n // Create context manager\n const ctx = runtime.createContextManager()\n\n // Create collector to capture execution metadata\n const collector = new Collector(\"bitfab-collector\")\n\n // Extract expected parameter types from BAML source\n const params = extractFunctionParameters(bamlSource)\n const expectedTypes = new Map(params.map((p) => [p.name, p.type]))\n\n // Coerce inputs from strings to proper types based on BAML signature\n const args = coerceInputs(inputs, expectedTypes)\n\n // Call the function with collector\n const functionResult = await runtime.callFunction(\n functionName,\n args,\n ctx,\n null, // TypeBuilder\n null, // ClientRegistry\n [collector], // Collectors - capture execution data\n {}, // Tags\n filteredEnvVars,\n )\n\n if (!functionResult.isOk()) {\n throw new Error(\"BAML function execution failed\")\n }\n\n // Serialize the collector to a dict for the server to parse\n const rawCollector = serializeCollector(collector)\n\n return {\n result: functionResult.parsed(false),\n rawCollector,\n }\n}\n","import { MixedTracingError } from \"./errors.js\"\n\nexport type CaptureSurface = \"opt-in\" | \"opt-out\"\n\nexport type SurfaceRequest = CaptureSurface | \"inherit\" | \"neutral\"\n\nexport const DEFAULT_SURFACE: CaptureSurface = \"opt-in\"\n\nconst SURFACE_API: Record<CaptureSurface, string> = {\n \"opt-in\": \"withSpan()\",\n \"opt-out\": \"withTrace()\",\n}\n\nconst MIXED_SURFACE_REMEDY: Record<CaptureSurface, string> = {\n \"opt-in\":\n \"Inside a withTrace/trace subtree, configure a discovered call with node()/withNode() instead, or trace this workflow with withSpan() only.\",\n \"opt-out\":\n \"Wrap the caller with withTrace()/trace() as well, or wrap this function with withSpan().\",\n}\n\nexport function resolveSurface(\n requested: SurfaceRequest,\n parentSurface: CaptureSurface | undefined,\n): CaptureSurface | undefined {\n if (requested === \"neutral\") {\n return undefined\n }\n if (requested === \"inherit\") {\n return parentSurface ?? DEFAULT_SURFACE\n }\n return requested\n}\n\nexport function mixedTracingError(\n enteredApi: string,\n entered: CaptureSurface,\n enclosing: CaptureSurface,\n traceFunctionKey?: string,\n): MixedTracingError {\n const subject =\n traceFunctionKey === undefined ? \"\" : ` for \"${traceFunctionKey}\"`\n return new MixedTracingError(\n `opt-in and opt-out tracing can't be mixed in one call stack: ${enteredApi} (${entered})${subject} was entered inside a ${SURFACE_API[enclosing]} call (${enclosing}). ${MIXED_SURFACE_REMEDY[entered]}`,\n )\n}\n\nexport function assertSurfacesCompatible(\n requested: SurfaceRequest,\n resolved: CaptureSurface | undefined,\n parentSurface: CaptureSurface | undefined,\n traceFunctionKey: string,\n): void {\n if (requested === \"inherit\" || requested === \"neutral\") {\n return\n }\n if (resolved === undefined || parentSurface === undefined) {\n return\n }\n if (parentSurface === resolved) {\n return\n }\n throw mixedTracingError(\n SURFACE_API[resolved],\n resolved,\n parentSurface,\n traceFunctionKey,\n )\n}\n","import type { HttpClient } from \"./http.js\"\n\nexport interface DatasetGraderRef {\n id: string\n name: string | null\n}\n\nexport interface Dataset {\n id: string\n traceFunctionKey: string\n name: string\n description: string | null\n traceCount: number\n graders: DatasetGraderRef[]\n createdAt: string\n updatedAt: string\n}\n\nexport interface SaveDatasetParams {\n traceFunctionKey: string\n name: string\n description?: string\n}\n\nexport interface SaveDatasetResult {\n dataset: Dataset\n created: boolean\n}\n\nexport interface ListDatasetsParams {\n traceFunctionKey?: string\n}\n\nexport interface DatasetTraceIds {\n datasetId: string\n traceIds: string[]\n}\n\nexport interface AddDatasetTracesResult {\n dataset: Dataset\n addedTraceIds: string[]\n alreadyPresentTraceIds: string[]\n skippedTraceIds: string[]\n}\n\nexport interface RemoveDatasetTracesResult {\n dataset: Dataset\n removedTraceIds: string[]\n notPresentTraceIds: string[]\n}\n\nexport interface AddDatasetGradersResult {\n dataset: Dataset\n addedGraderIds: string[]\n alreadyAssignedGraderIds: string[]\n skippedGraderIds: string[]\n}\n\nexport interface RemoveDatasetGradersResult {\n dataset: Dataset\n removedGraderIds: string[]\n notAssignedGraderIds: string[]\n}\n\nexport type GraderRerunStatus = \"pending\" | \"running\" | \"completed\" | \"errored\"\n\nexport interface GraderRerunProgress {\n completedTraces: number\n totalTraces: number\n graderCount: number\n}\n\nexport interface GraderRerunResult {\n tracesGraded: number\n gradersRun: number\n}\n\nexport interface GraderRerun {\n id: string\n status: GraderRerunStatus\n graderIds: string[]\n progress: GraderRerunProgress | null\n result: GraderRerunResult | null\n error: string | null\n createdAt: string\n updatedAt: string\n}\n\nexport interface RerunGradersOptions {\n graderIds?: string[]\n wait?: boolean\n timeoutMs?: number\n pollIntervalMs?: number\n}\n\nexport interface RerunGradersResult {\n run: GraderRerun\n joinedExisting: boolean\n}\n\nconst DEFAULT_RERUN_TIMEOUT_MS = 90_000\nconst DEFAULT_RERUN_POLL_INTERVAL_MS = 1_000\nconst TERMINAL_RERUN_STATUSES: ReadonlySet<GraderRerunStatus> = new Set([\n \"completed\",\n \"errored\",\n])\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction datasetPath(datasetId: string, suffix = \"\"): string {\n return `/api/sdk/datasets/${encodeURIComponent(datasetId)}${suffix}`\n}\n\n/**\n * Dataset operations for the authenticated organization, reached as\n * `client.datasets`. A dataset is a named bucket of traces scoped to one trace\n * function. Experiments replay against it and its graders score its members.\n */\nexport class DatasetsClient {\n constructor(private readonly httpClient: HttpClient) {}\n\n /**\n * Create a dataset, or update the one already named this way under the same\n * trace function. `created` reports which happened. An omitted description\n * leaves an existing one untouched.\n */\n async save(params: SaveDatasetParams): Promise<SaveDatasetResult> {\n return this.httpClient.request<SaveDatasetResult>(\"/api/sdk/datasets\", {\n traceFunctionKey: params.traceFunctionKey,\n name: params.name,\n ...(params.description === undefined\n ? {}\n : { description: params.description }),\n })\n }\n\n /**\n * List datasets, scoped to one trace function when `traceFunctionKey` is\n * given and organization-wide otherwise.\n */\n async list(params: ListDatasetsParams = {}): Promise<Dataset[]> {\n const query =\n params.traceFunctionKey === undefined\n ? \"\"\n : `?traceFunctionKey=${encodeURIComponent(params.traceFunctionKey)}`\n const response = await this.httpClient.get<{ datasets: Dataset[] }>(\n `/api/sdk/datasets${query}`,\n )\n return response.datasets\n }\n\n /** Fetch one dataset by id. Rejects with a 404 `BitfabError` when it is not in this organization. */\n async get(datasetId: string): Promise<Dataset> {\n const response = await this.httpClient.get<{ dataset: Dataset }>(\n datasetPath(datasetId),\n )\n return response.dataset\n }\n\n /** The ids of every trace in the dataset, the same membership a replay with `datasetId` selects. */\n async listTraces(datasetId: string): Promise<DatasetTraceIds> {\n return this.httpClient.get<DatasetTraceIds>(\n datasetPath(datasetId, \"/traces\"),\n )\n }\n\n /**\n * Add traces to the dataset (1 to 100 ids per call). Traces outside the\n * organization or under another trace function are reported in\n * `skippedTraceIds` rather than failing the call.\n */\n async addTraces(\n datasetId: string,\n traceIds: string[],\n ): Promise<AddDatasetTracesResult> {\n return this.httpClient.request<AddDatasetTracesResult>(\n datasetPath(datasetId, \"/traces\"),\n { traceIds },\n )\n }\n\n /** Remove traces from the dataset. The traces themselves are never deleted. */\n async removeTraces(\n datasetId: string,\n traceIds: string[],\n ): Promise<RemoveDatasetTracesResult> {\n return this.httpClient.request<RemoveDatasetTracesResult>(\n datasetPath(datasetId, \"/removeTraces\"),\n { traceIds },\n )\n }\n\n /**\n * Assign graders to the dataset (1 to 100 ids per call). Graders outside the\n * organization or under another trace function are reported in\n * `skippedGraderIds` rather than failing the call.\n */\n async addGraders(\n datasetId: string,\n graderIds: string[],\n ): Promise<AddDatasetGradersResult> {\n return this.httpClient.request<AddDatasetGradersResult>(\n datasetPath(datasetId, \"/graders\"),\n { graderIds },\n )\n }\n\n /** Unassign graders from the dataset. */\n async removeGraders(\n datasetId: string,\n graderIds: string[],\n ): Promise<RemoveDatasetGradersResult> {\n return this.httpClient.request<RemoveDatasetGradersResult>(\n datasetPath(datasetId, \"/removeGraders\"),\n { graderIds },\n )\n }\n\n /**\n * Re-run graders over every trace in the dataset. Defaults to every assigned\n * grader; an unassigned id is rejected. Waits for the run to finish (up to\n * `timeoutMs`, default 90s) unless `wait` is `false`, and returns the last\n * run state seen either way. A request matching an in-flight run joins it.\n */\n async rerunGraders(\n datasetId: string,\n options: RerunGradersOptions = {},\n ): Promise<RerunGradersResult> {\n const started = await this.httpClient.request<RerunGradersResult>(\n datasetPath(datasetId, \"/rerunGraders\"),\n options.graderIds === undefined ? {} : { graderIds: options.graderIds },\n )\n if (options.wait === false) {\n return started\n }\n\n const deadline =\n Date.now() + (options.timeoutMs ?? DEFAULT_RERUN_TIMEOUT_MS)\n const interval = options.pollIntervalMs ?? DEFAULT_RERUN_POLL_INTERVAL_MS\n let run = started.run\n while (!TERMINAL_RERUN_STATUSES.has(run.status) && Date.now() < deadline) {\n await sleep(interval)\n run = (await this.getGraderRerun(datasetId, run.id)) ?? run\n }\n return { run, joinedExisting: started.joinedExisting }\n }\n\n /**\n * The dataset's active grader re-run, or the run named by `runId`. Returns\n * `null` when nothing is active or the run does not belong to this dataset.\n */\n async getGraderRerun(\n datasetId: string,\n runId?: string,\n ): Promise<GraderRerun | null> {\n const query =\n runId === undefined ? \"\" : `?runId=${encodeURIComponent(runId)}`\n const response = await this.httpClient.get<{ run: GraderRerun | null }>(\n datasetPath(datasetId, `/rerunGraders${query}`),\n )\n return response.run\n }\n}\n","/**\n * Per-trace database snapshot ref capture.\n *\n * Every root span carries a `DbSnapshotRef` that pins the DB state at trace\n * open by wall-clock timestamp. Capturing the timestamp is free (no IO) and\n * harmless, so it happens on every trace regardless of configuration: that\n * lets any trace be replayed against a historical branch later. A `provider`\n * is attached only when the customer configured `dbSnapshot`; when absent it\n * is resolved at replay time. The Bitfab service uses the timestamp to\n * materialize an ephemeral branch from `customer-main`.\n */\n\nimport { BitfabError } from \"./errors.js\"\n\n// TODO: add more providers as resolvers are built (ardent, dolt, gfs, ...).\nexport const SUPPORTED_PROVIDERS = [\"neon\"] as const\n\nexport type DbSnapshotProvider = (typeof SUPPORTED_PROVIDERS)[number]\n\nexport interface DbSnapshotConfig {\n /** Discriminator for the server-side resolver. */\n provider: DbSnapshotProvider\n}\n\nexport interface DbSnapshotRef {\n /**\n * The wall-clock ISO timestamp the SDK observed immediately before\n * invoking the wrapped function. The name encodes its provenance:\n * SDK-observed, wall clock (not monotonic), captured before user code\n * began executing. Always present.\n */\n sdkWallClockBeforeFn: string\n /**\n * The configured provider for server-side branch resolution. Only set when\n * the customer configured `dbSnapshot`; otherwise the provider is resolved\n * at replay time.\n */\n provider?: DbSnapshotProvider\n}\n\nexport function validateDbSnapshotConfig(config: DbSnapshotConfig): void {\n if (!SUPPORTED_PROVIDERS.includes(config.provider)) {\n throw new BitfabError(\n `dbSnapshot.provider \"${config.provider}\" is not supported. Supported providers: ${SUPPORTED_PROVIDERS.join(\", \")}.`,\n )\n }\n}\n\n/**\n * Build a snapshot ref for one trace. Synchronous, no IO. Always stores the\n * wall clock the SDK observed immediately before invoking the wrapped\n * function; the resolver uses that as the Neon snapshot timestamp. The\n * `provider` is included only when `dbSnapshot` was configured (`config`\n * present); otherwise it is resolved at replay time.\n */\nexport function buildSnapshotRef(\n config: DbSnapshotConfig | undefined,\n sdkWallClockBeforeFn: string,\n): DbSnapshotRef {\n return {\n sdkWallClockBeforeFn,\n ...(config && { provider: config.provider }),\n }\n}\n","/**\n * LangGraph/LangChain callback handler for Bitfab tracing.\n *\n * Hooks into LangGraph's callback system to capture graph node execution,\n * LLM calls, and tool invocations as Bitfab spans, without requiring users\n * to wrap their functions with withSpan (which fails on non-serializable args).\n *\n * Duck-typed to match LangChain.js's BaseCallbackHandler interface.\n * No @langchain/core dependency required.\n */\n\nimport { DEFAULT_SERVICE_URL } from \"./constants.js\"\nimport { type ApiKeyInput, HttpClient } from \"./http.js\"\nimport {\n finalizeSpanPayload,\n finalizeTracePayload,\n} from \"./processorPayload.js\"\nimport { randomUuid } from \"./randomUuid.js\"\nimport { toJsonSafeReport } from \"./serialize.js\"\nimport { nowIsoTimestamp } from \"./timestamp.js\"\n\nexport interface ActiveSpanContext {\n traceId: string\n spanId: string\n}\n\ninterface SpanInfo {\n id: string\n spanId: string\n traceId: string\n rootRunId: string\n parentId: string | null\n startedAt: string\n endedAt?: string\n name: string\n type: string\n input?: unknown\n output?: unknown\n error?: string\n contexts: Array<Record<string, unknown>>\n model?: string\n hidden?: boolean\n // Type names of input/output values that could only be captured as\n // placeholders. Carried to the send boundary so finalizeSpanPayload can mark\n // the span non-replayable.\n dropped?: string[]\n}\n\ninterface InvocationState {\n traceId: string\n activeContext: ActiveSpanContext | null\n rootRunId: string\n}\n\nconst LANGSMITH_HIDDEN_TAG = \"langsmith:hidden\"\n\nconst CHAIN_RUN_TYPES = new Set([\"chain\", \"parser\", \"prompt\"])\n\nconst LANGGRAPH_METADATA_KEYS = [\n \"langgraph_step\",\n \"langgraph_node\",\n \"langgraph_triggers\",\n \"langgraph_path\",\n \"langgraph_checkpoint_ns\",\n] as const\n\nfunction nowIso(): string {\n return nowIsoTimestamp()\n}\n\nfunction normalizeChainStartArgs(\n parentRunIdOrRunType?: string,\n runTypeOrRunName?: string,\n runNameOrParentRunId?: string,\n): { parentRunId?: string; runName?: string } {\n if (parentRunIdOrRunType && CHAIN_RUN_TYPES.has(parentRunIdOrRunType)) {\n return {\n parentRunId: runNameOrParentRunId,\n runName: runTypeOrRunName,\n }\n }\n\n return {\n parentRunId: parentRunIdOrRunType,\n runName: runNameOrParentRunId,\n }\n}\n\nfunction convertMessage(message: unknown): Record<string, unknown> {\n if (typeof message !== \"object\" || message === null) {\n return { role: \"unknown\", content: String(message) }\n }\n\n const msg = message as Record<string, unknown>\n\n if (typeof msg.toDict === \"function\") {\n return (msg as { toDict(): Record<string, unknown> }).toDict()\n }\n\n const typeToRole: Record<string, string> = {\n human: \"user\",\n ai: \"assistant\",\n system: \"system\",\n tool: \"tool\",\n function: \"function\",\n }\n\n const result: Record<string, unknown> = {}\n\n const msgType = msg._getType\n ? String((msg as { _getType(): string })._getType())\n : (msg.type as string | undefined)\n\n result.role =\n (msgType ? typeToRole[msgType] : undefined) ?? msg.role ?? \"unknown\"\n result.content = msg.content ?? \"\"\n\n if (msg.tool_calls) {\n result.tool_calls = msg.tool_calls\n }\n if (msg.tool_call_id) {\n result.tool_call_id = msg.tool_call_id\n }\n if (msg.name) {\n result.name = msg.name\n }\n\n return result\n}\n\nfunction extractModelName(\n serialized: Record<string, unknown> | undefined,\n metadata: Record<string, unknown> | undefined,\n): string | undefined {\n if (serialized) {\n const kwargs = serialized.kwargs as Record<string, unknown> | undefined\n if (kwargs) {\n const model = kwargs.model_name ?? kwargs.model ?? kwargs.model_id\n if (model) {\n return String(model)\n }\n }\n }\n if (metadata) {\n const lsModel = metadata.ls_model_name\n if (lsModel) {\n return String(lsModel)\n }\n }\n return undefined\n}\n\ninterface NormalizedUsage {\n inputTokens: number | null\n outputTokens: number | null\n totalTokens: number | null\n cachedInputTokens: number | null\n}\n\nfunction asTokenCount(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null\n}\n\n/**\n * Normalize a provider-reported token-usage dict into Bitfab's span fields.\n *\n * Handles, in priority order:\n * - Anthropic native (`input_tokens` EXCLUDES cache reads/creation, so they\n * are added back to get the true prompt size)\n * - OpenAI native (`prompt_tokens` / `completion_tokens`, snake or camel case)\n * - Google Gemini / Vertex native (`prompt_token_count` / `candidates_token_count`)\n * - LangChain normalized `usage_metadata` (`input_tokens` / `output_tokens` /\n * `total_tokens` with `input_token_details.cache_read`)\n *\n * Returns null when the value carries no recognizable token counts. Never\n * estimates: only provider-reported numbers are returned.\n */\nfunction normalizeTokenUsage(raw: unknown): NormalizedUsage | null {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return null\n }\n const u = raw as Record<string, unknown>\n\n // Anthropic native: input_tokens excludes cached reads and cache writes.\n if (\"cache_read_input_tokens\" in u || \"cache_creation_input_tokens\" in u) {\n const cacheRead = asTokenCount(u.cache_read_input_tokens)\n const cacheCreation = asTokenCount(u.cache_creation_input_tokens)\n const baseInput = asTokenCount(u.input_tokens)\n const outputTokens = asTokenCount(u.output_tokens)\n if (\n cacheRead === null &&\n cacheCreation === null &&\n baseInput === null &&\n outputTokens === null\n ) {\n return null\n }\n const inputTokens =\n (baseInput ?? 0) + (cacheRead ?? 0) + (cacheCreation ?? 0)\n return {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + (outputTokens ?? 0),\n cachedInputTokens: cacheRead,\n }\n }\n\n // OpenAI native (snake_case) and LangChain.js legacy llmOutput (camelCase).\n if (\n \"prompt_tokens\" in u ||\n \"completion_tokens\" in u ||\n \"promptTokens\" in u ||\n \"completionTokens\" in u\n ) {\n const promptDetails = (u.prompt_tokens_details ?? {}) as Record<\n string,\n unknown\n >\n return withAnyTokenCount({\n inputTokens:\n asTokenCount(u.prompt_tokens) ?? asTokenCount(u.promptTokens),\n outputTokens:\n asTokenCount(u.completion_tokens) ?? asTokenCount(u.completionTokens),\n totalTokens: asTokenCount(u.total_tokens) ?? asTokenCount(u.totalTokens),\n cachedInputTokens: asTokenCount(promptDetails.cached_tokens),\n })\n }\n\n // Google Gemini / Vertex native.\n if (\"prompt_token_count\" in u || \"candidates_token_count\" in u) {\n return withAnyTokenCount({\n inputTokens: asTokenCount(u.prompt_token_count),\n outputTokens: asTokenCount(u.candidates_token_count),\n totalTokens: asTokenCount(u.total_token_count),\n cachedInputTokens: asTokenCount(u.cached_content_token_count),\n })\n }\n\n // LangChain normalized usage_metadata (also plain Anthropic without cache keys).\n if (\"input_tokens\" in u || \"output_tokens\" in u) {\n const inputDetails = (u.input_token_details ?? {}) as Record<\n string,\n unknown\n >\n const inputTokens = asTokenCount(u.input_tokens)\n const outputTokens = asTokenCount(u.output_tokens)\n let totalTokens = asTokenCount(u.total_tokens)\n if (totalTokens === null && inputTokens !== null && outputTokens !== null) {\n totalTokens = inputTokens + outputTokens\n }\n return withAnyTokenCount({\n inputTokens,\n outputTokens,\n totalTokens,\n cachedInputTokens: asTokenCount(inputDetails.cache_read),\n })\n }\n\n return null\n}\n\n/**\n * A recognizable usage shape whose values are all null/non-numeric carries no\n * usage. Returning null lets extraction fall through to the next source\n * (response_metadata, then legacy llm_output) instead of blocking it.\n */\nfunction withAnyTokenCount(usage: NormalizedUsage): NormalizedUsage | null {\n const hasCount =\n usage.inputTokens !== null ||\n usage.outputTokens !== null ||\n usage.totalTokens !== null ||\n usage.cachedInputTokens !== null\n return hasCount ? usage : null\n}\n\nfunction addUsage(totals: NormalizedUsage, usage: NormalizedUsage): void {\n for (const key of [\n \"inputTokens\",\n \"outputTokens\",\n \"totalTokens\",\n \"cachedInputTokens\",\n ] as const) {\n const value = usage[key]\n if (value !== null) {\n totals[key] = (totals[key] ?? 0) + value\n }\n }\n}\n\n/**\n * Extract usage from each generation's message: the standardized\n * `usage_metadata` (set by modern LangChain chat models, including the final\n * aggregated chunk of streaming runs), falling back to provider-native\n * `response_metadata`. Sums across generations when a result has several.\n */\nfunction usageFromGenerations(\n generations: unknown[][] | undefined,\n): NormalizedUsage | null {\n if (!generations?.length) {\n return null\n }\n const totals: NormalizedUsage = {\n inputTokens: null,\n outputTokens: null,\n totalTokens: null,\n cachedInputTokens: null,\n }\n let found = false\n for (const batch of generations) {\n if (!Array.isArray(batch)) {\n continue\n }\n for (const gen of batch) {\n const msg = (gen as Record<string, unknown> | null)?.message as\n | Record<string, unknown>\n | undefined\n if (!msg || typeof msg !== \"object\") {\n continue\n }\n const responseMetadata = msg.response_metadata as\n | Record<string, unknown>\n | undefined\n const usage =\n normalizeTokenUsage(msg.usage_metadata) ??\n normalizeTokenUsage(responseMetadata?.token_usage) ??\n normalizeTokenUsage(responseMetadata?.usage) ??\n normalizeTokenUsage(responseMetadata?.tokenUsage)\n if (!usage) {\n continue\n }\n found = true\n addUsage(totals, usage)\n }\n }\n return found ? totals : null\n}\n\n/**\n * Extract token usage from an LLM result.\n *\n * Resolution order: per-generation `message.usage_metadata` (normalized,\n * provider-agnostic), then `message.response_metadata` token usage, then the\n * legacy `llmOutput.tokenUsage` / `token_usage` / `usage` location. Fields\n * with no provider-reported value are omitted; nothing is ever estimated.\n */\nfunction extractUsage(\n output: Record<string, unknown>,\n): Record<string, unknown> {\n const generations = output.generations as unknown[][] | undefined\n const llmOutput = (output.llmOutput ?? output.llm_output) as\n | Record<string, unknown>\n | undefined\n\n const normalized =\n usageFromGenerations(generations) ??\n normalizeTokenUsage(llmOutput?.tokenUsage) ??\n normalizeTokenUsage(llmOutput?.token_usage) ??\n normalizeTokenUsage(llmOutput?.usage)\n\n const usage: Record<string, unknown> = {}\n if (!normalized) {\n return usage\n }\n if (normalized.inputTokens !== null) {\n usage.inputTokens = normalized.inputTokens\n }\n if (normalized.outputTokens !== null) {\n usage.outputTokens = normalized.outputTokens\n }\n if (normalized.totalTokens !== null) {\n usage.totalTokens = normalized.totalTokens\n }\n if (normalized.cachedInputTokens !== null) {\n usage.cachedInputTokens = normalized.cachedInputTokens\n }\n\n return usage\n}\n\nfunction extractLangGraphMetadata(\n metadata: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n if (!metadata) {\n return {}\n }\n const result: Record<string, unknown> = {}\n for (const key of LANGGRAPH_METADATA_KEYS) {\n if (key in metadata) {\n result[key] = metadata[key]\n }\n }\n return result\n}\n\n/**\n * LangChain/LangGraph callback handler that sends traces to Bitfab.\n *\n * Duck-typed to match LangChain.js's BaseCallbackHandler, so no\n * `@langchain/core` dependency is required. Pass as a callback:\n *\n * ```typescript\n * const handler = bitfab.getLangGraphCallbackHandler(\"my-agent\");\n * const result = await agent.invoke(\n * { messages: [...] },\n * { callbacks: [handler] },\n * );\n * ```\n */\nexport class BitfabLangGraphCallbackHandler {\n name = \"BitfabLangGraphCallbackHandler\"\n\n ignoreRetry = true\n // Retriever callbacks ARE captured (retriever queries -> function spans).\n ignoreRetriever = false\n ignoreCustomEvent = true\n\n private readonly httpClient: HttpClient\n private readonly ownsHttpClient: boolean\n private readonly traceFunctionKey: string\n private readonly getActiveSpanContext: (() => ActiveSpanContext | null) | null\n private readonly captureTools: boolean\n\n private runToSpan: Map<string, SpanInfo> = new Map()\n private invocations: Map<string, InvocationState> = new Map()\n\n constructor(config: {\n apiKey?: ApiKeyInput\n traceFunctionKey: string\n serviceUrl?: string\n timeout?: number\n getActiveSpanContext?: () => ActiveSpanContext | null\n /** Whether callback tool events should emit spans. Defaults to true. */\n captureTools?: boolean\n /**\n * The owning `Bitfab` client's HTTP client. Supplied by\n * `getLangGraphCallbackHandler()` so this handler shares that client's\n * single span-transport worker instead of starting a second one.\n * @internal\n */\n _httpClient?: HttpClient\n }) {\n this.ownsHttpClient = config._httpClient === undefined\n this.httpClient =\n config._httpClient ??\n new HttpClient({\n apiKey: config.apiKey,\n serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,\n timeout: config.timeout ?? 10000,\n })\n this.traceFunctionKey = config.traceFunctionKey\n this.getActiveSpanContext = config.getActiveSpanContext ?? null\n this.captureTools = config.captureTools ?? true\n }\n\n /**\n * Flush and release the span transport this handler started. A no-op when\n * the handler borrowed a `Bitfab` client's HTTP client: that client's\n * `close()` owns the worker's lifetime.\n */\n async close(timeoutMs?: number): Promise<boolean> {\n return this.ownsHttpClient ? this.httpClient.close(timeoutMs) : true\n }\n\n // ── lifecycle helpers ──────────────────────────────────────────\n\n private startSpan(\n runId: string,\n parentRunId: string | undefined,\n name: string,\n spanType: string,\n inputData?: unknown,\n metadata?: Record<string, unknown>,\n tags?: string[],\n ): SpanInfo {\n // If we have a tracked parent, inherit its invocation. Otherwise this\n // callback is the root of a fresh invocation: capture the outer Bitfab\n // span context now so concurrent invocations don't overwrite each other.\n const parentSpan = parentRunId ? this.runToSpan.get(parentRunId) : undefined\n const willHide = tags?.includes(LANGSMITH_HIDDEN_TAG) === true\n\n let invocation: InvocationState\n let effectiveParentId: string | null\n let isRootInvocation = false\n if (parentSpan) {\n const existing = this.invocations.get(parentSpan.rootRunId)\n if (existing) {\n invocation = existing\n } else {\n invocation = {\n traceId: parentSpan.traceId,\n activeContext: null,\n rootRunId: parentSpan.rootRunId,\n }\n this.invocations.set(invocation.rootRunId, invocation)\n }\n // Hidden callbacks stay local for parent resolution. Walk visible spans\n // to the nearest submitted ancestor so the stored tree has no orphan.\n if (!willHide) {\n let resolved: SpanInfo | undefined = parentSpan\n while (resolved?.hidden === true) {\n resolved = resolved.parentId\n ? this.runToSpan.get(resolved.parentId)\n : undefined\n }\n effectiveParentId = resolved\n ? resolved.spanId\n : (invocation.activeContext?.spanId ?? null)\n } else {\n effectiveParentId = parentRunId ?? null\n }\n } else {\n const activeContext = this.getActiveSpanContext?.() ?? null\n invocation = {\n traceId: activeContext ? activeContext.traceId : randomUuid(),\n activeContext,\n rootRunId: runId,\n }\n this.invocations.set(runId, invocation)\n effectiveParentId = activeContext?.spanId ?? null\n isRootInvocation = true\n }\n\n const lgMetadata = extractLangGraphMetadata(metadata)\n const contexts: Array<Record<string, unknown>> =\n Object.keys(lgMetadata).length > 0 ? [lgMetadata] : []\n\n const { safe: safeInput, dropped: inputDropped } =\n toJsonSafeReport(inputData)\n const spanInfo: SpanInfo = {\n id: randomUuid(),\n spanId: runId,\n traceId: invocation.traceId,\n rootRunId: invocation.rootRunId,\n parentId: effectiveParentId,\n startedAt: nowIso(),\n name,\n type: spanType,\n input: safeInput,\n contexts,\n }\n if (inputDropped.length > 0) {\n spanInfo.dropped = [...inputDropped]\n }\n if (willHide) {\n spanInfo.hidden = true\n }\n this.runToSpan.set(runId, spanInfo)\n if (isRootInvocation) {\n this.sendTraceStart(spanInfo)\n }\n return spanInfo\n }\n\n private completeSpan(\n runId: string,\n output?: unknown,\n error?: string,\n extraContexts?: Record<string, unknown>,\n ): void {\n const spanInfo = this.runToSpan.get(runId)\n if (!spanInfo) {\n return\n }\n this.runToSpan.delete(runId)\n\n spanInfo.endedAt = nowIso()\n const { safe: safeOutput, dropped: outputDropped } =\n toJsonSafeReport(output)\n spanInfo.output = safeOutput\n if (outputDropped.length > 0) {\n spanInfo.dropped = [...(spanInfo.dropped ?? []), ...outputDropped]\n }\n if (error !== undefined) {\n spanInfo.error = error\n }\n\n if (extraContexts && Object.keys(extraContexts).length > 0) {\n spanInfo.contexts.push(extraContexts)\n }\n\n if (spanInfo.hidden !== true) {\n this.sendSpan(spanInfo)\n }\n\n if (runId === spanInfo.rootRunId) {\n const invocation = this.invocations.get(runId)\n this.sendTraceCompletion(spanInfo, invocation?.activeContext ?? null)\n this.invocations.delete(runId)\n }\n }\n\n private sendSpan(spanInfo: SpanInfo): void {\n const spanData: Record<string, unknown> = {\n name: spanInfo.name,\n type: spanInfo.type,\n }\n if (spanInfo.input !== undefined) {\n spanData.input = spanInfo.input\n }\n if (spanInfo.output !== undefined) {\n spanData.output = spanInfo.output\n }\n if (spanInfo.error !== undefined) {\n spanData.error = spanInfo.error\n }\n if (spanInfo.contexts.length > 0) {\n spanData.contexts = spanInfo.contexts\n }\n const rawSpan: Record<string, unknown> = {\n id: spanInfo.spanId,\n trace_id: spanInfo.traceId,\n started_at: spanInfo.startedAt,\n ended_at: spanInfo.endedAt ?? nowIso(),\n span_data: spanData,\n }\n if (spanInfo.parentId !== null) {\n rawSpan.parent_id = spanInfo.parentId\n }\n\n const payload: Record<string, unknown> = {\n id: spanInfo.id,\n traceId: spanInfo.traceId,\n type: \"sdk-function\",\n source: \"typescript-sdk-langgraph\",\n traceFunctionKey: this.traceFunctionKey,\n sourceTraceId: spanInfo.traceId,\n rawSpan,\n }\n\n // Sanitize the whole span and mark a lossy capture non-replayable.\n // spanInfo.dropped carries losses from the capture-time input/output\n // snapshot above.\n const finalized = finalizeSpanPayload(payload, spanInfo.dropped)\n\n try {\n this.httpClient.sendExternalSpan(finalized)\n } catch {\n // Never crash the host app\n }\n }\n\n private sendTraceCompletion(\n rootSpan: SpanInfo,\n activeContext: ActiveSpanContext | null,\n ): void {\n const completed = activeContext === null\n\n const traceData: Record<string, unknown> = {\n id: rootSpan.traceId,\n type: \"sdk-function\",\n source: \"typescript-sdk-langgraph\",\n traceFunctionKey: this.traceFunctionKey,\n externalTrace: {\n id: rootSpan.traceId,\n started_at: rootSpan.startedAt,\n ended_at: rootSpan.endedAt ?? nowIso(),\n },\n completed,\n }\n\n const finalized = finalizeTracePayload(traceData)\n\n try {\n this.httpClient.sendExternalTrace(finalized)\n } catch {\n // Never crash the host app\n }\n }\n\n private sendTraceStart(rootSpan: SpanInfo): void {\n const traceData: Record<string, unknown> = {\n id: rootSpan.traceId,\n type: \"sdk-function\",\n source: \"typescript-sdk-langgraph\",\n traceFunctionKey: this.traceFunctionKey,\n externalTrace: {\n id: rootSpan.traceId,\n started_at: rootSpan.startedAt,\n },\n completed: false,\n }\n\n const finalized = finalizeTracePayload(traceData)\n\n try {\n this.httpClient.sendExternalTrace(finalized)\n } catch {\n // Never crash the host app\n }\n }\n\n // ── chain callbacks (graph nodes) ─────────────────────────────\n\n async handleChainStart(\n chain: Record<string, unknown> | null | undefined,\n inputs: Record<string, unknown>,\n runId: string,\n parentRunIdOrRunType?: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n runTypeOrRunName?: string,\n runNameOrParentRunId?: string,\n ): Promise<void> {\n try {\n const { parentRunId, runName } = normalizeChainStartArgs(\n parentRunIdOrRunType,\n runTypeOrRunName,\n runNameOrParentRunId,\n )\n const serialized = chain ?? {}\n const idArr = serialized.id as string[] | undefined\n const name =\n runName ??\n (serialized.name as string) ??\n idArr?.[idArr.length - 1] ??\n \"chain\"\n this.startSpan(\n runId,\n parentRunId,\n String(name),\n \"agent\",\n inputs,\n metadata,\n tags,\n )\n } catch {\n // Never crash the host app\n }\n }\n\n async handleChainEnd(\n outputs: Record<string, unknown>,\n runId: string,\n ): Promise<void> {\n try {\n this.completeSpan(runId, outputs)\n } catch {\n // Never crash the host app\n }\n }\n\n async handleChainError(error: unknown, runId: string): Promise<void> {\n try {\n const errorObj = error as { constructor?: { name?: string } }\n if (errorObj?.constructor?.name === \"GraphBubbleUp\") {\n this.completeSpan(runId, undefined, undefined)\n return\n }\n this.completeSpan(\n runId,\n undefined,\n error instanceof Error ? error.message : String(error),\n )\n } catch {\n // Never crash the host app\n }\n }\n\n // ── LLM callbacks ─────────────────────────────────────────────\n\n async handleChatModelStart(\n llm: Record<string, unknown> | null | undefined,\n messages: unknown[][],\n runId: string,\n parentRunId?: string,\n _extraParams?: Record<string, unknown>,\n tags?: string[],\n metadata?: Record<string, unknown>,\n runName?: string,\n ): Promise<void> {\n try {\n const serialized = llm ?? {}\n const model = extractModelName(serialized, metadata)\n const idArr = serialized.id as string[] | undefined\n const name = runName ?? model ?? idArr?.[idArr.length - 1] ?? \"llm\"\n const converted = messages.map((batch) => batch.map(convertMessage))\n\n const spanInfo = this.startSpan(\n runId,\n parentRunId,\n String(name),\n \"llm\",\n converted,\n metadata,\n tags,\n )\n spanInfo.model = model\n } catch {\n // Never crash the host app\n }\n }\n\n async handleLLMStart(\n llm: Record<string, unknown> | null | undefined,\n prompts: string[],\n runId: string,\n parentRunId?: string,\n _extraParams?: Record<string, unknown>,\n tags?: string[],\n metadata?: Record<string, unknown>,\n runName?: string,\n ): Promise<void> {\n try {\n const serialized = llm ?? {}\n const model = extractModelName(serialized, metadata)\n const idArr = serialized.id as string[] | undefined\n const name = runName ?? model ?? idArr?.[idArr.length - 1] ?? \"llm\"\n\n const spanInfo = this.startSpan(\n runId,\n parentRunId,\n String(name),\n \"llm\",\n prompts,\n metadata,\n tags,\n )\n spanInfo.model = model\n } catch {\n // Never crash the host app\n }\n }\n\n async handleLLMEnd(\n output: Record<string, unknown>,\n runId: string,\n ): Promise<void> {\n try {\n let llmOutput: unknown\n const generations = output.generations as unknown[][] | undefined\n if (generations?.length && generations[generations.length - 1]?.length) {\n const gen = generations[generations.length - 1][\n generations[generations.length - 1].length - 1\n ] as Record<string, unknown>\n const msg = gen.message as Record<string, unknown> | undefined\n llmOutput = msg ? convertMessage(msg) : (gen.text ?? String(gen))\n }\n\n const usage = extractUsage(output)\n const spanInfo = this.runToSpan.get(runId)\n const model = spanInfo?.model\n\n const llmContext: Record<string, unknown> = {}\n if (model) {\n llmContext.model = model\n }\n Object.assign(llmContext, usage)\n\n this.completeSpan(\n runId,\n llmOutput,\n undefined,\n Object.keys(llmContext).length > 0 ? llmContext : undefined,\n )\n } catch {\n // Never crash the host app\n }\n }\n\n async handleLLMError(error: unknown, runId: string): Promise<void> {\n try {\n this.completeSpan(\n runId,\n undefined,\n error instanceof Error ? error.message : String(error),\n )\n } catch {\n // Never crash the host app\n }\n }\n\n async handleLLMNewToken(): Promise<void> {\n // Intentionally empty: per-token events are not traced. Usage for\n // streaming runs is captured in handleLLMEnd from the final aggregated\n // chunk's usage_metadata / response_metadata.\n }\n\n // ── tool callbacks ────────────────────────────────────────────\n\n async handleToolStart(\n tool: Record<string, unknown> | null | undefined,\n input: string,\n runId: string,\n parentRunId?: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n runName?: string,\n ): Promise<void> {\n if (!this.captureTools) {\n return\n }\n try {\n const serialized = tool ?? {}\n const name = runName ?? (serialized.name as string) ?? \"tool\"\n this.startSpan(\n runId,\n parentRunId,\n String(name),\n \"function\",\n input,\n metadata,\n tags,\n )\n } catch {\n // Never crash the host app\n }\n }\n\n async handleToolEnd(output: unknown, runId: string): Promise<void> {\n if (!this.captureTools) {\n return\n }\n try {\n this.completeSpan(runId, output)\n } catch {\n // Never crash the host app\n }\n }\n\n async handleToolError(error: unknown, runId: string): Promise<void> {\n if (!this.captureTools) {\n return\n }\n try {\n this.completeSpan(\n runId,\n undefined,\n error instanceof Error ? error.message : String(error),\n )\n } catch {\n // Never crash the host app\n }\n }\n\n // ── retriever callbacks ───────────────────────────────────────\n\n async handleRetrieverStart(\n retriever: Record<string, unknown> | null | undefined,\n query: string,\n runId: string,\n parentRunId?: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n runName?: string,\n ): Promise<void> {\n try {\n const serialized = retriever ?? {}\n const name = runName ?? (serialized.name as string) ?? \"retriever\"\n this.startSpan(\n runId,\n parentRunId,\n String(name),\n \"function\",\n query,\n metadata,\n tags,\n )\n } catch {\n // Never crash the host app\n }\n }\n\n async handleRetrieverEnd(documents: unknown, runId: string): Promise<void> {\n try {\n this.completeSpan(runId, documents)\n } catch {\n // Never crash the host app\n }\n }\n\n async handleRetrieverError(error: unknown, runId: string): Promise<void> {\n try {\n this.completeSpan(\n runId,\n undefined,\n error instanceof Error ? error.message : String(error),\n )\n } catch {\n // Never crash the host app\n }\n }\n}\n","import { BitfabError } from \"./http.js\"\nimport type { BitfabLangGraphCallbackHandler } from \"./langgraph.js\"\nimport { importOptionalPeer } from \"./optionalPeer.js\"\nimport { getReplayContext } from \"./replayContext.js\"\n\nconst TOOL_RESULT_TAG = \"__bitfabLangGraphToolResult\"\n\ntype ToolMessageContent = string | Array<Record<string, unknown>>\n\ninterface ToolMessageFields {\n content: ToolMessageContent\n tool_call_id: string\n name?: string\n id?: string\n status?: \"success\" | \"error\"\n artifact?: unknown\n metadata?: Record<string, unknown>\n additional_kwargs?: Record<string, unknown>\n response_metadata?: Record<string, unknown>\n}\n\ninterface ToolMessageConstructor {\n new (fields: ToolMessageFields): unknown\n}\n\ninterface CommandConstructor {\n new (fields: {\n graph?: string\n update?: unknown\n resume?: unknown\n goto?: unknown\n }): unknown\n}\n\ninterface LangChainCoreRuntime {\n ToolMessage: ToolMessageConstructor\n}\n\ninterface LangGraphRuntime {\n Command: CommandConstructor\n}\n\ninterface SpanClient {\n withSpan<TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n options: {\n name?: string\n type?: \"agent\" | \"function\"\n captureWhen?: \"always\" | \"nested\"\n mockOnReplay?: boolean\n finalize?: (result: unknown) => unknown | Promise<unknown>\n surface?: \"inherit\"\n },\n fn: (...args: TArgs) => TReturn,\n ): (...args: TArgs) => TReturn\n}\n\ninterface LangGraphTool {\n readonly name?: string\n invoke(input: unknown, ...rest: unknown[]): unknown\n}\n\ninterface ConfiguredLangGraphRunnable<TInput, TConfig, TReturn> {\n invoke(input: TInput, config?: TConfig): TReturn\n}\n\ninterface LangGraphRunnable<TInput, TConfig, TReturn> {\n withConfig(config: {\n callbacks: unknown[]\n }): ConfiguredLangGraphRunnable<TInput, TConfig, TReturn>\n}\n\ninterface EncodedToolMessage extends Record<string, unknown> {\n [TOOL_RESULT_TAG]: \"tool-message\"\n content: ToolMessageContent\n}\n\ninterface EncodedCommand extends Record<string, unknown> {\n [TOOL_RESULT_TAG]: \"command\"\n graph?: string\n update?: unknown\n resume?: unknown\n goto?: unknown\n}\n\ntype EncodedToolResult = EncodedToolMessage | EncodedCommand\n\n/**\n * Options for first-class LangGraph ToolNode replay interception.\n *\n * @experimental This API may change before it is stable.\n */\nexport interface LangGraphIntegrationOptions {\n /**\n * Tools marked for recorded-output mocking under replay's default\n * `mock: \"marked\"` strategy. Defaults to every wrapped tool. Pass a list to\n * mark only those tool names, or `false` to require `mock: \"all\"` or an\n * override.\n */\n mockToolsOnReplay?: boolean | readonly string[]\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null\n}\n\nfunction isToolMessage(value: unknown): value is Record<string, unknown> & {\n content: ToolMessageContent\n} {\n return (\n isRecord(value) &&\n value.lc_direct_tool_output === true &&\n value.type === \"tool\" &&\n (typeof value.content === \"string\" || Array.isArray(value.content))\n )\n}\n\nfunction isCommand(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && value.lg_name === \"Command\"\n}\n\nfunction encodeNested(value: unknown): unknown {\n if (isToolMessage(value) || isCommand(value)) {\n return encodeNativeToolResult(value)\n }\n if (Array.isArray(value)) {\n return value.map(encodeNested)\n }\n if (isRecord(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [key, encodeNested(entry)]),\n )\n }\n return value\n}\n\nfunction encodeNativeToolResult(value: unknown): EncodedToolResult {\n if (isToolMessage(value)) {\n return {\n [TOOL_RESULT_TAG]: \"tool-message\",\n content: value.content,\n name: typeof value.name === \"string\" ? value.name : undefined,\n id: typeof value.id === \"string\" ? value.id : undefined,\n status:\n value.status === \"success\" || value.status === \"error\"\n ? value.status\n : undefined,\n artifact: encodeNested(value.artifact),\n metadata: encodeNested(value.metadata),\n additionalKwargs: encodeNested(value.additional_kwargs),\n responseMetadata: encodeNested(value.response_metadata),\n }\n }\n\n return {\n [TOOL_RESULT_TAG]: \"command\",\n graph:\n isRecord(value) && typeof value.graph === \"string\"\n ? value.graph\n : undefined,\n update: isRecord(value) ? encodeNested(value.update) : undefined,\n resume: isRecord(value) ? encodeNested(value.resume) : undefined,\n goto: isRecord(value) ? encodeNested(value.goto) : undefined,\n }\n}\n\nfunction finalizeToolResult(value: unknown): unknown {\n return isToolMessage(value) || isCommand(value)\n ? encodeNativeToolResult(value)\n : value\n}\n\nfunction isEncodedToolResult(value: unknown): value is EncodedToolResult {\n return isRecord(value) && typeof value[TOOL_RESULT_TAG] === \"string\"\n}\n\nasync function loadLangChainCore(): Promise<LangChainCoreRuntime> {\n try {\n return await importOptionalPeer<LangChainCoreRuntime>([\n \"@langchain\",\n \"core\",\n \"messages\",\n ])\n } catch {\n throw new BitfabError(\n \"LangGraph tool replay requires @langchain/core. Install @langchain/langgraph before using getLangGraphIntegration().\",\n \"https://docs.bitfab.ai/frameworks/langgraph\",\n )\n }\n}\n\nasync function loadLangGraph(): Promise<LangGraphRuntime> {\n try {\n return await importOptionalPeer<LangGraphRuntime>([\n \"@langchain\",\n \"langgraph\",\n ])\n } catch {\n throw new BitfabError(\n \"Replaying a LangGraph Command requires @langchain/langgraph.\",\n \"https://docs.bitfab.ai/frameworks/langgraph\",\n )\n }\n}\n\nasync function reviveNested(\n value: unknown,\n toolCallId: string,\n): Promise<unknown> {\n if (isEncodedToolResult(value)) {\n return reviveToolResult(value, toolCallId)\n }\n if (Array.isArray(value)) {\n return Promise.all(value.map((entry) => reviveNested(entry, toolCallId)))\n }\n if (isRecord(value)) {\n const entries = await Promise.all(\n Object.entries(value).map(async ([key, entry]) => [\n key,\n await reviveNested(entry, toolCallId),\n ]),\n )\n return Object.fromEntries(entries)\n }\n return value\n}\n\nasync function reviveToolResult(\n value: EncodedToolResult,\n toolCallId: string,\n): Promise<unknown> {\n if (value[TOOL_RESULT_TAG] === \"tool-message\") {\n const { ToolMessage } = await loadLangChainCore()\n return new ToolMessage({\n content: value.content,\n tool_call_id: toolCallId,\n ...(typeof value.name === \"string\" && { name: value.name }),\n ...(typeof value.id === \"string\" && { id: value.id }),\n ...((value.status === \"success\" || value.status === \"error\") && {\n status: value.status,\n }),\n ...(value.artifact !== undefined && {\n artifact: await reviveNested(value.artifact, toolCallId),\n }),\n ...(isRecord(value.metadata) && {\n metadata: await reviveNested(value.metadata, toolCallId),\n }),\n ...(isRecord(value.additionalKwargs) && {\n additional_kwargs: await reviveNested(\n value.additionalKwargs,\n toolCallId,\n ),\n }),\n ...(isRecord(value.responseMetadata) && {\n response_metadata: await reviveNested(\n value.responseMetadata,\n toolCallId,\n ),\n }),\n } as ToolMessageFields)\n }\n\n const { Command } = await loadLangGraph()\n return new Command({\n ...(typeof value.graph === \"string\" && { graph: value.graph }),\n ...(value.update !== undefined && {\n update: await reviveNested(value.update, toolCallId),\n }),\n ...(value.resume !== undefined && {\n resume: await reviveNested(value.resume, toolCallId),\n }),\n ...(value.goto !== undefined && {\n goto: await reviveNested(value.goto, toolCallId),\n }),\n })\n}\n\n/**\n * First-class LangGraph integration for callback tracing and replayable\n * `ToolNode` tools.\n *\n * @experimental This API may change before it is stable.\n */\nexport class BitfabLangGraphIntegration {\n /** Callback handler for the compiled graph's invocation config. */\n // biome-ignore lint/suspicious/noExplicitAny: avoids leaking an optional peer's declarations into every SDK consumer\n readonly callbackHandler: any\n\n private readonly client: SpanClient\n private readonly traceFunctionKey: string\n private readonly mockToolsOnReplay: boolean | readonly string[]\n\n constructor(config: {\n client: SpanClient\n traceFunctionKey: string\n callbackHandler: BitfabLangGraphCallbackHandler\n options?: LangGraphIntegrationOptions\n }) {\n this.client = config.client\n this.traceFunctionKey = config.traceFunctionKey\n this.callbackHandler = config.callbackHandler\n this.mockToolsOnReplay = config.options?.mockToolsOnReplay ?? true\n }\n\n /**\n * Wrap tools before passing the same returned array to both\n * `model.bindTools()` and `new ToolNode()`. Each invocation becomes an\n * independently mockable child span.\n */\n wrapTools<T extends readonly LangGraphTool[]>(tools: T): T {\n return tools.map((tool) => this.wrapTool(tool)) as unknown as T\n }\n\n /**\n * Create the normal graph entry point. The returned function adds Bitfab's\n * callback handler, preserves invocation config, and records only the graph\n * input as the replayable root input.\n *\n * @experimental This API may change before it is stable.\n */\n createInvoker<TInput, TConfig, TReturn>(\n graph: LangGraphRunnable<TInput, TConfig, TReturn>,\n ): (input: TInput, config?: TConfig) => TReturn {\n const configuredGraph = graph.withConfig({\n callbacks: [this.callbackHandler],\n })\n\n return (input, config) => {\n const invoke = this.wrapInvoke((rootInput: TInput) =>\n configuredGraph.invoke(rootInput, config),\n )\n return invoke(input)\n }\n }\n\n private wrapTool<T extends LangGraphTool>(tool: T): T {\n const toolName = tool.name\n if (typeof toolName !== \"string\" || toolName.length === 0) {\n throw new BitfabError(\n \"LangGraph replayable tools must have a name.\",\n \"https://docs.bitfab.ai/frameworks/langgraph\",\n )\n }\n\n const mockToolsOnReplay = this.mockToolsOnReplay\n const shouldMock =\n typeof mockToolsOnReplay === \"boolean\"\n ? mockToolsOnReplay\n : mockToolsOnReplay.includes(toolName)\n const originalInvoke = tool.invoke.bind(tool)\n\n return new Proxy(tool, {\n get: (target, property) => {\n if (property === \"invoke\") {\n return async (input: unknown, ...rest: unknown[]) => {\n const toolCallId =\n isRecord(input) && typeof input.id === \"string\" ? input.id : \"\"\n const args = isRecord(input) && \"args\" in input ? input.args : input\n this.assertReplayToolResultExists(toolName, shouldMock)\n const execute = this.client.withSpan(\n this.traceFunctionKey,\n {\n name: toolName,\n type: \"function\",\n captureWhen: \"nested\",\n mockOnReplay: shouldMock,\n finalize: finalizeToolResult,\n surface: \"inherit\",\n },\n async (_args: unknown) => await originalInvoke(input, ...rest),\n )\n const result = await execute(args)\n return isEncodedToolResult(result)\n ? await reviveToolResult(result, toolCallId)\n : result\n }\n }\n\n const value = Reflect.get(target, property, target)\n return typeof value === \"function\" ? value.bind(target) : value\n },\n })\n }\n\n private assertReplayToolResultExists(\n toolName: string,\n shouldMock: boolean,\n ): void {\n const replayContext = getReplayContext()\n if (!replayContext?.mockTree) {\n return\n }\n\n const counterKey = `${this.traceFunctionKey}:${toolName}`\n const callIndex = replayContext.callCounters?.get(counterKey) ?? 0\n const mockSpan = replayContext.mockTree.spans.get(\n `${counterKey}:${callIndex}`,\n )\n const hasMatchingOverride = replayContext.mockOverrides?.some((override) =>\n override.match({\n traceFunctionKey: this.traceFunctionKey,\n spanName: toolName,\n type: \"function\",\n originalSpanId: mockSpan?.sourceSpanId,\n }),\n )\n const expectsRecordedOutput =\n replayContext.mockStrategy === \"all\" ||\n (replayContext.mockStrategy === \"marked\" && shouldMock)\n\n if (hasMatchingOverride !== true && expectsRecordedOutput && !mockSpan) {\n throw new BitfabError(\n `No recorded LangGraph tool result for \"${toolName}\" at call ${callIndex + 1}; refusing to execute the live tool during replay.`,\n \"https://docs.bitfab.ai/frameworks/langgraph\",\n )\n }\n }\n\n /** Wrap the function that invokes the compiled graph as the replay root. */\n wrapInvoke<TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => TReturn,\n ): (...args: TArgs) => TReturn {\n return this.client.withSpan(\n this.traceFunctionKey,\n { name: this.traceFunctionKey, type: \"agent\", surface: \"inherit\" },\n fn,\n )\n }\n}\n","/**\n * OpenAI Agents SDK handler for Bitfab tracing.\n *\n * The OpenAI Agents SDK is instrumented in two layers:\n *\n * 1. A process-wide `TracingProcessor` (see `getOpenAiTracingProcessor` /\n * `BitfabOpenAITracingProcessor`) registered once with `addTraceProcessor`.\n * It captures everything *inside* a run - LLM calls, tool calls, handoffs -\n * as Bitfab spans.\n * 2. This handler's `wrapRun`, which owns the *root*. The processor never sees\n * the caller's input (the SDK's trace events don't carry it), so a\n * processor-only run records a root span with an empty input and is not\n * replayable. `wrapRun` is a thin drop-in for `run()` that opens a\n * `withSpan` root carrying the input and final output, so the run is\n * replayable with no hand-written `withSpan`. The processor's spans nest\n * underneath it automatically (it remaps onto the active span context).\n *\n * When `wrapRun` runs inside an enclosing Bitfab span (the replay auto-wrap, or\n * a caller's own `withSpan`), that span is already the replayable root: the\n * handler skips opening a second one and lets the processor nest the run's spans\n * under the existing root. This mirrors the Claude Agent SDK and LangGraph\n * handlers, which no-op their root span under an enclosing span, and keeps a\n * replayed run's span tree identical to the original (no doubled root agent\n * span).\n *\n * Use both together: register the processor once at startup, then call\n * `handler.wrapRun(agent, input)` instead of `run(agent, input)`.\n */\n\nimport { importOptionalPeer } from \"./optionalPeer.js\"\n\n// Local structural stand-ins for the OpenAI Agents SDK types this handler\n// touches. Declared here so neither this module nor the SDK's published `.d.ts`\n// references `@openai/agents` (an optional peer most consumers never install):\n// a top-level `import ... from \"@openai/agents\"` in the shipped types breaks a\n// consumer's `tsc` under `skipLibCheck: false` even when they never use this\n// handler. The stand-ins are deliberately loose supersets, so a consumer's real\n// `Agent` / run input is still assignable when they DO call `wrapRun`. The\n// concrete `@openai/agents` types enter only inside the function body (via\n// `importOptionalPeer<typeof import(\"@openai/agents\")>`), which the declaration\n// output erases.\n\n// biome-ignore lint/suspicious/noExplicitAny: structural stand-in for the agent SDK's `Agent<any, any>`\ntype AgentLike = any\n\n// The run input union `run()` accepts: a prompt string, a list of input items,\n// or a serialized run state. Items/state are opaque here (we only forward them).\ntype RunInput = string | unknown[] | Record<string, unknown>\n\n// The run options `run()` accepts; only `stream` is read by this handler.\ntype RunOptions = {\n stream?: boolean\n} & Record<string, unknown>\n\n// What this handler reads off a run result: streamed runs expose `completed`,\n// both variants expose `finalOutput`.\ntype RunResultLike = {\n finalOutput?: unknown\n completed?: Promise<void>\n}\n\n// The exact span options this handler passes to `withSpan`. Declared locally\n// (a structural subset of the client's `SpanOptions`, so the bound `withSpan`\n// is assignable) rather than imported from client.ts - that would create an\n// import cycle, since client.ts imports this handler. Mirrors how the other\n// framework handlers stay free of any client import.\ntype RootSpanOptions = {\n type: \"agent\"\n finalize: (result: unknown) => unknown | Promise<unknown>\n surface: \"inherit\"\n}\n\n// The subset of the Bitfab client this handler needs: a bound `withSpan`.\ntype WithSpanFn = <TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n options: RootSpanOptions,\n fn: (...args: TArgs) => TReturn,\n) => (...args: TArgs) => TReturn\n\n// Returns the active Bitfab span context (or null) so wrapRun can detect an\n// enclosing span and skip opening its own root. Only nullness is read, so the\n// context shape is left opaque (avoids importing SpanContext from client.ts,\n// which would create an import cycle).\ntype GetActiveSpanContextFn = () => unknown | null\n\n/**\n * OpenAI Agents SDK handler that records a replayable root span around a run.\n *\n * ```typescript\n * import { Bitfab } from \"@bitfab/sdk\";\n * import { addTraceProcessor, Agent, run } from \"@openai/agents\";\n *\n * const bitfab = new Bitfab({ apiKey: \"...\" });\n * addTraceProcessor(bitfab.getOpenAiTracingProcessor()); // captures internals\n *\n * const agent = new Agent({ name: \"Researcher\", instructions: \"...\" });\n * const handler = bitfab.getOpenAiAgentHandler(\"research-topic\");\n *\n * // Swap run(agent, input) -> handler.wrapRun(agent, input)\n * const result = await handler.wrapRun(agent, \"Find X\");\n * return result.finalOutput;\n * ```\n */\nexport class BitfabOpenAIAgentHandler {\n private readonly traceFunctionKey: string\n private readonly withSpanFn: WithSpanFn\n private readonly getActiveSpanContext?: GetActiveSpanContextFn\n\n constructor(config: {\n traceFunctionKey: string\n withSpan: WithSpanFn\n getActiveSpanContext?: GetActiveSpanContextFn\n }) {\n this.traceFunctionKey = config.traceFunctionKey\n this.withSpanFn = config.withSpan\n this.getActiveSpanContext = config.getActiveSpanContext\n }\n\n /**\n * Drop-in replacement for the OpenAI Agents SDK's `run()` that records a\n * replayable root `agent` span.\n *\n * The `input` is captured as the root span's input (as a single positional\n * argument, so `replay(key, fn)` re-feeds it), and the run's `finalOutput`\n * is recorded as the root output. For streaming runs (`{ stream: true }`),\n * the result is handed back immediately and the final output is recorded\n * once the stream completes - first-byte latency is untouched.\n *\n * The process-wide tracing processor (`getOpenAiTracingProcessor`) must still\n * be registered: it captures the LLM/tool/handoff spans that nest beneath\n * this root.\n */\n async wrapRun(\n agent: AgentLike,\n input: RunInput,\n options?: RunOptions,\n ): Promise<RunResultLike> {\n // Dynamic import keeps `@openai/agents` an optional peer dependency and\n // matches the SDK's browser-safe import rules (no static Node/agent SDK\n // imports). Callers of this handler necessarily have the package installed.\n // Routed through `importOptionalPeer` so the specifier never appears as a\n // literal - otherwise a consumer's bundler tries to resolve `@openai/agents`\n // at build time and fails even when they never use this handler.\n const { run } = await importOptionalPeer<typeof import(\"@openai/agents\")>([\n \"@openai\",\n \"agents\",\n ])\n\n // The local stand-in types are looser than `run()`'s real parameters, so\n // cast at the call boundary. These casts live in the function body, which\n // the declaration output erases, so no `@openai/agents` reference leaks\n // into the published `.d.ts`.\n type RunInputArg = Parameters<typeof run>[1]\n type RunOptionsArg = Parameters<typeof run>[2]\n\n // An enclosing span is already the replayable root: run directly and let the\n // processor nest the run's spans under it, instead of opening (and doubling)\n // a second root agent span. Covers the replay auto-wrap and a caller's own\n // withSpan; mirrors the Claude Agent SDK and LangGraph handlers.\n if (this.getActiveSpanContext?.() != null) {\n return run(\n agent,\n input as RunInputArg,\n options as RunOptionsArg,\n ) as Promise<RunResultLike>\n }\n\n const isStreaming = options?.stream === true\n\n // The recorded output is the run's final answer, not the (non-serializable)\n // result object. `finalize` records it without disturbing the caller's\n // return value; for streaming it also waits for the stream to drain so the\n // final output is present before the span is recorded.\n const finalize = async (result: unknown): Promise<unknown> => {\n const res = result as RunResultLike | null\n if (isStreaming && res?.completed) {\n try {\n await res.completed\n } catch {\n // Stream errors surface to the caller; the span still records what\n // final output is available rather than crashing finalize.\n }\n }\n return res?.finalOutput\n }\n\n const options_: RootSpanOptions = {\n type: \"agent\",\n finalize,\n surface: \"inherit\",\n }\n\n // Wrap a function that TAKES the input as its argument and call it with the\n // input, so withSpan records `[input]` as the root span input. run() runs\n // inside the withSpan context, so the tracing processor's onTraceStart sees\n // this root and nests the run's internal spans beneath it.\n const traced = this.withSpanFn(\n this.traceFunctionKey,\n options_,\n (agentInput: RunInput) =>\n run(\n agent,\n agentInput as RunInputArg,\n options as RunOptionsArg,\n ) as Promise<RunResultLike>,\n )\n\n return traced(input)\n }\n}\n","/**\n * The database branch a single replay item runs against.\n *\n * `getCurrentReplayBranch()` hands you one inside a replayed function when the\n * source trace carried a DB snapshot reference and the Bitfab service resolved\n * a branch from it. Outside a replay item, or when no branch was resolved, that\n * accessor returns null and your code keeps reading `process.env.DATABASE_URL`\n * the normal way.\n *\n * Immutable and scoped to one item: the accessor builds it from the replay\n * AsyncLocalStorage context, so parallel replay items each see their own branch\n * and no lease state lives on a long-lived object.\n *\n * Internally the resolved per-item state is a `DbBranchLease` (see\n * replayContext.ts), the SDK/server protocol term. Its useful fields are\n * exposed directly here so customer code never sees the word.\n */\n\nimport type { DbBranchLease, ReplayContext } from \"./replayContext.js\"\n\nexport class ReplayBranch implements Omit<DbBranchLease, \"databaseUrl\"> {\n /** The provider's own id for this branch, e.g. for correlating with its console. */\n declare readonly neonBranchId: string\n /** Env var name the customer's app reads, e.g. `DATABASE_URL`. */\n declare readonly envKey: string\n /** When this branch's URL stops being valid. ISO-8601. */\n declare readonly expiresAt: string\n /**\n * The instant this branch is pinned to: the source trace's wall clock, read\n * just before the traced function ran. Compare it against the trace you meant\n * to replay to confirm the branch is the right point in history.\n */\n declare readonly snapshotTimestamp?: string\n /** Deep link to the branch in the provider console, if available. */\n declare readonly providerConsoleUrl?: string\n /**\n * True if the branch is read-only. Use it to skip write operations during\n * replay when the provider returned a read-only lease.\n */\n declare readonly readOnly?: boolean\n /**\n * The branch's region, e.g. `aws-us-east-1`. A compute runs in its project's\n * region, so a replay runner elsewhere pays that round trip on every query.\n */\n declare readonly region?: string\n /** The historical trace ID that produced the input for this replay item. */\n declare readonly traceId: string\n\n // Genuine JS private fields, not TypeScript `private`: these must be\n // non-enumerable so neither the connection string nor the whole replay\n // context can ride along into a log line or a serialized payload.\n readonly #url: string\n readonly #context: ReplayContext\n\n /** @internal Built by `getCurrentReplayBranch()`; never constructed by callers. */\n constructor(lease: DbBranchLease, traceId: string, context: ReplayContext) {\n // Copy the lease wholesale minus the connection string, so a field the\n // server starts sending reaches customer code without an SDK release.\n // Everything here must stay a plain data property: `databaseUrl` is the\n // only member allowed to mark the branch as accessed.\n //\n // defineProperty, not Object.assign: assignment runs setters, so a lease\n // carrying a `__proto__` key would swap this object's prototype and leave\n // `databaseUrl` returning undefined, which reads as \"no branch\" and sends\n // the replay to the live database.\n const { databaseUrl, ...exposed } = lease\n for (const [key, value] of Object.entries(exposed)) {\n Object.defineProperty(this, key, {\n value,\n enumerable: true,\n configurable: true,\n })\n }\n Object.defineProperty(this, \"traceId\", {\n value: traceId,\n enumerable: true,\n configurable: true,\n })\n this.#url = databaseUrl\n this.#context = context\n }\n\n /**\n * Connection string for this item's branch. Point your database client at it\n * instead of the live database for the duration of the replayed call.\n *\n * Reading it records on the trace that the replayed code obtained the branch\n * URL, which is what separates \"a branch was provisioned\" from \"the branch\n * was actually used\". The other fields inspect the lease without exposing the\n * connection string, so they deliberately do not record anything. That is\n * also why this is a getter and not a plain field: the URL is absent from\n * `JSON.stringify(branch)` and from logging the object.\n */\n get databaseUrl(): string {\n this.#context.dbSnapshotAccessed = true\n return this.#url\n }\n}\n","import {\n type AsyncLocalStorageLike,\n asyncStorageReady,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\n\nexport interface SeedContext {\n traceId: string\n}\n\nlet seedContextStorage: AsyncLocalStorageLike<SeedContext | null> | null = null\nconst SEED_CONTEXT_STORAGE_SYMBOL = Symbol.for(\"bitfab.seedContextStorage\")\n\nexport const seedContextReady: Promise<void> = asyncStorageReady.then(() => {\n const shared = globalThis as typeof globalThis & Record<symbol, unknown>\n const existing = shared[SEED_CONTEXT_STORAGE_SYMBOL] as\n | AsyncLocalStorageLike<SeedContext | null>\n | undefined\n if (existing) {\n seedContextStorage = existing\n return\n }\n const created = createAsyncLocalStorage<SeedContext | null>()\n if (created) {\n shared[SEED_CONTEXT_STORAGE_SYMBOL] = created\n seedContextStorage = created\n }\n})\n\nexport function getSeedContext(): SeedContext | null {\n return seedContextStorage?.getStore() ?? null\n}\n\nexport function inSeedScope(): boolean {\n return getSeedContext() !== null\n}\n\nexport function runWithSeedContext<T>(ctx: SeedContext, fn: () => T): T {\n if (seedContextStorage) {\n return seedContextStorage.run(ctx, fn)\n }\n return fn()\n}\n","/**\n * Tracing utilities for external trace submission to Bitfab.\n *\n * This module provides utilities for sending external traces (e.g., from OpenAI API calls)\n * to Bitfab for monitoring and analysis.\n */\n\nimport { DEFAULT_SERVICE_URL } from \"./constants.js\"\nimport { type ApiKeyInput, HttpClient } from \"./http.js\"\nimport { finalizeSpanPayload } from \"./processorPayload.js\"\nimport { randomUuid } from \"./randomUuid.js\"\n\n// Minimal structural shapes of the OpenAI Agents SDK's `Trace` and `Span`,\n// declared locally so neither this module nor the SDK's published `.d.ts`\n// references `@openai/agents` - an optional peer many consumers never install.\n// We only touch the fields below; the real SDK objects are structural\n// supersets, so a consumer's `addTraceProcessor(processor)` still type-checks.\ninterface Trace {\n traceId: string\n toJSON(): unknown\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: mirrors the agent SDK's `Span<any>`\ninterface Span<_T = any> {\n traceId?: string\n toJSON(): unknown\n spanData?: {\n type?: string\n _input?: unknown\n _response?: unknown\n } | null\n}\n\nexport interface TraceResponse {\n traceId: string\n status: \"success\"\n}\n\nexport interface ActiveSpanContext {\n traceId: string\n spanId: string\n}\n\n/**\n * TracingProcessor interface from OpenAI Agents SDK v0.3.7\n */\nexport interface TracingProcessor {\n onTraceStart(trace: Trace): Promise<void>\n onTraceEnd(trace: Trace): Promise<void>\n // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data\n onSpanStart(span: Span<any>): Promise<void>\n // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data\n onSpanEnd(span: Span<any>): Promise<void>\n forceFlush(): Promise<void>\n shutdown(timeout?: number): Promise<void>\n}\n\n/**\n * Tracing processor for OpenAI Agents SDK integration.\n *\n * Implements the TracingProcessor interface from the OpenAI Agents SDK to\n * automatically capture traces and spans and send them to Bitfab for\n * monitoring and analysis.\n *\n * Example usage:\n * ```typescript\n * import { Bitfab } from 'bitfab';\n * import { addTraceProcessor } from '@openai/agents';\n *\n * const client = new Bitfab({ apiKey: 'your-api-key' });\n * const processor = client.getOpenAiTracingProcessor();\n * addTraceProcessor(processor);\n * ```\n */\nexport class BitfabOpenAITracingProcessor implements TracingProcessor {\n private readonly httpClient: HttpClient\n private readonly ownsHttpClient: boolean\n private activeTraces: Record<string, Trace> = {}\n private readonly getActiveSpanContext: (() => ActiveSpanContext | null) | null\n private activeSpanMappings: Record<string, ActiveSpanContext> = {}\n private canonicalTraceIds: Record<string, string> = {}\n\n private getCanonicalTraceId(sourceTraceId: string): string {\n const existing = this.canonicalTraceIds[sourceTraceId]\n if (existing) {\n return existing\n }\n\n const created = randomUuid()\n this.canonicalTraceIds[sourceTraceId] = created\n return created\n }\n\n /**\n * Initialize the tracing processor.\n *\n * @param config - Configuration options\n */\n constructor(config: {\n apiKey?: ApiKeyInput\n serviceUrl?: string\n timeout?: number\n getActiveSpanContext?: () => ActiveSpanContext | null\n /**\n * The owning `Bitfab` client's HTTP client. Supplied by\n * `getOpenAiTracingProcessor()` so this processor shares that client's\n * single span-transport worker instead of starting a second one.\n * @internal\n */\n _httpClient?: HttpClient\n }) {\n this.ownsHttpClient = config._httpClient === undefined\n this.httpClient =\n config._httpClient ??\n new HttpClient({\n apiKey: config.apiKey,\n serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,\n timeout: config.timeout ?? 10000,\n })\n this.getActiveSpanContext = config.getActiveSpanContext ?? null\n }\n\n /**\n * Flush and release the span transport this processor started. A no-op when\n * the processor borrowed a `Bitfab` client's HTTP client: that client's\n * `close()` owns the worker's lifetime.\n */\n async close(timeoutMs?: number): Promise<boolean> {\n return this.ownsHttpClient ? this.httpClient.close(timeoutMs) : true\n }\n\n /**\n * Called when a trace is started.\n * If there's an active withSpan context, the trace ID is remapped to the\n * outer trace and sent to pre-create the external_traces row on the server.\n */\n async onTraceStart(trace: Trace): Promise<void> {\n this.activeTraces[trace.traceId] = trace\n\n const activeContext = this.getActiveSpanContext?.()\n if (activeContext) {\n this.activeSpanMappings[trace.traceId] = activeContext\n }\n\n const canonicalTraceId =\n activeContext?.traceId ?? this.getCanonicalTraceId(trace.traceId)\n this.canonicalTraceIds[trace.traceId] = canonicalTraceId\n\n this.sendTrace(trace, {\n id: canonicalTraceId,\n sourceTraceId: activeContext?.traceId,\n })\n }\n\n /**\n * Called when a trace is ended.\n * If mapped to a withSpan trace, sends with remapped ID and completed=false\n * since the parent withSpan handles completion.\n */\n async onTraceEnd(trace: Trace): Promise<void> {\n const mapping = this.activeSpanMappings[trace.traceId]\n\n this.sendTrace(trace, {\n completed: mapping === undefined,\n id: mapping?.traceId ?? this.getCanonicalTraceId(trace.traceId),\n sourceTraceId: mapping?.traceId,\n })\n\n delete this.activeSpanMappings[trace.traceId]\n delete this.canonicalTraceIds[trace.traceId]\n delete this.activeTraces[trace.traceId]\n }\n\n /**\n * Called when a span is started. Span payloads are authoritative completed\n * snapshots, so start notifications do not cross the transport boundary.\n */\n // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data\n async onSpanStart(_span: Span<any>): Promise<void> {}\n\n /**\n * Called when a span is ended.\n *\n * Send the finalized span snapshot to Bitfab for complete trace capture.\n */\n // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data\n async onSpanEnd(span: Span<any>): Promise<void> {\n // Send the completed span to Bitfab (fire-and-forget).\n this.sendSpan(span)\n }\n\n /**\n * Called when a trace is being flushed.\n */\n async forceFlush(): Promise<void> {\n // Spans now enter a buffered transport, so this is no longer a no-op: the\n // agent SDK's own flush would otherwise return while Bitfab spans sit\n // queued, and a run that flushes then exits would lose them.\n await this.httpClient.waitForPendingRequests()\n }\n\n /**\n * Called when the trace processor is shutting down.\n */\n async shutdown(timeout?: number): Promise<void> {\n this.activeTraces = {}\n this.activeSpanMappings = {}\n this.canonicalTraceIds = {}\n // A directly constructed processor owns its transport worker and no\n // Bitfab client will ever close it, so this is its only release point.\n // A borrowed client's worker is left alone (see close()).\n await this.close(timeout)\n }\n\n /**\n * Send trace to Bitfab API (fire-and-forget).\n * When traceIdOverride is provided, the trace ID is remapped to link\n * the OpenAI trace into an outer withSpan trace.\n */\n private sendTrace(\n trace: Trace,\n options: {\n completed?: boolean\n id?: string\n sourceTraceId?: string\n } = {},\n ): void {\n try {\n const traceData = trace.toJSON() as Record<string, unknown>\n if (options.sourceTraceId) {\n traceData.id = options.sourceTraceId\n }\n\n this.httpClient.sendExternalTrace({\n ...(options.id && { id: options.id }),\n type: \"openai\",\n source: \"typescript-sdk-openai-tracing\",\n externalTrace: traceData,\n completed: options.completed ?? false,\n })\n } catch {\n // Silently ignore - never crash the host app\n }\n }\n\n /**\n * Export span to JSON object, collecting any errors.\n */\n private exportSpan(\n // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data\n span: Span<any>,\n ): [\n Record<string, unknown>,\n Array<{ source: string; step: string; error: string }>,\n ] {\n const errors: Array<{ source: string; step: string; error: string }> = []\n let serializedSpan: Record<string, unknown>\n\n try {\n const jsonResult = span.toJSON()\n if (typeof jsonResult !== \"object\" || jsonResult === null) {\n errors.push({\n source: \"sdk\",\n step: \"span.toJSON()\",\n error: `Returned unexpected type: ${typeof jsonResult}`,\n })\n serializedSpan = {}\n } else {\n serializedSpan = jsonResult as Record<string, unknown>\n }\n } catch (error) {\n errors.push({\n source: \"sdk\",\n step: \"span.toJSON()\",\n error: error instanceof Error ? error.message : String(error),\n })\n serializedSpan = {}\n }\n\n if (!serializedSpan.span_data) {\n serializedSpan.span_data = {} as Record<string, unknown>\n }\n\n return [serializedSpan, errors]\n }\n\n /**\n * Extract and add input/response to serialized span, updating errors list.\n */\n private extractSpanInputResponse(\n // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data\n span: Span<any>,\n serializedSpan: Record<string, unknown>,\n errors: Array<{ source: string; step: string; error: string }>,\n ): void {\n // Only ResponseSpanData hides its content from toJSON(): the SDK's\n // removePrivateFields strips its _input/_response, so we recover them here.\n // Every other span type (function, generation, agent, custom, ...) already\n // carries its data in span_data, so writing here would clobber a real input\n // with an empty placeholder. Gate strictly to response spans, and only set a\n // field when the value is actually present (never stamp []/null).\n if (span.spanData?.type !== \"response\") {\n return\n }\n\n const spanData = serializedSpan.span_data as Record<string, unknown>\n\n try {\n const input = span.spanData?._input\n if (input !== undefined) {\n spanData.input = input\n }\n } catch (error) {\n errors.push({\n source: \"sdk\",\n step: \"access_input\",\n error: error instanceof Error ? error.message : String(error),\n })\n }\n\n try {\n const response = span.spanData?._response\n if (response !== undefined) {\n spanData.response = response\n }\n } catch (error) {\n errors.push({\n source: \"sdk\",\n step: \"access_response\",\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n /**\n * If the span's trace is mapped to a withSpan trace, rewrite trace_id and parent_id.\n */\n private applySpanOverrides(\n serializedSpan: Record<string, unknown>,\n traceId: string,\n ): void {\n const mapping = this.activeSpanMappings[traceId]\n if (mapping) {\n serializedSpan.trace_id = mapping.traceId\n if (!serializedSpan.parent_id) {\n serializedSpan.parent_id = mapping.spanId\n }\n }\n }\n\n /**\n * Build span payload for the external spans API.\n */\n private buildSpanPayload(\n serializedSpan: Record<string, unknown>,\n errors: Array<{ source: string; step: string; error: string }>,\n ): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n id: randomUuid(),\n type: \"openai\",\n source: \"typescript-sdk-openai-tracing\",\n sourceTraceId: serializedSpan.trace_id ?? \"unknown\",\n rawSpan: serializedSpan,\n }\n\n if (errors.length > 0) {\n payload.errors = errors\n }\n\n // Sanitize the whole span (the raw OpenAI span_data is otherwise shipped\n // unsanitized, relying only on the http-layer net) and mark a lossy capture\n // non-replayable, merging with the SDK-level errors collected above.\n return finalizeSpanPayload(payload)\n }\n\n /**\n * Send span to Bitfab API (fire-and-forget).\n * If the span belongs to a trace mapped to a withSpan trace, the trace_id\n * and parent_id are rewritten to link the span into the withSpan tree.\n */\n private sendSpan(\n // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data\n span: Span<any>,\n ): void {\n const errors: Array<{ source: string; step: string; error: string }> = []\n const [serializedSpan, exportErrors] = this.exportSpan(span)\n errors.push(...exportErrors)\n\n this.extractSpanInputResponse(span, serializedSpan, errors)\n\n this.applySpanOverrides(serializedSpan, span.traceId ?? \"\")\n\n const payload = this.buildSpanPayload(serializedSpan, errors)\n const canonicalTraceId = span.traceId\n ? this.getCanonicalTraceId(span.traceId)\n : undefined\n if (canonicalTraceId) {\n payload.traceId = canonicalTraceId\n }\n\n this.httpClient.sendExternalSpan(payload)\n }\n}\n","/**\n * Vercel AI SDK integration for Bitfab tracing.\n *\n * The Vercel AI SDK (`ai`) routes every `generateText` / `streamText` /\n * `generateObject` / `streamObject` call through a language model. Bitfab hooks\n * that model with a *language-model middleware* (`wrapLanguageModel`), so each\n * model call is captured as a keyed `llm` span with no hand-written `withSpan`:\n *\n * ```typescript\n * import { Bitfab } from \"@bitfab/sdk\";\n * import { wrapLanguageModel, streamText } from \"ai\";\n * import { openai } from \"@ai-sdk/openai\";\n *\n * const bitfab = new Bitfab({ apiKey: \"...\" });\n *\n * const model = wrapLanguageModel({\n * model: openai(\"gpt-4o\"),\n * middleware: bitfab.getVercelAiMiddleware(\"chat-turn\"),\n * });\n *\n * const result = streamText({ model, messages });\n * return result.toUIMessageStreamResponse(); // live stream untouched\n * ```\n *\n * The span records the call parameters (the prompt/messages) as its input and a\n * serializable summary (`{ text, toolCalls, usage, finishReason }`) as its\n * output. Streaming is handled by passing the model's stream through a\n * transform that accumulates the assembled text/usage as the caller consumes\n * it: the live stream is handed back unchanged (first-byte latency untouched)\n * and the span is finalized once the stream completes.\n *\n * The middleware is fully duck-typed (no static or dynamic `ai` import), so it\n * adds no dependency and is browser-safe. It works with `ai` v5 and v6.\n */\n\n// The exact span options this middleware passes to `withSpan`. Declared locally\n// (a structural subset of the client's `SpanOptions`, so the bound `withSpan`\n// is assignable) rather than imported from client.ts - that would create an\n// import cycle, since client.ts imports this handler. Mirrors how the other\n// framework handlers stay free of any client import.\ntype LlmSpanOptions = {\n type: \"llm\"\n finalize: (result: unknown) => unknown | Promise<unknown>\n surface: \"inherit\"\n}\n\n// The subset of the Bitfab client this middleware needs: a bound `withSpan`.\ntype WithSpanFn = <TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n options: LlmSpanOptions,\n fn: (...args: TArgs) => TReturn,\n) => (...args: TArgs) => TReturn\n\n/**\n * Duck-typed subset of the Vercel AI SDK language-model call parameters. The\n * only field we read for the span input is `prompt` (the messages), but the\n * whole object is recorded so the call is reconstructable on replay.\n */\nexport interface VercelCallParams {\n prompt?: unknown\n [key: string]: unknown\n}\n\n/** A content part of a non-streaming `doGenerate` result. */\ninterface VercelContentPart {\n type: string\n text?: string\n toolCallId?: string\n toolName?: string\n // v3 names tool arguments `input`; v5/v2 used `args`.\n input?: unknown\n args?: unknown\n}\n\n/** Duck-typed subset of a non-streaming `doGenerate` result. */\nexport interface VercelGenerateResult {\n content?: VercelContentPart[]\n // Some providers expose a flattened `text`; prefer it when present.\n text?: string\n usage?: unknown\n finishReason?: unknown\n [key: string]: unknown\n}\n\n/** Duck-typed subset of a single streaming part from `doStream`. */\ninterface VercelStreamPart {\n type: string\n // v3 text-delta carries `delta`; v2 carried `textDelta`.\n delta?: string\n textDelta?: string\n toolCallId?: string\n toolName?: string\n input?: unknown\n args?: unknown\n usage?: unknown\n finishReason?: unknown\n}\n\n/** Duck-typed subset of a streaming `doStream` result. */\nexport interface VercelStreamResult {\n stream: ReadableStream<VercelStreamPart>\n [key: string]: unknown\n}\n\ninterface MiddlewareCall<TResult> {\n doGenerate: () => PromiseLike<VercelGenerateResult>\n doStream: () => PromiseLike<VercelStreamResult>\n params: VercelCallParams\n model: unknown\n __result?: TResult\n}\n\n/**\n * The structural shape of a Vercel AI SDK language-model middleware. Matches\n * `LanguageModelV3Middleware` from `@ai-sdk/provider` without importing it, so\n * the SDK stays dependency-free. `wrapLanguageModel` only reads the method\n * fields (it ignores `specificationVersion`), so this object drops straight in.\n */\nexport interface BitfabLanguageModelMiddleware {\n specificationVersion: \"v3\"\n // The wrap methods hand the provider's own result straight back (only the\n // span output is derived from it), so the return is typed `any` to stay\n // assignable to `LanguageModelV{2,3}Middleware` across AI SDK majors - the\n // SDK's strict result types (which require `warnings`, `content`, etc.) are a\n // superset of the duck-typed subset declared here. Implementation returns the\n // precise `VercelGenerateResult` / `VercelStreamResult` shapes.\n wrapGenerate: (\n options: MiddlewareCall<VercelGenerateResult>,\n // biome-ignore lint/suspicious/noExplicitAny: passthrough of the provider result; see note above\n ) => Promise<any>\n wrapStream: (\n options: MiddlewareCall<VercelStreamResult>,\n // biome-ignore lint/suspicious/noExplicitAny: passthrough of the provider result; see note above\n ) => Promise<any>\n}\n\n/** The provider/model that served a call (e.g. `{ provider, modelId }`). */\ntype ModelLabel = { provider?: string; modelId?: string }\n\n/** The serializable summary recorded as a model call's span output. */\ntype CallSummary = {\n text: string\n toolCalls?: unknown[]\n usage?: unknown\n finishReason?: unknown\n // Which provider/model actually served this call. Invaluable when a single\n // wrapped key spans multiple providers (e.g. a Claude-primary, GPT-4o-fallback\n // setup) so each span shows who answered.\n model?: ModelLabel\n}\n\n/** Read `{ provider, modelId }` off an AI SDK language model, defensively. */\nfunction modelLabel(model: unknown): ModelLabel | undefined {\n if (!model || typeof model !== \"object\") {\n return undefined\n }\n const m = model as { provider?: unknown; modelId?: unknown }\n const provider = typeof m.provider === \"string\" ? m.provider : undefined\n const modelId = typeof m.modelId === \"string\" ? m.modelId : undefined\n if (provider == null && modelId == null) {\n return undefined\n }\n return { provider, modelId }\n}\n\n/** Collapse a non-streaming generate result into a serializable span output. */\nfunction summarizeGenerate(\n result: VercelGenerateResult,\n model: ModelLabel | undefined,\n): CallSummary {\n const content = Array.isArray(result.content) ? result.content : []\n const text =\n typeof result.text === \"string\"\n ? result.text\n : content\n .filter((p) => p.type === \"text\" && typeof p.text === \"string\")\n .map((p) => p.text)\n .join(\"\")\n const toolCalls = content\n .filter((p) => p.type === \"tool-call\")\n .map((p) => ({\n toolCallId: p.toolCallId,\n toolName: p.toolName,\n input: p.input ?? p.args,\n }))\n const summary: CallSummary = {\n text,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n usage: result.usage,\n finishReason: result.finishReason,\n }\n if (model) {\n summary.model = model\n }\n return summary\n}\n\n/**\n * A pass-through transform that accumulates the assembled text, tool calls, and\n * final usage from a model's stream, resolving `onComplete` with that summary\n * once the stream finishes. Parts are enqueued unchanged so the caller's stream\n * is untouched; capture errors are swallowed so tracing never breaks the stream.\n */\nfunction accumulateStream(\n onComplete: (summary: CallSummary) => void,\n model: ModelLabel | undefined,\n): TransformStream<VercelStreamPart, VercelStreamPart> {\n let text = \"\"\n const toolCalls: unknown[] = []\n let usage: unknown\n let finishReason: unknown\n let completed = false\n const complete = (): void => {\n if (completed) {\n return\n }\n completed = true\n const summary: CallSummary = {\n text,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n usage,\n finishReason,\n }\n if (model) {\n summary.model = model\n }\n onComplete(summary)\n }\n return new TransformStream<VercelStreamPart, VercelStreamPart>({\n transform(part, controller) {\n try {\n if (part?.type === \"text-delta\") {\n text += part.delta ?? part.textDelta ?? \"\"\n } else if (part?.type === \"tool-call\") {\n toolCalls.push({\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input ?? part.args,\n })\n } else if (part?.type === \"finish\") {\n usage = part.usage\n finishReason = part.finishReason\n // The `finish` part is the stream's last meaningful event; resolve\n // the span output as soon as it passes rather than waiting for the\n // reader to close the stream.\n complete()\n }\n } catch {\n // Never let span capture break the caller's stream.\n }\n controller.enqueue(part)\n },\n flush() {\n // Fallback when a provider omits an explicit `finish` part.\n complete()\n },\n })\n}\n\n/**\n * Vercel AI SDK middleware that records each language-model call as a keyed\n * `llm` span. Obtain it from {@link BitfabClient.getVercelAiMiddleware} rather\n * than constructing it directly.\n */\nexport class BitfabVercelAiHandler {\n private readonly traceFunctionKey: string\n private readonly withSpanFn: WithSpanFn\n\n constructor(config: { traceFunctionKey: string; withSpan: WithSpanFn }) {\n this.traceFunctionKey = config.traceFunctionKey\n this.withSpanFn = config.withSpan\n }\n\n /** The `wrapLanguageModel` middleware object for this trace function key. */\n get middleware(): BitfabLanguageModelMiddleware {\n const key = this.traceFunctionKey\n const withSpan = this.withSpanFn\n return {\n specificationVersion: \"v3\",\n wrapGenerate: async ({ doGenerate, params, model }) => {\n const label = modelLabel(model)\n // Wrap a function that TAKES the call params as its argument and call it\n // with them, so withSpan records `[params]` (the prompt/settings) as the\n // span input. `finalize` records the serializable summary as the output\n // while the raw result is returned to the AI SDK unchanged.\n const traced = withSpan<\n [VercelCallParams],\n Promise<VercelGenerateResult>\n >(\n key,\n {\n type: \"llm\",\n finalize: (result) =>\n summarizeGenerate((result ?? {}) as VercelGenerateResult, label),\n surface: \"inherit\",\n },\n () => doGenerate() as Promise<VercelGenerateResult>,\n )\n return traced(params)\n },\n wrapStream: async ({ doStream, params, model }) => {\n const label = modelLabel(model)\n let resolveSummary: (summary: CallSummary) => void = () => {}\n const summary = new Promise<CallSummary>((resolve) => {\n resolveSummary = resolve\n })\n const traced = withSpan<\n [VercelCallParams],\n Promise<VercelStreamResult>\n >(\n key,\n // The wrapped fn returns immediately with the live stream, so the span\n // output cannot be read from the return value. `finalize` instead\n // awaits the summary the accumulator resolves once the stream drains.\n { type: \"llm\", finalize: () => summary, surface: \"inherit\" },\n async () => {\n const result = await doStream()\n const stream = result.stream.pipeThrough(\n accumulateStream(resolveSummary, label),\n )\n return { ...result, stream }\n },\n )\n return traced(params)\n },\n }\n }\n}\n","/**\n * Bitfab client for provider-based API calls.\n */\n\nimport {\n type AsyncLocalStorageLike,\n asyncStorageReady,\n createAsyncLocalStorage,\n isAsyncStorageInitDone,\n} from \"./asyncStorage.js\"\nimport {\n __bitfabAutoTraceActive,\n __setBitfabAutoTraceCapturePolicy,\n type AutoTraceContext,\n type AutoTraceFunctionDefinition,\n type AutoTraceNodeConfiguration,\n getAutoTraceCapturePolicy,\n runWithAutoTraceContext,\n runWithAutoTraceNodeConfiguration,\n runWithAutoTraceRootContext,\n} from \"./autoTrace.js\"\nimport {\n type AllowedEnvVars,\n type ProviderDefinition,\n runFunctionWithBaml,\n} from \"./baml.js\"\nimport type { CaptureSurface, SurfaceRequest } from \"./captureSurface.js\"\nimport {\n assertSurfacesCompatible,\n DEFAULT_SURFACE,\n mixedTracingError,\n resolveSurface,\n} from \"./captureSurface.js\"\nimport { BitfabClaudeAgentHandler } from \"./claudeAgentSdk.js\"\nimport { DEFAULT_SERVICE_URL } from \"./constants.js\"\nimport { DatasetsClient } from \"./datasets.js\"\nimport type { DbSnapshotConfig, DbSnapshotRef } from \"./dbSnapshot.js\"\nimport { buildSnapshotRef, validateDbSnapshotConfig } from \"./dbSnapshot.js\"\nimport { MixedTracingError } from \"./errors.js\"\nimport {\n BitfabError,\n type CapturedSpan,\n HttpClient,\n type SpanLookup,\n} from \"./http.js\"\nimport { BitfabLangGraphCallbackHandler } from \"./langgraph.js\"\nimport {\n BitfabLangGraphIntegration,\n type LangGraphIntegrationOptions,\n} from \"./langgraphIntegration.js\"\nimport type {\n MockOverride,\n MockOverrideResolver,\n MockSource,\n MockTarget,\n MockValue,\n NodeMatcher,\n SpanNodeMeta,\n} from \"./mockOverride.js\"\nimport { NO_MOCK_OVERRIDE, resolveMockValue } from \"./mockOverride.js\"\nimport { BitfabOpenAIAgentHandler } from \"./openaiAgentSdk.js\"\nimport { importOptionalPeer } from \"./optionalPeer.js\"\nimport { randomUuid } from \"./randomUuid.js\"\nimport type {\n ReplayOptions,\n ReplayResult,\n TraceIngestionType,\n} from \"./replay.js\"\nimport { ReplayBranch } from \"./replayBranch.js\"\nimport type { DbBranchTimings } from \"./replayContext.js\"\nimport { getReplayContext } from \"./replayContext.js\"\nimport {\n getSeedContext,\n inSeedScope,\n runWithSeedContext,\n seedContextReady,\n} from \"./seedContext.js\"\nimport { deserializeValue, serializeValue } from \"./serialize.js\"\nimport { nowIsoTimestamp } from \"./timestamp.js\"\nimport { BitfabOpenAITracingProcessor } from \"./tracing.js\"\nimport { BitfabVercelAiHandler } from \"./vercelAiSdk.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\n// Context entry for addContext calls - each entry is an object with multiple key-value pairs\ntype ContextEntry = Record<string, unknown>\n\n// Trace state for tracking trace-level data\ninterface TraceState {\n traceId: string\n sessionId?: string\n name?: string\n metadata?: Record<string, unknown>\n contexts: ContextEntry[]\n startedAt: string\n testRunId?: string\n inputSourceTraceId?: string\n replayAttempt?: number\n dbSnapshotRef?: DbSnapshotRef\n // Set by getCurrentTrace().drop(); ridden out on trace completion so the\n // server scrubs and marks the trace `dropped` instead of `completed`.\n dropped?: boolean\n ingestionType?: TraceIngestionType\n}\n\nexport type { CaptureSurface } from \"./captureSurface.js\"\n\n// Span context for tracking nested spans\ninterface SpanContext {\n traceId: string\n spanId: string\n contexts: ContextEntry[]\n prompt?: string\n surface?: CaptureSurface\n}\n\n// Global map to track active trace states\nconst activeTraceStates = new Map<string, TraceState>()\n\nlet asyncLocalStorage: AsyncLocalStorageLike<SpanContext[]> | null = null\nconst SPAN_CONTEXT_STORAGE_SYMBOL = Symbol.for(\"bitfab.spanContextStorage\")\n\nconst initializeAsyncContext = () => {\n if (asyncLocalStorage) {\n return\n }\n const shared = globalThis as typeof globalThis & Record<symbol, unknown>\n const existing = shared[SPAN_CONTEXT_STORAGE_SYMBOL] as\n | AsyncLocalStorageLike<SpanContext[]>\n | undefined\n if (existing) {\n asyncLocalStorage = existing\n return\n }\n const created = createAsyncLocalStorage<SpanContext[]>()\n if (created) {\n shared[SPAN_CONTEXT_STORAGE_SYMBOL] = created\n asyncLocalStorage = created\n }\n}\n\nconst asyncLocalStorageReady: Promise<void> = asyncStorageReady.then(() => {\n initializeAsyncContext()\n})\n\n// Browser fallback: a single module-level stack shared across all async\n// execution chains. Works correctly for synchronous nesting and sequential\n// async nesting (the common browser cases), but breaks when multiple\n// independent spans are in-flight concurrently (e.g. Promise.all with\n// separate withSpan calls). In that scenario, whichever span resumes last\n// overwrites the shared stack, so inner spans may see the wrong parent.\n//\n// Node.js avoids this via AsyncLocalStorage, which gives each async chain\n// its own isolated copy of the stack.\n//\n// Potential future fixes:\n// - TC39 AsyncContext proposal (stage 2) would provide AsyncLocalStorage\n// semantics natively in all JS environments, including browsers.\n// https://github.com/tc39/proposal-async-context\n// - Zone.js could work today but is ~50KB, monkey-patches Promise/setTimeout/\n// fetch/etc., and can conflict with frameworks like React. Too invasive for\n// an SDK dependency.\nlet browserSpanStack: SpanContext[] = []\n\nfunction getSpanStack(): SpanContext[] {\n if (asyncLocalStorage) {\n return asyncLocalStorage.getStore() ?? []\n }\n return browserSpanStack\n}\n\nfunction enclosingSurface(): CaptureSurface | undefined {\n const stack = getSpanStack()\n return stack[stack.length - 1]?.surface\n}\n\nfunction runWithSpanStack<T>(stack: SpanContext[], fn: () => T): T {\n if (asyncLocalStorage) {\n return asyncLocalStorage.run(stack, fn)\n }\n // Browser fallback: save/restore the stack around the function call.\n // This is correct for sequential async but not for concurrent async -\n // see the browserSpanStack comment above for details.\n const previousStack = browserSpanStack\n browserSpanStack = stack\n try {\n const result = fn()\n if (result instanceof Promise) {\n return result.finally(() => {\n browserSpanStack = previousStack\n }) as T\n }\n browserSpanStack = previousStack\n return result\n } catch (error) {\n browserSpanStack = previousStack\n throw error\n }\n}\n\nfunction isAsyncGenerator(\n value: unknown,\n): value is AsyncGenerator<unknown, unknown, unknown> {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n const candidate = value as Record<PropertyKey, unknown>\n return (\n typeof candidate.next === \"function\" &&\n typeof candidate.return === \"function\" &&\n typeof candidate.throw === \"function\" &&\n typeof candidate[Symbol.asyncIterator] === \"function\"\n )\n}\n\n// Wrap an async generator so that:\n// 1. Each .next()/.return()/.throw() resumes the generator body inside\n// the parent span's context, so nested withSpan calls nest correctly.\n// 2. The span is sent only after iteration completes (or errors), with\n// the yielded values plus any final return value as the result.\n//\n// Without this, async-generator functions returned from withSpan close their\n// span synchronously when the generator object is created - before any of\n// the body has run - and every child span becomes its own root trace.\nfunction wrapAsyncGenerator<TYield, TReturn>(\n source: AsyncGenerator<TYield, TReturn, unknown>,\n spanStack: SpanContext[],\n sendSpan: (params: { result: unknown; error?: string }) => Promise<void>,\n): AsyncGenerator<TYield, TReturn, unknown> {\n const yielded: TYield[] = []\n let returnValue: TReturn | undefined\n let finalized = false\n\n const finalize = (errorMsg?: string) => {\n if (finalized) {\n return\n }\n finalized = true\n void sendSpan({\n result: { yielded, return: returnValue },\n ...(errorMsg && { error: errorMsg }),\n })\n }\n\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n arg: unknown,\n ): Promise<IteratorResult<TYield, TReturn>> =>\n runWithSpanStack(spanStack, () => {\n const op = source[method] as (\n a?: unknown,\n ) => Promise<IteratorResult<TYield, TReturn>>\n return op.call(source, arg)\n })\n\n const handle = async (\n method: \"next\" | \"return\" | \"throw\",\n arg: unknown,\n ): Promise<IteratorResult<TYield, TReturn>> => {\n try {\n const result = await step(method, arg)\n if (result.done) {\n returnValue = result.value\n finalize()\n } else {\n yielded.push(result.value)\n }\n return result\n } catch (error) {\n finalize(error instanceof Error ? error.message : String(error))\n throw error\n }\n }\n\n const wrapped = {\n next(arg?: unknown) {\n return handle(\"next\", arg)\n },\n return(value: TReturn | PromiseLike<TReturn>) {\n return handle(\"return\", value)\n },\n throw(err: unknown) {\n return handle(\"throw\", err)\n },\n [Symbol.asyncIterator]() {\n return wrapped\n },\n [Symbol.asyncDispose]() {\n return handle(\"return\", undefined).then(() => undefined)\n },\n } as AsyncGenerator<TYield, TReturn, unknown>\n\n return wrapped\n}\n\n// --- BAML Collector support for wrapBAML ---\n\ntype CollectorConstructor = new (name: string) => unknown\n\nlet cachedCollectorClass: CollectorConstructor | null | undefined\n\n/** @internal Reset the cached Collector class - for testing only. */\nexport function _resetCollectorCache(): void {\n cachedCollectorClass = undefined\n}\n\n/** @internal Inject a mock Collector class - for testing only. */\nexport function _setCollectorCache(cls: CollectorConstructor | null): void {\n cachedCollectorClass = cls\n}\n\n/** @internal Count of in-flight (registered, not yet completed) trace states - for testing only. */\nexport function _activeTraceStateCount(): number {\n return activeTraceStates.size\n}\n\nasync function loadCollectorClass(): Promise<CollectorConstructor | null> {\n if (cachedCollectorClass !== undefined) {\n return cachedCollectorClass\n }\n try {\n // Reconstructed specifier (see importOptionalPeer): a consumer's bundler\n // must not try to resolve `@boundaryml/baml` at build time when it is not\n // installed (optional peer, only needed for BAML execution / collectors).\n const baml = await importOptionalPeer<typeof import(\"@boundaryml/baml\")>([\n \"@boundaryml\",\n \"baml\",\n ])\n cachedCollectorClass = baml.Collector as CollectorConstructor\n return cachedCollectorClass\n } catch {\n cachedCollectorClass = null\n return null\n }\n}\n\n// Typed accessors for the BAML Collector's internal structure.\n// Uses defensive access since these are untyped objects from the BAML runtime.\n\ninterface CollectorCall {\n selected?: boolean\n clientName?: string\n provider?: string\n usage?: {\n inputTokens?: number\n outputTokens?: number\n cachedInputTokens?: number\n }\n httpRequest?: {\n url?: string\n body?: { json: () => Record<string, unknown> | null }\n }\n}\n\ninterface CollectorLog {\n calls?: CollectorCall[]\n timing?: { durationMs?: number }\n}\n\ninterface CollectorLike {\n last?: CollectorLog | null\n usage?: {\n inputTokens?: number\n outputTokens?: number\n cachedInputTokens?: number\n }\n}\n\nfunction extractPromptFromCollector(collector: unknown): string | null {\n try {\n const c = collector as CollectorLike\n const calls = c?.last?.calls ?? []\n const selectedCall = calls.find((call) => call.selected) ?? calls[0]\n if (!selectedCall?.httpRequest?.body) {\n return null\n }\n const body = selectedCall.httpRequest.body.json()\n if (!body || typeof body !== \"object\") {\n return null\n }\n const messages = body.messages\n if (!Array.isArray(messages) || messages.length === 0) {\n return null\n }\n const rendered = (messages as Record<string, unknown>[])\n .filter(\n (msg): msg is { role: string; content: unknown } =>\n typeof msg === \"object\" &&\n msg !== null &&\n \"role\" in msg &&\n typeof (msg as { role: unknown }).role === \"string\",\n )\n .map((msg) => ({\n role: msg.role,\n content:\n typeof msg.content === \"string\"\n ? msg.content\n : JSON.stringify(msg.content),\n }))\n if (rendered.length > 0) {\n return JSON.stringify(rendered)\n }\n return null\n } catch {\n return null\n }\n}\n\nfunction extractContextFromCollector(\n collector: unknown,\n): Record<string, unknown> | null {\n try {\n const c = collector as CollectorLike\n const calls = c?.last?.calls ?? []\n const selectedCall = calls.find((call) => call.selected) ?? calls[0]\n const usage = c?.usage\n\n const context: Record<string, unknown> = {}\n if (selectedCall?.provider) {\n context.provider = selectedCall.provider\n }\n\n // Extract model from HTTP request body (OpenAI/Anthropic) or URL (Vertex AI)\n const body = selectedCall?.httpRequest?.body?.json()\n if (body && typeof body === \"object\" && typeof body.model === \"string\") {\n context.model = body.model\n } else {\n const url = selectedCall?.httpRequest?.url\n if (url) {\n const match = url.match(/\\/models\\/([^/:]+)/)\n if (match?.[1]) {\n context.model = match[1]\n }\n }\n }\n\n const inputTokens =\n usage?.inputTokens ?? selectedCall?.usage?.inputTokens ?? null\n const outputTokens =\n usage?.outputTokens ?? selectedCall?.usage?.outputTokens ?? null\n if (inputTokens !== null) {\n context.inputTokens = inputTokens\n }\n if (outputTokens !== null) {\n context.outputTokens = outputTokens\n }\n\n const durationMs = c?.last?.timing?.durationMs ?? null\n if (durationMs !== null) {\n context.durationMs = durationMs\n }\n\n return Object.keys(context).length > 0 ? context : null\n } catch {\n return null\n }\n}\n\n/**\n * Options for wrapBAML.\n */\nexport interface WrapBAMLOptions {\n /** Called after each BAML invocation with the Collector instance. */\n onCollector?: (collector: unknown) => void\n}\n\n/**\n * A function returned by wrapBAML that exposes the BAML collector from the last call.\n */\nexport interface WrappedBamlFn<TArgs extends unknown[], TReturn> {\n (...args: TArgs): Promise<TReturn>\n /** The BAML Collector instance from the most recent call. `null` before the first call or if @boundaryml/baml is unavailable. */\n collector: unknown | null\n}\n\n/**\n * A handle to the current active span, allowing context to be added.\n */\nexport interface CurrentSpan {\n /** The Bitfab ID for the current span. */\n readonly id: string\n /** The trace ID for the current span. */\n readonly traceId: string\n /**\n * Add a context entry to this span. Each call appends to the contexts array.\n * Context entries are stored in span_data.contexts as [{key, value}, ...].\n */\n addContext(context: Record<string, unknown>): void\n /**\n * Set the prompt for this span. Stored in span_data.prompt.\n * Calling multiple times overwrites the previous value.\n */\n setPrompt(prompt: string): void\n}\n\n/**\n * A detached handle to a previously-created trace, looked up by its\n * canonical Bitfab trace ID.\n *\n * Unlike `getCurrentTrace()`, this handle is not tied to AsyncLocalStorage -\n * each method sends to the server immediately. Useful for adding context\n * to a trace from a different process, request, or thread (e.g. a forked\n * agent that wants to annotate the original conversation's trace).\n */\nexport interface DetachedTrace {\n /** The canonical Bitfab trace ID this handle resolves. */\n readonly traceId: string\n /**\n * Append a context entry to this trace. Each call adds one entry to the\n * server-side contexts array; existing entries are preserved.\n *\n * Resolves once the server has applied the change and REJECTS if the server\n * refused it. A detached patch targets an already-closed trace, so it rides\n * no batch and no later signal would reveal a silent failure - the caller is\n * the only one who can react.\n */\n addContext(context: Record<string, unknown>): Promise<void>\n /**\n * Merge metadata into this trace. Server-side shallow-merges the new keys\n * into the existing metadata object; existing keys are preserved unless\n * overwritten by the new values. Rejects if the server refused the update.\n */\n setMetadata(metadata: Record<string, unknown>): Promise<void>\n /**\n * Set the sessionId for this trace. Replaces any existing sessionId.\n * Rejects if the server refused the update.\n */\n setSessionId(sessionId: string): Promise<void>\n setName(name: string): Promise<void>\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n\nfunction validateTraceId(traceId: string): void {\n if (typeof traceId !== \"string\" || !UUID_PATTERN.test(traceId)) {\n throw new BitfabError(\"traceId must be a valid Bitfab trace ID\")\n }\n}\n\nfunction validateSpanId(id: string): void {\n if (typeof id !== \"string\" || !UUID_PATTERN.test(id)) {\n throw new BitfabError(\"id must be a valid Bitfab span ID\")\n }\n}\n\n/**\n * A handle to the current active trace, allowing trace-level context to be set.\n */\nexport interface CurrentTrace {\n /**\n * Set the session ID for this trace. Stored in the database session_id column.\n */\n setSessionId(sessionId: string): void\n setName(name: string): void\n /**\n * Set metadata for this trace. Stored in rawData.metadata.\n * Subsequent calls merge with existing metadata, with later values taking precedence.\n */\n setMetadata(metadata: Record<string, unknown>): void\n /**\n * Add a context entry to this trace. Each call appends to the contexts array.\n * Context entries are stored in rawData.contexts as [{key, value}, ...].\n */\n addContext(context: Record<string, unknown>): void\n /**\n * Flag this trace to be dropped. Once flagged, spans that complete afterward\n * are not uploaded at all, and when the trace completes the server scrubs any\n * payloads that already raced out (trace, external trace, and sibling spans),\n * marking it `dropped` instead of `completed` and retaining only a skeleton\n * audit record. Use this to discard runs you never want stored (e.g. health\n * checks, or a run you know contains sensitive data). Takes effect\n * immediately for later spans; the server-side scrub takes effect at trace\n * completion, so a trace that is flagged but never completes is not scrubbed.\n */\n drop(): void\n}\n\n// No-op implementations for when called outside a span context\nconst noOpSpan: CurrentSpan = {\n id: \"\",\n traceId: \"\",\n addContext(): void {\n // No-op\n },\n setPrompt(): void {\n // No-op\n },\n}\n\nconst noOpTrace: CurrentTrace = {\n setSessionId(): void {\n // No-op\n },\n setName(): void {},\n setMetadata(): void {\n // No-op\n },\n addContext(): void {\n // No-op\n },\n drop(): void {\n // No-op\n },\n}\n\n/**\n * Get a handle to the current active span.\n *\n * Call this from inside a traced function (wrapped with `withSpan`) to get\n * a span handle that allows adding context at runtime.\n *\n * Returns a no-op object if called outside of a span context (methods do nothing).\n */\nexport function getCurrentSpan(): CurrentSpan {\n const stack = getSpanStack()\n const current = stack[stack.length - 1]\n if (!current) {\n return noOpSpan\n }\n return {\n id: current.spanId,\n traceId: current.traceId,\n addContext(context: Record<string, unknown>): void {\n try {\n if (typeof context !== \"object\" || context === null) {\n return\n }\n // Push the entire context object as one entry\n current.contexts.push(context)\n } catch {\n // Silently ignore - never crash the host app\n }\n },\n setPrompt(prompt: string): void {\n try {\n if (typeof prompt !== \"string\") {\n return\n }\n current.prompt = prompt\n } catch {\n // Silently ignore - never crash the host app\n }\n },\n }\n}\n\n/**\n * Get the database branch the current replay item is running against.\n *\n * Call this from inside a function being replayed with `replay({ dbBranch })`\n * and point your database client at `branch.databaseUrl` so the replay reads\n * the data as it was at trace time:\n *\n * ```ts\n * const branch = getCurrentReplayBranch()\n * const url = branch?.databaseUrl ?? process.env.DATABASE_URL\n * ```\n *\n * Returns null outside a replay item, and for an item whose source trace\n * carried no DB snapshot reference, so live request code takes the same path\n * it always did.\n */\nexport function getCurrentReplayBranch(): ReplayBranch | null {\n const ctx = getReplayContext()\n if (!ctx?.dbBranchLease) {\n return null\n }\n // Surface the Bitfab traceId (what the customer sees in the dashboard), not\n // the external_traces.id. Falling back to the external ID keeps replays from\n // external sources working until the source-system path is fully wired.\n const traceId = ctx.sourceBitfabTraceId ?? ctx.inputSourceTraceId\n if (!traceId) {\n return null\n }\n return new ReplayBranch(ctx.dbBranchLease, traceId, ctx)\n}\n\n/**\n * Get a handle to the current active trace.\n *\n * Call this from inside a traced function (wrapped with `withSpan`) to get\n * a trace handle that allows setting trace-level context at runtime.\n *\n * Returns a no-op object if called outside of a span context (methods do nothing).\n */\nexport function getCurrentTrace(): CurrentTrace {\n const stack = getSpanStack()\n const current = stack[stack.length - 1]\n if (!current) {\n return noOpTrace\n }\n\n const traceId = current.traceId\n\n const getOrCreateTraceState = (): TraceState => {\n let traceState = activeTraceStates.get(traceId)\n if (!traceState) {\n traceState = {\n traceId,\n startedAt: nowIsoTimestamp(),\n contexts: [],\n }\n activeTraceStates.set(traceId, traceState)\n }\n return traceState\n }\n\n return {\n setSessionId(sessionId: string): void {\n try {\n const traceState = getOrCreateTraceState()\n traceState.sessionId = sessionId\n } catch {\n // Silently ignore - never crash the host app\n }\n },\n setName(name: string): void {\n if (typeof name !== \"string\" || name.length === 0) {\n return\n }\n try {\n getOrCreateTraceState().name = name\n } catch {}\n },\n setMetadata(metadata: Record<string, unknown>): void {\n try {\n if (typeof metadata !== \"object\" || metadata === null) {\n return\n }\n const traceState = getOrCreateTraceState()\n traceState.metadata = { ...traceState.metadata, ...metadata }\n } catch {\n // Silently ignore - never crash the host app\n }\n },\n addContext(context: Record<string, unknown>): void {\n try {\n if (typeof context !== \"object\" || context === null) {\n return\n }\n const traceState = getOrCreateTraceState()\n // Push the entire context object as one entry\n traceState.contexts.push(context)\n } catch {\n // Silently ignore - never crash the host app\n }\n },\n drop(): void {\n try {\n getOrCreateTraceState().dropped = true\n } catch {\n // Silently ignore - never crash the host app\n }\n },\n }\n}\n\n/**\n * Read an environment variable without throwing in non-Node runtimes\n * (browsers, edge workers) where `process` is absent. The SDK ships to\n * browsers, so this must never assume `process` exists.\n */\nfunction readEnv(name: string): string | undefined {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[name]\n }\n return undefined\n}\n\nexport interface SeedCaseOptions {\n input: unknown[]\n expected?: unknown\n // biome-ignore lint/suspicious/noExplicitAny: matches the replay callable\n fn?: (...args: any[]) => unknown\n metadata?: Record<string, unknown>\n sessionId?: string\n name?: string\n spanName?: string\n spanType?: SpanType\n}\n\nexport interface SeedRunOptions<TArgs extends unknown[]> {\n args?: TArgs\n metadata?: Record<string, unknown>\n sessionId?: string\n name?: string\n}\n\nexport interface BitfabConfig {\n /**\n * The API key for Bitfab API authentication. Resolved lazily, the first\n * time a span actually needs it, not at construction. When it resolves\n * empty, tracing is disabled (a no-op, unless `strict` is set).\n *\n * Accepts either a string or a function returning the key. The function\n * form is resolved at first use, so it survives the ESM trap where a shim\n * built at module load runs before the script body's `dotenv.config()`:\n * `apiKey: () => process.env.BITFAB_API_KEY`. When omitted (or it resolves\n * empty), the SDK also falls back to reading `BITFAB_API_KEY` from the\n * environment itself, again at first use.\n */\n apiKey?: string | (() => string | null | undefined)\n /** The base URL for the Bitfab API (default: https://bitfab.ai) */\n serviceUrl?: string\n /** Request timeout in milliseconds (default: 120000) */\n timeout?: number\n /** Environment variables for LLM provider API keys (only OPENAI_API_KEY is supported) */\n envVars?: AllowedEnvVars\n captureEnabled?: boolean\n enabled?: boolean\n /**\n * Fail loud instead of degrading quietly. When true, the first traced call\n * with no resolvable API key throws a `BitfabError` rather than silently\n * disabling tracing. Off by default so a missing telemetry key never takes\n * down the host app; turn it on in standalone scripts where a run that\n * emits no traces is a failure you want surfaced immediately.\n */\n strict?: boolean\n /** The generated BAML client instance (e.g., `b` from your baml_client). Used by wrapBAML() when no explicit client is passed. */\n bamlClient?: unknown\n /**\n * Per-trace database snapshot config. When set, every root span captures\n * a wall-clock timestamp (and, if `captureRef` is provided, a provider-\n * specific point-in-time ref) so the trace can later be replayed against\n * a branch materialized from that point.\n */\n dbSnapshot?: DbSnapshotConfig\n}\n\n/**\n * Span types matching the backend enum.\n * - llm: LLM API calls\n * - agent: Autonomous orchestrators\n * - function: Tool implementations\n * - guardrail: Safety/validation checks\n * - handoff: Agent-to-agent transfers\n * - custom: Application-specific tracing (default)\n */\nexport type SpanType =\n | \"llm\"\n | \"agent\"\n | \"function\"\n | \"guardrail\"\n | \"handoff\"\n | \"custom\"\n\n/**\n * Controls when a span is captured.\n * - always: Capture the span even when it becomes the root of a new trace.\n * - nested: Capture the span only when another Bitfab span is already active.\n */\nexport type CaptureWhen = \"always\" | \"nested\"\n\n/**\n * Options for configuring span behavior.\n */\nexport interface SpanOptions {\n /**\n * The name of the span. Defaults to the function name if available,\n * otherwise falls back to the trace function key.\n */\n name?: string\n /**\n * The type of span. Defaults to \"custom\" if not specified.\n */\n type?: SpanType\n /**\n * Controls whether this span may start a new trace. Defaults to \"always\".\n *\n * Use \"nested\" for reusable helpers that should appear inside an existing\n * trace but should run untraced when called on their own.\n * Unknown values warn once and default to \"always\".\n */\n captureWhen?: CaptureWhen\n /**\n * When true, replay will reuse this span's historical output instead of\n * executing the wrapped function. Read by the \"marked\" replay strategy;\n * ignored outside replay and under the \"all\"/\"none\" strategies.\n *\n * Use this for child spans that are expensive (paid LLM/API calls),\n * slow, or non-deterministic - the root function still runs real code,\n * only the marked descendants return their recorded output. If a selected\n * occurrence is unavailable, replay fails the item without executing the\n * real child.\n */\n mockOnReplay?: boolean\n /** Optional test run ID included on the span and on the trace it starts. */\n testRunId?: string\n /**\n * Record a serializable view of a non-serializable result (e.g. a live\n * stream object) as the span output.\n *\n * When set, the wrapped function's raw return value is handed back to the\n * caller unchanged (so streaming and first-byte latency are untouched),\n * but instead of serializing that raw value, the span records\n * `await finalize(result)`. Use this to trace functions that return a live\n * stream consumed by the caller (Vercel AI SDK `streamText`, a\n * `ReadableStream`, an SSE response) while still capturing a serializable,\n * replayable output such as `{ text, usage, toolCalls }`.\n *\n * Reading from a multi-consumer stream result (like the AI SDK's, which\n * tees internally) does not disturb the caller's own consumption. For the\n * Vercel AI SDK shape, pass the prebuilt `finalizers.aiSdk` helper.\n *\n * Ignored for async-generator results, which are captured automatically.\n */\n // biome-ignore lint/suspicious/noExplicitAny: the result type is the wrapped fn's return; SpanOptions is not generic, so callers narrow it inside finalize\n finalize?: (result: any) => unknown | Promise<unknown>\n}\n\n/**\n * The standard method context passed to a decorator.\n *\n * Defined structurally instead of referencing TypeScript's built-in\n * `ClassMethodDecoratorContext`, which was added in TypeScript 5.0. This keeps\n * the SDK's non-decorator APIs consumable by projects on older compilers.\n */\nexport interface SpanMethodDecoratorContext<TThis, TValue> {\n readonly kind: \"method\"\n readonly name: string | symbol\n readonly static: boolean\n readonly private: boolean\n readonly access: {\n has(object: TThis): boolean\n get(object: TThis): TValue\n }\n addInitializer(initializer: (this: TThis) => void): void\n readonly metadata?: Record<PropertyKey, unknown>\n}\n\n/** A standard ECMAScript method decorator produced by {@link Bitfab.span}. */\nexport type SpanMethodDecorator = <TThis, TArgs extends unknown[], TReturn>(\n originalMethod: (this: TThis, ...args: TArgs) => TReturn,\n context: SpanMethodDecoratorContext<\n TThis,\n (this: TThis, ...args: TArgs) => TReturn\n >,\n) => (this: TThis, ...args: TArgs) => TReturn\n\n/** Trace-owned configuration for a function discovered beneath `trace()`. */\nexport interface NodeOptions extends Omit<SpanOptions, \"captureWhen\"> {\n /** Whether the enclosing trace captures this call. Defaults to true. */\n capture?: boolean\n}\n\ntype NodeConfigurationOptions = Omit<AutoTraceNodeConfiguration, \"functionName\">\n\ntype StandardNodeMethodDecorator = SpanMethodDecorator\n\ntype LegacyNodeMethodDecorator = <TThis, TArgs extends unknown[], TReturn>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<(this: TThis, ...args: TArgs) => TReturn>,\n) => void\n\n/** A method decorator produced by {@link Bitfab.node}. */\nexport type NodeMethodDecorator = StandardNodeMethodDecorator &\n LegacyNodeMethodDecorator\n\n/** Options for experimental automatic subtree tracing. */\nexport interface TraceOptions {\n /** Root span name. Defaults to the decorated or wrapped function name. */\n name?: string\n /** Root span type. Descendants are always `function` spans. */\n type?: SpanType\n /**\n * Default replay-mocking policy for automatically captured descendants.\n * When true, those descendants are mocked by the default \"marked\" strategy\n * unless a node explicitly sets `mockOnReplay: false`. Defaults to false.\n */\n mockOnReplayDefault?: boolean\n /** Maximum number of recorded descendant levels. Defaults to 30. */\n maxDepth?: number\n /** Maximum descendant spans recorded per root invocation. Defaults to 500. */\n maxSpans?: number\n /** Qualified or simple function names to leave out of the subtree. */\n exclude?: readonly string[] | ReadonlySet<string>\n /** Record rest-argument wrapper functions. Defaults to false. */\n includeWrappers?: boolean\n}\n\ninterface InternalSpanOptions extends SpanOptions {\n functionId?: string\n captureContent?: boolean\n autoTraceDefinition?: AutoTraceFunctionDefinition\n surface?: SurfaceRequest\n}\n\ntype StandardTraceMethodDecorator = <This, TArgs extends unknown[], TReturn>(\n method: (this: This, ...args: TArgs) => TReturn,\n context: { kind: \"method\"; name: string | symbol },\n) => (this: This, ...args: TArgs) => TReturn\n\ntype LegacyTraceMethodDecorator = <This, TArgs extends unknown[], TReturn>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<(this: This, ...args: TArgs) => TReturn>,\n) => void\n\ntype TraceMethodDecorator = StandardTraceMethodDecorator &\n LegacyTraceMethodDecorator\n\nconst DEFAULT_AUTO_TRACE_MAX_DEPTH = 30\nconst DEFAULT_AUTO_TRACE_MAX_SPANS = 500\nconst AUTO_TRACE_PROTOCOL = \"ts-auto-v1\"\nconst AUTO_TRACE_POLICY_REFRESH_MS = 60_000\nconst AUTO_TRACE_POLICY_RETRY_MS = 10_000\n\ninterface AutoTracePolicyResponse {\n protocol: typeof AUTO_TRACE_PROTOCOL\n functionIds: string[]\n revision: string | null\n}\n\ninterface AutoTracePolicyRefresh {\n refreshAfter: number\n inFlight?: Promise<void>\n}\n\nfunction autoTraceLimit(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isFinite(value) && value >= 0\n ? Math.floor(value)\n : fallback\n}\n\ninterface FunctionVersionResponse {\n id: string\n name: string\n versionId: string\n versionNumber: number | null\n prompt: string\n providers: ProviderDefinition[]\n}\n\nexport { MixedTracingError }\n\n// Re-export BitfabError for backwards compatibility\nexport { BitfabError }\n\n/**\n * Client for making provider-based API calls via BAML.\n */\nexport class Bitfab {\n private readonly apiKeyConfig:\n | string\n | (() => string | null | undefined)\n | undefined\n /** Cached only once a non-empty key is found, so an early resolve (before env loaded) can't poison a later one. */\n private resolvedApiKey: string | undefined\n /** Gate the empty-key warning to fire at most once. */\n private apiKeyWarned: boolean = false\n private readonly serviceUrl: string\n private readonly timeout: number\n private readonly envVars: AllowedEnvVars\n private readonly captureConfigured: boolean\n private readonly strict: boolean\n private readonly httpClient: HttpClient\n /** Dataset operations for the authenticated organization. */\n readonly datasets: DatasetsClient\n private readonly bamlClient: unknown\n private readonly dbSnapshot: DbSnapshotConfig | undefined\n private readonly autoTracePolicyRefreshes = new Map<\n string,\n AutoTracePolicyRefresh\n >()\n /**\n * Mock overrides registered via {@link Bitfab.registerMockOverride}, applied\n * to every `replay` on this client (after any per-call `mockOverride`). In\n * registration order; first matcher wins within this list.\n */\n private readonly mockOverrides: MockOverride[] = []\n\n /**\n * Initialize the Bitfab client.\n *\n * @param config - Configuration options for the client\n */\n constructor(config: BitfabConfig) {\n this.apiKeyConfig = config.apiKey\n this.serviceUrl = config.serviceUrl ?? DEFAULT_SERVICE_URL\n this.timeout = config.timeout ?? 120000\n this.envVars = config.envVars ?? {}\n if (config.enabled !== undefined) {\n warnOnce(\n \"deprecated-enabled-option\",\n \"Bitfab({ enabled }) is deprecated; pass captureEnabled instead.\",\n )\n }\n this.captureConfigured =\n (config.captureEnabled ?? true) && (config.enabled ?? true)\n this.strict = config.strict ?? false\n this.bamlClient = config.bamlClient ?? null\n if (config.dbSnapshot) {\n validateDbSnapshotConfig(config.dbSnapshot)\n }\n this.dbSnapshot = config.dbSnapshot\n // The key is NOT read here. HttpClient gets a thunk so the key is resolved\n // at send time, after any in-script dotenv.config() has run.\n this.httpClient = new HttpClient({\n apiKey: () => this.resolveApiKey(),\n serviceUrl: this.serviceUrl,\n timeout: this.timeout,\n })\n this.datasets = new DatasetsClient(this.httpClient)\n }\n\n /**\n * Decorate a class method as an automatically expanded trace root.\n *\n * Build instrumentation turns repository functions called beneath this\n * method into nested spans that capture inputs, outputs, and errors by\n * default. A confirmed capture policy can narrow rich capture to selected\n * function IDs.\n * Without a compatible build transform, this still records the decorated\n * method as a normal rich root span but cannot discover child calls.\n *\n * @param traceFunctionKey - Groups traces and their capture policy.\n * @param options - Root presentation, subtree bounds, and exclusions.\n * @experimental Automatic child-call instrumentation is experimental.\n */\n trace(\n traceFunctionKey: string,\n options: TraceOptions = {},\n ): TraceMethodDecorator {\n const decorator = (...args: unknown[]): unknown => {\n if (args.length === 3) {\n const propertyKey = args[1] as string | symbol\n const descriptor = args[2] as TypedPropertyDescriptor<\n (this: unknown, ...methodArgs: unknown[]) => unknown\n >\n if (!descriptor || typeof descriptor.value !== \"function\") {\n throw new BitfabError(\"@bitfab.trace can only decorate methods\")\n }\n descriptor.value = this.createAutoTraceRoot(\n traceFunctionKey,\n String(propertyKey),\n options,\n descriptor.value,\n )\n return\n }\n\n const method = args[0]\n const context = args[1] as\n | { kind?: string; name?: string | symbol }\n | undefined\n if (\n typeof method !== \"function\" ||\n context?.kind !== \"method\" ||\n context.name === undefined\n ) {\n throw new BitfabError(\"@bitfab.trace can only decorate methods\")\n }\n return this.createAutoTraceRoot(\n traceFunctionKey,\n String(context.name),\n options,\n method as (this: unknown, ...methodArgs: unknown[]) => unknown,\n )\n }\n\n return decorator as TraceMethodDecorator\n }\n\n /**\n * Wrap a function as an automatically expanded trace root.\n *\n * This is the function-oriented equivalent of {@link Bitfab.trace}. Build\n * instrumentation turns repository functions called beneath the wrapped\n * function into nested spans that capture inputs, outputs, and errors by\n * default. A confirmed capture policy can narrow rich capture to selected\n * function IDs. Without a compatible transform, this still records one\n * normal rich root span and runs the function unchanged.\n *\n * @param traceFunctionKey - Groups traces and their capture policy.\n * @param optionsOrFn - Options or the workflow entrypoint to wrap.\n * @param maybeFn - Workflow entrypoint when options are provided.\n * @experimental Automatic child-call instrumentation is experimental.\n */\n withTrace<This, TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn\n withTrace<This, TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n options: TraceOptions,\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn\n withTrace<This, TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n optionsOrFn: TraceOptions | ((this: This, ...args: TArgs) => TReturn),\n maybeFn?: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn {\n const options = typeof optionsOrFn === \"function\" ? {} : optionsOrFn\n const fn = typeof optionsOrFn === \"function\" ? optionsOrFn : maybeFn\n if (!fn) {\n throw new BitfabError(\"bitfab.withTrace requires a function\")\n }\n const name = fn.name !== \"\" ? fn.name : traceFunctionKey\n return this.createAutoTraceRoot(traceFunctionKey, name, options, fn)\n }\n\n /**\n * Configure a transformed class method when it is discovered beneath a\n * {@link Bitfab.trace} root.\n *\n * The decorator creates no span or trace by itself. Beneath an active trace,\n * it can rename or retype the discovered call, capture its contents, mark it\n * for recorded-output replay, finalize its output, or omit it while leaving\n * captured descendants attached to the nearest captured parent.\n *\n * @param options - Trace-owned call configuration.\n * @experimental Automatic child-call instrumentation is experimental.\n */\n node(options: NodeOptions = {}): NodeMethodDecorator {\n const configuration = this.resolveNodeConfiguration(options)\n const decorator = (...args: unknown[]): unknown => {\n if (args.length === 3) {\n const descriptor = args[2] as TypedPropertyDescriptor<\n (this: unknown, ...methodArgs: unknown[]) => unknown\n >\n if (!descriptor || typeof descriptor.value !== \"function\") {\n throw new BitfabError(\"@bitfab.node can only decorate methods\")\n }\n descriptor.value = this.createAutoTraceNode(\n configuration,\n descriptor.value,\n String(args[1]),\n )\n return\n }\n\n const method = args[0]\n const context = args[1] as\n | { kind?: string; name?: string | symbol }\n | undefined\n if (typeof method !== \"function\" || context?.kind !== \"method\") {\n throw new BitfabError(\"@bitfab.node can only decorate methods\")\n }\n return this.createAutoTraceNode(\n configuration,\n method as (this: unknown, ...methodArgs: unknown[]) => unknown,\n String(context.name),\n )\n }\n\n return decorator as NodeMethodDecorator\n }\n\n /**\n * Configure a transformed standalone function when it is discovered beneath\n * a {@link Bitfab.trace} or {@link Bitfab.withTrace} root.\n *\n * This is the function-oriented equivalent of {@link Bitfab.node}. Without\n * an active automatic trace, the returned function runs normally and never\n * creates a span or trace. The function must be named so configuration can\n * be bound to its transformed definition without leaking to a descendant.\n *\n * @param optionsOrFn - Node options or the function to configure.\n * @param maybeFn - Function to configure when options are provided.\n * @experimental Automatic child-call instrumentation is experimental.\n */\n withNode<This, TArgs extends unknown[], TReturn>(\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn\n withNode<This, TArgs extends unknown[], TReturn>(\n options: NodeOptions,\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn\n withNode<This, TArgs extends unknown[], TReturn>(\n optionsOrFn: NodeOptions | ((this: This, ...args: TArgs) => TReturn),\n maybeFn?: (this: This, ...args: TArgs) => TReturn,\n internalFunctionName?: string,\n ): (this: This, ...args: TArgs) => TReturn {\n const options = typeof optionsOrFn === \"function\" ? {} : optionsOrFn\n const fn = typeof optionsOrFn === \"function\" ? optionsOrFn : maybeFn\n if (!fn) {\n throw new BitfabError(\"bitfab.withNode requires a function\")\n }\n const configuration = this.resolveNodeConfiguration(options)\n const functionName = internalFunctionName ?? fn.name\n if (functionName === \"\") {\n throw new BitfabError(\n \"bitfab.withNode requires a named function so the subtree transform can bind its configuration to the correct call.\",\n )\n }\n return this.createAutoTraceNode(configuration, fn, functionName)\n }\n\n private resolveNodeConfiguration(\n options: NodeOptions,\n ): NodeConfigurationOptions {\n const capture = options.capture ?? true\n if (!capture && options.mockOnReplay === true) {\n throw new BitfabError(\n \"bitfab.node({ capture: false }) cannot use mockOnReplay: true because an uncaptured node has no recorded output.\",\n )\n }\n return {\n capture,\n type: options.type ?? \"custom\",\n ...(options.name !== undefined && { name: options.name }),\n ...(options.testRunId !== undefined && {\n testRunId: options.testRunId,\n }),\n ...(options.mockOnReplay !== undefined && {\n mockOnReplay: options.mockOnReplay,\n }),\n ...(options.finalize !== undefined && { finalize: options.finalize }),\n }\n }\n\n private createAutoTraceNode<This, TArgs extends unknown[], TReturn>(\n configuration: NodeConfigurationOptions,\n fn: (this: This, ...args: TArgs) => TReturn,\n functionName: string,\n ): (this: This, ...args: TArgs) => TReturn {\n const nodeConfiguration = { ...configuration, functionName }\n return function (this: This, ...args: TArgs): TReturn {\n if (!__bitfabAutoTraceActive()) {\n if (enclosingSurface() === \"opt-in\") {\n throw mixedTracingError(\"node()\", \"opt-out\", \"opt-in\")\n }\n return fn.apply(this, args)\n }\n return runWithAutoTraceNodeConfiguration(nodeConfiguration, () =>\n fn.apply(this, args),\n )\n }\n }\n\n private createAutoTraceRoot<This, TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n name: string,\n options: TraceOptions,\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn {\n const self = this\n const maxDepth = autoTraceLimit(\n options.maxDepth,\n DEFAULT_AUTO_TRACE_MAX_DEPTH,\n )\n const maxSpans = autoTraceLimit(\n options.maxSpans,\n DEFAULT_AUTO_TRACE_MAX_SPANS,\n )\n const excluded = new Set(options.exclude ?? [])\n const includeWrappers = options.includeWrappers ?? false\n const rootOptions: InternalSpanOptions = {\n name: options.name ?? name,\n type: options.type ?? \"custom\",\n surface: \"opt-out\",\n }\n const tracedRoot = this.withSpan(\n traceFunctionKey,\n rootOptions,\n function (this: This, ...args: TArgs): TReturn {\n const capturePolicy = getAutoTraceCapturePolicy(self, traceFunctionKey)\n self.refreshAutoTraceCapturePolicy(traceFunctionKey)\n let spansUsed = 0\n let truncated = false\n const warnTruncated = (): void => {\n if (!truncated) {\n truncated = true\n getCurrentTrace().setMetadata({\n bitfabAutoTrace: {\n protocol: AUTO_TRACE_PROTOCOL,\n truncated: true,\n maxDepth,\n maxSpans,\n },\n })\n }\n warnOnce(\n `auto-trace-truncated:${traceFunctionKey}`,\n `\"${traceFunctionKey}\" hit an automatic subtree capture limit (maxDepth=${maxDepth}, maxSpans=${maxSpans}); its trace is incomplete. Raise the limits or narrow the subtree with exclude.`,\n )\n }\n const autoTraceContext: AutoTraceContext = {\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n invokeFn: () => T,\n depth: number,\n nodeConfiguration?: AutoTraceNodeConfiguration,\n ): T {\n const nameParts = definition.name.split(\".\")\n const simpleName = nameParts[nameParts.length - 1]\n const invokeWithoutNode = (): T =>\n nodeConfiguration === undefined\n ? invokeFn()\n : runWithAutoTraceContext(autoTraceContext, invokeFn, depth)\n if (\n excluded.has(definition.name) ||\n (simpleName !== undefined && excluded.has(simpleName)) ||\n (nodeConfiguration === undefined &&\n definition.wrapper === true &&\n !includeWrappers)\n ) {\n return invokeWithoutNode()\n }\n if (nodeConfiguration?.capture === false) {\n return runWithAutoTraceContext(autoTraceContext, invokeFn, depth)\n }\n if (depth >= maxDepth || spansUsed >= maxSpans) {\n warnTruncated()\n return invokeWithoutNode()\n }\n spansUsed += 1\n const mockOnReplay =\n nodeConfiguration?.mockOnReplay ?? options.mockOnReplayDefault\n const childOptions: InternalSpanOptions = {\n name: nodeConfiguration?.name ?? definition.name,\n type: nodeConfiguration?.type ?? \"function\",\n captureWhen: \"nested\",\n surface: \"opt-out\",\n functionId: definition.id,\n captureContent:\n nodeConfiguration !== undefined ||\n capturePolicy === undefined ||\n capturePolicy.has(definition.id),\n autoTraceDefinition: definition,\n ...(nodeConfiguration?.testRunId !== undefined && {\n testRunId: nodeConfiguration.testRunId,\n }),\n ...(mockOnReplay !== undefined && {\n mockOnReplay,\n }),\n ...(nodeConfiguration?.finalize !== undefined && {\n finalize: nodeConfiguration.finalize,\n }),\n }\n const invokeWithAutoTraceContext = (): T =>\n runWithAutoTraceContext(autoTraceContext, invokeFn, depth + 1)\n if (definition.async === true) {\n const tracedAsyncChild = self.withSpan(\n traceFunctionKey,\n childOptions,\n async (..._inputs: unknown[]) =>\n await invokeWithAutoTraceContext(),\n )\n return tracedAsyncChild(...inputs) as T\n }\n const tracedChild = self.withSpan(\n traceFunctionKey,\n childOptions,\n (..._inputs: unknown[]): T => invokeWithAutoTraceContext(),\n )\n return tracedChild(...inputs)\n },\n }\n\n return runWithAutoTraceRootContext(autoTraceContext, () =>\n fn.apply(this, args),\n )\n },\n )\n const autoTraceRoot = function (this: This, ...args: TArgs): TReturn {\n if (!self.shouldRecord()) {\n return fn.apply(this, args)\n }\n return tracedRoot.apply(this, args)\n }\n Object.defineProperty(autoTraceRoot, \"_bitfabTraceFunctionKey\", {\n value: traceFunctionKey,\n })\n Object.defineProperty(autoTraceRoot, \"_bitfabWrappedFn\", { value: fn })\n return autoTraceRoot\n }\n\n private refreshAutoTraceCapturePolicy(traceFunctionKey: string): void {\n const now = Date.now()\n const state = this.autoTracePolicyRefreshes.get(traceFunctionKey) ?? {\n refreshAfter: 0,\n }\n if (state.inFlight || now < state.refreshAfter) {\n return\n }\n\n const request = this.httpClient\n .getAutoTracePolicy<AutoTracePolicyResponse>(\n traceFunctionKey,\n AUTO_TRACE_PROTOCOL,\n )\n .then((policy) => {\n if (policy.protocol !== AUTO_TRACE_PROTOCOL) {\n state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS\n return\n }\n const functionIds = Array.isArray(policy.functionIds)\n ? policy.functionIds\n .filter(\n (id): id is string =>\n typeof id === \"string\" &&\n id.startsWith(`${AUTO_TRACE_PROTOCOL}:`),\n )\n .slice(0, DEFAULT_AUTO_TRACE_MAX_SPANS)\n : []\n __setBitfabAutoTraceCapturePolicy(\n this,\n traceFunctionKey,\n policy.revision === null ? undefined : functionIds,\n )\n state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_REFRESH_MS\n })\n .catch(() => {\n state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS\n })\n .finally(() => {\n state.inFlight = undefined\n })\n state.inFlight = request\n this.autoTracePolicyRefreshes.set(traceFunctionKey, state)\n }\n\n /**\n * Flush and permanently close this client's tracing resources: its pending\n * requests and the single span-transport worker shared by its decorators and\n * framework handlers.\n *\n * Resolves `false` when delivery failed or the deadline expired. Long-lived\n * processes never need this (the transport batches in the background and the\n * exit hook drains it); scripts and tests that want a hard guarantee should\n * await it.\n *\n * Deliberately not a `Symbol.asyncDispose` method: the SDK targets runtimes\n * where that symbol may be absent, and a computed key on a missing symbol\n * throws at class-definition time, taking the whole SDK down on load.\n */\n close(timeoutMs?: number): Promise<boolean> {\n return this.httpClient.close(timeoutMs)\n }\n\n /**\n * Resolve the API key lazily, the first time a span actually needs it.\n *\n * The key is intentionally NOT read at construction. In ESM, a shim that\n * does `new Bitfab({ apiKey: process.env.BITFAB_API_KEY })` is hoisted and\n * evaluated before the importing script's body runs `dotenv.config()`, so\n * the key would be empty at construction even though it is set moments\n * later. Resolving here (at first `withSpan` call / first request) reads\n * the key after env loading has run.\n *\n * Resolution order: the configured value (string, or function called each\n * time it is still unresolved), then a fallback read of `BITFAB_API_KEY`\n * from the environment. Once a non-empty key is found it is cached, so an\n * early resolve that found nothing never poisons a later one.\n */\n private resolveApiKey(): string | undefined {\n if (this.resolvedApiKey !== undefined) {\n return this.resolvedApiKey\n }\n const fromConfig =\n typeof this.apiKeyConfig === \"function\"\n ? this.apiKeyConfig()\n : this.apiKeyConfig\n const candidate =\n fromConfig && fromConfig.trim() !== \"\"\n ? fromConfig\n : readEnv(\"BITFAB_API_KEY\")\n const key = candidate && candidate.trim() !== \"\" ? candidate : undefined\n if (key) {\n this.resolvedApiKey = key\n return key\n }\n if (this.strict) {\n throw new BitfabError(\n \"Bitfab: no API key resolved. Set BITFAB_API_KEY or pass apiKey to \" +\n \"new Bitfab(). If a script loads env with dotenv, load it before the \" +\n \"module that constructs the client is imported (e.g. \" +\n \"`node --env-file=.env script.ts`), or pass \" +\n \"`apiKey: () => process.env.BITFAB_API_KEY`.\",\n )\n }\n if (this.captureConfigured && !this.apiKeyWarned) {\n this.apiKeyWarned = true\n console.warn(\n \"Bitfab: apiKey is empty - tracing is disabled. Provide a valid API key to enable tracing.\",\n )\n }\n return undefined\n }\n\n private isCaptureEnabled(): boolean {\n if (!this.captureConfigured) {\n return false\n }\n return this.resolveApiKey() !== undefined\n }\n\n private shouldRecord(): boolean {\n if (!this.captureConfigured && !getReplayContext() && !inSeedScope()) {\n return false\n }\n return this.resolveApiKey() !== undefined\n }\n\n get captureEnabled(): boolean {\n return this.isCaptureEnabled()\n }\n\n /**\n * Fetch the function with its current version and BAML prompt from the server.\n *\n * @param methodName - The name of the method to fetch\n * @returns The function with current version, BAML prompt, and provider definitions\n * @throws {BitfabError} If the function is not found or an error occurs\n */\n private async fetchFunctionVersion(\n methodName: string,\n ): Promise<FunctionVersionResponse> {\n const result =\n await this.httpClient.lookupFunction<FunctionVersionResponse>(methodName)\n\n // Check if function was not found\n if (result.id === null) {\n throw new BitfabError(\n `Function \"${methodName}\" not found. Create it at: ${this.serviceUrl}/functions`,\n \"/functions\",\n )\n }\n\n // Check if function has no prompt\n if (!result.prompt) {\n throw new BitfabError(\n `Function \"${methodName}\" has no prompt configured. Add one at: ${this.serviceUrl}/functions/${result.id}`,\n `/functions/${result.id}`,\n )\n }\n\n return result\n }\n\n /**\n * Call a method with the given named arguments via BAML execution.\n *\n * @param methodName - The name of the method to call\n * @param inputs - Named arguments to pass to the method\n * @returns The result of the BAML function execution\n * @throws {BitfabError} If service_url is not set, or if an error occurs\n */\n async call<T = unknown>(\n methodName: string,\n inputs: Record<string, unknown> = {},\n ): Promise<T> {\n try {\n const functionVersion = await this.fetchFunctionVersion(methodName)\n const executionResult = await runFunctionWithBaml(\n functionVersion.prompt,\n inputs,\n functionVersion.providers,\n this.envVars,\n )\n\n // Create trace for the local execution. A non-serializable result must\n // not throw into the user's `call()`: fall back to String() if\n // JSON.stringify throws or yields undefined (e.g. a function result).\n let resultStr: string\n if (typeof executionResult.result === \"string\") {\n resultStr = executionResult.result\n } else {\n try {\n resultStr =\n JSON.stringify(executionResult.result) ??\n String(executionResult.result)\n } catch {\n warnOnce(\n \"call-result-serialize\",\n \"a local execution result could not be JSON-serialized; storing its String() form instead. The call still returns its real value.\",\n )\n resultStr = String(executionResult.result)\n }\n }\n\n // Create trace in background so user doesn't have to wait\n this.httpClient.sendInternalTrace(functionVersion.id, {\n result: resultStr,\n source: \"typescript-sdk\",\n ...(Object.keys(inputs).length > 0 && { inputs }),\n ...(executionResult.rawCollector != null && {\n rawCollector: executionResult.rawCollector,\n }),\n })\n\n return executionResult.result as T\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred during local execution\")\n }\n }\n\n /**\n * Get a tracing processor for OpenAI Agents SDK integration.\n *\n * This processor automatically captures traces and spans from the OpenAI Agents SDK\n * and sends them to Bitfab for monitoring and analysis.\n *\n * Example usage:\n * ```typescript\n * import { addTraceProcessor } from '@openai/agents';\n *\n * const client = new Bitfab({ apiKey: 'your-api-key' });\n * const processor = client.getOpenAiTracingProcessor();\n * addTraceProcessor(processor);\n * ```\n *\n * @returns A BitfabOpenAITracingProcessor instance configured for this client\n */\n getOpenAiTracingProcessor() {\n return new BitfabOpenAITracingProcessor({\n // Resolved at getter-call time (framework handlers are set up after env\n // loads); the withSpan path stays lazy via the constructor HttpClient thunk.\n apiKey: this.resolveApiKey(),\n serviceUrl: this.serviceUrl,\n getActiveSpanContext: () => {\n const stack = getSpanStack()\n return stack[stack.length - 1] ?? null\n },\n _httpClient: this.httpClient,\n })\n }\n\n /**\n * Get an OpenAI Agents SDK handler that records a replayable root span.\n *\n * The processor from {@link getOpenAiTracingProcessor} captures everything\n * inside a run (LLM calls, tools, handoffs) but never sees the caller's\n * input, so a processor-only run records an empty-input root and is not\n * replayable. This handler's `wrapRun` is a drop-in for `run()` that opens a\n * `withSpan` root carrying the input and final output; the processor's spans\n * nest beneath it. Register the processor once at startup, then call\n * `handler.wrapRun(agent, input)` in place of `run(agent, input)`.\n *\n * ```typescript\n * import { addTraceProcessor, Agent, run } from \"@openai/agents\";\n *\n * addTraceProcessor(client.getOpenAiTracingProcessor());\n * const handler = client.getOpenAiAgentHandler(\"research-topic\");\n * const result = await handler.wrapRun(agent, \"Find X\");\n * ```\n *\n * @param traceFunctionKey - Groups traces under this key in Bitfab\n * @returns A BitfabOpenAIAgentHandler configured for this client\n */\n getOpenAiAgentHandler(traceFunctionKey: string) {\n return new BitfabOpenAIAgentHandler({\n traceFunctionKey,\n withSpan: this.withSpan.bind(this),\n getActiveSpanContext: () => {\n const stack = getSpanStack()\n return stack[stack.length - 1] ?? null\n },\n })\n }\n\n /**\n * Get a LangGraph/LangChain callback handler for tracing.\n *\n * The handler captures graph node execution, LLM calls, and tool\n * invocations as Bitfab spans with proper parent-child hierarchy.\n *\n * ```typescript\n * const handler = client.getLangGraphCallbackHandler(\"my-agent\");\n * const result = await agent.invoke(\n * { messages: [...] },\n * { callbacks: [handler] },\n * );\n * ```\n *\n * @param traceFunctionKey - Groups traces under this key in Bitfab\n * @returns A BitfabLangGraphCallbackHandler configured for this client\n */\n getLangGraphCallbackHandler(traceFunctionKey: string) {\n return new BitfabLangGraphCallbackHandler({\n apiKey: this.resolveApiKey(),\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n getActiveSpanContext: () => {\n const stack = getSpanStack()\n return stack[stack.length - 1] ?? null\n },\n _httpClient: this.httpClient,\n })\n }\n\n /**\n * Get a LangChain callback handler for tracing.\n *\n * Alias of {@link getLangGraphCallbackHandler}: LangChain chains and\n * LangGraph graphs share the same callback system, so one handler serves\n * both.\n *\n * ```typescript\n * const handler = client.getLangChainCallbackHandler(\"my-chain\");\n * const result = await chain.invoke(input, { callbacks: [handler] });\n * ```\n *\n * @param traceFunctionKey - Groups traces under this key in Bitfab\n * @returns A BitfabLangGraphCallbackHandler configured for this client\n */\n getLangChainCallbackHandler(traceFunctionKey: string) {\n return this.getLangGraphCallbackHandler(traceFunctionKey)\n }\n\n /**\n * Get the first-class LangGraph integration for tracing and replaying tools\n * executed by `ToolNode`.\n *\n * The integration combines `wrapTools()` for per-tool replay interception\n * with `createInvoker()` for a callback-configured replayable graph entry\n * point. Lower-level callback and root wrappers remain available.\n *\n * @param traceFunctionKey - Groups traces under this key in Bitfab\n * @param options - Controls which tools are marked for replay mocking\n * @experimental This API may change before it is stable.\n */\n getLangGraphIntegration(\n traceFunctionKey: string,\n options?: LangGraphIntegrationOptions,\n ): BitfabLangGraphIntegration {\n const callbackHandler = new BitfabLangGraphCallbackHandler({\n apiKey: this.resolveApiKey(),\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n getActiveSpanContext: () => {\n const stack = getSpanStack()\n return stack[stack.length - 1] ?? null\n },\n captureTools: false,\n _httpClient: this.httpClient,\n })\n return new BitfabLangGraphIntegration({\n client: this,\n traceFunctionKey,\n callbackHandler,\n options,\n })\n }\n\n /**\n * Get a Claude Agent SDK handler for tracing.\n *\n * The handler captures LLM turns, tool invocations, and subagent\n * execution as Bitfab spans with proper parent-child hierarchy.\n *\n * ```typescript\n * import { query } from \"@anthropic-ai/claude-agent-sdk\";\n *\n * const handler = client.getClaudeAgentHandler(\"my-agent\");\n * const options = handler.instrumentOptions({\n * model: \"claude-sonnet-4-5-...\",\n * });\n * for await (const msg of handler.wrapQuery(\n * query({ prompt: \"Do something\", options })\n * )) {\n * // process messages\n * }\n * ```\n *\n * @param traceFunctionKey - Groups traces under this key in Bitfab\n * @returns A BitfabClaudeAgentHandler configured for this client\n */\n getClaudeAgentHandler(traceFunctionKey: string) {\n return new BitfabClaudeAgentHandler({\n apiKey: this.resolveApiKey(),\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n getActiveSpanContext: () => {\n const stack = getSpanStack()\n return stack[stack.length - 1] ?? null\n },\n _httpClient: this.httpClient,\n })\n }\n\n /**\n * Get a Vercel AI SDK language-model middleware for tracing.\n *\n * Pass it to the AI SDK's `wrapLanguageModel` and use the wrapped model with\n * `generateText` / `streamText` / `generateObject` / `streamObject`. Every\n * call through that model is captured as a keyed `llm` span carrying the call\n * parameters (the prompt) as input and a serializable summary\n * (`{ text, toolCalls, usage, finishReason }`) as output. Streaming is\n * captured without disturbing the caller's live stream.\n *\n * ```typescript\n * import { wrapLanguageModel, streamText } from \"ai\";\n * import { openai } from \"@ai-sdk/openai\";\n *\n * const model = wrapLanguageModel({\n * model: openai(\"gpt-4o\"),\n * middleware: client.getVercelAiMiddleware(\"chat-turn\"),\n * });\n * const result = streamText({ model, messages });\n * ```\n *\n * @param traceFunctionKey - Groups traces under this key in Bitfab\n * @returns A Vercel AI SDK middleware configured for this client\n */\n getVercelAiMiddleware(traceFunctionKey: string) {\n return new BitfabVercelAiHandler({\n traceFunctionKey,\n withSpan: this.withSpan.bind(this),\n }).middleware\n }\n\n /**\n * Wrap a BAML client method to automatically capture prompt and LLM metadata.\n *\n * Creates a BAML Collector, calls the method through a tracked client,\n * then extracts rendered messages and token usage - calling setPrompt()\n * and addContext() on the current span automatically.\n *\n * The BAML client can be provided in the constructor or passed explicitly:\n *\n * ```typescript\n * // Option 1: bamlClient in constructor (use wrapBAML with just the method)\n * const client = new Bitfab({ apiKey: 'your-api-key', bamlClient: b });\n * const traced = client.withSpan('classify', { type: 'llm' },\n * client.wrapBAML(b.ClassifyText)\n * );\n *\n * // Option 2: pass bamlClient at call site\n * const client = new Bitfab({ apiKey: 'your-api-key' });\n * const traced = client.withSpan('classify', { type: 'llm' },\n * client.wrapBAML(b, b.ClassifyText)\n * );\n * ```\n *\n * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance\n * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method\n * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form\n * @returns An async function with the same signature that instruments the BAML call\n */\n wrapBAML<TArgs extends unknown[], TReturn>(\n methodOrClient: unknown,\n maybeMethodOrOptions?:\n | ((...args: TArgs) => Promise<TReturn>)\n | WrapBAMLOptions,\n maybeOptions?: WrapBAMLOptions,\n ): WrappedBamlFn<TArgs, TReturn> {\n let bamlClient: unknown\n let method: (...args: TArgs) => Promise<TReturn>\n let options: WrapBAMLOptions | undefined\n\n if (typeof maybeMethodOrOptions === \"function\") {\n bamlClient = methodOrClient\n method = maybeMethodOrOptions\n options = maybeOptions\n } else {\n bamlClient = this.bamlClient\n method = methodOrClient as (...args: TArgs) => Promise<TReturn>\n options = maybeMethodOrOptions as WrapBAMLOptions | undefined\n if (!bamlClient) {\n throw new BitfabError(\n \"bamlClient is required for wrapBAML. Pass it in the constructor or as the first argument.\",\n )\n }\n }\n\n const methodName = method.name\n if (!methodName) {\n throw new BitfabError(\n \"wrapBAML requires a named function (e.g., b.ClassifyText).\",\n )\n }\n\n // Warm the Collector class cache so it's ready by the time the wrapper is called\n loadCollectorClass()\n\n const wrappedFn = async (...args: TArgs): Promise<TReturn> => {\n const CollectorClass = await loadCollectorClass()\n if (!CollectorClass) {\n // @boundaryml/baml not available - call method directly as fallback\n wrappedFn.collector = null\n return await (\n bamlClient as Record<string, (...a: TArgs) => Promise<TReturn>>\n )[methodName](...args)\n }\n\n const collector = new CollectorClass(\"bitfab-baml-tracing\")\n\n // Setting up the tracked client is a side-channel: a BAML version\n // mismatch, or a non-BAML object passed as `bamlClient`, must not stop\n // the user's call. If `withOptions` or the method lookup fails, fall back\n // to the untracked method so the call still runs (untraced).\n let trackedClient: Record<string, unknown>\n let trackedMethod: (...a: TArgs) => Promise<TReturn>\n try {\n trackedClient = (\n bamlClient as { withOptions: (opts: unknown) => unknown }\n ).withOptions({ collector }) as Record<string, unknown>\n const method = (\n trackedClient as Record<string, (...a: TArgs) => Promise<TReturn>>\n )[methodName]\n if (typeof method !== \"function\") {\n throw new BitfabError(\n \"bamlClient.withOptions did not return the wrapped method\",\n )\n }\n trackedMethod = method\n } catch {\n warnOnce(\n `wrapBAML-setup:${methodName}`,\n `BAML tracing setup failed for \"${methodName}\" (incompatible bamlClient or BAML version); calling it untraced. The call still runs; no span is recorded.`,\n )\n wrappedFn.collector = null\n return await (\n bamlClient as Record<string, (...a: TArgs) => Promise<TReturn>>\n )[methodName](...args)\n }\n\n const result = await trackedMethod.bind(trackedClient)(...args)\n\n wrappedFn.collector = collector\n\n try {\n const prompt = extractPromptFromCollector(collector)\n if (prompt) {\n getCurrentSpan().setPrompt(prompt)\n }\n const metadata = extractContextFromCollector(collector)\n if (metadata) {\n getCurrentSpan().addContext(metadata)\n }\n } catch {\n // Never crash the host app\n }\n\n try {\n options?.onCollector?.(collector)\n } catch {\n // Never crash the host app\n }\n\n return result\n }\n\n wrappedFn.collector = null as unknown | null\n\n return wrappedFn\n }\n\n /**\n * Wrap a function to automatically create a span for its inputs and outputs.\n *\n * The wrapped function behaves identically to the original, but sends\n * span data to Bitfab in the background after each call.\n *\n * Example usage:\n * ```typescript\n * const client = new Bitfab({ apiKey: 'your-api-key' });\n *\n * async function processOrder(orderId: string, items: string[]): Promise<{ total: number }> {\n * // ... process order\n * return { total: 100 };\n * }\n *\n * // Basic usage (defaults to \"custom\" span type)\n * const tracedProcessOrder = client.withSpan('order-processing', processOrder);\n *\n * // With explicit span type\n * const tracedProcessOrder = client.withSpan('order-processing', { type: 'function' }, processOrder);\n *\n * // Call the wrapped function normally\n * const result = await tracedProcessOrder('order-123', ['item-1', 'item-2']);\n * // Span is automatically sent to Bitfab\n * ```\n *\n * @param traceFunctionKey - A string identifier for grouping spans (e.g., 'order-processing', 'user-auth')\n * @param optionsOrFn - Either SpanOptions or the function to wrap\n * @param maybeFn - The function to wrap if options were provided\n * @returns A wrapped function with the same signature that creates spans for inputs and outputs\n */\n withSpan<TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n optionsOrFn: SpanOptions | ((...args: TArgs) => TReturn),\n maybeFn?: (...args: TArgs) => TReturn,\n ): (...args: TArgs) => TReturn {\n // Handle overloaded signature\n const options: InternalSpanOptions =\n typeof optionsOrFn === \"function\" ? {} : optionsOrFn\n const fn: (...args: TArgs) => TReturn =\n typeof optionsOrFn === \"function\" ? optionsOrFn : maybeFn!\n const self = this\n\n // Detect Promise-returning fn at wrap time so the mock-fire path can\n // match the original return shape. `AsyncFunction` covers `async fn`\n // declarations; for plain functions that return a Promise we fall back\n // to a `fn.toString()` heuristic (looks for `Promise` or `await`).\n // Brittle for minified code, but mock-fire is the only consumer and a\n // sync fallback (returning a raw value) is the safe degradation.\n const fnIsAsyncFunction = fn.constructor.name === \"AsyncFunction\"\n const fnReturnsPromise =\n fnIsAsyncFunction ||\n (() => {\n try {\n const src = fn.toString()\n return /\\b(?:Promise|await)\\b/.test(src)\n } catch {\n return false\n }\n })()\n\n const wrappedFn = function (this: unknown, ...args: TArgs): TReturn {\n // Decide whether to trace at CALL time, not wrap time. The shim builds\n // this wrapper at module load, often before env (dotenv) has loaded, so\n // freezing the decision here would permanently disable tracing for a key\n // that is set moments later. Re-checking per call lets a late-resolved\n // key take effect; once a key is found the resolution is cached.\n if (!self.shouldRecord()) {\n return fn.apply(this, args)\n }\n\n // The Node-specific entry registers async_hooks synchronously, but ESM\n // chunk evaluation can load this module before that registration runs.\n // Re-check at call time so the first traced invocation gets native\n // context propagation instead of briefly using the browser fallback.\n initializeAsyncContext()\n\n // Defer until AsyncLocalStorage init completes. In Node.js, the\n // dynamic import resolves in one microtask; in browsers, the init\n // resolves immediately to a no-op. The `asyncLocalStorageInitDone`\n // flag prevents an infinite loop when AsyncLocalStorage is\n // unavailable (browsers).\n if (!asyncLocalStorage && !isAsyncStorageInitDone()) {\n return asyncLocalStorageReady.then(() =>\n wrappedFn.apply(this, args),\n ) as unknown as TReturn\n }\n\n const captureWhen: unknown =\n options.captureWhen === undefined ? \"always\" : options.captureWhen\n const resolvedCaptureWhen: CaptureWhen =\n captureWhen === \"always\" || captureWhen === \"nested\"\n ? captureWhen\n : \"always\"\n if (resolvedCaptureWhen !== captureWhen) {\n let invalidValue: string\n try {\n invalidValue = String(captureWhen)\n } catch {\n invalidValue = \"<unprintable>\"\n }\n warnOnce(\n `invalid-capture-when:${traceFunctionKey}`,\n `unknown captureWhen value \"${invalidValue}\"; defaulting to \"always\". Valid values: \"always\", \"nested\".`,\n )\n }\n\n if (resolvedCaptureWhen === \"nested\") {\n let hasParent = false\n try {\n hasParent = getSpanStack().length > 0\n } catch (setupError) {\n if (getReplayContext()) {\n throw setupError\n }\n warnOnce(\n `withSpan-setup:${traceFunctionKey}`,\n `tracing setup failed for \"${traceFunctionKey}\"; running it untraced. The function still runs and returns normally; no span is recorded.`,\n )\n return fn.apply(this, args) as TReturn\n }\n if (!hasParent) {\n return fn.apply(this, args) as TReturn\n }\n }\n\n // Tracing is a side-channel: building the span context must never stop\n // the user's function from running. If any of this setup throws (e.g. a\n // runtime without a usable `crypto`, or a context/snapshot edge), fall\n // back to running `fn` directly, untraced. The `!` definite-assignments\n // are sound because the catch always returns: reaching past the\n // try/catch means the try completed and both values were assigned.\n let newStack!: SpanContext[]\n let executeWithContext!: () => TReturn\n // Set only if THIS call registers root trace state below, so a setup\n // failure after registration can clean up the orphaned entry (see catch).\n let registeredTraceId: string | undefined\n try {\n // Get current span stack to determine trace context\n const currentStack = getSpanStack()\n const parentContext = currentStack[currentStack.length - 1]\n\n // Generate trace ID (replay override > parent > new)\n const replayCtxForTraceId = parentContext ? null : getReplayContext()\n const seedCtxForTraceId = parentContext ? null : getSeedContext()\n const traceId =\n parentContext?.traceId ??\n replayCtxForTraceId?.traceId ??\n seedCtxForTraceId?.traceId ??\n randomUuid()\n const spanId = randomUuid()\n const parentSpanId = parentContext?.spanId ?? null\n const isRootSpan = parentSpanId === null\n\n const requestedSurface: SurfaceRequest =\n options.surface ?? DEFAULT_SURFACE\n const surface = resolveSurface(requestedSurface, parentContext?.surface)\n assertSurfacesCompatible(\n requestedSurface,\n surface,\n parentContext?.surface,\n traceFunctionKey,\n )\n\n // Create new context for this span with empty contexts array\n const newContext: SpanContext = {\n traceId,\n spanId,\n contexts: [],\n ...(surface !== undefined && { surface }),\n }\n newStack = [...currentStack, newContext]\n\n // Capture inputs and start time\n const inputs = args\n const startedAt = nowIsoTimestamp()\n const replayCtxAtStart = getReplayContext()\n const testRunId = replayCtxAtStart?.testRunId ?? options.testRunId\n\n // Register trace state for root spans\n if (isRootSpan && !activeTraceStates.has(traceId)) {\n // Synchronously snapshot the wall clock the SDK sees right now,\n // before invoking the wrapped function. This timestamp is the Neon\n // snapshot pin used by the server-side resolver. It is captured on\n // every trace (no IO, harmless to store) so any trace can later be\n // replayed against a historical branch; the provider is attached\n // only when dbSnapshot is configured, otherwise resolved at replay.\n const dbSnapshotRef = buildSnapshotRef(self.dbSnapshot, startedAt)\n activeTraceStates.set(traceId, {\n traceId,\n startedAt,\n contexts: [],\n ...(testRunId !== undefined && { testRunId }),\n ...(replayCtxAtStart?.inputSourceTraceId && {\n inputSourceTraceId: replayCtxAtStart.inputSourceTraceId,\n }),\n ...(replayCtxAtStart?.replayAttempt !== undefined && {\n replayAttempt: replayCtxAtStart.replayAttempt,\n }),\n dbSnapshotRef,\n })\n registeredTraceId = traceId\n }\n\n // Shared span parameters\n const functionName = fn.name !== \"\" ? fn.name : undefined\n const baseSpanParams = {\n traceFunctionKey,\n functionName,\n spanName: options.name ?? functionName ?? traceFunctionKey,\n traceId,\n spanId,\n parentSpanId,\n inputs,\n startedAt,\n spanType: options.type ?? \"custom\",\n functionId: options.functionId,\n captureContent: options.captureContent ?? true,\n autoTraceDefinition: options.autoTraceDefinition,\n }\n\n // Helper to send the span and, for root spans, the trace completion\n // that follows it. Both are handed to the client's span transport,\n // which owns queueing, batching and delivery: nothing here waits on\n // the network, and replay confirms persistence with a server-side\n // barrier rather than by chaining upload promises.\n // Wrapped in try/catch so span errors never crash the host app.\n const sendSpan = async (params: {\n result: unknown\n error?: string\n mocked?: boolean\n mockTarget?: MockTarget\n mockSource?: MockSource\n }) => {\n const replayCtx = getReplayContext()\n try {\n const endedAt = nowIsoTimestamp()\n\n // If drop() was called on this trace, suppress the span PAYLOAD\n // upload for every span that completes after the flag was set.\n // The trace completion signal below still rides out with\n // `dropped: true`, so the server scrubs any sibling spans that\n // already raced out (fire-and-forget) before the flag was set.\n // Skipping the upload here is belt-and-suspenders on top of that\n // scrub: it avoids shipping payloads the server will only discard.\n const traceDropped =\n activeTraceStates.get(traceId)?.dropped === true\n\n // dbSnapshotRef is attached to the trace, not the span (see\n // sendTraceCompletion). A trace-level pin is what replay reads;\n // duplicating it on the root span would just leak the same\n // value into two places.\n if (!traceDropped) {\n self.sendWrapperSpan({\n ...baseSpanParams,\n ...params,\n contexts: newContext.contexts,\n prompt: newContext.prompt,\n endedAt,\n ...(testRunId !== undefined && { testRunId }),\n ...(replayCtx?.inputSourceSpanId && {\n inputSourceSpanId: replayCtx.inputSourceSpanId,\n }),\n })\n }\n\n // A root span closing its trace queues the completion right behind\n // its own span. No wait for the children first: the transport\n // preserves submission order and Bitfab's ingress keys spans and\n // traces idempotently, so completion never races ahead of content.\n if (isRootSpan) {\n const traceState = activeTraceStates.get(traceId)\n self.sendTraceCompletion({\n traceFunctionKey,\n traceId,\n startedAt: traceState?.startedAt ?? startedAt,\n endedAt,\n sessionId: traceState?.sessionId,\n name: traceState?.name,\n metadata: traceState?.metadata,\n contexts: traceState?.contexts ?? [],\n testRunId: traceState?.testRunId,\n inputSourceTraceId: traceState?.inputSourceTraceId,\n replayAttempt: traceState?.replayAttempt,\n dbSnapshotRef: traceState?.dbSnapshotRef,\n dropped: traceState?.dropped,\n ingestionType: traceState?.ingestionType,\n // Built AFTER the wrapped fn finished, so `accessed` reflects\n // whether customer code obtained the branch URL during this\n // item. Omitted entirely when no lease was attached, so the\n // server can distinguish \"no branch\" from \"branch ignored\".\n ...(replayCtx?.dbBranchLease && {\n dbSnapshotUsage: {\n neonBranchId: replayCtx.dbBranchLease.neonBranchId,\n snapshotTimestamp:\n replayCtx.dbBranchLease.snapshotTimestamp,\n region: replayCtx.dbBranchLease.region,\n originalTraceId: replayCtx.sourceBitfabTraceId,\n accessed: replayCtx.dbSnapshotAccessed === true,\n timings: replayCtx.dbBranchTimings,\n },\n }),\n })\n activeTraceStates.delete(traceId)\n }\n } catch {\n // Silently ignore - user's result/exception takes priority\n }\n }\n\n // Record the span output. With `finalize`, the raw result is handed\n // back to the caller untouched (streaming stays live) while a drained,\n // serializable view is recorded as the span output instead. finalize\n // runs in the background and never affects the caller's value; a\n // throwing finalize records an error rather than crashing the host.\n const recordSpan = (result: unknown): void => {\n if (options.finalize) {\n // Tracked on the OWNING client: the span reaches the transport\n // only once finalize settles, so a flush that merely drained the\n // transport would race a root span not yet queued - and in replay\n // that root's trace would miss the barrier. Scoped per client so\n // one client's slow finalize cannot fail another's close().\n void self.httpClient.trackDeferred(\n Promise.resolve()\n .then(() => options.finalize!(result))\n .then((output) => sendSpan({ result: output }))\n .catch((error: unknown) =>\n sendSpan({\n result: undefined,\n error:\n error instanceof Error\n ? `finalize failed: ${error.message}`\n : `finalize failed: ${String(error)}`,\n }),\n ),\n )\n } else {\n void sendSpan({ result })\n }\n }\n\n // Assign before mock interception because an asynchronous resolver can\n // decline after this setup block has already returned.\n executeWithContext = (): TReturn => {\n let result: TReturn\n try {\n result = fn.apply(this, args)\n } catch (error) {\n void sendSpan({\n result: undefined,\n error: error instanceof Error ? error.message : String(error),\n })\n throw error\n }\n\n if (result instanceof Promise) {\n return result\n .then((resolvedResult) => {\n recordSpan(resolvedResult)\n return resolvedResult\n })\n .catch((error: unknown) => {\n void sendSpan({\n result: undefined,\n error: error instanceof Error ? error.message : String(error),\n })\n throw error\n }) as TReturn\n }\n\n if (isAsyncGenerator(result)) {\n return wrapAsyncGenerator(result, newStack, sendSpan) as TReturn\n }\n\n recordSpan(result)\n return result\n }\n\n // Mock interception: for a non-root child span under an active mock\n // context, decide whether to substitute its output instead of running\n // real code. Precedence: a matching override wins (per-call before\n // registered, first matcher within each); otherwise the base strategy\n // (\"all\"/\"marked\") replays recorded output. The lookup key matches\n // buildMockTree: `${traceFunctionKey}:${spanName}:${idx}` with callIndex\n // scoped per (key, name) - see comment on buildMockTree.\n const replayCtxForMock = getReplayContext()\n if (replayCtxForMock?.mockTree && !isRootSpan) {\n const counters = replayCtxForMock.callCounters!\n const counterKey = `${traceFunctionKey}:${baseSpanParams.spanName}`\n const callIndex = counters.get(counterKey) ?? 0\n counters.set(counterKey, callIndex + 1)\n\n const mockKey = `${counterKey}:${callIndex}`\n const mockSpan = replayCtxForMock.mockTree.spans.get(mockKey)\n\n // Emit a mocked span (flagged so the trace view marks it), then return\n // the value in the wrapped fn's call shape. fnReturnsPromise keeps a\n // sync-but-Promise-returning fn's `.then()` consumers working.\n const emitMock = (\n output: unknown,\n mockSource: MockSource,\n ): TReturn => {\n void sendSpan({\n result: output,\n mocked: true,\n mockTarget: \"output\",\n mockSource,\n })\n if (fnReturnsPromise) {\n return Promise.resolve(output) as TReturn\n }\n return output as TReturn\n }\n // Same, when the value resolves asynchronously (lazy recorded-output\n // fetch, or an async value function). A synchronous wrapped fn cannot\n // return a Promise its caller can use, so surface it under replay\n // rather than silently mis-typing the result.\n const emitMockAsync = (\n pending: Promise<unknown>,\n mockSource: MockSource,\n ): TReturn => {\n if (!fnReturnsPromise) {\n throw new BitfabError(\n `Cannot mock synchronous span \"${traceFunctionKey}\" with an ` +\n \"asynchronously-resolved value (lazy recorded-output fetch or \" +\n \"an async value function). Make the wrapped function async, or \" +\n 'use mock: \"all\" so recorded outputs are fetched eagerly.',\n )\n }\n return (async () => {\n const output = await pending\n void sendSpan({\n result: output,\n mocked: true,\n mockTarget: \"output\",\n mockSource,\n })\n return output\n })() as TReturn\n }\n // Resolve this span's recorded output. Prefer an inline output when\n // the tree carried one (eager \"all\", or an older server that ignores\n // includeOutputs and returns outputs without an externalSpanId); only\n // lazily fetch when the payload-free tree omitted it. Returns a value\n // or a Promise.\n const resolveRecordedOutput = (): unknown | Promise<unknown> => {\n const hasInlineOutput =\n mockSpan?.output !== undefined ||\n mockSpan?.outputMeta !== undefined\n if (\n !hasInlineOutput &&\n replayCtxForMock.fetchSpanOutput &&\n mockSpan?.externalSpanId\n ) {\n return replayCtxForMock.fetchSpanOutput(mockSpan.externalSpanId)\n }\n if (!mockSpan) {\n // No recorded counterpart at all (e.g. getOriginalOutput on a span\n // the changed code newly introduced).\n return Promise.reject(\n new BitfabError(\n `No recorded span to source output for \"${traceFunctionKey}\".`,\n ),\n )\n }\n let output = mockSpan.output\n if (\n mockSpan.outputMeta !== undefined &&\n mockSpan.outputMeta !== null\n ) {\n output = deserializeValue({\n json: mockSpan.output,\n meta: mockSpan.outputMeta,\n })\n }\n return output\n }\n\n const shouldMockWithBaseStrategy =\n replayCtxForMock.mockStrategy === \"all\" ||\n (replayCtxForMock.mockStrategy === \"marked\" &&\n options.mockOnReplay === true)\n\n // 1) Overrides. A resolver can decline with NO_MOCK_OVERRIDE, which\n // continues to the next override and then the base strategy.\n if (replayCtxForMock.mockOverrides?.length) {\n const nodeMeta: SpanNodeMeta = {\n traceFunctionKey,\n spanName: baseSpanParams.spanName,\n type: options.type ?? \"custom\",\n originalSpanId: mockSpan?.sourceSpanId,\n }\n const overrideCtx = {\n node: nodeMeta,\n inputs: args,\n getOriginalOutput: () => Promise.resolve(resolveRecordedOutput()),\n }\n type OverrideResolution =\n | { matched: true; output: unknown }\n | { matched: false }\n const resolveOverrideFrom = (\n startIndex: number,\n ): OverrideResolution | Promise<OverrideResolution> => {\n for (\n let index = startIndex;\n index < replayCtxForMock.mockOverrides!.length;\n index += 1\n ) {\n const override = replayCtxForMock.mockOverrides![index]\n if (!override?.match(nodeMeta)) {\n continue\n }\n const injected = resolveMockValue(override.value, overrideCtx)\n if (injected instanceof Promise) {\n return injected.then((output) =>\n output === NO_MOCK_OVERRIDE\n ? resolveOverrideFrom(index + 1)\n : { matched: true, output },\n )\n }\n if (injected !== NO_MOCK_OVERRIDE) {\n return { matched: true, output: injected }\n }\n }\n return { matched: false }\n }\n\n const resolution = resolveOverrideFrom(0)\n if (resolution instanceof Promise) {\n if (!fnReturnsPromise) {\n throw new BitfabError(\n `Cannot resolve an asynchronous mock override for synchronous span \"${traceFunctionKey}\". ` +\n \"Make the wrapped function async or return NO_MOCK_OVERRIDE synchronously.\",\n )\n }\n return runWithSpanStack(newStack, async () => {\n const resolved = await resolution\n if (resolved.matched) {\n void sendSpan({\n result: resolved.output,\n mocked: true,\n mockTarget: \"output\",\n mockSource: \"override\",\n })\n return resolved.output\n }\n if (shouldMockWithBaseStrategy && !mockSpan) {\n throw new BitfabError(\n `Replay selected span \"${traceFunctionKey}:${baseSpanParams.spanName}\" for mocking, but recorded occurrence ${callIndex + 1} is unavailable. The real span was not executed.`,\n )\n }\n if (shouldMockWithBaseStrategy) {\n const output = await resolveRecordedOutput()\n void sendSpan({\n result: output,\n mocked: true,\n mockTarget: \"output\",\n mockSource: \"recorded\",\n })\n return output\n }\n return executeWithContext()\n }) as TReturn\n }\n if (resolution.matched) {\n return emitMock(resolution.output, \"override\")\n }\n }\n\n // 2) Base strategy: replay recorded output for mocked spans.\n if (shouldMockWithBaseStrategy && !mockSpan) {\n throw new BitfabError(\n `Replay selected span \"${traceFunctionKey}:${baseSpanParams.spanName}\" for mocking, but recorded occurrence ${callIndex + 1} is unavailable. The real span was not executed.`,\n )\n }\n if (shouldMockWithBaseStrategy) {\n const recorded = resolveRecordedOutput()\n if (recorded instanceof Promise) {\n return emitMockAsync(recorded, \"recorded\")\n }\n return emitMock(recorded, \"recorded\")\n }\n }\n } catch (setupError) {\n // If this call registered root trace state before failing, remove the\n // now-orphaned entry: no span or completion will follow, so leaving it\n // would leak the maps and block that trace id's completion forever.\n if (registeredTraceId) {\n activeTraceStates.delete(registeredTraceId)\n }\n if (setupError instanceof MixedTracingError) {\n throw setupError\n }\n // During replay (a controlled eval), a setup failure must surface, not\n // silently fall through. The setup region includes the mock\n // interception: if a matched mock can't build its output (e.g.\n // deserializeValue on bad outputMeta), swallowing it would run the real\n // function - real side effects, and a skewed mock call counter - which\n // defeats replay. Re-throw so the replay runner records it as that\n // item's error. The never-crash fallback below is for production hosts.\n if (getReplayContext() || inSeedScope()) {\n throw setupError\n }\n // Tracing setup failed; run the user's function untraced so a tracing\n // failure never crashes the host app while preserving its receiver.\n warnOnce(\n `withSpan-setup:${traceFunctionKey}`,\n `tracing setup failed for \"${traceFunctionKey}\"; running it untraced. The function still runs and returns normally; no span is recorded.`,\n )\n return fn.apply(this, args) as TReturn\n }\n\n // Run OUTSIDE the setup try: a throw from the user's own function must\n // propagate unchanged and never be mistaken for a tracing failure (which\n // would double-invoke `fn`).\n return runWithSpanStack(newStack, executeWithContext)\n }\n // Mark the wrapper with its key so replay() can tell wrapped functions\n // from plain callables (which it auto-wraps) and reject key mismatches.\n Object.defineProperty(wrappedFn, \"_bitfabTraceFunctionKey\", {\n value: traceFunctionKey,\n })\n // The wrapper takes rest parameters, so its own `length` is 0 and says\n // nothing about what the traced function requires. Keep the original so\n // seedTrace can check a case against the real signature, mirroring\n // `inspect.unwrap` on the Python side.\n Object.defineProperty(wrappedFn, \"_bitfabWrappedFn\", { value: fn })\n return wrappedFn\n }\n\n /**\n * Create a standard ECMAScript method decorator that records each invocation\n * as a span.\n *\n * It supports instance, static, and private methods; use\n * {@link Bitfab.withSpan} for standalone functions, class fields, and\n * accessors.\n *\n * @example\n * ```typescript\n * const bitfab = new Bitfab({ apiKey: process.env.BITFAB_API_KEY });\n *\n * class OrderService {\n * @bitfab.span(\"order-processing\", { type: \"agent\" })\n * async process(orderId: string) {\n * return { orderId };\n * }\n * }\n * ```\n *\n * @param traceFunctionKey - A string identifier for grouping spans\n * @param options - Span configuration applied to the decorated method\n * @returns A standard ECMAScript method decorator\n */\n span(\n traceFunctionKey: string,\n options: SpanOptions = {},\n ): SpanMethodDecorator {\n return (originalMethod, context) => {\n if (context.kind !== \"method\") {\n throw new BitfabError(\n `Bitfab span decorators can only decorate methods; ${String(context.name)} is a ${context.kind}`,\n )\n }\n\n return this.withSpan(traceFunctionKey, options, originalMethod)\n }\n }\n\n /**\n * Get a detached handle to a previously-created trace, looked up by the\n * canonical Bitfab trace ID.\n *\n * The returned handle is not tied to AsyncLocalStorage - each method sends\n * to the server immediately. Useful for adding context to a trace from a\n * different process or thread than the one that created it.\n *\n * Throws synchronously if `traceId` is not a valid Bitfab trace ID. The\n * server returns 404 if no trace exists with that ID in the org; the failure surfaces as a\n * logged warning (fire-and-forget) or via the awaited promise.\n *\n * Example:\n * ```typescript\n * const trace = client.getTrace(traceId);\n * await trace.addContext({ refund_status: \"approved\" });\n * await trace.setMetadata({ region: \"us-west\" });\n * ```\n */\n getTrace(traceId: string): DetachedTrace {\n validateTraceId(traceId)\n\n return {\n traceId,\n addContext: (context: Record<string, unknown>): Promise<void> => {\n if (!this.shouldRecord()) {\n return Promise.resolve()\n }\n if (typeof context !== \"object\" || context === null) {\n return Promise.resolve()\n }\n return this.httpClient.patchTrace(traceId, {\n appendContexts: [context],\n })\n },\n setMetadata: (metadata: Record<string, unknown>): Promise<void> => {\n if (!this.shouldRecord()) {\n return Promise.resolve()\n }\n if (typeof metadata !== \"object\" || metadata === null) {\n return Promise.resolve()\n }\n return this.httpClient.patchTrace(traceId, { mergeMetadata: metadata })\n },\n setSessionId: (sessionId: string): Promise<void> => {\n if (!this.shouldRecord()) {\n return Promise.resolve()\n }\n if (typeof sessionId !== \"string\" || sessionId.length === 0) {\n return Promise.resolve()\n }\n return this.httpClient.patchTrace(traceId, { setSessionId: sessionId })\n },\n setName: (name: string): Promise<void> => {\n if (!this.shouldRecord()) {\n return Promise.resolve()\n }\n if (typeof name !== \"string\" || name.length === 0) {\n return Promise.resolve()\n }\n return this.httpClient.patchTrace(traceId, { setName: name })\n },\n }\n }\n\n /**\n * Fetch one persisted span from a trace without loading the full trace.\n * Name lookups return the last matching span by default. Pass `occurrence`\n * as `\"first\"` or a zero-based index to select a different match.\n */\n async getTraceSpan(\n traceId: string,\n lookup: SpanLookup,\n ): Promise<CapturedSpan | null> {\n validateTraceId(traceId)\n const hasId = lookup.id !== undefined\n const hasName = lookup.name !== undefined\n if (hasId === hasName) {\n throw new BitfabError(\"Provide exactly one of id or name\")\n }\n if (hasId) {\n validateSpanId(lookup.id)\n } else {\n if (lookup.name.length === 0) {\n throw new BitfabError(\"name must be a non-empty string\")\n }\n const occurrence = lookup.occurrence ?? \"last\"\n if (\n occurrence !== \"first\" &&\n occurrence !== \"last\" &&\n (!Number.isInteger(occurrence) || occurrence < 0)\n ) {\n throw new BitfabError(\n 'occurrence must be \"first\", \"last\", or a non-negative integer',\n )\n }\n }\n return this.httpClient.getTraceSpan(traceId, lookup)\n }\n\n /**\n * Get a function wrapper for a specific trace function key.\n *\n * This provides a fluent API alternative to calling withSpan directly,\n * allowing you to bind the traceFunctionKey once and wrap multiple functions.\n *\n * Example usage:\n * ```typescript\n * const client = new Bitfab({ apiKey: 'your-api-key' });\n *\n * const orderFunc = client.getFunction('order-processing');\n * const tracedProcessOrder = orderFunc.withSpan(processOrder);\n * const tracedValidateOrder = orderFunc.withSpan(validateOrder);\n * ```\n *\n * @param traceFunctionKey - A string identifier for grouping spans\n * @returns A BitfabFunction instance for wrapping functions\n */\n getFunction(traceFunctionKey: string): BitfabFunction {\n return new BitfabFunction(this, traceFunctionKey)\n }\n\n /**\n * Send trace completion when a root span ends.\n * Internal method to record trace completion with end time.\n * Queued on the client's span transport; delivery is the transport's job.\n */\n private sendTraceCompletion(params: {\n traceFunctionKey: string\n traceId: string\n startedAt: string\n endedAt: string\n sessionId?: string\n name?: string\n metadata?: Record<string, unknown>\n contexts?: ContextEntry[]\n testRunId?: string\n inputSourceTraceId?: string\n replayAttempt?: number\n dbSnapshotRef?: DbSnapshotRef\n dropped?: boolean\n ingestionType?: TraceIngestionType\n /**\n * Replay DB branch usage record, present only when a lease was\n * attached to the replay item. Serialized as `db_snapshot_usage` so\n * the server can stamp the trace's metadata at ingest.\n */\n dbSnapshotUsage?: {\n neonBranchId: string\n snapshotTimestamp?: string\n /**\n * The branch's region. Recorded so a duration gap between items can be\n * attributed to a cross-region round trip rather than to the code.\n */\n region?: string\n /** Bitfab trace id of the original trace this replay item pinned to. */\n originalTraceId?: string\n accessed: boolean\n /** Server-measured provisioning timings, echoed back verbatim. */\n timings?: DbBranchTimings\n }\n }): void {\n // Build the raw trace object for the externalTraces endpoint\n const rawTrace: Record<string, unknown> = {\n id: params.traceId,\n started_at: params.startedAt,\n ended_at: params.endedAt,\n }\n\n // Add optional fields to rawData\n if (params.name) {\n rawTrace.name = params.name\n }\n if (params.metadata && Object.keys(params.metadata).length > 0) {\n rawTrace.metadata = params.metadata\n }\n if (params.contexts && params.contexts.length > 0) {\n rawTrace.contexts = params.contexts\n }\n if (params.inputSourceTraceId) {\n rawTrace.input_source_trace_id = params.inputSourceTraceId\n }\n if (params.replayAttempt !== undefined) {\n rawTrace.replay_attempt = params.replayAttempt\n }\n if (params.dbSnapshotRef) {\n rawTrace.db_snapshot_ref = params.dbSnapshotRef\n }\n if (params.ingestionType) {\n rawTrace.ingestion_type = params.ingestionType\n }\n if (params.dbSnapshotUsage) {\n rawTrace.db_snapshot_usage = {\n neon_branch_id: params.dbSnapshotUsage.neonBranchId,\n ...(params.dbSnapshotUsage.snapshotTimestamp && {\n snapshot_timestamp: params.dbSnapshotUsage.snapshotTimestamp,\n }),\n ...(params.dbSnapshotUsage.region && {\n region: params.dbSnapshotUsage.region,\n }),\n ...(params.dbSnapshotUsage.originalTraceId && {\n original_trace_id: params.dbSnapshotUsage.originalTraceId,\n // Deprecated wire alias, kept so this SDK still reports usage\n // against servers that predate the rename.\n source_trace_id: params.dbSnapshotUsage.originalTraceId,\n }),\n accessed: params.dbSnapshotUsage.accessed,\n // Echoed verbatim (camelCase inside) rather than re-cased into this\n // record's snake_case: it is the server's own object coming back, and\n // a translation layer here is one more thing to drift.\n ...(params.dbSnapshotUsage.timings && {\n timings: params.dbSnapshotUsage.timings,\n }),\n }\n }\n\n this.httpClient.sendExternalTrace({\n id: params.traceId,\n type: \"sdk-function\",\n source: \"typescript-sdk-function\",\n traceFunctionKey: params.traceFunctionKey,\n externalTrace: rawTrace,\n completed: true,\n ...(params.dropped && { dropped: true }),\n ...(params.sessionId && { sessionId: params.sessionId }),\n ...(params.testRunId && { testRunId: params.testRunId }),\n })\n }\n\n /**\n * Send a wrapper span from function execution.\n * Internal method to record spans when using withSpan.\n * Queued on the client's span transport; delivery is the transport's job.\n */\n private sendWrapperSpan(params: {\n traceFunctionKey: string\n functionName?: string\n spanName: string\n traceId: string\n spanId: string\n parentSpanId: string | null\n inputs?: unknown[]\n result: unknown\n error?: string\n startedAt: string\n endedAt: string\n spanType: SpanType\n contexts?: ContextEntry[]\n prompt?: string\n testRunId?: string\n inputSourceSpanId?: string\n mocked?: boolean\n mockTarget?: MockTarget\n mockSource?: MockSource\n functionId?: string\n captureContent: boolean\n autoTraceDefinition?: AutoTraceFunctionDefinition\n }): void {\n const serializedInputs = params.captureContent\n ? serializeValue(params.inputs)\n : undefined\n const serializedResult = params.captureContent\n ? serializeValue(params.result)\n : undefined\n\n // Format as an external span with the wrapper format\n const externalSpan: Record<string, unknown> = {\n id: params.spanId,\n trace_id: params.traceId,\n started_at: params.startedAt,\n ended_at: params.endedAt,\n span_data: {\n name: params.spanName,\n type: params.spanType,\n ...(params.functionId !== undefined && {\n function_id: params.functionId,\n content_captured: params.captureContent,\n }),\n ...(params.autoTraceDefinition !== undefined && {\n function_file: params.autoTraceDefinition.file,\n function_line: params.autoTraceDefinition.line,\n function_column: params.autoTraceDefinition.column,\n }),\n ...(serializedInputs !== undefined && {\n input: serializedInputs.json,\n ...(serializedInputs.meta !== undefined && {\n input_meta: serializedInputs.meta,\n }),\n }),\n ...(serializedResult !== undefined && {\n output: serializedResult.json,\n ...(serializedResult.meta !== undefined && {\n output_meta: serializedResult.meta,\n }),\n }),\n ...(params.functionName !== undefined && {\n function_name: params.functionName,\n }),\n ...(params.captureContent &&\n params.error !== undefined && {\n error: params.error,\n error_source: \"code\",\n }),\n ...(params.captureContent &&\n params.contexts &&\n params.contexts.length > 0 && {\n contexts: params.contexts,\n }),\n ...(params.captureContent &&\n params.prompt !== undefined && { prompt: params.prompt }),\n },\n }\n\n // Add parent_id for nested spans\n if (params.parentSpanId) {\n externalSpan.parent_id = params.parentSpanId\n }\n if (params.inputSourceSpanId) {\n externalSpan.input_source_span_id = params.inputSourceSpanId\n }\n\n this.httpClient.sendExternalSpan({\n id: params.spanId,\n traceId: params.traceId,\n type: \"sdk-function\",\n source: \"typescript-sdk-function\",\n sourceTraceId: params.traceId,\n traceFunctionKey: params.traceFunctionKey,\n rawSpan: externalSpan,\n ...(params.testRunId && { testRunId: params.testRunId }),\n ...(params.mocked && { mocked: true }),\n ...(params.mockTarget && { mockTarget: params.mockTarget }),\n ...(params.mockSource && { mockSource: params.mockSource }),\n })\n }\n\n /**\n * Replay historical traces through a function and create a test run.\n *\n * Fetches the last N traces for the given trace function key, re-runs each\n * through the provided function, and returns comparison data.\n *\n * Accepts either a `withSpan`-wrapped function (under the same key) or any\n * plain callable: plain callables are wrapped internally so each replayed\n * invocation records a trace tied to the test run. The plain-callable form\n * is how handler-instrumented workflows (LangGraph/LangChain, Claude Agent\n * SDK) replay - those record traces under a key with no `withSpan`-wrapped\n * root in the app.\n *\n * @param traceFunctionKey - The trace function key to replay\n * @param fn - The function to run recorded inputs through\n * @param options - Optional replay options. When `traceIds` is passed,\n * `limit` is ignored (with a warning): an explicit ID list already\n * determines how many traces replay.\n * @returns ReplayResult with items, testRunId, and testRunUrl\n */\n /**\n * Register a mock override applied to every subsequent `replay` on this\n * client, so downstream real code runs against a value you supply for the\n * matched span. Instance-scoped (no global state); call {@link clearMockOverrides}\n * to reset. Per-call `replay({ mockOverride })` overrides take precedence, and\n * both take precedence over the base `mock` strategy.\n *\n * ```ts\n * // Object form (value is a flat value here)\n * bitfab.registerMockOverride({\n * match: (node) => node.traceFunctionKey === \"classify-intent\",\n * value: { label: \"refund\" },\n * })\n * // Ordered form (equivalent); value may also be a function of the context\n * bitfab.registerMockOverride(\n * (node) => node.traceFunctionKey === \"classify-intent\",\n * ({ inputs }) => ({ label: \"refund\" }),\n * )\n * // Keyed form: the resolver only sees spans for this trace function key.\n * bitfab.registerMockOverride(\"classify-intent\", ({ inputs }) => ({\n * label: String(inputs[0]),\n * }))\n * // Or one resolver for every child span:\n * bitfab.registerMockOverride(({ node }) =>\n * node.traceFunctionKey === \"classify-intent\"\n * ? { label: \"refund\" }\n * : NO_MOCK_OVERRIDE,\n * )\n * ```\n */\n registerMockOverride(override: MockOverride): void\n registerMockOverride(resolver: MockOverrideResolver): void\n registerMockOverride(match: NodeMatcher, value: MockValue): void\n registerMockOverride(\n traceFunctionKey: string,\n override: MockOverride | MockOverrideResolver,\n ): void\n registerMockOverride(\n overrideOrResolverOrMatch:\n | string\n | MockOverride\n | MockOverrideResolver\n | NodeMatcher,\n ...values: [] | [MockValue | MockOverride | MockOverrideResolver]\n ): void {\n let override: MockOverride\n if (typeof overrideOrResolverOrMatch === \"string\") {\n const keyedOverride = values[0]\n if (values.length !== 1 || keyedOverride === undefined) {\n throw new BitfabError(\n \"registerMockOverride(traceFunctionKey, override) requires a resolver function or { match, value } override.\",\n )\n }\n if (typeof keyedOverride === \"function\") {\n override = {\n match: (node) => node.traceFunctionKey === overrideOrResolverOrMatch,\n value: keyedOverride,\n }\n } else if (\n typeof keyedOverride === \"object\" &&\n keyedOverride !== null &&\n \"match\" in keyedOverride &&\n \"value\" in keyedOverride\n ) {\n override = {\n match: (node) =>\n node.traceFunctionKey === overrideOrResolverOrMatch &&\n keyedOverride.match(node),\n value: keyedOverride.value,\n }\n } else {\n throw new BitfabError(\n \"registerMockOverride(traceFunctionKey, override) requires a resolver function or { match, value } override.\",\n )\n }\n } else if (typeof overrideOrResolverOrMatch !== \"function\") {\n override = overrideOrResolverOrMatch\n } else if (values.length === 0) {\n override = { match: () => true, value: overrideOrResolverOrMatch }\n } else {\n override = {\n match: overrideOrResolverOrMatch as NodeMatcher,\n value: values[0],\n }\n }\n this.mockOverrides.push(override)\n }\n\n /** Remove all overrides registered via {@link registerMockOverride}. */\n clearMockOverrides(): void {\n this.mockOverrides.length = 0\n }\n\n seedTrace(traceFunctionKey: string, options: SeedCaseOptions): string\n seedTrace<TArgs extends unknown[], TReturn>(\n traceFunctionKey: string,\n fn: (...args: TArgs) => TReturn,\n options?: SeedRunOptions<TArgs>,\n ): Promise<string>\n seedTrace(\n traceFunctionKey: string,\n optionsOrFn: SeedCaseOptions | ((...args: never[]) => unknown),\n runOptions?: SeedRunOptions<never[]>,\n ): string | Promise<string> {\n if (typeof optionsOrFn === \"function\") {\n return this.seedTraceByRunning(traceFunctionKey, optionsOrFn, runOptions)\n }\n return this.seedTraceFromCase(traceFunctionKey, optionsOrFn)\n }\n\n private seedTraceFromCase(\n traceFunctionKey: string,\n options: SeedCaseOptions,\n ): string {\n const { input } = options\n const fn =\n (options.fn as { _bitfabWrappedFn?: (...args: unknown[]) => unknown })\n ?._bitfabWrappedFn ?? options.fn\n if (fn && input.length < fn.length) {\n throw new BitfabError(\n `Seeded case supplies ${input.length} argument(s) but ${\n fn.name === \"\" ? \"the function\" : fn.name\n } requires ${fn.length}. Fix the case, or omit fn to seed it anyway.`,\n )\n }\n\n const traceId = randomUuid()\n const startedAt = nowIsoTimestamp()\n\n activeTraceStates.set(traceId, {\n traceId,\n startedAt,\n contexts: [],\n ingestionType: \"seeded\",\n ...(options.sessionId !== undefined && { sessionId: options.sessionId }),\n ...(options.name !== undefined && { name: options.name }),\n ...(options.metadata !== undefined && { metadata: options.metadata }),\n })\n\n try {\n this.sendWrapperSpan({\n traceFunctionKey,\n spanName: options.spanName ?? traceFunctionKey,\n traceId,\n spanId: randomUuid(),\n parentSpanId: null,\n inputs: input,\n result: options.expected,\n startedAt,\n endedAt: startedAt,\n spanType: options.spanType ?? \"agent\",\n captureContent: true,\n })\n this.sendTraceCompletion({\n traceFunctionKey,\n traceId,\n startedAt,\n endedAt: startedAt,\n sessionId: options.sessionId,\n name: options.name,\n metadata: options.metadata,\n contexts: [],\n ingestionType: \"seeded\",\n })\n } finally {\n activeTraceStates.delete(traceId)\n }\n\n return traceId\n }\n\n private async seedTraceByRunning(\n traceFunctionKey: string,\n fn: (...args: never[]) => unknown,\n options?: SeedRunOptions<never[]>,\n ): Promise<string> {\n const wrappedKey = (fn as { _bitfabTraceFunctionKey?: string })\n ._bitfabTraceFunctionKey\n let target = fn\n if (wrappedKey === undefined) {\n const seedRootOptions: InternalSpanOptions = {\n name: traceFunctionKey,\n type: \"agent\",\n surface: \"neutral\",\n }\n target = this.withSpan(\n traceFunctionKey,\n seedRootOptions,\n fn as (...args: unknown[]) => unknown,\n ) as (...args: never[]) => unknown\n } else if (wrappedKey !== traceFunctionKey) {\n throw new BitfabError(\n `Function is wrapped with trace function key '${wrappedKey}' but ` +\n `seedTrace was called with '${traceFunctionKey}'. Pass matching ` +\n \"keys, or pass the unwrapped function to seed it under the \" +\n \"explicit key.\",\n )\n }\n\n await seedContextReady\n\n const traceId = randomUuid()\n activeTraceStates.set(traceId, {\n traceId,\n startedAt: nowIsoTimestamp(),\n contexts: [],\n ingestionType: \"seeded\",\n ...(options?.sessionId !== undefined && { sessionId: options.sessionId }),\n ...(options?.name !== undefined && { name: options.name }),\n ...(options?.metadata !== undefined && { metadata: options.metadata }),\n })\n\n const args = (options?.args ?? []) as never[]\n let unrecorded = true\n try {\n await runWithSeedContext({ traceId }, async () => target(...args))\n } finally {\n try {\n const { flushTraces } = await import(\"./http.js\")\n await flushTraces(30_000)\n } finally {\n unrecorded = activeTraceStates.delete(traceId)\n }\n }\n if (unrecorded) {\n throw new BitfabError(\n `seedTrace recorded nothing for '${traceFunctionKey}': the call ` +\n \"finished without a root span. Check that an API key resolves \" +\n \"(BITFAB_API_KEY or apiKey), and that fn is a regular or async \" +\n \"function rather than a generator.\",\n )\n }\n return traceId\n }\n\n async replay<TReturn>(\n traceFunctionKey: string,\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data, typed args would be incorrect\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n options?: ReplayOptions,\n ): Promise<ReplayResult<TReturn>> {\n const wrappedKey = (fn as { _bitfabTraceFunctionKey?: string })\n ._bitfabTraceFunctionKey\n let replayFn = fn\n if (wrappedKey === undefined) {\n // Name the root span after the key (not the callable's name) so it\n // matches the production root span: handler-instrumented roots (Claude\n // Agent SDK, OpenAI Agents) are named after the trace function key, so\n // naming the auto-wrap after fn.name would make the replayed root read\n // differently from the trace it replays.\n const replayRootOptions: InternalSpanOptions = {\n name: traceFunctionKey,\n type: \"agent\",\n surface: \"neutral\",\n }\n replayFn = this.withSpan(traceFunctionKey, replayRootOptions, fn)\n } else if (wrappedKey !== traceFunctionKey) {\n throw new BitfabError(\n `Function is wrapped with trace function key '${wrappedKey}' but ` +\n `replay was called with '${traceFunctionKey}'. Pass matching keys, ` +\n \"or pass the unwrapped function to replay it under the explicit key.\",\n )\n }\n const { replay: doReplay } = await import(\"./replay.js\")\n return doReplay(\n this.httpClient,\n this.serviceUrl,\n traceFunctionKey,\n replayFn,\n options,\n this.mockOverrides,\n )\n }\n}\n\n/**\n * Represents a Bitfab function that can wrap user functions for tracing.\n *\n * This provides a fluent API for binding a traceFunctionKey once and\n * then wrapping multiple functions with that key.\n *\n * Example usage:\n * ```typescript\n * const client = new Bitfab({ apiKey: 'your-api-key' });\n *\n * const orderFunc = client.getFunction('order-processing');\n * const tracedProcessOrder = orderFunc.withSpan(processOrder);\n * const tracedValidateOrder = orderFunc.withSpan(validateOrder);\n * ```\n */\nexport class BitfabFunction {\n constructor(\n private readonly client: Bitfab,\n private readonly traceFunctionKey: string,\n ) {}\n\n /**\n * Wrap a function to automatically create a span for its inputs and outputs.\n *\n * The wrapped function behaves identically to the original, but sends\n * span data to Bitfab in the background after each call.\n *\n * Example usage:\n * ```typescript\n * const orderFunc = client.getFunction('order-processing');\n *\n * // Basic usage (defaults to \"custom\" span type)\n * const tracedProcessOrder = orderFunc.withSpan(processOrder);\n *\n * // With explicit span type\n * const tracedProcessOrder = orderFunc.withSpan({ type: 'function' }, processOrder);\n * ```\n *\n * @param optionsOrFn - Either SpanOptions or the function to wrap\n * @param maybeFn - The function to wrap if options were provided\n * @returns A wrapped function with the same signature that creates spans\n */\n withSpan<TArgs extends unknown[], TReturn>(\n optionsOrFn: SpanOptions | ((...args: TArgs) => TReturn),\n maybeFn?: (...args: TArgs) => TReturn,\n ): (...args: TArgs) => TReturn {\n // Handle overloaded signature\n const options: SpanOptions =\n typeof optionsOrFn === \"function\" ? {} : optionsOrFn\n const fn: (...args: TArgs) => TReturn =\n typeof optionsOrFn === \"function\" ? optionsOrFn : maybeFn!\n\n return this.client.withSpan(this.traceFunctionKey, options, fn)\n }\n\n /**\n * Create a standard ECMAScript method decorator bound to this function key.\n *\n * @example\n * ```typescript\n * const orders = client.getFunction(\"order-processing\");\n *\n * class OrderService {\n * @orders.span({ type: \"agent\" })\n * async process(orderId: string) {\n * return { orderId };\n * }\n * }\n * ```\n *\n * @param options - Span configuration applied to the decorated method\n * @returns A standard ECMAScript method decorator\n */\n span(options: SpanOptions = {}): SpanMethodDecorator {\n return this.client.span(this.traceFunctionKey, options)\n }\n\n /**\n * Get a Vercel AI SDK language-model middleware bound to this function's key.\n *\n * Equivalent to `client.getVercelAiMiddleware(key)` but reuses the key bound\n * on this handle, so an outer `withSpan` root and the middleware-traced model\n * calls share one key without repeating the string. With a matching key, the\n * outer span is the replayable root and the model-call spans nest beneath it.\n *\n * Nesting is captured when the model is called, so keep the\n * `generateText` / `streamText` call inside this handle's `withSpan`; the\n * middleware object itself can be created anywhere.\n *\n * ```typescript\n * const chatTurn = client.getFunction(\"chat-turn\");\n * const runChatTurn = chatTurn.withSpan(\n * { type: \"agent\", finalize: finalizers.aiSdk },\n * (messages) => streamText({ model, messages }),\n * );\n * const model = wrapLanguageModel({\n * model: openai(\"gpt-4o\"),\n * middleware: chatTurn.getVercelAiMiddleware(),\n * });\n * ```\n *\n * @returns A Vercel AI SDK middleware configured for this client and key\n */\n getVercelAiMiddleware() {\n return this.client.getVercelAiMiddleware(this.traceFunctionKey)\n }\n\n /**\n * Get a Claude Agent SDK handler bound to this function's key.\n *\n * Equivalent to `client.getClaudeAgentHandler(key)` but reuses the key bound\n * on this handle, so an outer `withSpan` root and the handler share one key\n * without repeating the string. With a matching key, the outer span is the\n * replayable root and every handler span nests beneath it.\n *\n * Use the handler inside this handle's `withSpan` body so its spans capture\n * the enclosing root; framework calls made with no active span record their\n * own root instead.\n *\n * ```typescript\n * const pipeline = client.getFunction(\"my-agent\");\n * const tracedRun = pipeline.withSpan({ type: \"agent\" }, async (prompt) => {\n * const handler = pipeline.getClaudeAgentHandler();\n * const options = handler.instrumentOptions({ model: \"claude-sonnet-4-6\" });\n * for await (const msg of handler.wrapQuery(query({ prompt, options }))) { ... }\n * });\n * ```\n *\n * @returns A Claude Agent SDK handler configured for this client and key\n */\n getClaudeAgentHandler() {\n return this.client.getClaudeAgentHandler(this.traceFunctionKey)\n }\n\n /**\n * Get a LangGraph/LangChain callback handler bound to this function's key.\n *\n * Equivalent to `client.getLangGraphCallbackHandler(key)` but reuses the key\n * bound on this handle, so an outer `withSpan` root and the handler share one\n * key without repeating the string. With a matching key, the outer span is\n * the replayable root and the LangGraph spans nest beneath it.\n *\n * Use the handler inside this handle's `withSpan` body so its spans capture\n * the enclosing root; framework calls made with no active span record their\n * own root instead.\n *\n * ```typescript\n * const pipeline = client.getFunction(\"my-pipeline\");\n * const tracedRun = pipeline.withSpan({ type: \"agent\" }, async (query) => {\n * const handler = pipeline.getLangGraphCallbackHandler();\n * return agent.invoke({ messages: [...] }, { callbacks: [handler] });\n * });\n * ```\n *\n * @returns A LangGraph/LangChain callback handler for this client and key\n */\n getLangGraphCallbackHandler() {\n return this.client.getLangGraphCallbackHandler(this.traceFunctionKey)\n }\n\n /**\n * Alias of {@link getLangGraphCallbackHandler} - LangChain and LangGraph\n * share one callback system, so the same bound handler serves both.\n *\n * @returns A LangChain callback handler for this client and key\n */\n getLangChainCallbackHandler() {\n return this.client.getLangChainCallbackHandler(this.traceFunctionKey)\n }\n\n /**\n * Get the first-class LangGraph tool replay integration bound to this key.\n *\n * @experimental This API may change before it is stable.\n */\n getLangGraphIntegration(options?: LangGraphIntegrationOptions) {\n return this.client.getLangGraphIntegration(this.traceFunctionKey, options)\n }\n\n /**\n * Wrap a BAML client method to automatically capture prompt and LLM metadata.\n * Delegates to the parent client's wrapBAML method.\n *\n * Unlike the other methods on this handle, `wrapBAML` does NOT use the bound\n * key: it opens no span of its own. It enriches the *current* span (via\n * `getCurrentSpan().setPrompt()` / `addContext()`), so call it inside a\n * function wrapped by this handle's `withSpan` - the bound key keys that\n * wrapper, and the BAML prompt/metadata attach to it.\n *\n * @param methodOrClient - Either a BAML method (uses constructor bamlClient) or the BAML client instance\n * @param maybeMethodOrOptions - The BAML method when the first argument is a client, or WrapBAMLOptions when the first argument is the method\n * @param maybeOptions - WrapBAMLOptions when using the two-argument (client, method) form\n * @returns An async function with the same signature that instruments the BAML call\n */\n wrapBAML<TArgs extends unknown[], TReturn>(\n methodOrClient: unknown,\n maybeMethodOrOptions?:\n | ((...args: TArgs) => Promise<TReturn>)\n | WrapBAMLOptions,\n maybeOptions?: WrapBAMLOptions,\n ): WrappedBamlFn<TArgs, TReturn> {\n return this.client.wrapBAML(\n methodOrClient,\n maybeMethodOrOptions,\n maybeOptions,\n )\n }\n}\n","/**\n * Prebuilt `finalize` helpers for `withSpan({ finalize }, fn)`.\n *\n * A streaming function returns a live stream object that the caller consumes\n * directly (SSE, a UI message stream). `withSpan` hands that object back\n * unchanged; a `finalize` function tells it what serializable view to record\n * as the span output instead of the raw, non-serializable stream.\n */\n\n/**\n * Duck-typed subset of the Vercel AI SDK `streamText` / `streamObject`\n * result. Each field is exposed as a promise that resolves once the stream\n * finishes; reading them does not consume the live stream (the AI SDK tees\n * internally), so the caller's own consumption is unaffected. We avoid a\n * hard dependency on `ai` by matching structurally.\n */\ninterface AiSdkStreamResultLike {\n text?: Promise<string> | string\n usage?: Promise<unknown> | unknown\n totalUsage?: Promise<unknown> | unknown\n finishReason?: Promise<unknown> | unknown\n toolCalls?: Promise<unknown> | unknown\n toolResults?: Promise<unknown> | unknown\n reasoningText?: Promise<string> | string\n}\n\n/** Await a value that may be a promise, swallowing rejection to `undefined`. */\nasync function settle<T>(\n value: Promise<T> | T | undefined,\n): Promise<T | undefined> {\n try {\n return await value\n } catch {\n return undefined\n }\n}\n\n/**\n * Drain a Vercel AI SDK streaming result into a serializable, replayable\n * span output: `{ text, usage, finishReason, toolCalls, toolResults }`.\n *\n * Pass it straight to `withSpan`:\n *\n * ```ts\n * import { finalizers } from \"@bitfab/sdk\"\n *\n * const traced = bitfab.withSpan(\n * \"chat-turn\",\n * { type: \"agent\", finalize: finalizers.aiSdk },\n * () => streamText({ model, messages }),\n * )\n * const result = traced() // caller still gets the live StreamTextResult\n * return result.toUIMessageStreamResponse()\n * ```\n *\n * Never throws: any field that is absent or rejects is recorded as\n * `undefined` so finalize never drops the span.\n */\nasync function aiSdk(result: unknown): Promise<Record<string, unknown>> {\n const r = (result ?? {}) as AiSdkStreamResultLike\n const [text, usage, totalUsage, finishReason, toolCalls, toolResults] =\n await Promise.all([\n settle(r.text),\n settle(r.usage),\n settle(r.totalUsage),\n settle(r.finishReason),\n settle(r.toolCalls),\n settle(r.toolResults),\n ])\n return {\n text,\n usage: totalUsage ?? usage,\n finishReason,\n toolCalls,\n toolResults,\n }\n}\n\n/**\n * Collect a `ReadableStream`'s chunks into an array for the span output,\n * via a `tee()` so the caller's branch is untouched. The caller MUST use\n * the returned stream, not the original, since a stream can only be read\n * once:\n *\n * ```ts\n * let live: ReadableStream\n * const traced = bitfab.withSpan(\n * \"render\",\n * { finalize: (r) => finalizers.readableStream(r, (s) => { live = s }) },\n * () => makeReadableStream(),\n * )\n * traced()\n * return new Response(live!)\n * ```\n *\n * Prefer `aiSdk` for the Vercel AI SDK, whose result tees internally and\n * needs no caller rewiring.\n */\nasync function readableStream(\n stream: ReadableStream,\n onLive: (live: ReadableStream) => void,\n): Promise<{ chunks: unknown[] }> {\n const [live, copy] = stream.tee()\n onLive(live)\n const chunks: unknown[] = []\n const reader = copy.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) {\n break\n }\n chunks.push(value)\n }\n } catch {\n // Never let span capture crash the host app.\n }\n return { chunks }\n}\n\nexport const finalizers = {\n aiSdk,\n readableStream,\n}\n","import type { Bitfab } from \"./client.js\"\nimport { BitfabError } from \"./errors.js\"\nimport {\n type CodeChangeFile,\n ReplayError,\n type ReplayItem,\n type ReplayOptions,\n type ReplayResult,\n reportReplayProgress,\n serializeReplayResult,\n} from \"./replay.js\"\n\ntype ReplayFunction = (\n // biome-ignore lint/suspicious/noExplicitAny: replay functions receive historical arguments\n ...args: any[]\n) => unknown | Promise<unknown>\n\nexport type ReplayRegistryOptions = Omit<\n ReplayOptions,\n \"onItemStart\" | \"onItemFinish\" | \"onProgress\"\n>\n\nexport interface ReplayRegistryContext {\n /** Values supplied through `--params` and repeated `--param name=value`. */\n params: Readonly<Record<string, unknown>>\n}\n\nexport type ReplayOptionsFactory = (\n context: ReplayRegistryContext,\n) => ReplayRegistryOptions | Promise<ReplayRegistryOptions>\n\nexport interface ReplayRegistration {\n /** Client instance used by the production traced function. */\n client: Bitfab\n /** The exact traced function production calls. */\n fn: ReplayFunction\n /**\n * Required for handler-instrumented or otherwise plain callables. Omit for a\n * `withSpan`-wrapped function and the registry reads the wrapper's key.\n */\n traceFunctionKey?: string\n /**\n * Per-function replay behavior and defaults. Put executable configuration\n * such as `mockOverride` and `adaptInputs` here; command-line values override\n * overlapping scalar defaults such as `mock` and `maxConcurrency`.\n */\n options?: ReplayRegistryOptions\n /** Build executable replay behavior from caller-supplied CLI parameters. */\n optionsFactory?: ReplayOptionsFactory\n}\n\nexport type ReplayRegistry = Record<string, ReplayRegistration>\n\n/**\n * Define the project-owned list of replayable functions.\n *\n * The registry is deliberately data-only: the SDK owns the replay CLI, so an\n * SDK upgrade can add replay features without regenerating the project file.\n */\nexport function defineReplayRegistry<TRegistry extends ReplayRegistry>(\n registry: TRegistry,\n): TRegistry {\n return registry\n}\n\nexport interface ReplayCliIo {\n stdout?: (line: string) => void\n stderr?: (line: string) => void\n readFile?: (path: string) => Promise<string>\n}\n\ninterface ReplayCliArgs {\n pipeline: string\n limit?: number\n attempts?: number\n traceIds?: string[]\n name?: string\n maxConcurrency?: number\n codeChangePath?: string\n experimentGroupId?: string\n datasetId?: string\n graderIds?: string[]\n mock?: \"none\" | \"all\" | \"marked\"\n dbBranch?: boolean\n noCodeChange?: boolean\n dryRun?: boolean\n paramsPath?: string\n params: string[]\n}\n\ninterface CodeChange {\n description: string\n files: CodeChangeFile[]\n}\n\nconst VALUE_FLAGS = new Set([\n \"--limit\",\n \"--attempts\",\n \"--trace-ids\",\n \"--name\",\n \"--concurrency\",\n \"--max-concurrency\",\n \"--code-change\",\n \"--experiment-group-id\",\n \"--dataset-id\",\n \"--grader-ids\",\n \"--mock\",\n \"--param\",\n \"--params\",\n])\n\nconst BOOLEAN_FLAGS = new Set([\n \"--db-branch\",\n \"--no-db-branch\",\n \"--no-code-change\",\n \"--dry-run\",\n])\n\nconst HELP_FLAGS = new Set([\"--help\", \"-h\"])\n\nconst MAX_ATTEMPTS = 100\n\nfunction usage(registry: ReplayRegistry): string {\n return `Usage: bitfab-replay --registry <path> <${Object.keys(registry).join(\"|\")}> [options]\\n\\nOptions:\\n --limit N\\n --attempts N (replay each trace N times in this run, max ${MAX_ATTEMPTS})\\n --trace-ids id1,id2\\n --name NAME\\n --concurrency N, --max-concurrency N\\n --code-change PATH, --no-code-change\\n --experiment-group-id UUID\\n --dataset-id UUID\\n --grader-ids id1,id2\\n --mock none|all|marked\\n --db-branch, --no-db-branch\\n --dry-run (resolve inputs, run nothing)\\n --params PATH\\n --param name=value (repeatable)\\n -h, --help`\n}\n\nexport class ReplayCliHelp extends Error {}\n\n/** One case to seed, in the shape `--seed` reads from JSON or JSONL. */\nexport interface SeedCase {\n /** Arguments spread into the registered function at replay. */\n input: unknown[]\n /** The output this case should produce. */\n expected?: unknown\n /** Recorded on the trace, for tracing a seeded case back to its source row. */\n metadata?: Record<string, unknown>\n sessionId?: string\n}\n\nexport interface SeedResult {\n pipeline: string\n traceFunctionKey: string\n traceIds: string[]\n}\n\nfunction parseSeedCases(raw: string, path: string, run: boolean): SeedCase[] {\n const trimmed = raw.trim()\n if (trimmed.length === 0) {\n throw new BitfabError(`Seed file '${path}' is empty.`)\n }\n const values: unknown[] = trimmed.startsWith(\"[\")\n ? (JSON.parse(trimmed) as unknown[])\n : trimmed\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => JSON.parse(line) as unknown)\n\n return values.map((value, index) => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new BitfabError(\n `Seed case ${index} in '${path}' must be an object with an \"input\" array.`,\n )\n }\n const { input } = value as { input?: unknown }\n if (!Array.isArray(input)) {\n throw new BitfabError(\n `Seed case ${index} in '${path}' is missing an \"input\" array. Wrap a single argument as [arg].`,\n )\n }\n if (run && \"expected\" in value) {\n throw new BitfabError(\n `Seed case ${index} in '${path}' carries \"expected\", which --run does not record: the case is run once and its output is what the run produced. Remove the field, or drop --run to record the case without running it.`,\n )\n }\n return value as SeedCase\n })\n}\n\n/**\n * Seed cases through an already-registered pipeline.\n *\n * The registration is the whole point: it already holds the client, the exact\n * function production calls, and the trace function key replay selects by, so\n * a seeded case is guaranteed to line up with the replay that will read it.\n * Passing the registered function to `seedTrace` also means a case that cannot\n * supply its required arguments is rejected here rather than at replay.\n */\nexport async function seedFromRegistry(\n registry: ReplayRegistry,\n pipeline: string,\n cases: readonly SeedCase[],\n options: { run?: boolean } = {},\n): Promise<SeedResult> {\n const registration = registry[pipeline]\n if (registration === undefined) {\n throw new BitfabError(\n `Unknown pipeline '${pipeline}'. Registered: ${Object.keys(registry).join(\", \")}`,\n )\n }\n const traceFunctionKey = resolveTraceFunctionKey(registration)\n if (options.run === true) {\n const traceIds: string[] = []\n for (const seedCase of cases) {\n traceIds.push(\n await registration.client.seedTrace(traceFunctionKey, registration.fn, {\n args: seedCase.input,\n metadata: seedCase.metadata,\n sessionId: seedCase.sessionId,\n }),\n )\n }\n return { pipeline, traceFunctionKey, traceIds }\n }\n const traceIds = cases.map((seedCase) =>\n registration.client.seedTrace(traceFunctionKey, {\n input: seedCase.input,\n expected: seedCase.expected,\n fn: registration.fn,\n metadata: seedCase.metadata,\n sessionId: seedCase.sessionId,\n }),\n )\n const { flushTraces } = await import(\"./http.js\")\n await flushTraces(30_000)\n return { pipeline, traceFunctionKey, traceIds }\n}\n\nconst SEED_USAGE =\n 'Usage: bitfab-replay --registry <path> <pipeline> --seed <cases.jsonl> [--run]\\n\\nEach case is a JSON object with an \"input\" array, plus optional \"expected\", \"metadata\", and \"sessionId\". A JSON array of those objects works too.\\n\\nWithout --run, each case is written as a trace directly: \"input\" becomes the root span input and \"expected\" its output, and nothing executes.\\n\\nWith --run, each case is run once through the registered function with capture off and the execution is recorded, so the output is what the run produced. Cases carrying \"expected\" are rejected.'\n\nexport async function runSeedCli(\n registry: ReplayRegistry,\n argv: readonly string[],\n io: ReplayCliIo = {},\n): Promise<SeedResult> {\n const stdout = io.stdout ?? console.log\n const stderr = io.stderr ?? console.error\n if (argv.some((value) => HELP_FLAGS.has(value))) {\n throw new ReplayCliHelp(SEED_USAGE)\n }\n const pipeline = argv[0]\n if (pipeline === undefined || registry[pipeline] === undefined) {\n throw new BitfabError(SEED_USAGE)\n }\n const seedIndex = argv.indexOf(\"--seed\")\n const casesPath = argv[seedIndex + 1]\n if (casesPath === undefined || casesPath.startsWith(\"--\")) {\n throw new BitfabError(\"--seed requires a path to a cases file.\")\n }\n const run = argv.includes(\"--run\")\n const readFile = io.readFile ?? defaultReadFile\n const cases = parseSeedCases(await readFile(casesPath), casesPath, run)\n\n stderr(\n run\n ? `[seed] Running ${cases.length} case(s) through \"${pipeline}\"...`\n : `[seed] Seeding ${cases.length} case(s) into \"${pipeline}\"...`,\n )\n const result = await seedFromRegistry(registry, pipeline, cases, { run })\n stderr(\n `[seed] ${run ? \"Recorded\" : \"Wrote\"} ${result.traceIds.length} trace(s) for \"${result.traceFunctionKey}\". Replay them with --trace-ids ${result.traceIds.slice(0, 3).join(\",\")}${result.traceIds.length > 3 ? \",...\" : \"\"}`,\n )\n stdout(JSON.stringify(result, null, 2))\n return result\n}\n\nfunction requirePositiveInteger(\n flag: string,\n raw: string,\n max?: number,\n): number {\n const value = Number(raw)\n if (!Number.isInteger(value) || value < 1) {\n throw new BitfabError(\n `${flag} must be a positive integer (received '${raw}').`,\n )\n }\n if (max !== undefined && value > max) {\n throw new BitfabError(`${flag} must be at most ${max} (received '${raw}').`)\n }\n return value\n}\n\nfunction commaSeparated(flag: string, raw: string): string[] {\n const values = raw\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0)\n if (values.length === 0) {\n throw new BitfabError(`${flag} must contain at least one value.`)\n }\n return values\n}\n\nfunction parseReplayCliArgs(\n registry: ReplayRegistry,\n argv: readonly string[],\n): ReplayCliArgs {\n if (argv.some((value) => HELP_FLAGS.has(value))) {\n throw new ReplayCliHelp(usage(registry))\n }\n const pipeline = argv[0]\n if (pipeline === undefined || registry[pipeline] === undefined) {\n throw new BitfabError(usage(registry))\n }\n\n const parsed: ReplayCliArgs = { pipeline, params: [] }\n for (let index = 1; index < argv.length; index += 1) {\n const flag = argv[index]\n if (BOOLEAN_FLAGS.has(flag)) {\n switch (flag) {\n case \"--db-branch\":\n if (parsed.dbBranch === false) {\n throw new BitfabError(\n \"--db-branch and --no-db-branch cannot be used together.\",\n )\n }\n parsed.dbBranch = true\n break\n case \"--no-db-branch\":\n if (parsed.dbBranch === true) {\n throw new BitfabError(\n \"--db-branch and --no-db-branch cannot be used together.\",\n )\n }\n parsed.dbBranch = false\n break\n case \"--no-code-change\":\n parsed.noCodeChange = true\n break\n case \"--dry-run\":\n parsed.dryRun = true\n break\n }\n continue\n }\n if (!VALUE_FLAGS.has(flag)) {\n throw new BitfabError(\n `Unknown replay option '${flag}'.\\n${usage(registry)}`,\n )\n }\n const raw = argv[index + 1]\n if (raw === undefined || raw.startsWith(\"--\")) {\n throw new BitfabError(`${flag} requires a value.`)\n }\n index += 1\n\n switch (flag) {\n case \"--limit\":\n parsed.limit = requirePositiveInteger(flag, raw)\n break\n case \"--attempts\":\n parsed.attempts = requirePositiveInteger(flag, raw, MAX_ATTEMPTS)\n break\n case \"--trace-ids\":\n parsed.traceIds = commaSeparated(flag, raw)\n break\n case \"--name\":\n parsed.name = raw\n break\n case \"--concurrency\":\n case \"--max-concurrency\":\n parsed.maxConcurrency = requirePositiveInteger(flag, raw)\n break\n case \"--code-change\":\n parsed.codeChangePath = raw\n break\n case \"--experiment-group-id\":\n parsed.experimentGroupId = raw\n break\n case \"--dataset-id\":\n parsed.datasetId = raw\n break\n case \"--grader-ids\":\n parsed.graderIds = commaSeparated(flag, raw)\n break\n case \"--mock\":\n if (raw !== \"none\" && raw !== \"all\" && raw !== \"marked\") {\n throw new BitfabError(\n `--mock must be one of: none, all, marked (received '${raw}').`,\n )\n }\n parsed.mock = raw\n break\n case \"--params\":\n parsed.paramsPath = raw\n break\n case \"--param\":\n parsed.params.push(raw)\n break\n }\n }\n if (parsed.traceIds !== undefined && parsed.datasetId !== undefined) {\n throw new BitfabError(\n \"--trace-ids and --dataset-id select different replay sources and cannot be used together.\",\n )\n }\n if (parsed.codeChangePath !== undefined && parsed.noCodeChange === true) {\n throw new BitfabError(\n \"--code-change and --no-code-change cannot be used together.\",\n )\n }\n return parsed\n}\n\nfunction resolveTraceFunctionKey(registration: ReplayRegistration): string {\n const wrappedKey = (\n registration.fn as ReplayFunction & {\n _bitfabTraceFunctionKey?: string\n }\n )._bitfabTraceFunctionKey\n const key = registration.traceFunctionKey ?? wrappedKey\n if (key === undefined) {\n throw new BitfabError(\n \"Replay registry entry uses a plain function. Set traceFunctionKey to the key its production handler records.\",\n )\n }\n return key\n}\n\nasync function defaultReadFile(path: string): Promise<string> {\n const fs = await import(\"node:fs/promises\").catch(() => null)\n if (fs === null) {\n throw new BitfabError(\n \"--code-change requires a runtime that can read local files.\",\n )\n }\n return fs.readFile(path, \"utf8\")\n}\n\nasync function loadCodeChange(\n path: string | undefined,\n readFile: (path: string) => Promise<string>,\n): Promise<CodeChange | undefined> {\n if (path === undefined) {\n return undefined\n }\n const value = JSON.parse(await readFile(path)) as Partial<CodeChange>\n if (typeof value.description !== \"string\" || !Array.isArray(value.files)) {\n throw new BitfabError(\n `Invalid --code-change file '${path}': expected { description, files }.`,\n )\n }\n return { description: value.description, files: value.files }\n}\n\nfunction parseParameter(raw: string): [string, unknown] {\n const separator = raw.indexOf(\"=\")\n const key = raw.slice(0, separator).trim()\n if (separator < 1 || key.length === 0) {\n throw new BitfabError(\n `Invalid --param '${raw}': expected a non-empty name=value pair.`,\n )\n }\n const value = raw.slice(separator + 1)\n try {\n return [key, JSON.parse(value) as unknown]\n } catch {\n return [key, value]\n }\n}\n\nasync function loadParameters(\n path: string | undefined,\n rawParameters: readonly string[],\n readFile: (path: string) => Promise<string>,\n): Promise<Record<string, unknown>> {\n let params: Record<string, unknown> = {}\n if (path !== undefined) {\n const value = JSON.parse(await readFile(path)) as unknown\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new BitfabError(\n `Invalid --params file '${path}': expected a JSON object.`,\n )\n }\n params = { ...(value as Record<string, unknown>) }\n }\n for (const raw of rawParameters) {\n const [key, value] = parseParameter(raw)\n params[key] = value\n }\n return params\n}\n\nfunction valuesEqual(left: unknown, right: unknown): boolean {\n try {\n return JSON.stringify(left) === JSON.stringify(right)\n } catch {\n return Object.is(left, right)\n }\n}\n\nfunction renderSummary(\n pipeline: string,\n result: ReplayResult<unknown>,\n stderr: (line: string) => void,\n): void {\n let same = 0\n let changed = 0\n let matched = 0\n let missed = 0\n let errors = 0\n\n for (const item of result.items) {\n if (item.error !== null) {\n errors += 1\n continue\n }\n const equal = valuesEqual(item.result, item.originalOutput)\n if (item.ingestionType === \"seeded\") {\n if (equal) {\n matched += 1\n } else {\n missed += 1\n }\n } else if (equal) {\n same += 1\n } else {\n changed += 1\n }\n }\n\n stderr(\"\\n─── Summary ───\")\n stderr(` Pipeline: ${pipeline}`)\n stderr(` Replayed: ${result.items.length}`)\n if (result.attempts > 1) {\n stderr(` Attempts: ${result.attempts}`)\n }\n if (same > 0 || changed > 0 || matched + missed === 0) {\n stderr(` Same: ${same}`)\n stderr(` Changed: ${changed}`)\n }\n if (matched > 0 || missed > 0) {\n stderr(` Matched expected: ${matched}`)\n stderr(` Missed expected: ${missed}`)\n }\n if (errors > 0) {\n stderr(` Errors: ${errors}`)\n }\n stderr(`\\n ${result.testRunUrl}`)\n}\n\nfunction renderDryRun(\n pipeline: string,\n result: ReplayResult<unknown>,\n stderr: (line: string) => void,\n): void {\n stderr(\"\\n─── Dry run ───\")\n stderr(` Pipeline: ${pipeline}`)\n stderr(` Resolved: ${result.items.length} (nothing was executed)`)\n for (const item of result.items) {\n stderr(`\\n ${item.originalTraceId}`)\n stderr(` args: ${safeJson(item.input)}`)\n }\n stderr(`\\n ${result.testRunUrl}`)\n}\n\nfunction safeJson(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\nfunction reportReplayError(\n error: ReplayError,\n stderr: (line: string) => void,\n): void {\n for (const item of error.items as ReplayItem<unknown>[]) {\n stderr(\n `${item.originalTraceId}: ${String(item.traceError ?? item.replayError ?? item.error)}`,\n )\n }\n}\n\n/**\n * Run the SDK-owned replay command against a project-owned registry.\n *\n * The installed `bitfab-replay` executable calls this after loading the\n * registry passed through `--registry`. The SDK owns every common flag,\n * lifecycle callback, and output contract.\n */\nexport async function runReplayCli(\n registry: ReplayRegistry,\n argv: readonly string[] = typeof process === \"undefined\"\n ? []\n : process.argv.slice(2),\n io: ReplayCliIo = {},\n): Promise<ReplayResult<unknown>> {\n const stdout = io.stdout ?? console.log\n const stderr = io.stderr ?? console.error\n const args = parseReplayCliArgs(registry, argv)\n const registration = registry[args.pipeline]\n const traceFunctionKey = resolveTraceFunctionKey(registration)\n const readFile = io.readFile ?? defaultReadFile\n const params = await loadParameters(args.paramsPath, args.params, readFile)\n const dynamicOptions = await registration.optionsFactory?.({ params })\n const registrationOptions: ReplayRegistryOptions = {\n ...registration.options,\n ...dynamicOptions,\n }\n if (\n registrationOptions.traceIds !== undefined &&\n registrationOptions.datasetId !== undefined\n ) {\n throw new BitfabError(\n \"Replay registry options traceIds and datasetId select different sources and cannot be used together.\",\n )\n }\n const codeChange = await loadCodeChange(args.codeChangePath, readFile)\n\n const options: ReplayOptions = {\n ...registrationOptions,\n ...(args.name === undefined ? {} : { name: args.name }),\n ...(args.attempts === undefined ? {} : { attempts: args.attempts }),\n ...(args.maxConcurrency === undefined\n ? {}\n : { maxConcurrency: args.maxConcurrency }),\n ...(args.experimentGroupId === undefined\n ? {}\n : { experimentGroupId: args.experimentGroupId }),\n ...(args.datasetId === undefined ? {} : { datasetId: args.datasetId }),\n ...(args.graderIds === undefined ? {} : { graderIds: args.graderIds }),\n ...(args.mock === undefined ? {} : { mock: args.mock }),\n ...(args.dbBranch === undefined\n ? {}\n : {\n dbBranch:\n args.dbBranch &&\n registrationOptions.dbBranch !== undefined &&\n registrationOptions.dbBranch !== false\n ? registrationOptions.dbBranch\n : args.dbBranch,\n }),\n ...(args.noCodeChange === true\n ? { codeChangeDescription: null, codeChangeFiles: null }\n : {}),\n ...(args.dryRun === true ? { dryRun: true } : {}),\n ...(codeChange === undefined\n ? {}\n : {\n codeChangeDescription: codeChange.description,\n codeChangeFiles: codeChange.files,\n }),\n onItemStart: reportReplayProgress,\n onItemFinish: reportReplayProgress,\n }\n\n if (args.traceIds !== undefined) {\n options.traceIds = args.traceIds\n options.datasetId = undefined\n options.limit = undefined\n } else if (args.datasetId !== undefined) {\n options.traceIds = undefined\n options.limit = undefined\n } else if (args.limit !== undefined) {\n options.traceIds = undefined\n options.datasetId = undefined\n options.limit = args.limit\n } else if (\n registrationOptions.traceIds !== undefined ||\n registrationOptions.datasetId !== undefined\n ) {\n options.limit = undefined\n } else {\n options.limit = registrationOptions.limit ?? 10\n }\n\n const attemptsSuffix =\n options.attempts !== undefined && options.attempts > 1\n ? ` (${options.attempts} attempts each)`\n : \"\"\n stderr(\n `[replay] ${args.dryRun === true ? \"Resolving inputs for\" : \"Replaying\"} ${options.traceIds?.length ?? options.limit ?? \"dataset\"} traces from \"${traceFunctionKey}\"${attemptsSuffix}...`,\n )\n\n try {\n const result = await registration.client.replay(\n traceFunctionKey,\n registration.fn,\n options,\n )\n if (args.dryRun === true) {\n renderDryRun(args.pipeline, result, stderr)\n } else {\n renderSummary(args.pipeline, result, stderr)\n }\n stdout(serializeReplayResult(result))\n // A command that selected nothing did nothing, so it must not exit 0. This\n // is the shape an unseeded corpus takes: `--limit 10` against a trace\n // function with no traces reads as a clean run rather than as no run.\n if (result.items.length === 0) {\n throw new BitfabError(\n `No traces matched \"${traceFunctionKey}\", so nothing was replayed. Seed cases with --seed, or capture a trace first.`,\n )\n }\n return result\n } catch (error) {\n if (error instanceof ReplayError) {\n reportReplayError(error, stderr)\n }\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBO,IAAM,8BAA8B;AAQ3C,SAAS,cAAc,SAAkC;AACvD,QAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC,EAAE,KAAK,EAAE,KAAK,IAAI;AACpD,SAAO;AAAA,IACL,QAAQ;AA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AAS;AAChD;AAoLA,SAAS,wBAAwB,cAA0C;AACzE,QAAM,aACJ,aAAa,GAGb;AACF,QAAM,MAAM,aAAa,oBAAoB;AAC7C,MAAI,QAAQ,QAAW;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":["_context","nowIso","asTokenCount","extractUsage","method","flushTraces","traceIds","flushTraces"]}