@bitfab/sdk 0.65.5 → 0.65.7

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 +1 @@
1
- {"version":3,"file":"registryCommand-Di8x0YoJ.js","names":["DEFAULT_LIFECYCLE_TIMEOUT_MS","keyed"],"sources":["../src/errors.ts","../src/compress.ts","../src/asyncStorage.ts","../src/replayContext.ts","../src/captureSuppression.ts","../src/payloadBudget.ts","../src/warnOnce.ts","../src/spanOrigin.ts","../src/simulationPlan.ts","../src/unrefTimer.ts","../src/otel.ts","../src/transport.ts","../src/http.ts","../src/replayInterrupt.ts","../src/replayInvocation.ts","../src/replay.ts","../src/autoTrace.ts","../src/commitRef.ts","../src/openaiAgentsSpanContext.ts","../src/rivetContext.ts","../src/seedContext.ts","../src/client.ts","../src/replayRegistry.ts","../src/registryCommand.ts"],"sourcesContent":["/**\n * Shared error type for Bitfab SDK runtime errors. Lives in its own\n * module to avoid import cycles between `http.ts` and modules that need\n * to throw structured errors (e.g. `dbSnapshot.ts` validation).\n */\n\nexport class BitfabError extends Error {\n constructor(\n message: string,\n public readonly url?: string,\n /**\n * HTTP status the request failed with, when it failed with one. The\n * transport's retry policy needs the code itself (retry 408/425/429/5xx,\n * never a 4xx the server will reject again), which a formatted message\n * cannot supply. Absent for network failures and non-HTTP errors.\n */\n public readonly status?: number,\n /**\n * `Retry-After` in milliseconds, when the server sent one. A 429 or 503\n * carries the server's own instruction about when to come back; retrying\n * on our own schedule ignores it and keeps the pressure on.\n */\n public readonly retryAfterMs?: number,\n ) {\n super(message)\n this.name = \"BitfabError\"\n }\n}\n\nexport class MixedTracingError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"MixedTracingError\"\n }\n}\n","import { readEnv } from \"./readEnv.js\"\n\nconst DISABLE_COMPRESSION_ENV = \"BITFAB_DISABLE_COMPRESSION\"\n\n/**\n * Below this, compressing costs more than the saved bytes are worth, so small\n * requests (function lookups, replay status polls, single-span batches) ride\n * uncompressed.\n */\nconst MIN_COMPRESSED_BYTES = 8_192\n\nexport interface EncodedRequestBody {\n body: string | ArrayBuffer\n contentEncoding?: \"gzip\"\n rawBytes: number\n wireBytes: number\n}\n\n/**\n * Node's gzip, loaded dynamically so browser bundlers never have to resolve\n * `node:zlib`. Deliberately the async form: it runs on libuv's threadpool\n * rather than the event loop. Measured on 8 concurrent 1 MB bodies, the\n * synchronous form stalled the loop for 326ms and the async form for 1ms,\n * while also finishing 3.8x sooner because the threadpool compresses in\n * parallel. A tracing SDK must not block its host's event loop.\n */\nlet gzipNode: ((data: Uint8Array) => Promise<Uint8Array>) | undefined\n\ntype NodeZlib = {\n gzip: (\n data: Uint8Array,\n callback: (error: Error | null, result: Uint8Array) => void,\n ) => void\n}\n\nexport const _nodeGzipReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:zlib\" from static analysis so bundlers that\n // ban Node.js built-ins don't fail at build time. webpackIgnore tells\n // webpack/turbopack to emit a native import() so Node.js can resolve the\n // module at runtime. Same pattern as `asyncStorage.ts`.\n import(\n /* webpackIgnore: true */\n [\"node\", \"zlib\"].join(\":\")\n )\n .then(({ gzip }: NodeZlib) => {\n gzipNode = (data) =>\n new Promise((resolve, reject) => {\n gzip(data, (error, result) => {\n if (error) {\n reject(error)\n } else {\n resolve(result)\n }\n })\n })\n })\n .catch(() => {})\n : Promise.resolve()\n).then(() => {})\n\n/** Test seam for exercising the browser path on Node. */\nexport function _setNodeGzip(\n impl: ((data: Uint8Array) => Promise<Uint8Array>) | undefined,\n): void {\n gzipNode = impl\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n return view.buffer.slice(\n view.byteOffset,\n view.byteOffset + view.byteLength,\n ) as ArrayBuffer\n}\n\nfunction compressedRequest(\n body: string,\n rawBytes: number,\n compressed: Uint8Array | ArrayBuffer,\n): EncodedRequestBody {\n if (compressed.byteLength >= rawBytes) {\n return { body, rawBytes, wireBytes: rawBytes }\n }\n return {\n body:\n compressed instanceof Uint8Array ? toArrayBuffer(compressed) : compressed,\n contentEncoding: \"gzip\",\n rawBytes,\n wireBytes: compressed.byteLength,\n }\n}\n\nasync function gzipViaStream(bytes: Uint8Array): Promise<ArrayBuffer> {\n const stream = new Blob([bytes as BlobPart])\n .stream()\n .pipeThrough(new CompressionStream(\"gzip\"))\n return await new Response(stream).arrayBuffer()\n}\n\n/**\n * Compression is best-effort: any failure sends the original body rather than\n * dropping the span. `CompressionStream` is absent on older browsers, so its\n * presence is checked rather than assumed.\n *\n * Returns a plain value (not a promise) whenever it can, so a request still\n * reaches `fetch` in the caller's tick rather than one microtask later. Callers\n * await the union.\n */\nexport function encodeRequestBody(\n body: string,\n): EncodedRequestBody | Promise<EncodedRequestBody> {\n if (readEnv(DISABLE_COMPRESSION_ENV)) {\n const rawBytes = new TextEncoder().encode(body).byteLength\n return { body, rawBytes, wireBytes: rawBytes }\n }\n const bytes = new TextEncoder().encode(body)\n if (bytes.byteLength < MIN_COMPRESSED_BYTES) {\n return {\n body,\n rawBytes: bytes.byteLength,\n wireBytes: bytes.byteLength,\n }\n }\n if (gzipNode) {\n return gzipNode(bytes).then(\n (compressed) => compressedRequest(body, bytes.byteLength, compressed),\n () => ({\n body,\n rawBytes: bytes.byteLength,\n wireBytes: bytes.byteLength,\n }),\n )\n }\n if (typeof CompressionStream === \"undefined\") {\n return {\n body,\n rawBytes: bytes.byteLength,\n wireBytes: bytes.byteLength,\n }\n }\n return gzipViaStream(bytes).then(\n (compressed) => compressedRequest(body, bytes.byteLength, compressed),\n () => ({\n body,\n rawBytes: bytes.byteLength,\n wireBytes: bytes.byteLength,\n }),\n )\n}\n","/**\n * Shared AsyncLocalStorage loader.\n *\n * Provides two ways to initialize AsyncLocalStorage:\n *\n * 1. **Synchronous registration** (preferred for Node.js):\n * `asyncStorageNode.ts` calls `registerAsyncLocalStorageClass()` at module\n * evaluation time, so the class is available immediately - no async gap.\n * The `node.ts` entry point imports it before anything else.\n *\n * 2. **Async dynamic import** (fallback for the default entry point):\n * Loads `node:async_hooks` via a bundler-safe dynamic import. This is used\n * by the default `index.ts` entry point so the SDK works in browsers\n * (where the import silently fails) and in Node.js when imported via the\n * default entry point.\n *\n * ## Why the dynamic import looks like this\n *\n * We need to handle three environments:\n *\n * 1. **Pure Node.js** - `import(\"node:async_hooks\")` works natively.\n * 2. **Webpack/Turbopack (Next.js server)** - The bundler processes\n * `import()` calls at build time. The `webpackIgnore` magic comment tells\n * webpack (and turbopack) to emit a native `import()` call instead of\n * trying to resolve it, so Node.js handles it at runtime.\n * 3. **Browsers / Edge** - The `process.versions?.node` guard prevents\n * execution entirely. If it somehow runs, `.catch(() => {})` swallows\n * the failure.\n */\n\nexport interface AsyncLocalStorageLike<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\nlet AsyncLocalStorageClass: (new () => AsyncLocalStorageLike<unknown>) | null =\n null\nlet initDone = false\n\n/**\n * Register the AsyncLocalStorage class synchronously.\n *\n * Called by `asyncStorageNode.ts` at module evaluation time so the class\n * is available before any span is created - no async gap, no race condition.\n *\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport function registerAsyncLocalStorageClass(\n cls: new () => AsyncLocalStorageLike<unknown>,\n): void {\n if (!AsyncLocalStorageClass) {\n AsyncLocalStorageClass = cls\n }\n initDone = true\n}\n\n/**\n * Assert that AsyncLocalStorage was registered successfully.\n *\n * Called by `node.ts` after importing `asyncStorageNode.ts` to catch\n * import-order bugs at startup rather than silently degrading to the\n * browser fallback (flat spans with no nesting).\n *\n * This should ONLY be called from the Node.js entry point where we\n * know `node:async_hooks` must be available.\n */\nexport function assertAsyncStorageRegistered(): void {\n if (!AsyncLocalStorageClass) {\n console.warn(\n \"Bitfab: AsyncLocalStorage not available - nested span context will not propagate.\",\n )\n }\n}\n\nexport const asyncStorageReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:async_hooks\" from static analysis so\n // bundlers that ban Node.js built-ins don't fail at build time.\n // webpackIgnore tells webpack/turbopack to emit a native import()\n // so Node.js can resolve the module at runtime.\n import(\n /* webpackIgnore: true */\n [\"node\", \"async_hooks\"].join(\":\")\n )\n .then(\n (mod: {\n AsyncLocalStorage: new () => AsyncLocalStorageLike<unknown>\n }) => {\n registerAsyncLocalStorageClass(mod.AsyncLocalStorage)\n },\n )\n .catch(() => {})\n : Promise.resolve()\n).then(() => {\n initDone = true\n})\n\nexport function isAsyncStorageInitDone(): boolean {\n return initDone\n}\n\nexport function createAsyncLocalStorage<T>(): AsyncLocalStorageLike<T> | null {\n return AsyncLocalStorageClass\n ? (new AsyncLocalStorageClass() as AsyncLocalStorageLike<T>)\n : null\n}\n","/**\n * Replay context propagation via AsyncLocalStorage.\n *\n * When set, the withSpan wrapper injects experimentId into the span payload\n * so that new spans created during replay are linked to the experiment.\n * Optionally carries a mock tree so child spans can return historical\n * outputs instead of executing.\n */\n\nimport {\n type AsyncLocalStorageLike,\n asyncStorageReady,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\nimport type { MockOverride } from \"./mockOverride.js\"\nimport type { SelectiveReplayRuntime } from \"./selectiveReplayRuntime.js\"\n\n/**\n * A single span entry in the mock tree.\n *\n * Under the eager path (`mock: \"all\"`) `output`/`outputMeta` are populated\n * inline, even when overrides are present. Under a non-`all` path that needs a\n * tree (`marked`, or `none` with overrides), they are absent and the recorded\n * output is fetched on demand via `externalSpanId` - see\n * {@link ReplayContext.fetchSpanOutput}.\n */\nexport interface MockSpan {\n sourceSpanId: string\n /** Row id accepted by `getExternalSpan`, for the lazy per-span output fetch. */\n externalSpanId?: string\n output?: unknown\n outputMeta?: unknown\n}\n\n/**\n * Per-item DB branch resolved by the Bitfab service from the source\n * trace's `dbSnapshotRef`. Carried on the replay context so that\n * customer code reads `databaseUrl` through `getCurrentReplayBranch()`, and so\n * the process-isolated replay runner can materialize it into a `.env`\n * overlay file before customer code initializes its DB client.\n *\n * `neonBranchId` is the literal Neon branch id; passing it to\n * `releaseDbBranchLease` deletes that branch.\n */\nexport interface DbBranchLease {\n neonBranchId: string\n /** Env var name the customer's app reads, e.g. \"DATABASE_URL\". */\n envKey: string\n databaseUrl: string\n expiresAt: string\n /**\n * The instant the branch was pinned to (the source trace's wall clock).\n * Echoed back in `db_snapshot_usage` on the replayed trace's completion.\n */\n snapshotTimestamp?: string\n providerConsoleUrl?: string\n 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 runner elsewhere pays that round trip on every query.\n */\n region?: string\n}\n\n/**\n * How long each phase of provisioning one replay branch took, measured\n * server-side. A runner in another region sees these plus its own round trip.\n *\n * Durations, not instants: an instant is approximately `startedAt` plus the\n * running sum, and per-phase wall-clock stamps would make clock skew between\n * the server and your runner look like latency. Approximately, because\n * `totalMs` is the resolve's true wall time and covers a little work no phase\n * owns, so the phases account for it without summing to it exactly.\n *\n * `startedAt` and `totalMs` are always present. The phases are optional\n * because a failed resolve reports only the ones it reached, and `totalMs` is\n * then time-to-failure. On success every phase is present except `warmupMs`,\n * which is absent when no warm-up SQL was supplied.\n */\nexport interface DbBranchTimings {\n /** When the resolve began, ISO. */\n startedAt: string\n /** Resolving the project, plus its retention and region reads. */\n projectResolveMs?: number\n /** Creating the branch, through its provider operations reaching terminal. */\n branchCreateMs?: number\n /** Resolving the connection URI. 0 when the provider returns one inline. */\n connectionUriMs?: number\n /** The compute accepting a connection. */\n computeConnectMs?: number\n /** The branch answering a readiness query. */\n baseProbeMs?: number\n /** Your warm-up SQL. Absent when you supplied none. */\n warmupMs?: number\n /** The whole resolve, or time-to-failure when it threw. */\n totalMs: number\n}\n\n/**\n * Wire shape of the caller's `ReplayOptions.dbBranch`, sent to\n * `/api/sdk/replay/start` and applied per lease.\n */\nexport interface DbBranchSettings {\n minCu?: number\n maxCu?: number\n warmupSql?: string\n}\n\n/**\n * Pre-built lookup table of historical span outputs.\n * Keys are `${traceFunctionKey}:${spanName}:${callIndex}` so that repeated\n * calls with the same (key, name) are matched by call order, but spans\n * sharing only the traceFunctionKey (different name) do not collide.\n */\nexport interface MockTree {\n spans: Map<string, MockSpan>\n}\n\nexport interface ReplayContext {\n experimentId: string\n selectiveReplay?: SelectiveReplayRuntime\n traceId?: string\n inputSourceSpanId?: string\n /**\n * External trace ID from `external_traces.id`. Used for span-chain\n * lookup against the source platform's trace tree (Braintrust, etc.).\n * NOT the same as the Bitfab `traceId` - see `sourceBitfabTraceId`.\n */\n inputSourceTraceId?: string\n /**\n * The Bitfab `traces.id` of the historical trace that produced this\n * replay item's input. This is what customer-facing surfaces (e.g.\n * `ReplayBranch.traceId`) should expose, since it's the ID the\n * customer sees in the Bitfab dashboard.\n */\n sourceBitfabTraceId?: string\n replayAttempt?: number\n mockTree?: MockTree\n callCounters?: Map<string, number>\n mockStrategy?: \"none\" | \"all\" | \"marked\"\n /**\n * Resolved override chain for this replay, per-call overrides first then\n * registered ones (first matcher wins). Empty/absent when no overrides apply.\n */\n mockOverrides?: MockOverride[]\n /**\n * Memoized lazy fetch of a span's recorded output (deserialized), keyed by\n * `externalSpanId`. Present ONLY on a non-`all` path that needs a tree\n * (`marked`, or `none` with overrides); absent under `mock: \"all\"`, where\n * outputs are inline even when overrides are present. Its presence is the\n * signal that outputs must be fetched rather than read inline.\n */\n fetchSpanOutput?: (externalSpanId: string) => Promise<unknown>\n /** Internal framework state captured on the historical root span. */\n integrationFixtures?: Map<string, unknown>\n dbBranchLease?: DbBranchLease\n /**\n * Server-measured provisioning timings for this item's branch, echoed back\n * on the trace completion so the trace records what it cost to set up. Kept\n * off `ReplayBranch`: customer code reads that mid-replay to reach the\n * branch, and provisioning latency is a property of the run, not of the\n * connection.\n */\n dbBranchTimings?: DbBranchTimings\n /**\n * Set to true by `ReplayBranch` the first time customer code actually\n * obtains `databaseUrl` for this item. Reported on the trace completion inside\n * `db_snapshot_usage` so the server can distinguish \"branch was\n * provisioned and exposed\" from \"branch URL was actually consumed\".\n * Only an explicit `databaseUrl` read may set it. A path that hands the URL\n * over by other means (e.g. a process-isolated runner writing an env\n * overlay) must leave it alone: setting it there would make every such\n * replay report `accessed` for free, and the flag would stop separating\n * \"branch was used\" from \"branch was offered\".\n */\n dbSnapshotAccessed?: boolean\n}\n\nlet replayContextStorage: AsyncLocalStorageLike<ReplayContext | null> | null =\n null\nconst REPLAY_CONTEXT_STORAGE_SYMBOL = Symbol.for(\"bitfab.replayContextStorage\")\n\nexport const replayContextReady: Promise<void> = asyncStorageReady.then(() => {\n const shared = globalThis as typeof globalThis & Record<symbol, unknown>\n const existing = shared[REPLAY_CONTEXT_STORAGE_SYMBOL] as\n | AsyncLocalStorageLike<ReplayContext | null>\n | undefined\n if (existing) {\n replayContextStorage = existing\n return\n }\n const created = createAsyncLocalStorage<ReplayContext | null>()\n if (created) {\n shared[REPLAY_CONTEXT_STORAGE_SYMBOL] = created\n replayContextStorage = created\n }\n})\n\n/** Get the current replay context, if any. */\nexport function getReplayContext(): ReplayContext | null {\n return replayContextStorage?.getStore() ?? null\n}\n\n/** Run a function within a replay context. */\nexport function runWithReplayContext<T>(ctx: ReplayContext, fn: () => T): T {\n if (replayContextStorage) {\n return replayContextStorage.run(ctx, fn)\n }\n return fn()\n}\n","interface CaptureSuppressionState {\n depth: number\n}\n\ninterface CaptureSuppressionGlobal {\n __bitfabCaptureSuppressionV1?: CaptureSuppressionState\n}\n\nconst suppressionGlobal = globalThis as unknown as CaptureSuppressionGlobal\nconst suppressionState: CaptureSuppressionState =\n suppressionGlobal.__bitfabCaptureSuppressionV1 ?? { depth: 0 }\nsuppressionGlobal.__bitfabCaptureSuppressionV1 = suppressionState\n\nexport function isCaptureSuppressed(): boolean {\n return suppressionState.depth > 0\n}\n\nexport function runWithCaptureSuppressed<T>(fn: () => T): T {\n suppressionState.depth += 1\n try {\n return fn()\n } finally {\n suppressionState.depth -= 1\n }\n}\n","/**\n * The ceiling on a span's encoded carrier, and the trimming that enforces it.\n *\n * A span's whole payload (input, output, contexts, prompt, metadata) ships as\n * a single `bitfab.payload` string attribute, and the exporter drops any\n * carrier that exceeds the per-request byte ceiling outright rather than\n * trimming it. Capping each value on its own cannot prevent that: two values\n * that each fit can still add up to an undeliverable span. So the budget is\n * enforced on the whole span, and an oversized one ships with its largest\n * fields stubbed instead of vanishing.\n *\n * The budget is measured on the *carrier* (the payload re-escaped into the\n * OTLP attribute), not on the payload body, because the carrier is what the\n * exporter weighs. Bounding the body instead leaves escape-heavy content to\n * blow the request ceiling anyway: a body of escaped JSON, Windows paths, or\n * regexes is nearly all backslashes, and every one of them doubles. Measured\n * on a body sized exactly to a 2.4 MB cap, prose produced a 2.4 MB carrier but\n * backslash-dense content produced 4.8 MB, which the exporter dropped.\n *\n * The normal 2.8 MB fallback leaves room beneath the 3 MB wire target. Trace\n * transport may first preserve a carrier up to 7.8 MB when its single-span\n * request compresses below that wire target and remains below ingress's 8 MB\n * decompressed ceiling.\n */\nexport const MAX_SPAN_CARRIER_BYTES = 2_800_000\n\n/**\n * A larger carrier may still fit when its single-span request is compressed.\n * This leaves 200 kB beneath ingress's 8 MB decompressed-body ceiling for the\n * OTLP span and request envelopes.\n */\nexport const MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES = 7_800_000\n\nconst textEncoder =\n typeof TextEncoder !== \"undefined\" ? new TextEncoder() : null\n\nexport function byteLength(value: string): number {\n return textEncoder ? textEncoder.encode(value).length : value.length\n}\n\n/**\n * The byte length `body` occupies once re-escaped as a JSON string value.\n *\n * `body` is itself JSON text, so the first encode already replaced every\n * control character with a `\\uXXXX` sequence, leaving only `\"` and `\\` to\n * escape at one extra byte each.\n *\n * Counts UTF-8 width and escapes in the same pass and allocates nothing.\n * `TextEncoder.encode().length` would be the obvious way to get the byte count,\n * but it copies the entire body into a fresh array just to read its length,\n * which on a multi-megabyte span costs more than producing the body did.\n */\nexport function carrierByteLength(body: string): number {\n return carrierBytesOf(textEncoder ? textEncoder.encode(body) : null, body)\n}\n\n/**\n * Counts escapes over the UTF-8 bytes rather than the UTF-16 string. Bytes\n * `0x22` and `0x5c` are unambiguous there (a multi-byte sequence never uses a\n * byte below `0x80`), so a flat byte scan is exact, and it reuses the array the\n * byte count already had to produce instead of walking the string a second\n * time. Measured ~2x faster than the equivalent `charCodeAt` loop.\n */\nfunction carrierBytesOf(encoded: Uint8Array | null, body: string): number {\n if (!encoded) {\n // No TextEncoder (a browser old enough to lack it). Fall back to the string,\n // where `length` is the best available byte estimate.\n return body.length + 2\n }\n let extra = 2 // the quotes wrapping the attribute value\n for (let i = 0; i < encoded.length; i++) {\n const byte = encoded[i]\n if (byte === 34 || byte === 92) {\n extra += 1 // `\"` and `\\` take a leading backslash\n } else if (byte < 0x20) {\n extra +=\n byte === 8 || byte === 9 || byte === 10 || byte === 12 || byte === 13\n ? 1 // \\b \\f \\n \\r \\t\n : 5 // \\uXXXX\n }\n }\n return encoded.length + extra\n}\n\n/**\n * The most carrier bytes one UTF-16 code unit of a *JSON body* can become.\n *\n * A unit is at most 3 UTF-8 bytes, and the only characters that grow under\n * escaping are `\"` and `\\`, which are one byte and become two. A unit cannot be\n * both, so 3 is the ceiling. This holds because every caller passes the output\n * of a JSON encoder, which by specification never emits a raw control character\n * (the case that would otherwise expand to a 6-byte `\\uXXXX`); the invariant is\n * pinned by a test so a future caller that broke it would fail loudly rather\n * than silently ship an oversized carrier.\n */\nconst MAX_BYTES_PER_UNIT = 3\n\n/**\n * Whether `body` fits the carrier budget, escalating only as far as it must.\n *\n * `body.length` is O(1) and brackets the answer for both ordinary spans (far\n * under the budget) and hopeless ones (already past it on raw length alone),\n * which is every span in normal traffic: neither case touches the string. Only\n * a body near the budget is measured exactly, and that costs one encode plus\n * one byte scan.\n */\nexport function fitsCarrierBudget(\n body: string,\n maxBytes: number = MAX_SPAN_CARRIER_BYTES,\n): boolean {\n const units = body.length\n if (units * MAX_BYTES_PER_UNIT + 2 <= maxBytes) {\n return true\n }\n if (units + 2 > maxBytes) {\n return false\n }\n return carrierByteLength(body) <= maxBytes\n}\n\n/**\n * Span fields that identify the span rather than carry user data. Trimming one\n * would leave a span that no longer says what it is, so they stay whatever the\n * payload costs.\n */\nconst STRUCTURAL_SPAN_KEYS = new Set([\n \"name\",\n \"type\",\n \"function_name\",\n \"error_source\",\n])\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\ninterface Candidate {\n container: Record<string, unknown>\n key: string\n size: number\n}\n\n/**\n * The records holding user data, cloned so trimming never mutates the caller's\n * objects. Returns the payload copy to encode plus the containers to trim.\n */\nfunction cloneTrimmable(payload: Record<string, unknown>): {\n copy: Record<string, unknown>\n containers: Record<string, unknown>[]\n} {\n const copy = { ...payload }\n const containers: Record<string, unknown>[] = []\n\n const spanData = asRecord(copy.span_data)\n if (spanData) {\n const clone = { ...spanData }\n copy.span_data = clone\n containers.push(clone)\n }\n\n const rawSpan = asRecord(copy.rawSpan)\n const rawSpanData = rawSpan && asRecord(rawSpan.span_data)\n if (rawSpan && rawSpanData) {\n const clone = { ...rawSpanData }\n copy.rawSpan = { ...rawSpan, span_data: clone }\n containers.push(clone)\n }\n\n // No span_data anywhere: a trace-level or otherwise unfamiliar payload. Trim\n // its own fields rather than give up, so an oversized body still ships.\n if (containers.length === 0) {\n containers.push(copy)\n }\n\n return { copy, containers }\n}\n\nfunction collectCandidates(containers: Record<string, unknown>[]): Candidate[] {\n const candidates: Candidate[] = []\n for (const container of containers) {\n for (const [key, value] of Object.entries(container)) {\n if (STRUCTURAL_SPAN_KEYS.has(key) || value == null) {\n continue\n }\n let size: number\n try {\n size = byteLength(JSON.stringify(value) ?? \"\")\n } catch {\n continue\n }\n candidates.push({ container, key, size })\n }\n }\n return candidates.sort((a, b) => b.size - a.size)\n}\n\n/**\n * Stub the largest payload fields until the encoded body fits the budget.\n *\n * Returns the trimmed payload and the names of the fields that were stubbed, or\n * `undefined` when nothing could be trimmed (the caller then ships the\n * oversized body and lets the exporter report the drop, which is still better\n * than silently emptying a span).\n */\nexport function trimPayloadToBudget(\n payload: Record<string, unknown>,\n encode: (value: Record<string, unknown>) => string,\n maxBytes: number = MAX_SPAN_CARRIER_BYTES,\n): { value: Record<string, unknown>; trimmed: string[] } | undefined {\n const { copy, containers } = cloneTrimmable(payload)\n const candidates = collectCandidates(containers)\n if (candidates.length === 0) {\n return undefined\n }\n\n const trimmed: string[] = []\n for (const candidate of candidates) {\n candidate.container[candidate.key] =\n `<unserializable: too_large_${candidate.size}_bytes>`\n trimmed.push(candidate.key)\n let body: string\n try {\n body = encode(copy)\n } catch {\n return undefined\n }\n if (fitsCarrierBudget(body, maxBytes)) {\n return { value: copy, trimmed }\n }\n }\n return undefined\n}\n\n/**\n * Record a trim in the payload's own `errors`, which is what the server reads\n * to flag a trace as incomplete.\n */\nexport function markPayloadTrimmed(\n value: Record<string, unknown>,\n trimmed: string[],\n maxBytes: number = MAX_SPAN_CARRIER_BYTES,\n): void {\n const existing = Array.isArray(value.errors) ? value.errors : []\n value.errors = [\n ...existing,\n {\n source: \"sdk\",\n step: \"payload_budget\",\n error: `trimmed oversized field(s) to fit the ${maxBytes}-byte span carrier budget: ${[\n ...new Set(trimmed),\n ].join(\", \")}`,\n },\n ]\n}\n","/**\n * Emit a `console.warn` at most once per distinct `key` for the life of the\n * process.\n *\n * The SDK must NEVER crash a host app, so every failure on the user's path\n * degrades silently (a span is dropped, a call runs untraced, a payload is\n * stubbed). Silent is safe but undebuggable: a user who suddenly has no traces,\n * or sees `<unserializable>` in a span, has no signal as to why. A one-time\n * warning per distinct issue restores that signal without spamming the console\n * from a hot path.\n *\n * Keys should identify the specific degradation (e.g. include the traced\n * function key) so each distinct issue warns once, not just the first one seen.\n */\nconst warned = new Set<string>()\n\nexport function warn(message: string): void {\n try {\n console.warn(`[bitfab] ${message}`)\n } catch {\n // Logging must never crash the host app (e.g. a closed/replaced console).\n }\n}\n\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n warn(message)\n}\n\nexport function writeOnce(\n key: string,\n line: string,\n write: (line: string) => void = console.warn,\n): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n try {\n write(line)\n } catch {}\n}\n\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n","import { __version__ } from \"./constants.js\"\n\nexport const SPAN_ORIGIN_NAME = \"bitfab.sdk.typescript\"\n\nexport const SPAN_INSTRUMENTATIONS = [\n \"span\",\n \"trace\",\n \"openai-agents\",\n \"langgraph\",\n \"claude-agent-sdk\",\n \"vercel-ai\",\n \"rivet\",\n] as const\n\nexport type SpanInstrumentation = (typeof SPAN_INSTRUMENTATIONS)[number]\n\nexport const FRAMEWORK_INSTRUMENTATIONS: readonly SpanInstrumentation[] = [\n \"openai-agents\",\n \"langgraph\",\n \"claude-agent-sdk\",\n \"vercel-ai\",\n \"rivet\",\n]\n\nconst FRAMEWORK_INSTRUMENTATION_SET: ReadonlySet<string> = new Set(\n FRAMEWORK_INSTRUMENTATIONS,\n)\n\nexport function isFrameworkInstrumentation(value: unknown): boolean {\n return typeof value === \"string\" && FRAMEWORK_INSTRUMENTATION_SET.has(value)\n}\n\nexport interface SpanOrigin {\n name: string\n version: string\n instrumentation: { name: SpanInstrumentation }\n}\n\nexport function makeSpanOrigin(\n instrumentation: SpanInstrumentation,\n): SpanOrigin {\n return {\n name: SPAN_ORIGIN_NAME,\n version: __version__,\n instrumentation: { name: instrumentation },\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nexport function spanOriginOf(\n payload: Record<string, unknown>,\n): SpanOrigin | undefined {\n const rawSpan = payload.rawSpan\n if (!isRecord(rawSpan)) {\n return undefined\n }\n const origin = rawSpan.span_origin\n if (!isRecord(origin) || !isRecord(origin.instrumentation)) {\n return undefined\n }\n const { name, version } = origin\n const instrumentation = origin.instrumentation.name\n if (\n typeof name !== \"string\" ||\n typeof version !== \"string\" ||\n typeof instrumentation !== \"string\" ||\n !(SPAN_INSTRUMENTATIONS as readonly string[]).includes(instrumentation)\n ) {\n return undefined\n }\n return {\n name,\n version,\n instrumentation: { name: instrumentation as SpanInstrumentation },\n }\n}\n\nexport function spanInstrumentationOf(\n payload: Record<string, unknown>,\n): SpanInstrumentation | undefined {\n return spanOriginOf(payload)?.instrumentation.name\n}\n\nexport function recordedByFramework(payload: Record<string, unknown>): boolean {\n return isFrameworkInstrumentation(spanInstrumentationOf(payload))\n}\n","import { BitfabError } from \"./errors.js\"\nimport { PolicyRefresh } from \"./policyRefresh.js\"\nimport { readEnv } from \"./readEnv.js\"\nimport { recordedByFramework, spanInstrumentationOf } from \"./spanOrigin.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport const SIMULATION_PLAN_REFRESH_MS = 60_000\nexport const SIMULATION_PLAN_RETRY_MS = 10_000\nexport const SIMULATION_PLAN_READ_TIMEOUT_MS = 5_000\nexport const SIMULATION_PLAN_MAX_HELD = 1_000\nexport const DISABLE_SIMULATION_PLAN_ENV = \"BITFAB_DISABLE_SIM_PLAN\"\nexport const NO_API_KEY_FOR_SIMULATION_PLAN = \"no API key is set\"\nexport const ROOT_TRACE_FUNCTION_KEY_FIELD = \"rootTraceFunctionKey\"\nexport const DECLARED_NODE_FIELD = \"declaredNode\"\n\nexport const CONTENT_OFF_KEY = \"content_off_by_simulation_plan\"\nconst CONTENT_KEYS = [\n \"input\",\n \"input_meta\",\n \"output\",\n \"output_meta\",\n \"replay_recording\",\n \"prompt\",\n] as const\n\nexport interface SimulationPlanNode {\n traceFunctionKey: string\n name: string\n captureContent: boolean\n}\n\nexport interface SimulationPlanResponse {\n nodes: SimulationPlanNode[]\n}\n\ninterface SimulationPlanSource {\n getSimulationPlan(): Promise<SimulationPlanResponse>\n}\n\nexport type SimulationPlanSubmit = (payload: Record<string, unknown>) => void\n\ninterface HeldEntry {\n payload: Record<string, unknown>\n traceFunctionKey: string | undefined\n submit: SimulationPlanSubmit\n drop?: () => void\n}\n\nexport function planWaitSliceMs(timeoutMs: number): number {\n return Math.min(SIMULATION_PLAN_READ_TIMEOUT_MS, Math.max(timeoutMs, 0) / 2)\n}\n\nexport function parseSimulationPlan(\n body: unknown,\n): Map<string, Set<string>> | null {\n if (typeof body !== \"object\" || body === null) {\n return null\n }\n const nodes = (body as { nodes?: unknown }).nodes\n if (!Array.isArray(nodes)) {\n return null\n }\n const contentOff = new Map<string, Set<string>>()\n for (const node of nodes) {\n if (typeof node !== \"object\" || node === null) {\n continue\n }\n const { traceFunctionKey, name, captureContent } = node as Record<\n string,\n unknown\n >\n if (\n typeof traceFunctionKey !== \"string\" ||\n typeof name !== \"string\" ||\n typeof captureContent !== \"boolean\"\n ) {\n continue\n }\n if (captureContent) {\n continue\n }\n const names = contentOff.get(traceFunctionKey) ?? new Set<string>()\n names.add(name)\n contentOff.set(traceFunctionKey, names)\n }\n return contentOff\n}\n\nexport function traceIdOf(\n payload: Record<string, unknown>,\n): string | undefined {\n const traceId = payload.traceId\n if (typeof traceId === \"string\") {\n return traceId\n }\n const id = payload.id\n return typeof id === \"string\" ? id : undefined\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null\n}\n\nfunction rawSpanOf(\n payload: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n return isRecord(payload.rawSpan) ? payload.rawSpan : undefined\n}\n\nfunction spanDataOf(\n payload: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const spanData = rawSpanOf(payload)?.span_data\n return isRecord(spanData) ? spanData : undefined\n}\n\nexport function spanNameOf(\n payload: Record<string, unknown>,\n): string | undefined {\n const name = spanDataOf(payload)?.name\n return typeof name === \"string\" ? name : undefined\n}\n\nexport function stripContent(\n payload: Record<string, unknown>,\n): Record<string, unknown> {\n const rawSpan = rawSpanOf(payload)\n const spanData = spanDataOf(payload)\n if (rawSpan === undefined || spanData === undefined) {\n return payload\n }\n const kept: Record<string, unknown> = { ...spanData }\n for (const key of CONTENT_KEYS) {\n delete kept[key]\n }\n kept[CONTENT_OFF_KEY] = true\n return { ...payload, rawSpan: { ...rawSpan, span_data: kept } }\n}\n\nfunction simulationPlanEnvDisabled(): boolean {\n const value = readEnv(DISABLE_SIMULATION_PLAN_ENV)\n return typeof value === \"string\" && value.trim() !== \"\"\n}\n\nfunction missingSimulationPlanEndpoint(error: unknown): boolean {\n return error instanceof BitfabError && error.status === 404\n}\n\nfunction isTraceRootSpan(payload: Record<string, unknown>): boolean {\n const parentId = rawSpanOf(payload)?.parent_id\n return parentId === undefined || parentId === null\n}\n\nfunction declaredInCode(payload: Record<string, unknown>): boolean {\n return payload[DECLARED_NODE_FIELD] === true\n}\n\nfunction recordedError(payload: Record<string, unknown>): boolean {\n const error = spanDataOf(payload)?.error\n return error !== undefined && error !== null\n}\n\nexport class SimulationPlan {\n private contentOffByKey: Map<string, Set<string>> | undefined\n private readonly policyRefresh = new PolicyRefresh()\n private resolveLoaded: (() => void) | undefined\n private readonly loaded: Promise<void>\n private firstReadOver = false\n private resolveFirstReadEnded: (() => void) | undefined\n private readonly firstReadEnded: Promise<void>\n private rootWaitOver = false\n private rootWait: Promise<void> | undefined\n private resolveRootWait: (() => void) | undefined\n private rootWaitTimer: ReturnType<typeof setTimeout> | undefined\n private held: HeldEntry[] = []\n private stopped = false\n\n constructor(\n private readonly source: SimulationPlanSource,\n private readonly enabled: boolean = true,\n ) {\n this.loaded = new Promise((resolve) => {\n this.resolveLoaded = resolve\n })\n this.firstReadEnded = new Promise((resolve) => {\n this.resolveFirstReadEnded = resolve\n })\n }\n\n disabled(): boolean {\n return !this.enabled || simulationPlanEnvDisabled()\n }\n\n refresh(): void {\n if (this.stopped || this.disabled()) {\n return\n }\n this.policyRefresh.run(\n () => this.source.getSimulationPlan(),\n (body) => {\n const parsed = parseSimulationPlan(body)\n if (parsed === null) {\n this.scheduleRetry(\n \"sim-plan-unreadable\",\n \"the sim plan response was not understood\",\n )\n } else {\n this.markLoaded(parsed)\n }\n this.endFirstRead()\n },\n (error: unknown) => {\n if (missingSimulationPlanEndpoint(error)) {\n this.markLoaded(new Map())\n } else {\n this.scheduleRetry(\n \"sim-plan-unavailable\",\n `could not read the sim plan: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n this.endFirstRead()\n },\n )\n }\n\n private markLoaded(parsed: Map<string, Set<string>>): void {\n if (this.stopped) {\n return\n }\n this.contentOffByKey = parsed\n this.policyRefresh.hold(SIMULATION_PLAN_REFRESH_MS)\n this.resolveLoaded?.()\n this.resolveLoaded = undefined\n }\n\n private scheduleRetry(warnKey: string, reason: string): void {\n if (this.stopped) {\n return\n }\n this.policyRefresh.hold(SIMULATION_PLAN_RETRY_MS)\n if (this.contentOffByKey !== undefined) {\n return\n }\n warnOnce(\n warnKey,\n `${reason}. Until a read succeeds, spans are sent without their inputs and outputs, except each trace's root span and spans recorded by a framework integration. The read is retried on the next span after ${SIMULATION_PLAN_RETRY_MS / 1000}s.`,\n )\n }\n\n private endFirstRead(): void {\n this.endRootWait()\n if (!this.firstReadOver) {\n this.firstReadOver = true\n this.resolveFirstReadEnded?.()\n this.resolveFirstReadEnded = undefined\n }\n this.releaseHeld()\n }\n\n private endRootWait(): void {\n this.rootWaitOver = true\n if (this.rootWaitTimer !== undefined) {\n clearTimeout(this.rootWaitTimer)\n this.rootWaitTimer = undefined\n }\n this.resolveRootWait?.()\n this.resolveRootWait = undefined\n }\n\n waitForFirstRead(): Promise<void> | undefined {\n this.refresh()\n if (this.rootWaitOver || this.disabled() || !this.holdingForFirstRead()) {\n return undefined\n }\n if (this.rootWait === undefined) {\n this.rootWait = new Promise<void>((resolve) => {\n this.resolveRootWait = resolve\n })\n this.rootWaitTimer = setTimeout(\n () => this.endRootWait(),\n SIMULATION_PLAN_READ_TIMEOUT_MS,\n )\n }\n return this.rootWait\n }\n\n private holdingForFirstRead(): boolean {\n return (\n this.contentOffByKey === undefined && !this.firstReadOver && !this.stopped\n )\n }\n\n unavailableNow(): boolean {\n return (\n !this.disabled() &&\n this.contentOffByKey === undefined &&\n this.firstReadOver\n )\n }\n\n firstLoad(): Promise<void> | undefined {\n if (this.contentOffByKey !== undefined || this.stopped || this.disabled()) {\n return undefined\n }\n return this.loaded\n }\n\n send(\n payload: Record<string, unknown>,\n traceFunctionKey: string | undefined,\n submit: SimulationPlanSubmit,\n drop?: () => void,\n ): void {\n this.refresh()\n if (\n this.disabled() ||\n traceFunctionKey === undefined ||\n spanNameOf(payload) === undefined ||\n recordedByFramework(payload)\n ) {\n submit(payload)\n return\n }\n const entry = { payload, traceFunctionKey, submit, drop }\n if (this.holdingForFirstRead()) {\n this.hold(entry)\n return\n }\n this.submitEntry(entry)\n }\n\n sendTrace(\n payload: Record<string, unknown>,\n submit: SimulationPlanSubmit,\n ): void {\n this.refresh()\n if (\n this.disabled() ||\n !this.holdingForFirstRead() ||\n !this.holdsSpanOfTrace(traceIdOf(payload))\n ) {\n submit(payload)\n return\n }\n this.hold({ payload, traceFunctionKey: undefined, submit })\n }\n\n private holdsSpanOfTrace(traceId: string | undefined): boolean {\n if (traceId === undefined) {\n return false\n }\n return this.held.some(\n (entry) =>\n entry.traceFunctionKey !== undefined &&\n traceIdOf(entry.payload) === traceId,\n )\n }\n\n private hold(entry: HeldEntry): void {\n this.held.push(entry)\n let overflowed = false\n while (this.held.length > SIMULATION_PLAN_MAX_HELD) {\n const oldest = this.held.shift() as HeldEntry\n this.submitEntry(oldest)\n overflowed = true\n }\n if (overflowed) {\n warnOnce(\n \"sim-plan-held-overflow\",\n `more than ${SIMULATION_PLAN_MAX_HELD} records were waiting for the sim plan, so the oldest were sent without their inputs and outputs.`,\n )\n }\n }\n\n private payloadToSend(entry: HeldEntry): Record<string, unknown> {\n if (entry.traceFunctionKey === undefined || declaredInCode(entry.payload)) {\n return entry.payload\n }\n if (this.contentOffByKey !== undefined) {\n return this.apply(entry.payload, entry.traceFunctionKey)\n }\n if (recordedByFramework(entry.payload) || isTraceRootSpan(entry.payload)) {\n return entry.payload\n }\n return stripContent(entry.payload)\n }\n\n private submitEntry(entry: HeldEntry): void {\n if (\n entry.traceFunctionKey !== undefined &&\n this.skipsSpan(entry.payload, entry.traceFunctionKey)\n ) {\n entry.drop?.()\n return\n }\n try {\n entry.submit(this.payloadToSend(entry))\n } catch (error) {\n entry.drop?.()\n warnOnce(\n \"sim-plan-held-span-dropped\",\n `a span held for the sim plan was dropped when released: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n private releaseHeld(): void {\n const held = this.held\n this.held = []\n for (const entry of held) {\n this.submitEntry(entry)\n }\n }\n\n private releaseHeldWithoutPlan(): void {\n if (this.held.length === 0) {\n return\n }\n if (this.contentOffByKey === undefined) {\n warnOnce(\n \"sim-plan-not-loaded-at-release\",\n `${this.held.length} record(s) were sent without their inputs and outputs because the sim plan had not loaded`,\n )\n }\n this.releaseHeld()\n }\n\n async release(timeoutMs: number): Promise<void> {\n this.refresh()\n if (this.held.length > 0) {\n await this.waitForFirstReadEnd(timeoutMs)\n }\n this.releaseHeldWithoutPlan()\n }\n\n private waitForFirstReadEnd(timeoutMs: number): Promise<void> {\n if (this.firstReadOver) {\n return Promise.resolve()\n }\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, Math.max(timeoutMs, 0))\n void this.firstReadEnded.then(() => {\n clearTimeout(timer)\n resolve()\n })\n })\n }\n\n stop(): void {\n if (this.stopped) {\n return\n }\n this.releaseHeldWithoutPlan()\n this.stopped = true\n this.endFirstRead()\n }\n\n contentOff(traceFunctionKey: string, spanName: string): boolean {\n return this.contentOffByKey?.get(traceFunctionKey)?.has(spanName) === true\n }\n\n contentOffNow(traceFunctionKey: string, spanName: string): boolean {\n return (\n !this.stopped &&\n !this.disabled() &&\n this.contentOff(traceFunctionKey, spanName)\n )\n }\n\n private skipsSpan(\n payload: Record<string, unknown>,\n traceFunctionKey: string,\n ): boolean {\n const name = spanNameOf(payload)\n return (\n name !== undefined &&\n this.contentOff(traceFunctionKey, name) &&\n !isTraceRootSpan(payload) &&\n !declaredInCode(payload) &&\n spanInstrumentationOf(payload) !== undefined &&\n !recordedByFramework(payload) &&\n !recordedError(payload)\n )\n }\n\n apply(\n payload: Record<string, unknown>,\n traceFunctionKey: string,\n ): Record<string, unknown> {\n if (recordedByFramework(payload) || declaredInCode(payload)) {\n return payload\n }\n const name = spanNameOf(payload)\n if (name === undefined || !this.contentOff(traceFunctionKey, name)) {\n return payload\n }\n return stripContent(payload)\n }\n}\n","/**\n * Best-effort `unref()` on a timer handle so a pending timeout never keeps the\n * Node.js event loop alive on its own. An un-unref'd timeout would delay\n * process exit, prolong a serverless function's billed lifetime, and hang test\n * runners until it fires.\n *\n * In the browser `setTimeout` returns a number with no `unref`, so this is a\n * no-op there. Callers should still `clearTimeout` the handle once the work it\n * guards has settled.\n */\nexport function unrefTimer(timer: ReturnType<typeof setTimeout>): void {\n const handle = timer as { unref?: () => void }\n if (typeof handle.unref === \"function\") {\n handle.unref()\n }\n}\n","/**\n * OpenTelemetry transport for Bitfab spans and trace completions.\n *\n * OTel is used here as a queueing, batching, and delivery engine only. Bitfab\n * keeps ownership of logical trace identity: every payload travels inside an\n * internal *carrier* span whose `bitfab.payload` attribute holds the encoded\n * Bitfab body, and the server reconstructs the stored tree from that payload\n * rather than from the carrier's OTel topology. The provider and processor are\n * private to each client, so an application's own OTel traces are never mixed\n * into Bitfab traces and the global provider is never replaced.\n */\n\nimport { type Span, SpanStatusCode, type Tracer } from \"@opentelemetry/api\"\nimport {\n type ExportResult,\n ExportResultCode,\n type InstrumentationScope,\n} from \"@opentelemetry/core\"\nimport { resourceFromAttributes } from \"@opentelemetry/resources\"\nimport {\n AlwaysOnSampler,\n BasicTracerProvider,\n BatchSpanProcessor,\n type ReadableSpan,\n type SpanExporter,\n} from \"@opentelemetry/sdk-trace-base\"\nimport { type EncodedRequestBody, encodeRequestBody } from \"./compress.js\"\nimport { __version__ } from \"./constants.js\"\nimport { BitfabError } from \"./errors.js\"\nimport {\n byteLength,\n MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES,\n MAX_SPAN_CARRIER_BYTES,\n} from \"./payloadBudget.js\"\nimport { readEnv } from \"./readEnv.js\"\nimport { serializePayloadBody } from \"./serializePayload.js\"\nimport type {\n CarrierMeta,\n CarrierRef,\n DirectBatchSender,\n TraceOperation,\n TraceTransport,\n} from \"./transportTypes.js\"\nimport { DeliveryError } from \"./transportTypes.js\"\nimport { unrefTimer } from \"./unrefTimer.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nconst OPERATION_ATTRIBUTE = \"bitfab.operation\"\nconst PAYLOAD_ATTRIBUTE = \"bitfab.payload\"\nconst MAX_EXPORT_REQUEST_BYTES = 3_000_000\nconst MAX_DECOMPRESSED_REQUEST_BYTES = 8_000_000\nconst MAX_REQUEST_BYTES_ENV = \"BITFAB_OTEL_MAX_REQUEST_BYTES\"\nconst EXPORT_CONCURRENCY_ENV = \"BITFAB_OTEL_EXPORT_CONCURRENCY\"\nconst MAX_QUEUE_SIZE = 16_384\nconst DIRECT_MAX_EXPORT_BATCH_SIZE = 512\nconst DIRECT_MAX_REQUEST_BATCH_SIZE = 256\nconst DEFAULT_EXPORT_CONCURRENCY = 32\nconst MAX_EXPORT_CONCURRENCY = 64\nconst SCHEDULE_DELAY_MILLIS = 5_000\nconst EXPORT_TIMEOUT_MILLIS = 30_000\nconst RETRY_BASE_DELAY_MILLIS = 100\n// Ceiling on the exponential growth of our OWN backoff. It does not bound a\n// wait the server asked for: OTLP says to honor Retry-After, and warns that a\n// delay big enough to make the client drop data is the server's mistake to\n// avoid, not the client's cue to discard. What bounds an honored wait is the\n// export budget below, since a wait outliving the export cannot be served.\nconst RETRY_BACKOFF_CEILING_MILLIS = 5_000\nconst MAX_SEND_ATTEMPTS = 3\nconst DEFAULT_LIFECYCLE_TIMEOUT_MS = 30_000\n\nconst liveTransports = new Set<OtelBatchTransport>()\n\n// Keyed by the carrier span object so a dropped span needs no cleanup. The ref\n// cannot ride on the span as an attribute: `spanLimits` caps carriers at two,\n// and `bitfab.operation` and `bitfab.payload` hold both.\nconst carrierRefs = new WeakMap<object, CarrierRef>()\n\nfunction readBoundedIntEnv(\n name: string,\n max: number,\n fallback: number,\n warnKey: string,\n): number {\n const raw = readEnv(name)\n if (raw === undefined) {\n return fallback\n }\n const value = Number(raw)\n if (Number.isInteger(value) && value > 0 && value <= max) {\n return value\n }\n warnOnce(\n warnKey,\n `${name} must be a positive integer no greater than ${max}; using ${fallback}`,\n )\n return fallback\n}\n\nfunction logError(message: string, error?: unknown): void {\n try {\n if (error === undefined) {\n console.error(`[bitfab] ${message}`)\n } else {\n console.error(`[bitfab] ${message}`, error)\n }\n } catch {\n // Logging must never crash the host app.\n }\n}\n\nfunction otlpValue(value: unknown): Record<string, unknown> {\n if (typeof value === \"boolean\") {\n return { boolValue: value }\n }\n if (typeof value === \"number\") {\n return Number.isInteger(value)\n ? { intValue: String(value) }\n : { doubleValue: value }\n }\n if (typeof value === \"string\") {\n return { stringValue: value }\n }\n if (Array.isArray(value)) {\n return { arrayValue: { values: value.map(otlpValue) } }\n }\n return { stringValue: String(value) }\n}\n\nfunction otlpAttributes(\n attributes: Record<string, unknown> | undefined,\n): Record<string, unknown>[] {\n if (!attributes) {\n return []\n }\n return Object.entries(attributes)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => ({ key, value: otlpValue(value) }))\n}\n\n/**\n * Nanoseconds since the epoch as a decimal string. Built by concatenation\n * rather than arithmetic because the value exceeds `Number.MAX_SAFE_INTEGER`,\n * so multiplying seconds out would silently lose the low digits.\n */\nfunction hrTimeToNanoString(time: [number, number] | undefined): string {\n if (!time) {\n return \"0\"\n }\n return `${time[0]}${String(time[1]).padStart(9, \"0\")}`\n}\n\nfunction spanToOtlp(span: ReadableSpan): Record<string, unknown> {\n const spanContext = span.spanContext()\n const result: Record<string, unknown> = {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n name: span.name,\n kind: span.kind + 1,\n startTimeUnixNano: hrTimeToNanoString(span.startTime),\n endTimeUnixNano: hrTimeToNanoString(span.endTime),\n attributes: otlpAttributes(span.attributes as Record<string, unknown>),\n droppedAttributesCount: span.droppedAttributesCount,\n droppedEventsCount: span.droppedEventsCount,\n droppedLinksCount: span.droppedLinksCount,\n status: {\n code: span.status.code,\n ...(span.status.message ? { message: span.status.message } : {}),\n },\n flags: spanContext.traceFlags,\n }\n const parentSpanId = span.parentSpanContext?.spanId\n if (parentSpanId) {\n result.parentSpanId = parentSpanId\n }\n if (spanContext.traceState) {\n result.traceState = spanContext.traceState.serialize()\n }\n return result\n}\n\n/**\n * A span encoded exactly as it will appear on the wire, carrying its own byte\n * count. Encoding once and remembering the size is what keeps request packing\n * linear: sizing a candidate batch by re-encoding the whole request re-escapes\n * every carrier's `bitfab.payload` string on every span considered.\n */\ninterface EncodedSpan {\n json: string\n size: number\n ref?: CarrierRef\n}\n\ninterface RequestBatch {\n spans: EncodedSpan[]\n size: number\n}\n\n/**\n * The invariant head and tail of an OTLP request for one export window. Key\n * order matches what `JSON.stringify` emits for the equivalent object, so a\n * body assembled by concatenation is byte-identical to encoding that object.\n */\ninterface RequestEnvelope {\n head: string\n tail: string\n size: number\n}\n\n/** The comma `join` puts between adjacent spans in the request's span list. */\nconst SPAN_SEPARATOR_BYTES = 1\n\nfunction encodeSpan(span: ReadableSpan): EncodedSpan {\n const json = JSON.stringify(spanToOtlp(span))\n return {\n json,\n size: byteLength(json),\n ref: carrierRefs.get(span),\n }\n}\n\nfunction trimEncodedSpan(span: EncodedSpan): EncodedSpan | undefined {\n try {\n const carrier = JSON.parse(span.json) as {\n attributes?: Array<{\n key?: string\n value?: { stringValue?: string }\n }>\n }\n const attribute = carrier.attributes?.find(\n (entry) => entry.key === PAYLOAD_ATTRIBUTE,\n )\n const payloadBody = attribute?.value?.stringValue\n if (!attribute?.value || payloadBody === undefined) {\n return undefined\n }\n const payload = JSON.parse(payloadBody) as Record<string, unknown>\n attribute.value.stringValue = serializePayloadBody(\n payload,\n MAX_SPAN_CARRIER_BYTES,\n ).body\n const json = JSON.stringify(carrier)\n return { json, size: byteLength(json) }\n } catch {\n return undefined\n }\n}\n\nasync function prepareRequest(body: string): Promise<EncodedRequestBody> {\n const prepared = encodeRequestBody(body)\n return prepared instanceof Promise ? await prepared : prepared\n}\n\nfunction requestEnvelope(first: ReadableSpan): RequestEnvelope {\n const scope = first.instrumentationScope as InstrumentationScope\n const resource = JSON.stringify({\n attributes: otlpAttributes(\n first.resource.attributes as Record<string, unknown>,\n ),\n })\n const scopeJson = JSON.stringify({\n name: scope.name,\n version: scope.version ?? \"\",\n })\n const head = `{\"resourceSpans\":[{\"resource\":${resource},\"scopeSpans\":[{\"scope\":${scopeJson},\"spans\":[`\n const tail = \"]}]}]}\"\n return { head, tail, size: byteLength(head) + byteLength(tail) }\n}\n\nfunction encodeRequest(\n envelope: RequestEnvelope,\n spans: EncodedSpan[],\n): string {\n return (\n envelope.head + spans.map((span) => span.json).join(\",\") + envelope.tail\n )\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms)\n unrefTimer(timer)\n })\n}\n\n/**\n * Race `work` against `timeoutMs`. Resolves `false` when the deadline wins, so\n * a wedged export can never hold a flush or shutdown open past its budget.\n */\nasync function withDeadline(\n work: Promise<boolean>,\n timeoutMs: number,\n): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n work,\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs))\n unrefTimer(timer)\n }),\n ])\n } finally {\n if (timer) {\n clearTimeout(timer)\n }\n }\n}\n\n/** Run `task` over `items` with at most `limit` in flight at any moment. */\nasync function mapWithConcurrency<T, R>(\n items: T[],\n limit: number,\n task: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length)\n let next = 0\n const workers = Array.from(\n { length: Math.min(Math.max(limit, 1), items.length) },\n async () => {\n while (next < items.length) {\n const index = next\n next += 1\n results[index] = await task(items[index])\n }\n },\n )\n await Promise.all(workers)\n return results\n}\n\n/**\n * Only what the sender classified. Anything else reaching here is a fault in\n * the sender itself, and retrying a deterministic bug just delays it.\n */\nfunction isRetryable(error: unknown): boolean {\n return error instanceof DeliveryError && error.retryable\n}\n\nfunction isOversized(error: unknown): boolean {\n return error instanceof DeliveryError && error.oversized\n}\n\n/**\n * How long to wait before the next send attempt, or `null` to stop trying.\n *\n * A server that sent `Retry-After` has told us when it wants us back, so that\n * wait is honored exactly. Clamping it would return early, which is the single\n * thing the server asked us not to do; when the wait is longer than we are\n * willing to hold a batch, the honest answer is to give up rather than come\n * back sooner and add load to something already struggling.\n *\n * Absent an instruction, back off exponentially so a struggling server is not\n * hit on a fixed cadence, and jitter it so every client in a fleet does not\n * return in lockstep.\n */\n/**\n * How long to wait before the next attempt, or null when the wait cannot be\n * served inside `remainingMillis` and the batch has to be given up.\n *\n * A server that sent Retry-After told us when it wants us back, so that wait is\n * honored whole rather than shortened: coming back early is the one thing it\n * asked us not to do. It is refused only when it outlasts the export budget,\n * where waiting would mean being killed mid-wait and losing the batch anyway.\n *\n * Absent an instruction, back off exponentially so a struggling server is not\n * hit on a fixed cadence, and jitter it so a fleet does not return in lockstep.\n */\nfunction retryWaitMillis(\n error: unknown,\n attempt: number,\n remainingMillis: number,\n): number | null {\n const requested =\n error instanceof DeliveryError ? error.retryAfterMs : undefined\n // Half the remaining budget, not all of it: a wait is only worth taking if\n // what is left afterwards can still carry the request. Spending the whole\n // budget waiting means being killed mid-wait, which loses the batch AND holds\n // an export slot for the duration.\n const affordable = remainingMillis / 2\n if (requested !== undefined) {\n return requested < affordable ? requested : null\n }\n const backoff = Math.min(\n RETRY_BASE_DELAY_MILLIS * 2 ** attempt,\n RETRY_BACKOFF_CEILING_MILLIS,\n )\n const jittered = backoff / 2 + Math.random() * (backoff / 2)\n return jittered < affordable ? jittered : null\n}\n\n/**\n * Direct delivery to Bitfab's OTLP/JSON ingress.\n *\n * OTel hands this exporter one batch as a candidate window. The window is\n * repacked into requests bounded by both a carrier count and the exact encoded\n * request size, and those complete requests are sent concurrently. That keeps\n * OTel's queue, scheduling, force-flush and shutdown while restoring the small\n * independent requests Bitfab's serverless ingress is built to scale.\n */\nexport class BitfabSpanExporter implements SpanExporter {\n constructor(\n private readonly directSender: DirectBatchSender,\n private readonly maxRequestBytes: number,\n private readonly maxRequestBatchSize: number,\n private readonly exportConcurrency: number,\n private readonly onDelivered?: (refs: CarrierRef[]) => void,\n // The same budget the processor enforces around this export. Waits are\n // measured against it, so a configured timeout and the deadline a wait is\n // judged by can never drift apart.\n private readonly exportTimeoutMillis: number = EXPORT_TIMEOUT_MILLIS,\n ) {}\n\n /** Epoch ms until which the server has asked this exporter to stay away. */\n private throttledUntil = 0\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): void {\n void this.exportAsync(spans).then(\n (succeeded) => {\n resultCallback({\n code: succeeded ? ExportResultCode.SUCCESS : ExportResultCode.FAILED,\n })\n },\n (error) => {\n resultCallback({ code: ExportResultCode.FAILED, error })\n },\n )\n }\n\n private async exportAsync(spans: ReadableSpan[]): Promise<boolean> {\n if (spans.length === 0) {\n return true\n }\n let encoded: EncodedSpan[]\n let envelope: RequestEnvelope\n try {\n encoded = spans.map(encodeSpan)\n envelope = requestEnvelope(spans[0])\n } catch (error) {\n logError(\"failed to encode an OpenTelemetry span batch\", error)\n return false\n }\n\n const batches = this.buildRequestBatches(envelope, encoded)\n const results = await mapWithConcurrency(\n batches,\n this.exportConcurrency,\n (batch) => this.send(envelope, batch),\n )\n return results.every(Boolean)\n }\n\n private buildRequestBatches(\n envelope: RequestEnvelope,\n spans: EncodedSpan[],\n ): RequestBatch[] {\n const batches: RequestBatch[] = []\n let current: EncodedSpan[] = []\n let size = envelope.size\n\n for (const span of spans) {\n const addition =\n span.size + (current.length > 0 ? SPAN_SEPARATOR_BYTES : 0)\n if (\n current.length > 0 &&\n (current.length >= this.maxRequestBatchSize ||\n size + addition > this.maxRequestBytes)\n ) {\n batches.push({ spans: current, size })\n current = []\n size = envelope.size\n }\n current.push(span)\n size += span.size + (current.length > 1 ? SPAN_SEPARATOR_BYTES : 0)\n }\n\n if (current.length > 0) {\n batches.push({ spans: current, size })\n }\n return batches\n }\n\n private async send(\n envelope: RequestEnvelope,\n batch: RequestBatch,\n ): Promise<boolean> {\n try {\n let requestSpans = batch.spans\n let requestRawBytes = batch.size\n let alreadyTrimmed = false\n while (true) {\n if (requestRawBytes <= MAX_DECOMPRESSED_REQUEST_BYTES) {\n const prepared = await prepareRequest(\n encodeRequest(envelope, requestSpans),\n )\n if (prepared.wireBytes <= this.maxRequestBytes) {\n await this.sendWithRetries(prepared)\n // Refs come from the batch, not the possibly-trimmed request:\n // trimming rebuilds a span without its ref, and a trimmed carrier\n // still reached the server under its original identity.\n this.reportDelivered(batch.spans)\n return true\n }\n }\n\n if (batch.spans.length !== 1) {\n logError(\n \"an OpenTelemetry span batch exceeded the configured request-size target and could not be exported\",\n )\n return false\n }\n if (alreadyTrimmed) {\n logError(\n \"a single OpenTelemetry span exceeded the configured request-size target after trimming\",\n )\n return false\n }\n const trimmed = trimEncodedSpan(batch.spans[0])\n if (!trimmed) {\n logError(\n \"a single OpenTelemetry span exceeded the configured request-size target and could not be trimmed\",\n )\n return false\n }\n requestSpans = [trimmed]\n requestRawBytes = envelope.size + trimmed.size\n alreadyTrimmed = true\n }\n } catch (error) {\n if (isOversized(error)) {\n logError(\n batch.spans.length === 1\n ? \"a single OpenTelemetry span exceeded the ingestion request limit and could not be exported\"\n : \"an OpenTelemetry span batch exceeded the ingestion request limit and could not be exported\",\n )\n return false\n }\n logError(\"failed to export an OpenTelemetry span batch\", error)\n return false\n }\n }\n\n /**\n * Retries transient failures. Span and trace-completion carriers are safe to\n * retry: the server keys them idempotently on `sourceSpanId`/`sourceTraceId`,\n * so a duplicate delivery cannot create a duplicate row.\n *\n * KNOWN LIMITATION: an `internal_trace` (a `call()` BAML trace) carries no\n * such key, so retrying a batch that holds one can create a duplicate trace -\n * including when a request times out client-side but the server goes on to\n * persist it. Accepted deliberately for now, matching the other SDKs, rather\n * than skipping retries for a whole batch or inventing an idempotency scheme\n * the server does not yet understand. The fix is a client-supplied\n * idempotency key that ingestion dedupes on.\n */\n /**\n * Remember a throttle the server asked for, so the requests fanned out\n * alongside this one respect it too. Delaying only the request that was\n * refused leaves the other seven in the window hitting a server that just\n * asked for room.\n */\n private recordThrottle(error: unknown): void {\n const requested =\n error instanceof DeliveryError ? error.retryAfterMs : undefined\n if (requested !== undefined) {\n this.throttledUntil = Math.max(\n this.throttledUntil,\n Date.now() + requested,\n )\n }\n }\n\n /**\n * Waits out an active throttle, or reports the batch undeliverable when the\n * throttle outlasts what we are willing to hold it for. Either way nothing is\n * sent while the server has asked us to stay away.\n */\n private async awaitThrottle(deadline: number): Promise<void> {\n const remaining = this.throttledUntil - Date.now()\n if (remaining <= 0) {\n return\n }\n // Waited out, not refused: OTLP asks the client to hold off until the\n // window passes, and treats data dropped while throttled as the outcome to\n // avoid. Only a throttle outliving the export budget is refused, because\n // the processor would kill the wait before it could send anyway.\n if (remaining >= (deadline - Date.now()) / 2) {\n throw new DeliveryError(\n `OTLP ingestion is throttled for another ${remaining}ms, longer than the export budget`,\n )\n }\n await delay(remaining)\n }\n\n private async sendWithRetries(request: EncodedRequestBody): Promise<void> {\n // One budget for the whole exchange, waits included: the processor kills\n // the export at this deadline, so a wait past it cannot be served.\n const deadline = Date.now() + this.exportTimeoutMillis\n for (let attempt = 0; attempt < MAX_SEND_ATTEMPTS; attempt += 1) {\n try {\n await this.awaitThrottle(deadline)\n await this.directSender(request, Math.max(0, deadline - Date.now()))\n return\n } catch (error) {\n if (isOversized(error)) {\n throw error\n }\n this.recordThrottle(error)\n if (attempt === MAX_SEND_ATTEMPTS - 1 || !isRetryable(error)) {\n throw error\n }\n const wait = retryWaitMillis(error, attempt, deadline - Date.now())\n if (wait === null) {\n throw error\n }\n await delay(wait)\n }\n }\n }\n\n /**\n * Announce the carriers a request delivered. Wrapped because a listener that\n * throws must never turn a delivered batch into a failed export.\n */\n private reportDelivered(spans: EncodedSpan[]): void {\n if (this.onDelivered === undefined) {\n return\n }\n const refs = spans\n .map((span) => span.ref)\n .filter((ref): ref is CarrierRef => ref !== undefined)\n if (refs.length === 0) {\n return\n }\n try {\n this.onDelivered(refs)\n } catch (error) {\n logError(\"a delivery listener threw\", error)\n }\n }\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\n/**\n * Counts export failures so `flush` can answer \"was this delivered?\" instead of\n * only \"did the processor queue drain?\". Without it a flush would report\n * success for a batch the exporter dropped, and replay would finalize a run\n * whose traces never landed.\n */\nclass DeliveryTrackingExporter implements SpanExporter {\n // Deliberately unscoped, matching the Python SDK. An export can outlive\n // OTel's export timeout and report failure after the flush that was waiting\n // on it already returned, so that failure surfaces on the NEXT flush instead.\n // That over-reports: a good flush can inherit an older failure. The\n // alternative - discarding failures from completed flush windows - under-\n // reports, and `BatchSpanProcessor` also runs scheduled exports that belong\n // to no flush at all, so their failures would vanish entirely. For a\n // telemetry SDK a false \"flush failed\" is investigable; a false \"flush\n // succeeded\" silently loses traces. We take the noisy direction on purpose.\n private failedExports = 0\n\n constructor(private readonly exporter: SpanExporter) {}\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): void {\n try {\n this.exporter.export(spans, (result) => {\n if (result.code !== ExportResultCode.SUCCESS) {\n this.failedExports += 1\n }\n resultCallback(result)\n })\n } catch (error) {\n this.failedExports += 1\n resultCallback({ code: ExportResultCode.FAILED, error: error as Error })\n }\n }\n\n takeFailedExports(): number {\n const failed = this.failedExports\n this.failedExports = 0\n return failed\n }\n\n shutdown(): Promise<void> {\n return this.exporter.shutdown()\n }\n\n forceFlush(): Promise<void> {\n return this.exporter.forceFlush?.() ?? Promise.resolve()\n }\n}\n\nexport interface OtelBatchTransportOptions {\n directSender: DirectBatchSender\n /** Called with the refs of every carrier a request delivered. */\n onDelivered?: (refs: CarrierRef[]) => void\n maxExportBatchSize?: number\n maxRequestBatchSize?: number\n maxQueueSize?: number\n exportConcurrency?: number\n maxRequestBytes?: number\n /** Overridable so tests can drive OTel's export-timeout path in ms, not 30s. */\n exportTimeoutMillis?: number\n}\n\nexport class OtelBatchTransport implements TraceTransport {\n private readonly provider: BasicTracerProvider\n private readonly processor: BatchSpanProcessor\n private readonly deliveryTracker: DeliveryTrackingExporter\n private readonly tracer: Tracer\n private closed = false\n private pendingFlush: Promise<boolean> | undefined\n\n constructor(options: OtelBatchTransportOptions) {\n const maxRequestBytes = options.maxRequestBytes ?? MAX_EXPORT_REQUEST_BYTES\n const maxRequestBatchSize =\n options.maxRequestBatchSize ?? DIRECT_MAX_REQUEST_BATCH_SIZE\n if (maxRequestBatchSize <= 0) {\n throw new BitfabError(\"maxRequestBatchSize must be a positive integer\")\n }\n\n this.deliveryTracker = new DeliveryTrackingExporter(\n new BitfabSpanExporter(\n options.directSender,\n maxRequestBytes,\n maxRequestBatchSize,\n options.exportConcurrency ?? DEFAULT_EXPORT_CONCURRENCY,\n options.onDelivered,\n options.exportTimeoutMillis ?? EXPORT_TIMEOUT_MILLIS,\n ),\n )\n\n this.processor = new BatchSpanProcessor(this.deliveryTracker, {\n maxQueueSize: options.maxQueueSize ?? MAX_QUEUE_SIZE,\n maxExportBatchSize:\n options.maxExportBatchSize ?? DIRECT_MAX_EXPORT_BATCH_SIZE,\n scheduledDelayMillis: SCHEDULE_DELAY_MILLIS,\n exportTimeoutMillis: options.exportTimeoutMillis ?? EXPORT_TIMEOUT_MILLIS,\n })\n\n // Every option is passed explicitly: `BasicTracerProvider` otherwise reads\n // OTEL_* defaults, so a host application's sampler or attribute-length\n // limit would silently drop or truncate Bitfab payloads.\n this.provider = new BasicTracerProvider({\n sampler: new AlwaysOnSampler(),\n resource: resourceFromAttributes({\n \"service.name\": \"bitfab-typescript-sdk\",\n \"service.version\": __version__,\n }),\n spanLimits: {\n attributeCountLimit: 2,\n attributeValueLengthLimit: Number.POSITIVE_INFINITY,\n },\n spanProcessors: [this.processor],\n })\n this.tracer = this.provider.getTracer(\"bitfab\", __version__)\n liveTransports.add(this)\n }\n\n submit(\n operation: TraceOperation,\n payload: Record<string, unknown>,\n meta: CarrierMeta = {},\n ): void {\n if (this.closed) {\n warnOnce(\n \"otel-submit-after-shutdown\",\n \"OpenTelemetry transport is shut down; dropping spans\",\n )\n return\n }\n try {\n // Not a bare JSON.stringify: contexts, metadata and `call()` inputs\n // never pass through `serializeValue`, so one stray value here would\n // throw and drop the whole span rather than being stubbed. This is the\n // same backstop the pre-transport HTTP path applied.\n const { body, dropped } = serializePayloadBody(\n payload,\n MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES,\n )\n if (dropped.length > 0) {\n warnOnce(\n \"otel-carrier-payload-stubbed\",\n `a span payload held non-serializable value(s) (${[\n ...new Set(dropped),\n ].join(\", \")}); they were stubbed so the span still ships, but the ` +\n \"trace may be incomplete or not replayable.\",\n )\n }\n const span = this.tracer.startSpan(meta.name ?? `bitfab.${operation}`, {\n attributes: {\n [OPERATION_ATTRIBUTE]: operation,\n [PAYLOAD_ATTRIBUTE]: body,\n },\n startTime: meta.startTime,\n })\n if (meta.ref !== undefined) {\n carrierRefs.set(span, meta.ref)\n }\n if (meta.errored === true) {\n span.setStatus({ code: SpanStatusCode.ERROR })\n }\n endSpan(span, meta.endTime)\n } catch (error) {\n logError(\"failed to queue an OpenTelemetry span\", error)\n }\n }\n\n async flush(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n ): Promise<boolean> {\n // Serialized: two concurrent force-flushes would race for the same\n // delivery counter and one would report the other's failures as success.\n const pending = (this.pendingFlush ?? Promise.resolve(true)).then(() =>\n this.forceFlushOnce(),\n )\n this.pendingFlush = pending.catch(() => false)\n return withDeadline(pending, timeoutMs)\n }\n\n private async forceFlushOnce(): Promise<boolean> {\n try {\n await this.processor.forceFlush()\n } catch (error) {\n logError(\"failed to flush OpenTelemetry spans\", error)\n this.deliveryTracker.takeFailedExports()\n return false\n }\n return this.deliveryTracker.takeFailedExports() === 0\n }\n\n async shutdown(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n ): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n this.closed = true\n const flushed = await this.flush(Math.max(0, deadline - Date.now()))\n liveTransports.delete(this)\n const shutdownCompleted = await withDeadline(\n this.provider\n .shutdown()\n .then(() => true)\n .catch((error) => {\n logError(\"failed to shut down the OpenTelemetry transport\", error)\n return false\n }),\n Math.max(0, deadline - Date.now()),\n )\n return flushed && shutdownCompleted\n }\n}\n\nfunction endSpan(span: Span, endTime: number | undefined): void {\n span.end(endTime)\n}\n\nexport function createOtelTransport(options: {\n directSender: DirectBatchSender\n onDelivered?: (refs: CarrierRef[]) => void\n}): OtelBatchTransport {\n return new OtelBatchTransport({\n ...options,\n exportConcurrency: readBoundedIntEnv(\n EXPORT_CONCURRENCY_ENV,\n MAX_EXPORT_CONCURRENCY,\n DEFAULT_EXPORT_CONCURRENCY,\n \"otel-export-concurrency-invalid\",\n ),\n maxRequestBytes: readBoundedIntEnv(\n MAX_REQUEST_BYTES_ENV,\n MAX_EXPORT_REQUEST_BYTES,\n MAX_EXPORT_REQUEST_BYTES,\n \"otel-max-request-bytes-invalid\",\n ),\n })\n}\n\nasync function forEachLiveTransport(\n timeoutMs: number,\n run: (transport: OtelBatchTransport, remainingMs: number) => Promise<boolean>,\n): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n let succeeded = true\n for (const transport of [...liveTransports]) {\n succeeded =\n (await run(transport, Math.max(0, deadline - Date.now()))) && succeeded\n }\n return succeeded\n}\n\nexport function flushOtelTransports(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n): Promise<boolean> {\n return forEachLiveTransport(timeoutMs, (transport, remaining) =>\n transport.flush(remaining),\n )\n}\n\nexport function shutdownOtelTransports(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n): Promise<boolean> {\n return forEachLiveTransport(timeoutMs, (transport, remaining) =>\n transport.shutdown(remaining),\n )\n}\n","/**\n * The single seam between the HTTP client and whichever transport implements\n * span delivery. Keeping the factory here (rather than importing `otel.ts`\n * from `http.ts` directly) is what lets the OpenTelemetry implementation\n * depend on `HttpClient`'s request path without an import cycle.\n */\n\nimport {\n createOtelTransport,\n flushOtelTransports,\n shutdownOtelTransports,\n} from \"./otel.js\"\nimport type {\n CarrierRef,\n DirectBatchSender,\n TraceTransport,\n} from \"./transportTypes.js\"\n\nexport function createTraceTransport(options: {\n directSender: DirectBatchSender\n onDelivered?: (refs: CarrierRef[]) => void\n}): TraceTransport {\n return createOtelTransport(options)\n}\n\nexport function flushTraceTransports(timeoutMs?: number): Promise<boolean> {\n return flushOtelTransports(timeoutMs)\n}\n\nexport function shutdownTraceTransports(timeoutMs?: number): Promise<boolean> {\n return shutdownOtelTransports(timeoutMs)\n}\n","import { TraceCompletion } from \"./traceCompletion.js\"\n/**\n * HTTP client utilities for Bitfab API requests.\n *\n * This module provides:\n * - HttpClient class for making API requests\n * - awaitOnExit helper so deferred span work still gates process exit\n */\n\nimport { type EncodedRequestBody, encodeRequestBody } from \"./compress.js\"\nimport { __packageName__, __version__ } from \"./constants.js\"\nimport type { DbSnapshotRef } from \"./dbSnapshot.js\"\nimport { BitfabError } from \"./errors.js\"\nimport { isEmptyGitState, resolvedGitState } from \"./gitState.js\"\nimport {\n type DbBranchLease,\n type DbBranchSettings,\n type DbBranchTimings,\n replayContextReady,\n} from \"./replayContext.js\"\nimport type { ReplayInvocation } from \"./replayInvocation.js\"\nimport { serializePayloadBody } from \"./serializePayload.js\"\nimport {\n DECLARED_NODE_FIELD,\n NO_API_KEY_FOR_SIMULATION_PLAN,\n planWaitSliceMs,\n ROOT_TRACE_FUNCTION_KEY_FIELD,\n SIMULATION_PLAN_READ_TIMEOUT_MS,\n type SimulationPlanResponse,\n type SimulationPlanSubmit,\n} from \"./simulationPlan.js\"\nimport { mergeCallerMetadataIntoTracePayload } from \"./traceMetadata.js\"\nimport {\n createTraceTransport,\n flushTraceTransports,\n shutdownTraceTransports,\n} from \"./transport.js\"\nimport {\n type CarrierMeta,\n type CarrierRef,\n DeliveryError,\n type TraceOperation,\n type TraceTransport,\n} from \"./transportTypes.js\"\nimport { unrefTimer } from \"./unrefTimer.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\n// BitfabError lives in `errors.ts` to break the http ↔ dbSnapshot import\n// cycle. Re-exported here for backwards compatibility with existing\n// callers that import it from \"./http.js\".\nexport { BitfabError, serializePayloadBody }\n\nconst REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS = 300_000\nconst REPLAY_COMPLETE_REQUEST_TIMEOUT_MS = 120_000\nconst REPLAY_INTERRUPT_REQUEST_TIMEOUT_MS = 5_000\nconst REPLAY_HEARTBEAT_REQUEST_TIMEOUT_MS = 5_000\nconst OTLP_TRACES_ENDPOINT = \"/api/sdk/otel/v1/traces\"\n// OTLP's retryable set, plus 500. Every other 4xx is the server's verdict on\n// the payload and will be the same next time.\n//\n// 500 is a deliberate deviation: OTLP treats it as the app being broken, which\n// assumes a collector that fails deterministically. Bitfab ingestion answers\n// every unhandled error with 500, so a connection blip or a cold start arrives\n// here indistinguishable from a real fault, and giving up on the first one\n// drops spans that a second attempt would have delivered.\nconst RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504])\nconst EXIT_FLUSH_TIMEOUT_MS = 5_000\nconst DEFAULT_LIFECYCLE_TIMEOUT_MS = 30_000\n\nconst pendingTracePromises = new Set<Promise<unknown>>()\n\nconst liveHttpClients = new Set<HttpClient>()\n\nasync function releaseHeldExternalSpans(timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n let released = true\n for (const client of [...liveHttpClients]) {\n const result = await client.releaseHeldExternalSpans?.(\n Math.max(0, deadline - Date.now()),\n )\n released = result !== false && released\n }\n return released\n}\n\nfunction stopSimulationPlans(): void {\n for (const client of [...liveHttpClients]) {\n client.stopSimulationPlan?.()\n }\n}\n\n/**\n * Track a promise so `flushTraces()` and the exit hook wait for it.\n *\n * Exactly one caller remains: the deferred `finalize` chain, which hands its\n * span to the transport only after finalize settles. Everything else submits\n * synchronously, so the transport's own queue is the complete picture. Python\n * has no equivalent because its finalize runs inline.\n *\n * @param promise - The promise to track\n * @returns The same promise (for chaining)\n */\nexport function awaitOnExit<T>(promise: Promise<T>): Promise<T> {\n pendingTracePromises.add(promise)\n // Use void to prevent unhandled rejection warnings from the .finally() chain\n // The actual error handling is done by the caller's .catch() on the returned promise\n void promise\n .finally(() => {\n pendingTracePromises.delete(promise)\n })\n .catch(() => {\n // Swallow rejection in this chain - the caller handles errors via their own .catch()\n })\n return promise\n}\n\n/**\n * Wait for pending fire-and-forget requests AND every live span transport to\n * deliver, within one total deadline. Useful in tests and scripts to ensure all\n * data has been sent before asserting or exiting.\n *\n * Returns `false` when delivery failed or the deadline expired, so a caller\n * that depends on persistence (replay does) can react instead of assuming a\n * drained queue means the server has the data.\n *\n * @param timeoutMs - Maximum total time to wait in milliseconds (default: 5000)\n */\nexport async function flushTraces(timeoutMs: number = 5000): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n const released = await releaseHeldExternalSpans(planWaitSliceMs(timeoutMs))\n const requestsFlushed = await awaitPendingRequests(\n Math.max(0, deadline - Date.now()),\n )\n const releasedAfterDeferred = await releaseHeldExternalSpans(0)\n const transportsFlushed = await flushTraceTransports(\n Math.max(0, deadline - Date.now()),\n )\n return (\n released && releasedAfterDeferred && requestsFlushed && transportsFlushed\n )\n}\n\n/**\n * Wait for in-flight fire-and-forget requests and deferred span work, WITHOUT\n * flushing the transports.\n *\n * Replay needs this half on its own: a `finalize` span reaches the transport\n * only after its deferred chain settles, so the expected-span tally has to be\n * read after that work lands but before a flush is issued (which would be\n * wasted, and would emit a request, when the run submitted nothing).\n */\nexport async function awaitPendingRequests(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n): Promise<boolean> {\n // Async-context storage loads asynchronously, and spans traced before it\n // resolves have their recording deferred behind it. Without this, a script\n // that traces and immediately flushes or closes races its own first spans.\n await replayContextReady.catch(() => {})\n return waitForPromises(Array.from(pendingTracePromises), timeoutMs)\n}\n\n/**\n * Await `promises` within `timeoutMs`, reporting whether they all settled in\n * time rather than throwing. Rejections count as settled: a failed span upload\n * is already reported by its own catch handler, and the caller is asking about\n * completion, not success.\n */\nasync function waitForPromises(\n promises: Promise<unknown>[],\n timeoutMs: number,\n): Promise<boolean> {\n if (promises.length === 0) {\n return true\n }\n // Clear and unref the timeout so the loser of the race never leaves a\n // dangling timer holding the event loop open after flush resolves.\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n Promise.allSettled(promises).then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs)\n unrefTimer(timer)\n }),\n ])\n } finally {\n if (timer) {\n clearTimeout(timer)\n }\n }\n}\n\n// Register beforeExit handler to wait for pending traces (Node.js only)\n// This ensures traces are sent before the process exits (for scripts).\n// The transport is included: its batch worker sits on an unref'd timer, so a\n// script that ends without an explicit flush would otherwise exit with a queue\n// of spans still waiting on the scheduled delay.\nif (\n typeof process !== \"undefined\" &&\n process.versions != null &&\n process.versions.node != null\n) {\n let isFlushing = false\n process.on(\"beforeExit\", () => {\n if (isFlushing) {\n return\n }\n isFlushing = true\n const planWaitMs = SIMULATION_PLAN_READ_TIMEOUT_MS\n const stopFlushing = () => {\n isFlushing = false\n }\n const deadline = setTimeout(\n stopFlushing,\n EXIT_FLUSH_TIMEOUT_MS + planWaitMs,\n )\n unrefTimer(deadline)\n void releaseHeldExternalSpans(planWaitMs)\n .catch(() => {})\n .then(() => {\n stopSimulationPlans()\n })\n .then(() =>\n Promise.allSettled([\n ...Array.from(pendingTracePromises).map((p) => p.catch(() => {})),\n shutdownTraceTransports(EXIT_FLUSH_TIMEOUT_MS).catch(() => false),\n ]),\n )\n .then(() => {\n clearTimeout(deadline)\n stopFlushing()\n })\n })\n}\n\n/**\n * How the API key is supplied internally: either a literal string or a\n * function resolved each time the key is needed (at request/send time). The\n * function form is what defers key resolution past module-load construction\n * so an env var loaded after the client is built (the ESM dotenv-hoisting\n * case) is still picked up.\n */\nexport type ApiKeyInput = string | (() => string | undefined)\n\nexport interface HttpClientConfig {\n apiKey?: ApiKeyInput\n serviceUrl: string\n timeout?: number\n}\n\nexport type SpanOccurrence = \"first\" | \"last\" | number\n\nexport const SPAN_TYPES = [\n \"llm\",\n \"agent\",\n \"function\",\n \"guardrail\",\n \"handoff\",\n \"custom\",\n] as const\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 = (typeof SPAN_TYPES)[number]\n\n/**\n * Which span `getTraceSpan` returns: `id` alone, or `name` and/or `type`\n * with an optional `occurrence` (`\"first\"`, `\"last\"` by default, or a\n * zero-based index into the matches in the order they ran).\n */\nexport type SpanLookup =\n | { id: string; name?: never; type?: never; occurrence?: never }\n | { name: string; type?: SpanType; id?: never; occurrence?: SpanOccurrence }\n | { type: SpanType; name?: string; id?: never; occurrence?: SpanOccurrence }\n\nexport interface CapturedSpan {\n id: string\n traceId: string\n parentSpanId: string | null\n name: string | null\n type: string\n input: unknown\n output: unknown\n contexts: Record<string, unknown>[]\n prompt: string | null\n metadata: Record<string, unknown>\n metrics: Record<string, unknown> | null\n errors: unknown\n startedAt: string | null\n endedAt: string | null\n}\n\n/**\n * HTTP client for Bitfab API requests.\n *\n * Provides methods for different API endpoints with proper error handling,\n * timeouts, and authentication.\n */\n/**\n * `Retry-After` as milliseconds. The header is either a delay in seconds or an\n * HTTP date; both forms appear in the wild, so both are read. Anything else, or\n * a date already in the past, yields `undefined` so the caller falls back to\n * its own backoff.\n */\n/**\n * Read one response header without letting it break delivery. `Response.headers`\n * is always present from a real `fetch`, but polyfills and doubles are looser,\n * and an optional header must never be the reason a batch fails to send.\n */\nfunction readHeader(response: Response, name: string): string | null {\n try {\n return response.headers?.get(name) ?? null\n } catch {\n return null\n }\n}\n\nexport function parseRetryAfterMs(header: string | null): number | undefined {\n // Trimmed and emptiness-checked before Number(), which reads \"\" and \" \" as\n // 0 and would turn a blank header into \"retry immediately\", skipping the\n // backoff entirely. The other SDKs treat a blank header as no instruction.\n const value = header?.trim()\n if (!value) {\n return undefined\n }\n const seconds = Number(value)\n if (Number.isFinite(seconds)) {\n return seconds >= 0 ? seconds * 1_000 : undefined\n }\n const at = Date.parse(value)\n if (Number.isNaN(at)) {\n return undefined\n }\n return Math.max(0, at - Date.now())\n}\n\n/**\n * The delivery identity of a carrier, read from the payload here because this\n * is where the payload shape is owned. The transport is handed the result and\n * never looks inside a payload itself.\n */\n/**\n * Everything the transport needs to know about a carrier, derived here because\n * this is where the payload shape is owned. The transport applies these and\n * never looks inside a payload itself.\n */\nfunction carrierMeta(\n operation: TraceOperation,\n payload: Record<string, unknown>,\n ref: CarrierRef | undefined,\n): CarrierMeta {\n return {\n ref,\n name: carrierName(operation, payload),\n startTime: payloadTimestamp(payload, \"started_at\"),\n endTime: payloadTimestamp(payload, \"ended_at\"),\n errored: payloadHasError(payload),\n }\n}\n\nfunction carrierName(\n operation: TraceOperation,\n payload: Record<string, unknown>,\n): string {\n if (operation === \"external_span\") {\n const spanData = asPayloadRecord(\n asPayloadRecord(payload.rawSpan)?.span_data,\n )\n if (typeof spanData?.name === \"string\") {\n return spanData.name\n }\n }\n if (typeof payload.traceFunctionKey === \"string\") {\n return payload.traceFunctionKey\n }\n return `bitfab.${operation}`\n}\n\n/**\n * Milliseconds since the epoch for a payload timestamp, or `undefined` to let\n * OTel stamp the carrier with the current time.\n */\nfunction payloadTimestamp(\n payload: Record<string, unknown>,\n field: string,\n): number | undefined {\n const rawSpan = asPayloadRecord(payload.rawSpan)\n const rawTrace =\n asPayloadRecord(payload.externalTrace) ?? asPayloadRecord(payload.rawTrace)\n const raw = rawSpan?.[field] ?? rawTrace?.[field]\n if (typeof raw !== \"string\") {\n return undefined\n }\n const parsed = Date.parse(raw)\n return Number.isNaN(parsed) ? undefined : parsed\n}\n\nfunction payloadHasError(payload: Record<string, unknown>): boolean {\n const spanData = asPayloadRecord(asPayloadRecord(payload.rawSpan)?.span_data)\n if (spanData?.error != null) {\n return true\n }\n const errors = payload.errors\n return Array.isArray(errors) ? errors.length > 0 : Boolean(errors)\n}\n\nfunction asPayloadRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/** What a caller learns about one tracked trace once it takes it back. */\nexport interface DeliveryReport {\n spanCount: number\n /** A closing carrier was submitted, so the expected set is final. */\n closed: boolean\n /** Every carrier submitted under this trace came back accepted. */\n delivered: boolean\n /**\n * The server's assigned `traces.id`, read back from the OTLP ingest response.\n * Absent when talking to a server that predates this field, or before any\n * carrier for the trace has been acked.\n */\n serverTraceId?: string\n}\n\ninterface TraceDelivery {\n submittedSpanIds: Set<string>\n ackedSpanIds: Set<string>\n closed: boolean\n closingAcked: boolean\n serverTraceId?: string\n}\n\nfunction carrierRef(payload: Record<string, unknown>): CarrierRef | undefined {\n const traceId = sourceTraceIdOf(payload)\n if (traceId === undefined) {\n return undefined\n }\n const rawSpan = payload.rawSpan\n if (rawSpan === undefined) {\n return { traceId }\n }\n const spanId = (rawSpan as Record<string, unknown>)?.id\n return {\n traceId,\n spanId: typeof spanId === \"string\" ? spanId : `submission-${++carrierSeq}`,\n }\n}\n\nfunction sourceTraceIdOf(payload: Record<string, unknown>): string | undefined {\n if (typeof payload.sourceTraceId === \"string\") {\n return payload.sourceTraceId\n }\n const rawTrace = (payload.externalTrace ?? payload.rawTrace) as\n | Record<string, unknown>\n | undefined\n const id = rawTrace?.id\n return typeof id === \"string\" ? id : undefined\n}\n\nlet carrierSeq = 0\n\nfunction describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction warnDroppedExternalSpan(error: unknown): void {\n warnOnce(\n \"external-span-dropped\",\n `a span was dropped because the send step failed: ${describeError(error)}`,\n )\n}\n\nfunction warnDroppedExternalTrace(error: unknown): void {\n warnOnce(\n \"external-trace-dropped\",\n `a trace was dropped because the send step failed: ${describeError(error)}`,\n )\n}\n\nexport class HttpClient {\n private readonly apiKey: ApiKeyInput | undefined\n private readonly serviceUrl: string\n private readonly timeout: number\n private traceTransport: TraceTransport | undefined\n // Only traces a caller asked about are tracked, so ordinary tracing stores\n // nothing here.\n private readonly traceDeliveries = new Map<string, TraceDelivery>()\n // Deferred span work owned by THIS client. The module-global set backs the\n // process-wide `flushTraces()` and the exit hook, but per-client lifecycle\n // must not wait on another client's slow finalize: a false `close()` failure\n // caused by unrelated work is worse than no signal at all.\n private readonly deferredWork = new Set<Promise<unknown>>()\n readonly traceCompletion = new TraceCompletion()\n private closed = false\n private closing: Promise<boolean> | undefined\n externalSpanTransform:\n | ((\n payload: Record<string, unknown>,\n submit: SimulationPlanSubmit,\n drop: () => void,\n ) => void)\n | undefined\n externalTraceTransform:\n | ((payload: Record<string, unknown>, submit: SimulationPlanSubmit) => void)\n | undefined\n releaseHeldExternalSpans:\n | ((timeoutMs: number) => Promise<boolean> | Promise<void>)\n | undefined\n stopSimulationPlan: (() => void) | undefined\n\n constructor(config: HttpClientConfig) {\n this.apiKey = config.apiKey\n this.serviceUrl = config.serviceUrl\n this.timeout = config.timeout ?? 120000\n liveHttpClients.add(this)\n }\n\n /**\n * Resolve the API key at the moment it is needed (request time), invoking\n * the function form if one was supplied. Never read at construction.\n */\n private resolveApiKey(): string | undefined {\n return typeof this.apiKey === \"function\" ? this.apiKey() : this.apiKey\n }\n\n /** @internal Whether this client currently has credentials for trace delivery. */\n hasApiKey(): boolean {\n try {\n const apiKey = this.resolveApiKey()\n return apiKey !== undefined && apiKey.trim() !== \"\"\n } catch {\n return false\n }\n }\n\n /**\n * This client's span transport, built on first use.\n *\n * Lazy on purpose: a client that never sends a span must never start a batch\n * worker. Every framework integration created from a `Bitfab` client shares\n * the owning client's `HttpClient`, so handlers reuse this one worker instead\n * of each spinning up their own.\n */\n private getTraceTransport(): TraceTransport | undefined {\n if (this.closed) {\n warnOnce(\n \"http-client-closed\",\n \"the Bitfab client is closed; dropping spans\",\n )\n return undefined\n }\n if (!this.traceTransport) {\n this.traceTransport = createTraceTransport({\n directSender: (request, timeoutMs) =>\n this.deliverCarriers(request, timeoutMs),\n onDelivered: (refs) => this.recordDeliveredCarriers(refs),\n })\n }\n return this.traceTransport\n }\n\n /**\n * Post one encoded batch and decide what the server's answer means, so the\n * transport never reads a response. Rejections and permanent statuses come\n * back as a non-retryable {@link DeliveryError}; anything the server might\n * still accept on a second try comes back retryable.\n */\n private async deliverCarriers(\n request: EncodedRequestBody,\n timeoutMs: number,\n ): Promise<void> {\n let response: Record<string, unknown>\n try {\n // sendPrepared, not sendEncoded: the exporter already encoded this batch\n // to size the request, and re-encoding here would do that work twice.\n response = await this.sendPrepared<Record<string, unknown>>(\n OTLP_TRACES_ENDPOINT,\n request,\n { timeout: timeoutMs },\n )\n } catch (error) {\n const status = error instanceof BitfabError ? error.status : undefined\n if (status === undefined) {\n // No verdict from the server (a network fault): worth another attempt.\n throw new DeliveryError(`OTLP ingestion failed: ${String(error)}`, {\n retryable: true,\n })\n }\n throw new DeliveryError(`OTLP ingestion failed with HTTP ${status}`, {\n retryable: RETRYABLE_STATUSES.has(status),\n oversized: status === 413,\n ...(error instanceof BitfabError && error.retryAfterMs !== undefined\n ? { retryAfterMs: error.retryAfterMs }\n : {}),\n })\n }\n\n const serverTraceIds = asPayloadRecord(response?.traceIds)\n if (serverTraceIds !== undefined) {\n this.recordServerTraceIds(serverTraceIds)\n }\n\n const partialSuccess = asPayloadRecord(response?.partialSuccess)\n const rejected = partialSuccess?.rejectedSpans\n if (rejected !== undefined && rejected !== \"0\" && rejected !== 0) {\n // The server's verdict on the payload, not a transient fault.\n throw new DeliveryError(\n `OTLP ingestion rejected ${rejected} span(s): ${\n partialSuccess?.errorMessage ?? \"no reason provided\"\n }`,\n )\n }\n }\n\n /**\n * Start tracking delivery for `traceIds`. Nothing is recorded for a trace\n * that was never tracked, so ordinary tracing costs no bookkeeping at all.\n */\n trackTraceDeliveries(traceIds: string[]): void {\n for (const traceId of traceIds) {\n if (!this.traceDeliveries.has(traceId)) {\n this.traceDeliveries.set(traceId, {\n submittedSpanIds: new Set(),\n ackedSpanIds: new Set(),\n closed: false,\n closingAcked: false,\n })\n }\n }\n }\n\n /**\n * The server's assigned `traces.id` for a tracked trace if it has already\n * been read back off an ingest response, without stopping tracking. Lets a\n * replay surface the id mid-run for items whose spans already landed.\n */\n peekServerTraceId(traceId: string): string | undefined {\n return this.traceDeliveries.get(traceId)?.serverTraceId\n }\n\n /** Whether any tracked trace has had its closing carrier submitted. */\n hasClosedDeliveries(traceIds: string[]): boolean {\n return traceIds.some((traceId) => this.traceDeliveries.get(traceId)?.closed)\n }\n\n /**\n * Report what each tracked trace submitted and whether the server confirmed\n * it, and stop tracking them. Every id passed is freed, so a caller cannot\n * leak a record for a trace that never closed.\n *\n * `delivered` is only meaningful once a flush has settled: acks land before\n * an export resolves, so a flush that reported success has already collected\n * every ack it is going to collect.\n */\n takeTraceDeliveries(traceIds: string[]): Record<string, DeliveryReport> {\n const reports: Record<string, DeliveryReport> = {}\n for (const traceId of traceIds) {\n const delivery = this.traceDeliveries.get(traceId)\n if (delivery === undefined) {\n continue\n }\n this.traceDeliveries.delete(traceId)\n reports[traceId] = {\n spanCount: delivery.submittedSpanIds.size,\n closed: delivery.closed,\n delivered:\n delivery.closingAcked &&\n [...delivery.submittedSpanIds].every((spanId) =>\n delivery.ackedSpanIds.has(spanId),\n ),\n serverTraceId: delivery.serverTraceId,\n }\n }\n return reports\n }\n\n /** Build a carrier's meta and record what it adds to its trace's expected set. */\n private recordedMeta(\n operation: TraceOperation,\n payload: Record<string, unknown>,\n ref: CarrierRef | undefined,\n ): CarrierMeta {\n this.recordSubmittedCarrier(ref)\n return carrierMeta(operation, payload, ref)\n }\n\n private recordSubmittedCarrier(ref: CarrierRef | undefined): void {\n if (ref === undefined) {\n return\n }\n const delivery = this.traceDeliveries.get(ref.traceId)\n if (delivery === undefined) {\n return\n }\n if (ref.spanId === undefined) {\n delivery.closed = true\n } else {\n delivery.submittedSpanIds.add(ref.spanId)\n }\n }\n\n /**\n * Ingestion commits every carrier in a request before it answers, so a\n * delivered ref is proof its row exists: the same fact the replay status\n * endpoint would report, already in hand.\n */\n /**\n * Record the server's assigned `traces.id` for each tracked source trace,\n * read back from the OTLP ingest response. Keyed by source trace id, the same\n * key the delivery ledger uses. Untracked ids are ignored.\n */\n private recordServerTraceIds(map: Record<string, unknown>): void {\n for (const [sourceTraceId, serverTraceId] of Object.entries(map)) {\n if (typeof serverTraceId !== \"string\") {\n continue\n }\n const delivery = this.traceDeliveries.get(sourceTraceId)\n if (delivery === undefined) {\n continue\n }\n delivery.serverTraceId = serverTraceId\n }\n }\n\n private recordDeliveredCarriers(refs: CarrierRef[]): void {\n for (const ref of refs) {\n const delivery = this.traceDeliveries.get(ref.traceId)\n if (delivery === undefined) {\n continue\n }\n if (ref.spanId === undefined) {\n delivery.closingAcked = true\n } else {\n delivery.ackedSpanIds.add(ref.spanId)\n }\n }\n }\n\n /**\n * Track deferred span work so this client's own lifecycle waits for it, and\n * so the process-wide flush and exit hook do too.\n */\n trackDeferred<T>(promise: Promise<T>): Promise<T> {\n this.deferredWork.add(promise)\n void promise\n .finally(() => this.deferredWork.delete(promise))\n .catch(() => {})\n return awaitOnExit(promise)\n }\n\n /**\n * Settle only THIS client's deferred span work. Scoped deliberately: the\n * global set can contain another client's long-running finalize, and\n * attributing its timeout here would fail a client whose own work succeeded.\n */\n async settleDeferredWork(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n ): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n const released = await this.releaseHeldExternalSpans?.(\n planWaitSliceMs(timeoutMs),\n )\n await replayContextReady.catch(() => {})\n const settled = await waitForPromises(\n Array.from(this.deferredWork),\n Math.max(0, deadline - Date.now()),\n )\n const releasedAfterDeferred = await this.releaseHeldExternalSpans?.(0)\n return released !== false && releasedAfterDeferred !== false && settled\n }\n\n /**\n * Wait for spans queued by this client to be delivered, within one deadline.\n * Returns false on delivery failure or timeout.\n */\n async waitForPendingRequests(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n ): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n const settled = await this.settleDeferredWork(\n Math.max(0, deadline - Date.now()),\n )\n const flushed =\n (await this.traceTransport?.flush(Math.max(0, deadline - Date.now()))) ??\n true\n return settled && flushed\n }\n\n /**\n * Flush and permanently close this client's tracing transport. Idempotent:\n * a second call joins the first rather than tearing down a pipeline the\n * first call already owns.\n */\n close(timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS): Promise<boolean> {\n if (this.closing) {\n return this.closing\n }\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n this.closing = (async () => {\n liveHttpClients.delete(this)\n const settled = await this.settleDeferredWork(\n Math.max(0, deadline - Date.now()),\n )\n this.stopSimulationPlan?.()\n this.closed = true\n this.externalSpanTransform = undefined\n this.externalTraceTransform = undefined\n this.releaseHeldExternalSpans = undefined\n this.stopSimulationPlan = undefined\n const transport = this.traceTransport\n this.traceTransport = undefined\n const shutdownOk =\n (await transport?.shutdown(Math.max(0, deadline - Date.now()))) ?? true\n return settled && shutdownOk\n })()\n return this.closing\n }\n\n /**\n * Make an HTTP request to the Bitfab API. Defaults to POST; pass\n * `options.method` to use a different verb (e.g. \"PATCH\").\n *\n * @param endpoint - The API endpoint (without base URL)\n * @param payload - The request body\n * @param options - Optional request options\n * @returns The parsed JSON response\n * @throws {BitfabError} If the request fails\n */\n async request<T>(\n endpoint: string,\n payload: Record<string, unknown>,\n options?: {\n timeout?: number\n method?: \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\"\n },\n ): Promise<T> {\n // Serialize the payload so a stray non-serializable value (BigInt,\n // function, circular ref, a class instance that slipped past upstream\n // serialization) can never abort the send and silently drop the span.\n // Strays are stubbed in place, preserving span content, and a degraded\n // payload warns loudly.\n const { body, dropped } = serializePayloadBody(payload)\n if (dropped.length > 0) {\n try {\n console.warn(\n `Bitfab: request body to ${endpoint} held ${dropped.length} ` +\n `non-serializable value(s) (${[...new Set(dropped)].join(\", \")}); ` +\n \"they were stubbed so the span still sends, but the trace may be \" +\n \"incomplete or not replayable. Capture a JSON-safe projection of \" +\n \"this input to make it replayable.\",\n )\n } catch {}\n }\n return this.sendEncoded<T>(endpoint, body, options)\n }\n\n /**\n * POST an already-encoded body. The span transport encodes its own batches,\n * so routing them back through {@link HttpClient.request} would encode the\n * same data twice.\n */\n async sendEncoded<T>(\n endpoint: string,\n body: string,\n options?: {\n timeout?: number\n method?: \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\"\n },\n ): Promise<T> {\n // Awaited only when compression actually runs, so an uncompressed request\n // still calls `fetch` synchronously the way it did before compression.\n const prepared = encodeRequestBody(body)\n const encoded = prepared instanceof Promise ? await prepared : prepared\n return this.sendPrepared<T>(endpoint, encoded, options)\n }\n\n private async sendPrepared<T>(\n endpoint: string,\n encoded: EncodedRequestBody,\n options?: {\n timeout?: number\n method?: \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\"\n },\n ): Promise<T> {\n const url = `${this.serviceUrl}${endpoint}`\n const timeout = options?.timeout ?? this.timeout\n const method = options?.method ?? \"POST\"\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.resolveApiKey() ?? \"\"}`,\n }\n if (encoded.contentEncoding) {\n headers[\"Content-Encoding\"] = encoded.contentEncoding\n }\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body: encoded.body,\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new BitfabError(\n `HTTP ${response.status}: ${errorText.slice(0, 500)}`,\n undefined,\n response.status,\n parseRetryAfterMs(readHeader(response, \"retry-after\")),\n )\n }\n\n const result = await response.json()\n\n // Check for errors in the response\n if (result.error) {\n if (result.url) {\n throw new BitfabError(\n `${result.error} Configure it at: ${this.serviceUrl}${result.url}`,\n result.url,\n )\n }\n throw new BitfabError(result.error)\n }\n\n return result as T\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new BitfabError(`Request timed out after ${timeout}ms`)\n }\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred\")\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /**\n * Look up a function by name.\n * Blocks until complete - needed for function execution.\n */\n async lookupFunction<T>(name: string): Promise<T> {\n return this.request<T>(\"/api/sdk/functions/lookup\", { name })\n }\n\n async getSimulationPlan(): Promise<SimulationPlanResponse> {\n // Without a key the server answers 401, so skip the request entirely.\n if (!this.hasApiKey()) {\n throw new BitfabError(NO_API_KEY_FOR_SIMULATION_PLAN)\n }\n return this.get<SimulationPlanResponse>(\n \"/api/sdk/sim-plan\",\n SIMULATION_PLAN_READ_TIMEOUT_MS,\n )\n }\n\n async getTraceSpan(\n traceId: string,\n lookup: SpanLookup,\n ): Promise<CapturedSpan | null> {\n const searchParams = new URLSearchParams()\n if (lookup.id !== undefined) {\n searchParams.set(\"id\", lookup.id)\n } else {\n if (lookup.name !== undefined) {\n searchParams.set(\"name\", lookup.name)\n }\n if (lookup.type !== undefined) {\n searchParams.set(\"type\", lookup.type)\n }\n searchParams.set(\"occurrence\", String(lookup.occurrence ?? \"last\"))\n }\n\n const endpoint = `/api/sdk/traces/${encodeURIComponent(traceId)}/span?${searchParams.toString()}`\n const response = await this.get<{ span: CapturedSpan | null }>(endpoint)\n return response.span\n }\n\n async getSpan(spanId: string): Promise<CapturedSpan | null> {\n const response = await this.get<{ span: CapturedSpan | null }>(\n `/api/sdk/spans/${encodeURIComponent(spanId)}`,\n )\n return response.span\n }\n\n /**\n * GET a JSON endpoint on the service with the client's API key. Throws a\n * `BitfabError` carrying the status text for any non-2xx response.\n */\n async get<T>(\n endpoint: string,\n timeoutMs?: number,\n extraHeaders?: Record<string, string>,\n ): Promise<T> {\n const url = `${this.serviceUrl}${endpoint}`\n const timeout = timeoutMs ?? this.timeout\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${this.resolveApiKey() ?? \"\"}`,\n ...extraHeaders,\n },\n signal: controller.signal,\n })\n if (!response.ok) {\n const errorText = await response.text()\n throw new BitfabError(\n `HTTP ${response.status}: ${errorText.slice(0, 500)}`,\n undefined,\n response.status,\n parseRetryAfterMs(readHeader(response, \"retry-after\")),\n )\n }\n return (await response.json()) as T\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new BitfabError(`Request timed out after ${timeout}ms`)\n }\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred\")\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /**\n * Queue an internal trace (from local BAML execution via `call()`) onto this\n * client's batching transport. `functionId` moves into the payload because\n * the OTLP carrier has no path to carry it.\n */\n sendInternalTrace(\n functionId: string,\n payload: Record<string, unknown>,\n ): void {\n const body = {\n ...payload,\n functionId,\n sdkPackage: __packageName__,\n sdkVersion: __version__,\n }\n this.getTraceTransport()?.submit(\n \"internal_trace\",\n body,\n carrierMeta(\"internal_trace\", body, undefined),\n )\n }\n\n sendExternalSpan(payload: Record<string, unknown>): void {\n const ref = carrierRef(payload)\n if (ref?.spanId !== undefined) {\n this.traceCompletion.record(ref.traceId, ref.spanId)\n }\n const drop = (): void => {\n if (ref?.spanId !== undefined) {\n this.traceCompletion.abort(ref.traceId, ref.spanId)\n }\n }\n const gate = this.externalSpanTransform\n if (gate === undefined) {\n this.submitExternalSpan(payload)\n return\n }\n try {\n gate(payload, (ready) => this.submitExternalSpan(ready), drop)\n } catch (error) {\n drop()\n warnDroppedExternalSpan(error)\n }\n }\n\n submitExternalSpan(payload: Record<string, unknown>): void {\n const body: Record<string, unknown> = {\n ...payload,\n sdkVersion: __version__,\n }\n delete body[ROOT_TRACE_FUNCTION_KEY_FIELD]\n delete body[DECLARED_NODE_FIELD]\n this.getTraceTransport()?.submit(\n \"external_span\",\n body,\n this.recordedMeta(\"external_span\", payload, carrierRef(payload)),\n )\n }\n\n /**\n * Queue an external trace completion (from OpenAI tracing) onto this\n * client's batching transport. Fire-and-forget for the same reason as\n * {@link HttpClient.sendExternalSpan}; replay confirms persistence with the\n * server-authoritative barrier in `replay.ts`, not by awaiting this call.\n */\n sendExternalTrace(rawPayload: Record<string, unknown>): void {\n const payload = mergeCallerMetadataIntoTracePayload(rawPayload)\n const traceId = sourceTraceIdOf(payload)\n if (payload.completed === true && traceId !== undefined) {\n this.traceCompletion.close(\n traceId,\n (expectedSpanCount) =>\n this.sendCountedExternalTrace({ ...payload, expectedSpanCount }),\n payload.dropped === true,\n )\n return\n }\n if (traceId !== undefined) {\n this.traceCompletion.open(traceId)\n }\n this.sendCountedExternalTrace(payload)\n }\n\n private sendCountedExternalTrace(payload: Record<string, unknown>): void {\n try {\n const gate = this.externalTraceTransform\n if (gate === undefined) {\n this.submitExternalTrace(payload)\n } else {\n gate(payload, (ready) => this.submitExternalTrace(ready))\n }\n } catch (error) {\n warnDroppedExternalTrace(error)\n }\n }\n\n submitExternalTrace(payload: Record<string, unknown>): void {\n this.getTraceTransport()?.submit(\n \"external_trace\",\n {\n ...payload,\n sdkPackage: __packageName__,\n sdkVersion: __version__,\n },\n this.recordedMeta(\n \"external_trace\",\n payload,\n payload.completed === true ? carrierRef(payload) : undefined,\n ),\n )\n }\n\n /**\n * Partial update of an existing trace identified by its Bitfab trace ID.\n * Used by the detached `client.getTrace(id)` handle.\n *\n * Blocking, like the other trace-API calls: it resolves once the server has\n * applied the change and rejects if the server refused it. A patch targets a\n * trace that is already closed, so there is no batch for it to ride along\n * with and no later signal that would reveal a silent failure.\n */\n async patchTrace(\n traceId: string,\n payload: {\n appendContexts?: Record<string, unknown>[]\n mergeMetadata?: Record<string, unknown>\n setSessionId?: string\n setName?: string\n },\n ): Promise<void> {\n const endpoint = `/api/sdk/traces/${encodeURIComponent(traceId)}`\n await this.request(endpoint, payload, { method: \"PATCH\" })\n }\n\n /**\n * Start a replay session by fetching historical traces.\n * Blocking call - creates an experiment and returns lightweight item references.\n */\n async startReplay(\n traceFunctionKey: string,\n limit: number | undefined,\n traceIds?: string[],\n name?: string,\n codeChangeDescription?: string | null,\n codeChangeFiles?: CodeChangeFile[] | null,\n includeDbBranchLease?: boolean,\n experimentGroupId?: string,\n datasetIds?: string[],\n graderIds?: string[],\n dbBranchSettings?: DbBranchSettings,\n attempts?: number,\n includeOriginalMetadata?: boolean,\n onlyWithAssertions?: boolean,\n skipAssertionJudging?: boolean,\n experimentalSelectiveReplay?: import(\"./selectiveReplay.js\").SelectiveReplayOptions,\n notes?: string,\n metadata?: Record<string, string>,\n dryRun?: boolean,\n experimentGroupName?: string,\n invocation?: ReplayInvocation,\n ): Promise<StartReplayResponse> {\n // limit is only meaningful without traceIds (an explicit ID list\n // already determines the count), so it's omitted when undefined.\n const payload: Record<string, unknown> = { traceFunctionKey }\n if (experimentalSelectiveReplay !== undefined) {\n payload.experimentalSelectiveReplay = experimentalSelectiveReplay\n }\n if (limit !== undefined) {\n payload.limit = limit\n }\n if (traceIds) {\n payload.traceIds = traceIds\n }\n if (name !== undefined) {\n payload.name = name\n }\n if (notes !== undefined) {\n payload.notes = notes\n }\n if (metadata !== undefined) {\n payload.metadata = metadata\n }\n if (codeChangeDescription !== undefined) {\n payload.codeChangeDescription = codeChangeDescription\n }\n if (codeChangeFiles !== undefined) {\n payload.codeChangeFiles = codeChangeFiles\n }\n if (includeDbBranchLease) {\n payload.includeDbBranchLease = true\n payload.lazyDbBranchLease = true\n }\n if (experimentGroupId !== undefined) {\n payload.experimentGroupId = experimentGroupId\n }\n if (experimentGroupName !== undefined) {\n payload.experimentGroupName = experimentGroupName\n }\n if (datasetIds !== undefined) {\n if (datasetIds.length === 1) {\n payload.datasetId = datasetIds[0]\n } else {\n payload.datasetIds = datasetIds\n }\n }\n if (graderIds !== undefined) {\n payload.graderIds = graderIds\n }\n if (dbBranchSettings !== undefined) {\n payload.dbBranchSettings = dbBranchSettings\n }\n if (attempts !== undefined && attempts > 1) {\n payload.attempts = attempts\n }\n if (includeOriginalMetadata) {\n payload.includeOriginalMetadata = true\n }\n if (onlyWithAssertions) {\n payload.onlyWithAssertions = true\n }\n if (skipAssertionJudging !== true) {\n payload.judgeAssertions = true\n }\n if (dryRun) {\n payload.dryRun = true\n }\n if (invocation !== undefined) {\n payload.invocation = invocation\n }\n const git = await resolvedGitState()\n if (git && !isEmptyGitState(git)) {\n payload.git = git\n }\n // When DB branching is on, the server resolves a Neon preview branch\n // per item (snapshot + restore + poll), which can run ~5-10s each, and\n // runs any `warmupSql` against each branch on a 240s budget of its own.\n // The server gives up at 280s and answers, so this is a backstop for a\n // reply that never comes rather than the thing that normally fires; it\n // sits above the server's own ceiling so the server's error is the one\n // callers see. Not raisable in practice either: undici's default\n // `headersTimeout` is also 300s and `fetch` cannot override it per\n // request.\n const timeout = includeDbBranchLease\n ? REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS\n : 30_000\n const response = await this.request<StartReplayWireResponse>(\n \"/api/sdk/replay/start\",\n payload,\n { timeout },\n )\n const { testRunId, testRunUrl, ...rest } = response\n const experimentId = response.experimentId ?? testRunId\n const experimentUrl = response.experimentUrl ?? testRunUrl\n // A dry run is the one start the server answers without an experiment.\n if (dryRun && response.experimentId === null) {\n return { ...rest, experimentId: null, experimentUrl: null }\n }\n if (\n experimentId === undefined ||\n experimentId === null ||\n experimentUrl === undefined ||\n experimentUrl === null\n ) {\n throw new BitfabError(\n \"Replay start response is missing the experiment ID or URL.\",\n )\n }\n return { ...rest, experimentId, experimentUrl }\n }\n\n async resumeReplay(\n experimentId: string,\n traceFunctionKey: string,\n codeChangeFiles?: CodeChangeFile[] | null,\n force?: boolean,\n ): Promise<ResumeReplayResponse> {\n const payload: Record<string, unknown> = {\n experimentId,\n traceFunctionKey,\n lazyDbBranchLease: true,\n }\n if (force === true) {\n payload.force = true\n }\n if (codeChangeFiles !== undefined) {\n payload.codeChangeFiles = codeChangeFiles\n }\n const git = await resolvedGitState()\n if (git && !isEmptyGitState(git)) {\n payload.git = git\n }\n const response = await this.request<ResumeReplayWireResponse>(\n \"/api/sdk/replay/resume\",\n payload,\n { timeout: REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS },\n )\n const { testRunId, testRunUrl, ...rest } = response\n const resumedExperimentId = response.experimentId ?? testRunId\n const experimentUrl = response.experimentUrl ?? testRunUrl\n if (resumedExperimentId === undefined || experimentUrl === undefined) {\n throw new BitfabError(\n \"Replay resume response is missing the experiment ID or URL.\",\n )\n }\n return {\n ...rest,\n experimentId: resumedExperimentId,\n experimentUrl,\n work: rest.work ?? [],\n finished: rest.finished ?? [],\n skippedOriginalTraceIds: rest.skippedOriginalTraceIds ?? [],\n includeDbBranchLease: rest.includeDbBranchLease ?? false,\n dbBranchSettings: rest.dbBranchSettings ?? null,\n }\n }\n\n /**\n * Fetch an external span by ID.\n * Blocking GET request.\n * The replay view limits rawData to input/output serialization fields.\n */\n async getExternalSpan(\n spanId: string,\n options?: { view?: \"full\" | \"replay\" },\n ): Promise<ExternalSpanResponse> {\n const query = options?.view === \"replay\" ? \"?view=replay\" : \"\"\n const url = `${this.serviceUrl}/api/sdk/externalSpans/${spanId}${query}`\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), 30_000)\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.resolveApiKey() ?? \"\"}` },\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new BitfabError(\n `HTTP ${response.status}: ${errorText.slice(0, 500)}`,\n )\n }\n\n return (await response.json()) as ExternalSpanResponse\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new BitfabError(\"Request timed out after 30000ms\")\n }\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred\")\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /**\n * Fetch the span tree for a root span.\n * Blocking GET request.\n *\n * Pass `includeOutputs: false` for a payload-free tree (structure +\n * `externalSpanId` only), so recorded outputs are fetched lazily per mocked\n * span instead of all up front. Omit it (default eager) for `mock: \"all\"`.\n * Pass `includeRootOutput: false` when the root was already fetched.\n */\n async getSpanTree(\n externalSpanId: string,\n options?: { includeOutputs?: boolean; includeRootOutput?: boolean },\n ): Promise<SpanTreeResponse> {\n const searchParams = new URLSearchParams()\n if (options?.includeOutputs === false) {\n searchParams.set(\"includeOutputs\", \"false\")\n }\n if (options?.includeRootOutput === false) {\n searchParams.set(\"includeRootOutput\", \"false\")\n }\n const encodedQuery = searchParams.toString()\n const query = encodedQuery ? `?${encodedQuery}` : \"\"\n const url = `${this.serviceUrl}/api/sdk/replay/spanTree/${externalSpanId}${query}`\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), 30_000)\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.resolveApiKey() ?? \"\"}` },\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new BitfabError(\n `HTTP ${response.status}: ${errorText.slice(0, 500)}`,\n )\n }\n\n return (await response.json()) as SpanTreeResponse\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new BitfabError(\"Request timed out after 30000ms\")\n }\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred\")\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /**\n * Read which of a replay run's traces the server has fully persisted.\n *\n * With `expectedSpanCounts`, a trace appears in the response only once it\n * has a final status AND at least that many persisted spans, which is what\n * makes this a real barrier rather than a \"the row exists\" check.\n */\n async getReplayStatus(\n experimentId: string,\n expectedSpanCounts: Record<string, number>,\n ): Promise<ReplayStatusResponse> {\n return this.request<ReplayStatusResponse>(\n \"/api/sdk/replay/status\",\n { ...experimentIdWireFields(experimentId), expectedSpanCounts },\n { timeout: 30_000 },\n )\n }\n\n /**\n * Mark a replay experiment as completed.\n * Blocking call.\n */\n async completeReplay(experimentId: string): Promise<CompleteReplayResponse> {\n return this.request<CompleteReplayResponse>(\n \"/api/sdk/replay/complete\",\n experimentIdWireFields(experimentId),\n { timeout: REPLAY_COMPLETE_REQUEST_TIMEOUT_MS },\n )\n }\n\n async interruptReplay(experimentId: string): Promise<boolean> {\n try {\n await this.request<unknown>(\n \"/api/sdk/replay/interrupt\",\n experimentIdWireFields(experimentId),\n { timeout: REPLAY_INTERRUPT_REQUEST_TIMEOUT_MS },\n )\n return true\n } catch {\n return false\n }\n }\n\n async heartbeatReplay(experimentId: string): Promise<void> {\n try {\n await this.request<unknown>(\n \"/api/sdk/replay/heartbeat\",\n experimentIdWireFields(experimentId),\n { timeout: REPLAY_HEARTBEAT_REQUEST_TIMEOUT_MS },\n )\n } catch {}\n }\n\n async getReseedSource(traceId: string): Promise<ReseedSourceResponse> {\n return this.get<ReseedSourceResponse>(\n `/api/sdk/traces/${encodeURIComponent(traceId)}/reseedSource`,\n )\n }\n\n async reseedTrace(\n traceId: string,\n runTraceId: string,\n ): Promise<ReseedTraceResponse> {\n return this.request<ReseedTraceResponse>(\n `/api/sdk/traces/${encodeURIComponent(traceId)}/reseed`,\n { runTraceId },\n { timeout: 30_000 },\n )\n }\n\n /**\n * Ask the server to materialize a per-trace DB branch lease from a\n * captured `dbSnapshotRef`. Blocking - the resolver creates a Neon\n * snapshot + preview branch and polls operations to readiness, which\n * can take seconds.\n */\n async resolveDbBranchLease(\n experimentId: string,\n traceId: string,\n dbBranchSettings?: DbBranchSettings,\n attempt?: number,\n ): Promise<{\n dbSnapshotRef: DbSnapshotRef | null\n lease: DbBranchLease | null\n leaseError: { code: string; message: string } | null\n timings: DbBranchTimings | null\n }> {\n return this.request<{\n dbSnapshotRef: DbSnapshotRef | null\n lease: DbBranchLease | null\n leaseError: { code: string; message: string } | null\n timings: DbBranchTimings | null\n }>(\n \"/api/sdk/replay/resolveDbBranchLease\",\n {\n ...experimentIdWireFields(experimentId),\n traceId,\n dbBranchSettings,\n ...(attempt !== undefined && attempt > 0 ? { attempt } : {}),\n },\n { timeout: REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS },\n )\n }\n\n /** Release a previously-resolved DB branch by deleting its Neon branch. Idempotent server-side. */\n async releaseDbBranchLease(neonBranchId: string): Promise<void> {\n await this.request<{ released: true }>(\n \"/api/sdk/replay/releaseDbBranchLease\",\n { neonBranchId },\n { timeout: 30_000 },\n )\n }\n}\n\nexport interface TokenUsage {\n input: number | null\n output: number | null\n cached: number | null\n total: number | null\n}\n\n/**\n * Describes a single file edited as part of a code change.\n *\n * - `path`: file path (relative to the repo root, or any consistent root)\n * - `before`: file contents before the change (\"\" for newly created files)\n * - `after`: file contents after the change (\"\" for deleted files)\n */\nexport interface CodeChangeFile {\n path: string\n before: string\n after: string\n}\n\nexport function experimentIdWireFields(experimentId: string): {\n experimentId: string\n testRunId: string\n} {\n return { experimentId, testRunId: experimentId }\n}\n\ntype StartReplayWireResponse = Omit<\n StartReplayResponse,\n \"experimentId\" | \"experimentUrl\"\n> & {\n experimentId?: string | null\n experimentUrl?: string | null\n testRunId?: string | null\n testRunUrl?: string | null\n}\n\nexport interface StartReplayResponse {\n /** Null for a dry run, which the server records no experiment for. */\n experimentId: string | null\n experimentUrl: string | null\n attempts?: number\n items: Array<{\n selectiveReplayPlan?: import(\"./selectiveReplay.js\").SelectiveReplayPlan\n /** Bitfab trace ID of the original (historical) trace being replayed. */\n originalTraceId?: string\n /** External span ID the recorded inputs were read from (the original root span). */\n originalSpanId?: string\n /** @deprecated alias for `originalTraceId`; the only key emitted by servers that predate the rename. */\n sourceTraceId: string\n /** @deprecated alias for `originalSpanId`; the only key emitted by servers that predate the rename. */\n sourceSpanId: string\n durationMs: number | null\n tokens: TokenUsage | null\n model: string | null\n /**\n * The DB snapshot ref captured by the SDK at trace open. Surfaced so\n * the SDK can pass it to the lease-resolver step (or report when no\n * snapshot was captured for this trace).\n */\n dbSnapshotRef?: DbSnapshotRef\n /**\n * Populated once the server-side resolver has materialized a per-item\n * branch from `dbSnapshotRef`. The SDK exposes this to customer code\n * via `getCurrentReplayBranch()`. Absent until the resolver lands.\n */\n dbBranchLease?: DbBranchLease\n /**\n * Why the branch could not be resolved, when one was requested and the\n * attempt failed. Distinct from both fields being absent, which means the\n * trace carried no snapshot ref so nothing was attempted.\n */\n dbBranchLeaseError?: { code: string; message: string }\n /**\n * How long provisioning took, per phase. Sits beside the two fields above\n * rather than inside either: it is reported on both outcomes, complete on\n * success and partial up to the failing phase on error. Absent from\n * servers that predate it.\n */\n dbBranchTimings?: DbBranchTimings\n originalMetadata?: Record<string, unknown>\n }>\n}\n\nexport type StartReplayItem = StartReplayResponse[\"items\"][number]\n\nexport interface ResumeReplayWorkPair {\n itemIndex: number\n attempt: number\n}\n\nexport interface ResumeReplayFinishedItem {\n originalTraceId: string\n attempt: number\n traceId: string\n hasError: boolean\n}\n\nexport interface ResumeReplayResponse {\n experimentId: string\n experimentUrl: string\n attempts: number\n items: StartReplayItem[]\n work: ResumeReplayWorkPair[]\n finished: ResumeReplayFinishedItem[]\n skippedOriginalTraceIds: string[]\n includeDbBranchLease: boolean\n dbBranchSettings: DbBranchSettings | null\n}\n\ntype ResumeReplayWireResponse = Omit<\n ResumeReplayResponse,\n | \"experimentId\"\n | \"experimentUrl\"\n | \"work\"\n | \"finished\"\n | \"skippedOriginalTraceIds\"\n | \"includeDbBranchLease\"\n | \"dbBranchSettings\"\n> & {\n experimentId?: string\n experimentUrl?: string\n testRunId?: string\n testRunUrl?: string\n work?: ResumeReplayWorkPair[]\n finished?: ResumeReplayFinishedItem[]\n skippedOriginalTraceIds?: string[]\n includeDbBranchLease?: boolean\n dbBranchSettings?: DbBranchSettings | null\n}\n\nexport interface ExternalSpanResponse {\n id: string\n externalTraceId: string\n rawData: {\n span_data: {\n input: unknown\n output: unknown\n input_meta?: unknown\n output_meta?: unknown\n input_serialized?: { json: unknown; meta: unknown }\n output_serialized?: { json: unknown; meta: unknown }\n }\n }\n}\n\nexport interface ReplayStatusResponse {\n /**\n * Local replay trace id -> server trace row id, for the traces the server\n * considers fully persisted. Traces still short of their expected span count\n * are simply absent.\n */\n traceIds?: Record<string, string>\n}\n\nexport interface CompleteReplayResponse {\n id: string\n status: string\n traceIds?: Record<string, string>\n /**\n * Per-replay-trace token usage, keyed by the server trace id (the values of\n * `traceIds`). Aggregated server-side from the freshly-uploaded replay spans,\n * so it's the REPLAYED run's tokens (the same source the dashboard reads), not the\n * original trace's. The SDK maps each item onto this to set\n * `ReplayItem.tokens`. Absent on servers that predate this field.\n */\n tokens?: Record<string, TokenUsage | null>\n /**\n * Number of traces the server has persisted for this experiment at\n * completion time. Lets the SDK distinguish \"uploads failed\" from\n * \"server never saw them\" when the trace-ID mapping is incomplete.\n */\n traceCount?: number\n}\n\nexport interface ReseedSourceResponse {\n traceId: string\n traceFunctionKey: string\n ingestionType: string\n name: string | null\n sessionId: string | null\n metadata: Record<string, unknown>\n input: unknown\n inputMeta: unknown\n inputSerialized: unknown\n}\n\nexport interface ReseedTraceResponse {\n traceId: string\n previousRunTraceId: string\n}\n\nexport interface SpanTreeNode {\n /** Upstream platform span id. Stable structural identity; NOT the row id. */\n sourceSpanId: string\n /**\n * The `externalSpans` row id, accepted by {@link HttpClient.getExternalSpan}.\n * Distinct from `sourceSpanId`; used to lazily fetch this node's output when\n * the tree was fetched with `includeOutputs: false`. Optional so trees from\n * older servers (which omit it) still deserialize.\n */\n externalSpanId?: string\n traceFunctionKey: string\n spanName: string\n type: string\n /** Omitted when the tree was fetched payload-free (`includeOutputs: false`). */\n output?: unknown\n outputMeta?: unknown\n children: SpanTreeNode[]\n}\n\nexport interface SpanTreeResponse {\n root: SpanTreeNode\n}\n","export type ReplayInterruptSignal = \"SIGINT\" | \"SIGTERM\"\n\nexport interface ReplayInterrupt {\n experimentId: string\n experimentUrl: string\n signal: ReplayInterruptSignal\n markedInterrupted: boolean\n}\n\ninterface ReplayInterruptTarget {\n experimentId: string\n experimentUrl: string\n interrupt: () => Promise<boolean>\n onInterrupt?: (interrupt: ReplayInterrupt) => void\n}\n\nconst REPLAY_INTERRUPT_SIGNALS: readonly ReplayInterruptSignal[] = [\n \"SIGINT\",\n \"SIGTERM\",\n]\n\nconst replayListeners = new Set<unknown>()\n\nfunction signalCapableProcess(): NodeJS.Process | undefined {\n if (typeof process === \"undefined\" || typeof process.on !== \"function\") {\n return undefined\n }\n return process\n}\n\nexport function describeReplayInterrupt(\n experimentId: string,\n markedInterrupted: boolean,\n): string {\n if (markedInterrupted) {\n return `[replay] Experiment ${experimentId} interrupted.`\n }\n return `[replay] Experiment ${experimentId} stopped, but Bitfab could not mark it interrupted. It will be marked interrupted within 15 minutes. A resume in the next two minutes may be refused as still running.`\n}\n\nfunction reportInterrupted(\n experimentId: string,\n markedInterrupted: boolean,\n): void {\n try {\n console.error(describeReplayInterrupt(experimentId, markedInterrupted))\n } catch {}\n}\n\nexport interface ReplayInterruptHandlers {\n remove: () => void\n interrupted: () => boolean\n}\n\nexport function installReplayInterruptHandlers(\n target: ReplayInterruptTarget,\n): ReplayInterruptHandlers {\n const host = signalCapableProcess()\n if (host === undefined) {\n return { remove: () => {}, interrupted: () => false }\n }\n const handlers = new Map<ReplayInterruptSignal, () => void>()\n const removeHandlers = (): void => {\n for (const [signal, handler] of handlers) {\n host.removeListener(signal, handler)\n replayListeners.delete(handler)\n }\n handlers.clear()\n }\n let interrupting = false\n const handleSignal = async (signal: ReplayInterruptSignal): Promise<void> => {\n const hostHandlesSignal = host\n .listeners(signal)\n .some((listener) => !replayListeners.has(listener))\n const markedInterrupted = await target.interrupt()\n removeHandlers()\n if (target.onInterrupt !== undefined) {\n try {\n target.onInterrupt({\n experimentId: target.experimentId,\n experimentUrl: target.experimentUrl,\n signal,\n markedInterrupted,\n })\n } catch {}\n return\n }\n reportInterrupted(target.experimentId, markedInterrupted)\n if (!hostHandlesSignal) {\n host.kill(host.pid, signal)\n }\n }\n for (const signal of REPLAY_INTERRUPT_SIGNALS) {\n const handler = (): void => {\n if (interrupting) {\n return\n }\n interrupting = true\n void handleSignal(signal)\n }\n handlers.set(signal, handler)\n replayListeners.add(handler)\n host.on(signal, handler)\n }\n return { remove: removeHandlers, interrupted: () => interrupting }\n}\n","import { __version__ } from \"./constants.js\"\nimport { readEnv } from \"./readEnv.js\"\n\nconst REPLAY_EXECUTION_TARGET_ENV = \"BITFAB_REPLAY_EXECUTION_TARGET\"\nconst HOSTED_EXECUTION_TARGET = \"hosted\"\nconst CI_ENV = \"CI\"\nconst CI_TRUE_VALUES = new Set([\"true\", \"1\"])\nconst CI_PRESENCE_ENV_VARS = [\n \"GITHUB_ACTIONS\",\n \"GITLAB_CI\",\n \"CIRCLECI\",\n \"BUILDKITE\",\n \"JENKINS_URL\",\n \"TF_BUILD\",\n] as const\nconst MAX_FLAGS = 100\nconst MAX_FLAG_NAME_LENGTH = 100\nconst MAX_FLAG_STRING_LENGTH = 1_000\nconst MAX_FLAG_LIST_LENGTH = 100\nconst SECRET_FLAG_NAME = /key|token|secret|password/i\nconst CLI_FLAGS = Symbol(\"bitfab.replayCliFlags\")\nconst METADATA_FLAG = \"metadata\"\nconst CLI_FLAG_ALIASES: Record<string, string> = {\n \"max-concurrency\": \"concurrency\",\n \"dataset-id\": \"dataset-ids\",\n}\nconst OPTION_FLAG_NAMES: Record<string, string> = {\n maxConcurrency: \"concurrency\",\n datasetId: \"dataset-ids\",\n datasetIds: \"dataset-ids\",\n}\n\ntype FlagScalar = string | number | boolean | null\ntype FlagValue = FlagScalar | FlagScalar[]\n\ntype ReplayEnvironment = \"local\" | \"ci\" | \"cloud_replay\"\n\nexport interface ReplayInvocation {\n flags: Record<string, FlagValue>\n sdk: { language: \"typescript\"; version: string }\n environment: ReplayEnvironment\n}\n\nexport function replayEnvironment(): ReplayEnvironment {\n if (readEnv(REPLAY_EXECUTION_TARGET_ENV) === HOSTED_EXECUTION_TARGET) {\n return \"cloud_replay\"\n }\n if (CI_TRUE_VALUES.has((readEnv(CI_ENV) ?? \"\").toLowerCase())) {\n return \"ci\"\n }\n if (CI_PRESENCE_ENV_VARS.some((name) => (readEnv(name) ?? \"\") !== \"\")) {\n return \"ci\"\n }\n return \"local\"\n}\n\nfunction flagScalar(value: unknown): FlagScalar | undefined {\n if (typeof value === \"string\") {\n return value.slice(0, MAX_FLAG_STRING_LENGTH)\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined\n }\n if (typeof value === \"boolean\" || value === null) {\n return value\n }\n return undefined\n}\n\nfunction flagValue(value: unknown): FlagValue {\n if (Array.isArray(value)) {\n const items = value.slice(0, MAX_FLAG_LIST_LENGTH).map(flagScalar)\n return items.every((item) => item !== undefined)\n ? (items as FlagScalar[])\n : true\n }\n const scalar = flagScalar(value)\n return scalar === undefined ? true : scalar\n}\n\nexport function canonicalCliFlag(name: string): string {\n return CLI_FLAG_ALIASES[name] ?? name\n}\n\nexport function optionFlagName(option: string): string {\n return (\n OPTION_FLAG_NAMES[option] ??\n option.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)\n )\n}\n\nfunction metadataKeys(value: unknown): string[] | true {\n const keys = Array.isArray(value)\n ? value.map((pair) => String(pair).split(\"=\")[0])\n : typeof value === \"object\" && value !== null\n ? Object.keys(value)\n : undefined\n return keys === undefined ? true : [...new Set(keys)].sort()\n}\n\nexport function invocationFlags(\n entries: Iterable<readonly [string, unknown]>,\n): Record<string, FlagValue> {\n const flags: Record<string, FlagValue> = {}\n const seen = new Set<string>()\n for (const [name, value] of entries) {\n if (seen.size >= MAX_FLAGS) {\n break\n }\n if (\n value === undefined ||\n seen.has(name) ||\n name.length === 0 ||\n name.length > MAX_FLAG_NAME_LENGTH ||\n SECRET_FLAG_NAME.test(name)\n ) {\n continue\n }\n flags[name] = flagValue(\n name === METADATA_FLAG ? metadataKeys(value) : value,\n )\n seen.add(name)\n }\n return flags\n}\n\nexport function buildReplayInvocation(\n entries: Iterable<readonly [string, unknown]> = [],\n): ReplayInvocation {\n return {\n flags: invocationFlags(entries),\n sdk: { language: \"typescript\", version: __version__ },\n environment: replayEnvironment(),\n }\n}\n\nexport function safeReplayInvocation(\n build: () => ReplayInvocation,\n): ReplayInvocation | undefined {\n try {\n return build()\n } catch {\n return undefined\n }\n}\n\nexport function withCliFlags<T extends object>(\n options: T,\n flags: Record<string, unknown>,\n): T {\n Object.defineProperty(options, CLI_FLAGS, {\n value: flags,\n enumerable: false,\n })\n return options\n}\n\nexport function cliFlags(\n options: object | undefined,\n): Record<string, unknown> | undefined {\n return (options as { [CLI_FLAGS]?: Record<string, unknown> } | undefined)?.[\n CLI_FLAGS\n ]\n}\n","/**\n * Replay historical traces through a function and create an experiment.\n *\n * The replay flow has three phases:\n * 1. Start: fetches historical traces from the server and creates an experiment\n * 2. Execute: re-runs each trace's inputs through the provided function locally\n * 3. Complete: marks the experiment as completed on the server\n */\n\nimport { resolveAutoCodeChange } from \"./codeChange.js\"\nimport type { DbSnapshotRef } from \"./dbSnapshot.js\"\nimport { BitfabError } from \"./errors.js\"\nimport {\n type CodeChangeFile,\n flushTraces,\n type HttpClient,\n type ResumeReplayFinishedItem,\n type SpanTreeNode,\n type StartReplayItem,\n type TokenUsage,\n} from \"./http.js\"\nimport { extractIntegrationFixtures } from \"./integrationFixture.js\"\nimport type { MockOverride, MockOverrideInput } from \"./mockOverride.js\"\nimport { normalizeMockOverrides } from \"./mockOverride.js\"\nimport { randomUuid } from \"./randomUuid.js\"\nimport type {\n DbBranchLease,\n DbBranchSettings,\n DbBranchTimings,\n MockSpan,\n MockTree,\n} from \"./replayContext.js\"\nimport { replayContextReady, runWithReplayContext } from \"./replayContext.js\"\nimport { startReplayHeartbeat } from \"./replayHeartbeat.js\"\nimport {\n installReplayInterruptHandlers,\n type ReplayInterrupt,\n} from \"./replayInterrupt.js\"\nimport {\n buildReplayInvocation,\n cliFlags,\n optionFlagName,\n safeReplayInvocation,\n} from \"./replayInvocation.js\"\nimport type {\n SelectiveReplayOptions,\n SelectiveReplayPlan,\n SelectiveReplayReport,\n} from \"./selectiveReplay.js\"\nimport {\n SelectiveReplayRuntime,\n validateSelectiveReplayOptions,\n} from \"./selectiveReplayRuntime.js\"\nimport { deserializeValue } from \"./serialize.js\"\nimport { writeOnce } from \"./warnOnce.js\"\n\nexport type MockStrategy = \"none\" | \"all\" | \"marked\"\n\nexport type TraceIngestionType = \"captured\" | \"seeded\"\n\nconst REPLAY_PERSISTENCE_TIMEOUT_MS = 30_000\nconst MAX_REPLAY_ATTEMPTS = 100\n\nfunction expandReplayWork<T>(\n serverItems: T[],\n attempts: number,\n): Array<{ serverItem: T; attempt: number }> {\n return Array.from({ length: attempts }, (_, attempt) =>\n serverItems.map((serverItem) => ({ serverItem, attempt })),\n ).flat()\n}\n\nconst RESUME_CONFLICTING_OPTIONS = [\n \"traceIds\",\n \"limit\",\n \"datasetId\",\n \"datasetIds\",\n \"attempts\",\n \"graderIds\",\n \"onlyWithAssertions\",\n \"dryRun\",\n \"experimentalSelectiveReplay\",\n] as const satisfies ReadonlyArray<keyof ReplayOptions>\n\nconst CARRIED_OVER_ERROR =\n \"This item errored in an earlier run of this experiment, before it was resumed.\"\n\ninterface ReplaySession {\n /** Null for a dry run: the server creates no experiment for one. */\n experimentId: string | null\n experimentUrl: string | null\n attempts: number\n work: Array<{ serverItem: StartReplayItem; attempt: number }>\n finished: ResumeReplayFinishedItem[]\n includeDbBranchLease: boolean\n dbBranchSettings: DbBranchSettings | undefined\n}\n\nfunction validateResume(resume: string, options: ReplayOptions): void {\n if (resume.trim().length === 0) {\n throw new BitfabError(\"resume must be the ID of the experiment to resume.\")\n }\n const conflicting = RESUME_CONFLICTING_OPTIONS.filter(\n (name) => options[name] !== undefined && options[name] !== false,\n )\n if (conflicting.length > 0) {\n throw new BitfabError(\n `resume continues experiment ${resume} with the traces, attempts, and graders it started with, so it cannot be combined with ${conflicting.join(\", \")}. Drop those options, or start a new replay without resume.`,\n )\n }\n}\n\nasync function resumeReplaySession(\n httpClient: HttpClient,\n experimentId: string,\n traceFunctionKey: string,\n codeChangeFiles: CodeChangeFile[] | null | undefined,\n force: boolean | undefined,\n requestedDbBranch: DbBranchOptions | boolean | undefined,\n): Promise<ReplaySession> {\n const response = await httpClient.resumeReplay(\n experimentId,\n traceFunctionKey,\n codeChangeFiles,\n force,\n )\n const work = response.work.map(({ itemIndex, attempt }) => {\n const serverItem = response.items[itemIndex]\n if (serverItem === undefined) {\n throw new BitfabError(\n `Replay resume for experiment ${response.experimentId} named item ${itemIndex}, but the server returned only ${response.items.length} item(s).`,\n )\n }\n return { serverItem, attempt }\n })\n if (response.skippedOriginalTraceIds.length > 0) {\n try {\n console.warn(\n `Bitfab: ${response.skippedOriginalTraceIds.length} trace(s) selected when experiment ${response.experimentId} started no longer exist, so resume skips them: ${response.skippedOriginalTraceIds.join(\", \")}`,\n )\n } catch {}\n }\n if (\n requestedDbBranch !== undefined &&\n dbBranchEnabled(requestedDbBranch) !== response.includeDbBranchLease\n ) {\n try {\n console.warn(\n `Bitfab: experiment ${response.experimentId} started with database branching ${response.includeDbBranchLease ? \"on\" : \"off\"}, so resume keeps it ${response.includeDbBranchLease ? \"on\" : \"off\"} and ignores the dbBranch option passed here.`,\n )\n } catch {}\n }\n return {\n experimentId: response.experimentId,\n experimentUrl: response.experimentUrl,\n attempts: response.attempts,\n work,\n finished: response.finished,\n includeDbBranchLease: response.includeDbBranchLease,\n dbBranchSettings: response.dbBranchSettings ?? undefined,\n }\n}\n\nfunction carriedOverReplayItem<T>(\n finished: ResumeReplayFinishedItem,\n): ReplayItem<T> {\n return {\n traceId: finished.traceId,\n originalTraceId: finished.originalTraceId,\n originalSpanId: \"\",\n sourceTraceId: finished.originalTraceId,\n sourceSpanId: \"\",\n attempt: finished.attempt,\n input: [],\n result: undefined,\n originalOutput: undefined,\n error: finished.hasError ? CARRIED_OVER_ERROR : null,\n traceError: null,\n replayError: null,\n durationMs: null,\n originalDurationMs: null,\n originalTokens: null,\n originalModel: null,\n tokens: null,\n model: null,\n dbSnapshotRef: null,\n dbBranchTimings: null,\n carriedOver: true,\n }\n}\n\nfunction resolveAttempts(attempts: number | undefined): number {\n if (attempts === undefined) {\n return 1\n }\n if (\n !Number.isInteger(attempts) ||\n attempts < 1 ||\n attempts > MAX_REPLAY_ATTEMPTS\n ) {\n throw new BitfabError(\n `attempts must be an integer from 1 to ${MAX_REPLAY_ATTEMPTS} (got ${attempts}).`,\n )\n }\n return attempts\n}\n\n/**\n * How the DB-snapshot branch each replay item runs against is sized and warmed.\n *\n * Every field is optional, so this object is only worth passing when you want\n * to override the mirror project's own sizing. To branch with those defaults,\n * pass `dbBranch: true` instead of an empty object.\n */\nexport interface DbBranchOptions {\n /**\n * Autoscaling floor for the branch's compute, in Neon Compute Units (0.25 to\n * 56). Omit to keep the mirror project's own default. Raise it when the\n * mirror is provisioned smaller than the database it stands in for, so\n * replay latency reflects your code rather than a cold, undersized branch.\n */\n minCu?: number\n /**\n * Autoscaling ceiling for the branch's compute, in Neon Compute Units.\n * Setting it equal to `minCu` pins the size, which keeps items comparable:\n * otherwise a later item can run against an endpoint that has already\n * scaled up and post a better number for the same code.\n */\n maxCu?: number\n /**\n * SQL that warms the branch's cache. The server appends it to the branch's\n * readiness check, so it runs BEFORE your function sees the branch and its\n * time is not charged to the replayed call. Invalid SQL fails the branch\n * rather than silently leaving it cold.\n */\n warmupSql?: string\n}\n\n/**\n * Whether the caller asked for database branching. `true` and a settings object\n * both turn it on; `false` and omission leave it off. Kept separate from\n * `resolveDbBranchSettings` because `dbBranch: true` enables branching while\n * contributing no settings, so presence of settings can't stand in for the\n * switch.\n */\nfunction resolveDatasetIds(\n options: Pick<ReplayOptions, \"datasetId\" | \"datasetIds\"> | undefined,\n): string[] | undefined {\n if (options?.datasetId !== undefined && options?.datasetIds !== undefined) {\n throw new BitfabError(\n \"datasetId and datasetIds are the same selector: pass one dataset through datasetId, or several through datasetIds.\",\n )\n }\n if (options?.datasetId !== undefined) {\n return [options.datasetId]\n }\n if (options?.datasetIds === undefined) {\n return undefined\n }\n if (options.datasetIds.length === 0) {\n throw new BitfabError(\"datasetIds must contain at least one dataset ID.\")\n }\n return [...new Set(options.datasetIds)]\n}\n\nfunction dbBranchEnabled(\n dbBranch: DbBranchOptions | boolean | undefined,\n): boolean {\n return dbBranch !== undefined && dbBranch !== false\n}\n\n/**\n * Narrow the caller's branch options to the wire shape, dropping the object\n * entirely when nothing was set so the request stays byte-identical to what\n * older SDKs send. Booleans carry no settings: they only move the switch.\n */\nfunction resolveDbBranchSettings(\n dbBranch: DbBranchOptions | boolean | undefined,\n): DbBranchSettings | undefined {\n if (!dbBranch || dbBranch === true) {\n return undefined\n }\n const { minCu, maxCu, warmupSql } = dbBranch\n const settings: DbBranchSettings = {\n ...(minCu === undefined ? {} : { minCu }),\n ...(maxCu === undefined ? {} : { maxCu }),\n ...(warmupSql === undefined ? {} : { warmupSql }),\n }\n return Object.keys(settings).length === 0 ? undefined : settings\n}\n\nexport interface ReplayOptions {\n /**\n * Experimental selective replay. Explicit required nodes\n * always execute; eligible output-only nodes reuse JSON recordings only\n * when runtime inputs match. Requires a compatible server, mock: \"marked\",\n * and no mock overrides or resume. Does not infer changes from codeChangeFiles.\n * The server reads active/inherited assertions and protects their scoped\n * execution evidence. Coverage in item.selectiveReplay is not a verdict.\n */\n experimentalSelectiveReplay?: SelectiveReplayOptions\n /**\n * Maximum number of traces to replay (1-5,000, default 5). Ignored when\n * `traceIds` is passed (with a warning), or when `datasetId` / `datasetIds`\n * is passed, because either source already determines how many traces replay.\n * To replay part of a dataset selection, name the members to run in\n * `traceIds` rather than bounding it here.\n */\n limit?: number\n attempts?: number\n /**\n * Optional list of specific trace IDs to replay (max 100). Passed alongside\n * `datasetId` or `datasetIds` it pins which members of that selection replay,\n * and the server rejects any ID none of those datasets contains. On its own\n * it selects by ID with no dataset attribution.\n */\n traceIds?: string[]\n /**\n * What this run is testing, in a few words, such as 'baseline' or 'shorter\n * system prompt'. Bitfab records the commit, branch, tree state, datasets,\n * and who ran it with every experiment, so do not repeat them here.\n */\n name?: string\n /**\n * Run conditions Bitfab cannot see on its own, such as an environment\n * override or a forced feature flag. Kept on the experiment next to its name.\n */\n notes?: string\n metadata?: Record<string, string>\n /** Positive integer limiting parallel items. Set to 1 for sequential. Default 10. */\n maxConcurrency?: number\n /**\n * Description of the code change being tested in this replay. Stored on\n * the resulting experiment so the change can be reviewed alongside results.\n * Supplying a description without `codeChangeFiles` preserves this text\n * while the SDK automatically captures the files.\n * Pass `null` when the replay should have no description; use\n * `codeChangeFiles: null` to suppress automatic file capture.\n */\n codeChangeDescription?: string | null\n /**\n * Files edited as part of this code change. Each entry holds the file path\n * and the full `before`/`after` contents. The agent reads each file before\n * and after editing and passes the two strings. Use `\"\"` for newly created\n * files (`before`) or deleted files (`after`). Omit this field to capture\n * automatically, or pass `null` to suppress file capture for this replay.\n */\n codeChangeFiles?: CodeChangeFile[] | null\n /**\n * Mock strategy for child spans during replay.\n * - \"marked\": only spans tagged with { mockOnReplay: true } in SpanOptions are mocked (default)\n * - \"none\": everything runs real code\n * - \"all\": every matched recorded child withSpan returns historical output;\n * a missing occurrence fails the replay item closed\n */\n mock?: MockStrategy\n /**\n * Selective mock overrides: inject custom values into specific spans during\n * replay, so downstream real code runs against the substituted output. Each\n * Pass `{ match, value }` pairs, or one resolver invoked for every child span.\n * A resolver can route on `ctx.node.traceFunctionKey` and return\n * `NO_MOCK_OVERRIDE` to continue to the next override and base strategy.\n * Per-call overrides take precedence over registrations on the client.\n */\n mockOverride?: MockOverrideInput | MockOverrideInput[]\n /**\n * Run each item against a database branch restored to the state its source\n * trace saw. Pass `true` to branch with the mirror project's own sizing, or a\n * {@link DbBranchOptions} object to tune how each branch is sized and warmed.\n * `false` and omission leave branching off. Inside `fn`, read the resolved\n * branch with `getCurrentReplayBranch()`.\n *\n * Items whose source trace carried no DB snapshot reference get no branch and\n * use the app's normal database path. Unsafe calls on that path still require\n * replay mocking. An item whose branch was requested but could not be resolved\n * fails instead of running, so replay never silently reports a result that did\n * not use the historical data you asked for.\n */\n dbBranch?: DbBranchOptions | boolean\n /**\n * Experiment group this replay joins, shown together on the experiments\n * page. An ID with no group yet creates the group.\n */\n experimentGroupId?: string\n /**\n * Name for the experiment group in `experimentGroupId`. Applied when this\n * replay creates the group, or when the group exists without a name. A group\n * that already has a name keeps it. Requires `experimentGroupId`.\n */\n experimentGroupName?: string\n /**\n * Dataset this replay runs against. Mutually exclusive with `datasetIds`.\n * Alone it replays the dataset's full membership, and with `traceIds` it\n * replays only those members. When set, the resulting experiment is\n * durably attributed to the dataset (stored on the experiment), so it appears\n * under the dataset's experiments even if the trace lineage can't be\n * reconstructed. Validated server-side against the org.\n */\n datasetId?: string\n datasetIds?: string[]\n /**\n * Graders to attach directly to this experiment, independent of any\n * graders already on the dataset. The resulting experiment is graded by the\n * union of these and the dataset's runnable graders at completion, so use this\n * to grade a single run with a check you don't want to add to the dataset\n * permanently. Each id must be an active/live grader belonging to the same\n * organization and trace function, otherwise the server rejects the replay.\n */\n graderIds?: string[]\n /**\n * Replay only the selected traces that carry at least one approved assertion.\n *\n * Narrows whatever `limit`, `traceIds` or `datasetIds` selected, so a run that\n * measures assertion outcomes does not pay to re-execute traces nothing can\n * grade. The server applies it as part of selection, which is what makes it\n * compose with `limit`: `{ limit: 10, onlyWithAssertions: true }` is the ten\n * most recent traces that HAVE approved assertions, not the ten most recent\n * filtered down to however few do. An archived assertion does not count, and\n * neither does one still awaiting review: a replay is only ever judged\n * against assertions a person has approved, so a trace carrying nothing but\n * drafts has nothing here to measure. A selection that narrows to nothing\n * replays nothing.\n */\n onlyWithAssertions?: boolean\n skipAssertionJudging?: boolean\n judgeAssertions?: boolean\n /**\n * Reshape recorded inputs before they are spread into `fn`.\n *\n * Replay pulls each trace's inputs exactly as they were captured against the\n * function's signature AT TRACE TIME. When the function's shape has since\n * changed (params renamed, reordered, collapsed into an options object, etc.),\n * the recorded inputs no longer line up and `fn(...inputs)` throws. This hook\n * lets a caller map the recorded inputs onto the current signature so replay\n * can still run.\n *\n * Receives the deserialized recorded inputs and a per-trace {@link AdaptContext}\n * (so a table-driven adapter can look up the adapted inputs by `traceId`), and\n * returns the array actually spread into `fn`. The returned array is also what\n * `ReplayItem.input` reports, so the experiment shows what was really run.\n *\n * Runs per item, inside the same try/catch as `fn`: if the adapter throws, the\n * failure is surfaced on that item's `error` rather than crashing the run.\n * Omit it to spread the recorded inputs unchanged.\n */\n adaptInputs?: (inputs: unknown[], ctx: AdaptContext) => unknown[]\n /**\n * Resolve every item's inputs and stop, without calling the function.\n *\n * Selection, span fetch, deserialization, and `adaptInputs` all run, so each\n * item reports the exact arguments the function would have received. Nothing\n * executes and no replay traces are produced, which is the cheap way to check\n * that recorded inputs still fit the current signature. No experiment is\n * created either, so the result's `experimentId` and `experimentUrl` are null\n * and `onExperimentStart` is not called.\n */\n dryRun?: boolean\n /**\n * Called once per item as it finishes, in completion order (not input\n * order), with running totals for the whole run. Use it to render replay\n * progress, for example a terminal progress bar. Replay does not know\n * pass/fail at this point (verdicts are assigned later), so the totals only\n * distinguish items whose function ran (`succeeded`) from items that threw\n * (`errored`).\n *\n * Invoked synchronously right after each item finishes, so keep it cheap. A\n * throwing callback never crashes the run: the error is swallowed so progress\n * UI can't break replay.\n */\n onItemFinish?: (progress: ReplayItemFinishProgress) => void\n /**\n * @deprecated Use {@link onItemFinish}. This compatibility callback receives\n * the same per-item finish events plus the legacy whole-run `\"complete\"`\n * event. It is ignored when `onItemFinish` is also provided.\n */\n onProgress?: (progress: ReplayProgress) => void\n /**\n * Called once when each replay item begins processing, before input loading,\n * mock preparation, database branching, or the customer function runs. Use\n * it with {@link onItemFinish} to distinguish queued items from items that\n * are still in flight. A throwing callback never crashes the run.\n */\n onItemStart?: (progress: ReplayItemStartProgress) => void\n /**\n * Called once, right after the server creates the experiment and before any\n * item runs, with the experiment ID and its dashboard URL. Use it to show\n * where results will appear while the replay is still running. A throwing\n * callback never crashes the run.\n */\n onExperimentStart?: (experiment: ReplayExperiment) => void\n onInterrupt?: (interrupt: ReplayInterrupt) => void\n resume?: string\n force?: boolean\n}\n\nconst REPLAY_OPTION_NAMES = [\n \"experimentalSelectiveReplay\",\n \"limit\",\n \"attempts\",\n \"traceIds\",\n \"name\",\n \"notes\",\n \"metadata\",\n \"maxConcurrency\",\n \"codeChangeDescription\",\n \"codeChangeFiles\",\n \"mock\",\n \"mockOverride\",\n \"dbBranch\",\n \"experimentGroupId\",\n \"experimentGroupName\",\n \"datasetId\",\n \"datasetIds\",\n \"graderIds\",\n \"onlyWithAssertions\",\n \"skipAssertionJudging\",\n \"judgeAssertions\",\n \"adaptInputs\",\n \"dryRun\",\n \"onItemFinish\",\n \"onProgress\",\n \"onItemStart\",\n \"onExperimentStart\",\n \"onInterrupt\",\n \"resume\",\n \"force\",\n] as const satisfies readonly (keyof ReplayOptions)[]\n\nfunction explicitReplayOptions(\n options: ReplayOptions | undefined,\n): Record<string, unknown> {\n const explicit: Record<string, unknown> = {}\n for (const name of REPLAY_OPTION_NAMES) {\n if (options?.[name] !== undefined) {\n explicit[optionFlagName(name)] ??= options[name]\n }\n }\n return explicit\n}\n\n/** The experiment a replay records into, passed to {@link ReplayOptions.onExperimentStart}. */\nexport interface ReplayExperiment {\n /** Experiment ID created for this replay. */\n experimentId: string\n /** Full URL to view the experiment in the dashboard. */\n experimentUrl: string\n}\n\n/** Emitted through {@link ReplayOptions.onItemStart} when a worker starts an item. */\nexport interface ReplayItemStartProgress {\n type: \"started\"\n /** Experiment ID created for this replay. Null for a dry run, which creates none. */\n experimentId: string | null\n /** @deprecated Use {@link experimentId}. Same value. */\n testRunId: string | null\n /** Items whose processing has started so far. */\n started: number\n /** Items that have finished so far, whether they succeeded or errored. */\n completed: number\n /** Total number of items in this replay run. */\n total: number\n /** Of the completed items, how many finished without a code or replay error. */\n succeeded: number\n /** Of the completed items, how many finished with an error. */\n errored: number\n /** The historical trace and span whose replay processing just started. */\n item: {\n originalTraceId: string\n originalSpanId: string\n /** @deprecated alias for `originalTraceId`. */\n sourceTraceId: string\n /** @deprecated alias for `originalSpanId`. */\n sourceSpanId: string\n attempt: number\n }\n}\n\n/** Running totals reported to {@link ReplayOptions.onItemFinish} as replay proceeds. */\nexport interface ReplayItemFinishProgress {\n /** Event kind, omitted for backward-compatible per-item events. */\n type?: \"item\"\n /** Experiment ID created for this replay. Null for a dry run, which creates none. */\n experimentId: string | null\n /** @deprecated Use {@link experimentId}. Same value. */\n testRunId: string | null\n /** Items that have finished so far, whether they succeeded or errored. */\n completed: number\n /** Total number of items in this replay run. */\n total: number\n /** Of the completed items, how many finished without a code or replay error. */\n succeeded: number\n /** Of the completed items, how many have `item.error` set. */\n errored: number\n /**\n * The single item that just finished to produce this event. Field-for-field\n * the same shape and meaning as {@link ReplayItem}, so a progress UI and a\n * final-result UI read one contract. `traceId` is null at this stage (the\n * server replay id arrives at completion), and `tokens` is null for the same\n * reason: the replayed run's usage is aggregated server-side by\n * completeReplay. `durationMs` is how long this item took to replay; the\n * `original*` fields describe the trace it replayed.\n */\n item: ReplayProgressItem\n}\n\n/** See {@link ReplayItemFinishProgress.item}. Mirrors {@link ReplayItem}. */\nexport interface ReplayProgressItem {\n selectiveReplay?: SelectiveReplayReport\n /** Trace ID of the new replay trace (null during the run; the server id arrives at completion). */\n traceId?: string | null\n /** Bitfab trace ID of the original (historical) trace being replayed. */\n originalTraceId: string | null\n /** External span ID the recorded inputs were read from (the original root span). */\n originalSpanId?: string | null\n /** @deprecated alias for `originalTraceId`. */\n sourceTraceId: string | null\n /** @deprecated alias for `originalSpanId`. */\n sourceSpanId?: string | null\n attempt: number\n /** Deserialized inputs from the original trace. */\n input?: unknown[]\n /** The result returned by the replayed function, or undefined on error. */\n result?: unknown\n /** The original output from the historical trace. */\n originalOutput?: unknown\n /** Backward-compatible message for either error kind. */\n error: string | null\n /** The actual value thrown by the replayed customer function. */\n traceError?: unknown | null\n /** The actual value thrown while Bitfab prepared this replay item. */\n replayError?: unknown | null\n /** How long the replayed function took on this run. */\n durationMs?: number | null\n /** The original trace's duration, tokens, and model. */\n originalDurationMs?: number | null\n originalTokens?: TokenUsage | null\n originalModel?: string | null\n ingestionType?: TraceIngestionType\n /** Always null here: the replayed run's usage is only known at completion. */\n tokens?: TokenUsage | null\n /** @deprecated renamed to `originalModel`. */\n model?: string | null\n dbSnapshotRef?: DbSnapshotRef | null\n dbBranchTimings?: DbBranchTimings | null\n}\n\n/**\n * @deprecated Use {@link ReplayItemFinishProgress}. This legacy shape also\n * represents the item-less terminal `\"complete\"` event emitted by\n * {@link ReplayOptions.onProgress}.\n */\nexport interface ReplayProgress {\n type?: \"item\" | \"complete\"\n result?: ReplayResult<unknown>\n /** Null for a dry run, which creates no experiment. */\n experimentId?: string | null\n /** @deprecated Use {@link experimentId}. Same value. */\n testRunId?: string | null\n completed: number\n total: number\n succeeded: number\n errored: number\n item?: ReplayItemFinishProgress[\"item\"]\n}\n\n/**\n * Wire prefix the Bitfab plugin scans for. Each line {@link reportReplayProgress}\n * writes is this prefix followed by the JSON of the running totals (plus the\n * finished `item`). The plugin polls these lines to report live progress while a\n * replay runs in the background; keep the SDK emitter and the plugin parser in\n * sync.\n */\nexport const BITFAB_PROGRESS_PREFIX = \"@@bitfab:progress \"\n\n/**\n * A ready-made replay lifecycle callback for replay scripts.\n * Pass it straight in:\n *\n * ```ts\n * await bitfab.replay(\"my-fn\", fn, {\n * limit,\n * onItemStart: reportReplayProgress,\n * onItemFinish: reportReplayProgress,\n * })\n * ```\n *\n * It writes `@@bitfab:progress` lines to stderr, which the Bitfab plugin polls\n * to report in-flight and finished items while replay runs in the background,\n * so scripts never hand-format the wire protocol.\n * stdout is left untouched for direct-run ReplayResult JSON. Outside Node (no\n * `process.stderr`, e.g. a browser) it is a no-op, and a write failure is\n * swallowed so progress can never crash a run.\n */\nexport function reportReplayProgress(\n progress: ReplayItemFinishProgress | ReplayItemStartProgress | ReplayProgress,\n): void {\n const stderr = typeof process !== \"undefined\" ? process.stderr : undefined\n if (!stderr) {\n return\n }\n try {\n stderr.write(\n `${BITFAB_PROGRESS_PREFIX}${JSON.stringify(progress, replayJsonReplacer)}\\n`,\n )\n } catch {\n // A progress reporter must never crash the replay run.\n }\n}\n\n/** Per-trace context passed to {@link ReplayOptions.adaptInputs}. */\nexport interface AdaptContext {\n /** Bitfab trace ID of the original (historical) trace being replayed. */\n originalTraceId: string\n /** External span ID the recorded inputs were read from. */\n originalSpanId: string\n /** @deprecated alias for {@link AdaptContext.originalTraceId}. */\n sourceTraceId: string\n /** @deprecated alias for {@link AdaptContext.originalSpanId}. */\n sourceSpanId: string\n metadata: Record<string, unknown>\n}\n\n/**\n * The shape an adapter module must export as `adaptInputs`.\n *\n * Author an adapter in its own file (e.g. `scripts/replay-adapters/<name>.ts`),\n * import it in your replay script, and pass it to `replay({ adaptInputs })`:\n *\n * ```ts\n * import type { AdaptInputsFn } from \"@bitfab/sdk\"\n * export const adaptInputs: AdaptInputsFn = (inputs, ctx) => [reshape(inputs)]\n * ```\n */\nexport type AdaptInputsFn = (inputs: unknown[], ctx: AdaptContext) => unknown[]\n\nexport interface ReplayItem<T> {\n /** Decisions and changed-code coverage for experimental selective replay. */\n selectiveReplay?: SelectiveReplayReport\n /**\n * Server trace ID of the new replay trace this item produced. Written in by\n * `replay()` from the complete-replay response once the server has minted the\n * trace row; the client-side id used to correlate spans during the run is\n * never surfaced here. Null until completion, on older servers that omit the\n * mapping, or if the item produced no trace. Not the verdict-persistence key:\n * that is the original-trace lineage (`originalTraceId` + `experimentId`).\n */\n traceId: string | null\n /** Bitfab trace ID of the original (historical) trace being replayed. */\n originalTraceId: string\n /** External span ID the recorded inputs were read from (the original root span). */\n originalSpanId: string\n /** @deprecated alias for {@link ReplayItem.originalTraceId}. */\n sourceTraceId: string\n /** @deprecated alias for {@link ReplayItem.originalSpanId}. */\n sourceSpanId: string\n attempt: number\n /** Deserialized inputs from the original trace. */\n input: unknown[]\n /** The result returned by the function during replay, or undefined on error. */\n result: T | undefined\n originalOutput: unknown\n /**\n * How the source trace came to exist. Absent on servers that predate the\n * field, which only ever served captured traces.\n */\n ingestionType?: TraceIngestionType\n /**\n * Backward-compatible message for either error kind. Prefer `traceError` and\n * `replayError` when callers need the original exception and its source.\n */\n error: string | null\n /** The actual value thrown by the replayed customer function. */\n traceError: unknown | null\n /**\n * The actual value thrown by replay setup before the customer function ran,\n * such as database warmup, input hydration, or mock preparation.\n */\n replayError: unknown | null\n /**\n * How long the replayed function took on this run, in ms. Null if the item\n * failed before it ran. Compare against\n * {@link ReplayItem.originalDurationMs} for the before/after.\n */\n durationMs: number | null\n /** The original trace's duration in ms, or null if its timestamps are missing. */\n originalDurationMs: number | null\n /**\n * Token usage recorded on the original trace, or null if it captured none.\n * The \"old\" side of a token delta; {@link ReplayItem.tokens} is the new one.\n */\n originalTokens: TokenUsage | null\n /** Model name from the original trace, or null if not captured. */\n originalModel: string | null\n /**\n * Token usage from the REPLAYED run (this item's new execution), aggregated\n * server-side from the spans it produced, or null if the run captured no\n * token data. Compare against {@link ReplayItem.originalTokens} to see how\n * the code change moved cost. Matches what the experiments page shows.\n *\n * Unprefixed because the replay is this item's subject: anything describing\n * the trace being replayed carries `original`.\n */\n tokens: TokenUsage | null\n /** @deprecated renamed to {@link ReplayItem.originalModel}. */\n model: string | null\n /**\n * The DB snapshot ref the SDK captured at trace open. Useful for debugging\n * (\"what state was this trace pinned to?\") and for customers building\n * their own resolvers. Undefined when the source trace was captured\n * without `dbSnapshot` configured.\n */\n dbSnapshotRef: DbSnapshotRef | null\n /**\n * How long this item's DB branch took to provision, per phase, measured\n * server-side. Present whenever a branch was attempted, on both outcomes:\n * complete on success, partial up to the failing phase when the resolve\n * failed. Null when no branch was asked for, when the source trace carried\n * no snapshot ref, or against a server that predates timings.\n */\n dbBranchTimings: DbBranchTimings | null\n carriedOver?: boolean\n}\n\nexport type { CodeChangeFile, TokenUsage }\n\nexport interface ReplayResult<T> {\n /** Individual replay items with inputs, results, and comparison data. */\n items: ReplayItem<T>[]\n /**\n * The experiment ID created on the server. Null for a dry run, which\n * executes nothing and so creates no experiment.\n */\n experimentId: string | null\n /** Full URL to view the experiment in the dashboard. Null for a dry run. */\n experimentUrl: string | null\n /** @deprecated Use {@link experimentId}. Same value. */\n testRunId: string | null\n /** @deprecated Use {@link experimentUrl}. Same value. */\n testRunUrl: string | null\n attempts: number\n}\n\n/**\n * Whole-run replay failure that preserves every item collected before the run\n * failed. The original whole-run exception is available as `cause`.\n */\nexport class ReplayError<T = unknown> extends BitfabError {\n /** @deprecated Use {@link experimentId}. Same value. */\n public readonly testRunId: string\n /** @deprecated Use {@link experimentUrl}. Same value. */\n public readonly testRunUrl: string\n\n constructor(\n message: string,\n public readonly items: ReplayItem<T>[],\n public readonly experimentId: string,\n public readonly experimentUrl: string,\n public readonly cause: unknown,\n ) {\n super(message, experimentUrl)\n this.name = \"ReplayError\"\n this.testRunId = experimentId\n this.testRunUrl = experimentUrl\n }\n}\n\n/**\n * A database branch requested for one replay item could not be resolved.\n *\n * The server's resolver code and message are retained as structured fields so\n * callers can handle failures such as `branch_create_failed` and\n * `snapshot_from_replaced_origin` without parsing the compatible `item.error`\n * string.\n */\nexport class DbBranchReplayError extends BitfabError {\n constructor(\n public readonly code: string,\n message: string,\n public readonly originalTraceId: string,\n public readonly cause?: unknown,\n ) {\n super(message)\n this.name = \"DbBranchReplayError\"\n }\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction replayItemErrorMessage(error: unknown): string {\n if (error instanceof DbBranchReplayError) {\n return `Replay requested a database branch for trace ${error.originalTraceId} but it could not be resolved (${error.code}): ${error.message}. The function was not run, because replaying it against the live database would produce a result that looks valid but did not use the historical data you asked for.`\n }\n return errorMessage(error)\n}\n\nfunction replayJsonReplacer(_key: string, value: unknown): unknown {\n if (value instanceof Error) {\n const serialized: Record<string, unknown> = {\n name: value.name,\n message: value.message,\n stack: value.stack,\n }\n if (value instanceof DbBranchReplayError) {\n serialized.code = value.code\n serialized.originalTraceId = value.originalTraceId\n if (value.cause !== undefined) {\n serialized.cause = value.cause\n }\n }\n return serialized\n }\n return value\n}\n\n/**\n * Serialize a replay result as JSON while retaining structured trace and replay\n * errors. Use this for direct-run stdout instead of raw `JSON.stringify`, which\n * drops the useful fields on JavaScript `Error` objects.\n */\nexport function serializeReplayResult<T>(result: ReplayResult<T>): string {\n return JSON.stringify(result, replayJsonReplacer, 2)\n}\n\nasync function preserveReplayFailure<T, TItem>(\n operation: () => Promise<T>,\n items: ReplayItem<TItem>[],\n experimentId: string,\n experimentUrl: string,\n): Promise<T> {\n try {\n return await operation()\n } catch (cause) {\n if (cause instanceof ReplayError) {\n throw cause\n }\n throw new ReplayError(\n errorMessage(cause),\n items,\n experimentId,\n experimentUrl,\n cause,\n )\n }\n}\n\n/**\n * Deserialize inputs from a historical span's rawData.\n *\n * Prefers superjson-serialized `input_meta` for type preservation,\n * falls back to the raw `input` field.\n */\nexport function deserializeInputs(\n spanData: Record<string, unknown>,\n): unknown[] {\n const inputMeta = spanData.input_meta as unknown\n const rawInput = spanData.input\n\n // If superjson meta is available, deserialize with type reconstruction\n if (inputMeta !== undefined && inputMeta !== null) {\n const deserialized = deserializeValue({ json: rawInput, meta: inputMeta })\n if (Array.isArray(deserialized)) {\n return deserialized\n }\n return deserialized !== undefined && deserialized !== null\n ? [deserialized]\n : []\n }\n\n // Fall back to raw input\n if (Array.isArray(rawInput)) {\n return rawInput\n }\n return rawInput !== undefined && rawInput !== null ? [rawInput] : []\n}\n\n/**\n * Deserialize the original output from a historical span's rawData.\n */\nfunction deserializeOutput(spanData: Record<string, unknown>): unknown {\n const outputMeta = spanData.output_meta as unknown\n const rawOutput = spanData.output\n\n if (outputMeta !== undefined && outputMeta !== null) {\n return deserializeValue({ json: rawOutput, meta: outputMeta })\n }\n\n return rawOutput\n}\n\n/**\n * Walk the children of a root span tree node in depth-first order and build\n * a MockTree keyed by `${traceFunctionKey}:${spanName}:${callIndex}`.\n *\n * The historical root itself is NOT walked. At replay time the runtime root\n * span has `isRootSpan === true` and never queries the mockTree (mock\n * interception is skipped for root spans by design), so the root has nothing\n * to look up. Walking it would just leave an unreachable entry in the table.\n *\n * The (key, name) compound match is what disambiguates same-key spans:\n * - A wrapped function's children commonly share its traceFunctionKey via\n * the fluent `getFunction(key).withSpan({ name }, ...)` pattern. They\n * disambiguate by `name`, never colliding with each other.\n * - Recursion: same (key, name) at every depth. callIndex per (key, name)\n * orders them correctly without leaking the historical root into the\n * nested call's slot.\n * - Outer-wrapper replay scripts: the outer wrapper's `name` is distinct\n * from anything in the historical tree (it only exists at replay), so\n * its presence never disturbs counters or lookups for spans that do\n * exist in the historical tree.\n */\nfunction buildMockTree(rootNode: SpanTreeNode): MockTree {\n const spans = new Map<string, MockSpan>()\n const counters = new Map<string, number>()\n\n function walk(node: SpanTreeNode): void {\n const key = node.traceFunctionKey\n if (key) {\n const name = node.spanName || key\n const counterKey = `${key}:${name}`\n const index = counters.get(counterKey) ?? 0\n counters.set(counterKey, index + 1)\n // `output`/`outputMeta` are undefined on a payload-free (lazy) tree;\n // `externalSpanId` is what the lazy path fetches them by. Both are copied\n // verbatim so eager and lazy trees build through the same walk.\n spans.set(`${counterKey}:${index}`, {\n sourceSpanId: node.sourceSpanId,\n externalSpanId: node.externalSpanId,\n output: node.output,\n outputMeta: node.outputMeta,\n })\n }\n for (const child of node.children) {\n walk(child)\n }\n }\n\n for (const child of rootNode.children) {\n walk(child)\n }\n\n return { spans }\n}\n\n/**\n * Execute a single replay item: fetch span data, deserialize inputs, call\n * the function within a replay context that injects experimentId into new spans.\n */\nasync function processItem<TReturn>(\n httpClient: HttpClient,\n serverItem: {\n originalTraceId?: string\n originalSpanId?: string\n /** @deprecated alias emitted by servers that predate the originalTraceId rename. */\n sourceTraceId: string\n /** @deprecated alias emitted by servers that predate the originalSpanId rename. */\n sourceSpanId: string\n originalDurationMs?: number | null\n originalTokens?: TokenUsage | null\n originalModel?: string | null\n originalMetadata?: Record<string, unknown>\n selectiveReplayPlan?: SelectiveReplayPlan\n ingestionType?: TraceIngestionType\n /** @deprecated unprefixed aliases emitted by servers that predate the rename.\n * `tokens` here is the ORIGINAL trace's usage: the start item has never\n * carried the replay's, which only exists after completeReplay. */\n durationMs: number | null\n tokens?: TokenUsage | null\n model: string | null\n dbSnapshotRef?: DbSnapshotRef\n dbBranchLease?: DbBranchLease\n dbBranchLeaseError?: { code: string; message: string }\n dbBranchTimings?: DbBranchTimings\n },\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n experimentId: string | null,\n mockStrategy: MockStrategy,\n resolvedOverrides: MockOverride[],\n replayedTraceId: string,\n attempt: number,\n includeDbBranchLease: boolean,\n dbBranchSettings: DbBranchSettings | undefined,\n adaptInputs:\n | ((inputs: unknown[], ctx: AdaptContext) => unknown[])\n | undefined,\n dryRun: boolean,\n selectiveOptions?: SelectiveReplayOptions,\n): Promise<ReplayItem<TReturn>> {\n // The server-side resolver materializes a Neon preview branch per item\n // during `/api/sdk/replay/start` (when the customer passed `dbBranch`,\n // which triggers `includeDbBranchLease: true`). The lease arrives on the\n // server item; we just attach it to the replay context and release the\n // branch in `finally` so any throw (in fetch, mock-tree build, or the\n // customer fn) frees the Neon resource. Items whose source trace had no\n // snapshot ref arrive without a lease; `getCurrentReplayBranch()` returns\n // null for those, and the app uses its normal DB path. Unsafe calls on that\n // path still require replay mocking.\n let lease = includeDbBranchLease ? serverItem.dbBranchLease : undefined\n // A resolve that was attempted and FAILED is different: the caller asked for\n // a branch, so running their function against live data would produce a\n // result that looks valid and isn't. Fail this item instead, loudly.\n let leaseError = includeDbBranchLease\n ? serverItem.dbBranchLeaseError\n : undefined\n let dbSnapshotRef = serverItem.dbSnapshotRef\n // Reported whichever way the resolve went, so it is tracked separately from\n // both the lease and the error rather than hanging off either.\n let dbBranchTimings = includeDbBranchLease\n ? serverItem.dbBranchTimings\n : undefined\n\n let inputs: unknown[] = []\n let originalOutput: unknown\n let result: TReturn | undefined\n let error: string | null = null\n let traceError: unknown | null = null\n let replayError: unknown | null = null\n // Timed around the replayed function only, so it is comparable to\n // originalDurationMs (that same function's wall time on the original run)\n // rather than to the span fetches and persistence around it.\n let replayDurationMs: number | null = null\n // Null until the replayed function actually starts, so an item that fails in\n // the span fetch or mock-tree build reports no replay duration rather than\n // timing work that was not the function.\n let replayStarted: number | null = null\n let selectiveReplay: SelectiveReplayRuntime | undefined\n\n // The ORIGINAL (historical) trace/span this item replays. Canonical server\n // keys are originalTraceId/originalSpanId; older servers only send the\n // deprecated sourceTraceId/sourceSpanId aliases.\n const originalTraceId = serverItem.originalTraceId ?? serverItem.sourceTraceId\n const originalSpanId = serverItem.originalSpanId ?? serverItem.sourceSpanId\n\n try {\n if (\n includeDbBranchLease &&\n experimentId !== null &&\n !lease &&\n !leaseError\n ) {\n let resolved: Awaited<ReturnType<HttpClient[\"resolveDbBranchLease\"]>>\n try {\n resolved = await httpClient.resolveDbBranchLease(\n experimentId,\n originalTraceId,\n dbBranchSettings,\n attempt,\n )\n } catch (cause) {\n throw new DbBranchReplayError(\n \"lease_request_failed\",\n `Bitfab could not request the database branch: ${errorMessage(cause)}`,\n originalTraceId,\n cause,\n )\n }\n lease = resolved.lease ?? undefined\n leaseError = resolved.leaseError ?? undefined\n dbSnapshotRef = resolved.dbSnapshotRef ?? dbSnapshotRef\n dbBranchTimings = resolved.timings ?? dbBranchTimings\n }\n\n if (leaseError) {\n throw new DbBranchReplayError(\n leaseError.code,\n leaseError.message,\n originalTraceId,\n )\n }\n\n if (selectiveOptions !== undefined) {\n if (serverItem.selectiveReplayPlan === undefined) {\n throw new BitfabError(\n \"Server did not return a selective replay plan. Update the server or disable experimentalSelectiveReplay.\",\n )\n }\n selectiveReplay = new SelectiveReplayRuntime(\n serverItem.selectiveReplayPlan,\n selectiveOptions,\n )\n }\n\n const span = await httpClient.getExternalSpan(originalSpanId, {\n view: \"replay\",\n })\n const spanData = (span.rawData?.span_data ?? {}) as Record<string, unknown>\n\n inputs = deserializeInputs(spanData)\n originalOutput = deserializeOutput(spanData)\n const integrationFixtures = extractIntegrationFixtures(spanData)\n\n // Reshape the recorded inputs onto the current signature when an adapter\n // is supplied. Runs before the mock tree / fn call so the adapted array is\n // what fn receives and what `item.input` reports.\n if (adaptInputs) {\n const originalMetadata = serverItem.originalMetadata\n inputs = adaptInputs(inputs, {\n originalTraceId,\n originalSpanId,\n // Deprecated aliases for originalTraceId/originalSpanId.\n sourceTraceId: originalTraceId,\n sourceSpanId: originalSpanId,\n metadata: isPlainRecord(originalMetadata)\n ? { ...originalMetadata }\n : {},\n })\n }\n\n // Build the mock tree whenever mocking could apply: any non-\"none\" strategy,\n // OR overrides are present (overrides substitute even under \"none\" - the\n // \"run real code but replace node X\" case). Only \"all\" needs outputs inline;\n // Non-\"all\" runs that need a tree (\"marked\", or \"none\" with overrides)\n // keep it payload-free and pull outputs lazily, so we never drag down every\n // span's recorded output when only a few get mocked.\n const hasOverrides = resolvedOverrides.length > 0\n const needTree =\n selectiveReplay === undefined &&\n (mockStrategy === \"all\" || mockStrategy === \"marked\" || hasOverrides)\n const includeOutputs = mockStrategy === \"all\"\n\n let mockTree: MockTree | undefined\n if (needTree) {\n try {\n const treeResponse = await httpClient.getSpanTree(originalSpanId, {\n includeOutputs,\n includeRootOutput: false,\n })\n if (!treeResponse.root) {\n throw new BitfabError(\n `Replay mock strategy \"${mockStrategy}\"${hasOverrides ? \" with overrides\" : \"\"} requires a span tree root for original span ${originalSpanId}.`,\n )\n }\n mockTree = buildMockTree(treeResponse.root)\n } catch (error) {\n if (mockStrategy !== \"marked\" || hasOverrides) {\n throw error\n }\n // The root still runs under \"marked\". An empty active tree lets an\n // unmarked-only root proceed, while any selected child fails closed at\n // its call site instead of executing the real span.\n mockTree = { spans: new Map() }\n }\n }\n\n // Lazy per-span output fetch, memoized per item so a span read twice (once\n // as a marked mock, once via an override's getOriginalOutput) fetches once.\n // Present only when outputs were NOT fetched inline (not the eager \"all\"\n // path); its presence signals the mock path to fetch on demand.\n const outputCache = new Map<string, Promise<unknown>>()\n const fetchSpanOutput =\n mockTree && !includeOutputs\n ? (externalSpanId: string): Promise<unknown> => {\n let pending = outputCache.get(externalSpanId)\n if (!pending) {\n pending = httpClient\n .getExternalSpan(externalSpanId, { view: \"replay\" })\n .then((s) =>\n deserializeOutput(\n (s.rawData?.span_data ?? {}) as Record<string, unknown>,\n ),\n )\n outputCache.set(externalSpanId, pending)\n }\n return pending\n }\n : undefined\n\n if (dryRun || experimentId === null) {\n return {\n traceId: null,\n originalTraceId,\n originalSpanId,\n sourceTraceId: originalTraceId,\n sourceSpanId: originalSpanId,\n attempt,\n input: inputs,\n result: undefined,\n originalOutput,\n ...(serverItem.ingestionType && {\n ingestionType: serverItem.ingestionType,\n }),\n error: null,\n traceError: null,\n replayError: null,\n durationMs: null,\n originalDurationMs:\n serverItem.originalDurationMs ?? serverItem.durationMs ?? null,\n originalTokens: serverItem.originalTokens ?? serverItem.tokens ?? null,\n originalModel: serverItem.originalModel ?? serverItem.model ?? null,\n tokens: null,\n model: serverItem.originalModel ?? serverItem.model ?? null,\n dbSnapshotRef: dbSnapshotRef ?? null,\n dbBranchTimings: dbBranchTimings ?? null,\n }\n }\n\n try {\n replayStarted = performance.now()\n const maybePromise = runWithReplayContext(\n {\n experimentId,\n traceId: replayedTraceId,\n inputSourceSpanId: span.id,\n inputSourceTraceId: span.externalTraceId,\n sourceBitfabTraceId: originalTraceId,\n replayAttempt: attempt,\n mockTree,\n selectiveReplay,\n callCounters: mockTree ? new Map() : undefined,\n mockStrategy,\n mockOverrides: hasOverrides ? resolvedOverrides : undefined,\n fetchSpanOutput,\n integrationFixtures,\n dbBranchLease: lease,\n dbBranchTimings,\n },\n () => fn(...inputs),\n )\n result =\n maybePromise instanceof Promise ? await maybePromise : maybePromise\n selectiveReplay?.assertNoSafetyConflict()\n replayDurationMs = Math.round(performance.now() - replayStarted)\n } catch (e) {\n // The function ran and threw, so it still has a duration worth reporting.\n if (replayStarted !== null) {\n replayDurationMs = Math.round(performance.now() - replayStarted)\n }\n traceError = e\n error = errorMessage(e)\n }\n } catch (e) {\n // Replay setup failed. replayStarted is null unless the customer function\n // had already begun, so this leaves durationMs null for a genuine\n // setup failure rather than timing work that was not the function.\n if (replayStarted !== null) {\n replayDurationMs = Math.round(performance.now() - replayStarted)\n }\n replayError = e\n error = replayItemErrorMessage(e)\n } finally {\n if (lease) {\n try {\n await httpClient.releaseDbBranchLease(lease.neonBranchId)\n } catch (e) {\n try {\n console.warn(\n `Bitfab: failed to release DB branch ${lease.neonBranchId} (TTL janitor will catch it): ${\n e instanceof Error ? e.message : String(e)\n }`,\n )\n } catch {\n // Never crash the host\n }\n }\n }\n }\n\n // Canonical names first, falling back to the unprefixed ones a server that\n // predates the rename sends.\n const originalDurationMs =\n serverItem.originalDurationMs ?? serverItem.durationMs ?? null\n const originalModel = serverItem.originalModel ?? serverItem.model ?? null\n return {\n // Written in by replay() from the complete-replay response once the server\n // has minted this replay trace's row. Null until then: the client-side\n // correlation id (replayedTraceId) is never surfaced as the item's traceId.\n traceId: null,\n originalTraceId,\n originalSpanId,\n // Deprecated aliases for originalTraceId/originalSpanId.\n sourceTraceId: originalTraceId,\n sourceSpanId: originalSpanId,\n attempt,\n input: inputs,\n result,\n originalOutput,\n ...(serverItem.ingestionType && {\n ingestionType: serverItem.ingestionType,\n }),\n error,\n traceError,\n replayError,\n durationMs: replayDurationMs,\n ...(selectiveReplay === undefined\n ? {}\n : { selectiveReplay: selectiveReplay.report() }),\n originalDurationMs,\n originalTokens: serverItem.originalTokens ?? serverItem.tokens ?? null,\n originalModel,\n // Filled in by replay() from the complete-replay response once the\n // replay traces are persisted and their spans aggregated server-side.\n // Null here (and on older servers) means \"replay tokens not known\".\n tokens: null,\n model: originalModel,\n dbSnapshotRef: dbSnapshotRef ?? null,\n dbBranchTimings: dbBranchTimings ?? null,\n }\n}\n\n/**\n * Block until the server has fully persisted every replay trace this run\n * submitted, or warn about each one it never confirmed and carry on.\n *\n * `completeReplay` reads at a single instant: it mints the trace-ID mapping and\n * aggregates each trace's tokens from its spans. Run it while spans are still\n * in flight and `item.traceId` comes back null with undercounted tokens.\n *\n * In the normal case the verdict is local: ingestion commits a request's\n * carriers before it answers, so a flush that delivered every carrier has\n * already proven the traces are whole and polling only asked the server to\n * repeat itself. Acks cannot settle a request that timed out client-side after\n * the server committed, so anything short of fully delivered falls through to\n * the server poll, which stays the authority there.\n */\nexport async function waitForReplayPersistence(\n httpClient: HttpClient,\n experimentId: string,\n replayedTraceIds: string[],\n replayLabels: Record<string, string> = {},\n warn: (line: string) => void = console.warn,\n): Promise<Record<string, string>> {\n // Settle deferred submissions before counting. A `finalize` root span only\n // reaches the transport once its finalize chain resolves, so tallying first\n // would under-count and let the barrier pass on a trace that is still short.\n // This waits for that work WITHOUT flushing: a run that submitted nothing\n // must not emit an export request just to discover it has nothing to wait on.\n const deferredSettled = await httpClient.settleDeferredWork(\n REPLAY_PERSISTENCE_TIMEOUT_MS,\n )\n\n // Checked BEFORE the tally: deferred work that never landed means no\n // completion may have registered at all, and an empty tally would then look\n // like \"nothing to wait for\" and finalize the run with root spans pending.\n if (!deferredSettled) {\n // Freed before throwing: every other exit releases these, and a retained\n // record would carry this run's submitted-but-unacked spans into the next\n // replay of the same trace ids.\n httpClient.takeTraceDeliveries(replayedTraceIds)\n throw new BitfabError(\n `Replay could not settle deferred span work before the deadline, so the ` +\n `expected span counts are incomplete (experiment ${experimentId}).`,\n )\n }\n\n // Peeked before flushing: a run whose traces never closed submitted nothing\n // to wait on, and must not emit an export request just to discover that.\n if (!httpClient.hasClosedDeliveries(replayedTraceIds)) {\n httpClient.takeTraceDeliveries(replayedTraceIds)\n return {}\n }\n\n // A failed flush is a hint, not a verdict. It means delivery was not\n // CONFIRMED within the deadline, which is not the same as lost: the export\n // timeout can fire while requests are still in flight and the server goes on\n // to persist every one of them. Throwing here failed runs whose data had\n // fully landed.\n const flushed = await flushTraces(REPLAY_PERSISTENCE_TIMEOUT_MS)\n\n const deliveries = httpClient.takeTraceDeliveries(replayedTraceIds)\n const expectedSpanCounts: Record<string, number> = {}\n const readBackTraceIds: Record<string, string> = {}\n let allDelivered = true\n for (const [traceId, delivery] of Object.entries(deliveries)) {\n if (delivery.serverTraceId !== undefined) {\n readBackTraceIds[traceId] = delivery.serverTraceId\n }\n if (!delivery.closed) {\n continue\n }\n expectedSpanCounts[traceId] = delivery.spanCount\n allDelivered = allDelivered && delivery.delivered\n }\n if (allDelivered) {\n return readBackTraceIds\n }\n\n // Unacked is not unpersisted: a request that timed out client-side may have\n // committed anyway, and an export the flush deadline abandoned may still be\n // in flight. Neither is knowable here, so from this point the server is the\n // only authority and the run polls it until it answers or the budget ends.\n //\n // The poll gets its own budget. Sharing one deadline with the flush meant a\n // flush that used it all left zero polling window, so the barrier failed\n // after a single not-ready answer - exactly the case where the export is\n // still in flight and about to persist.\n const deadline = Date.now() + REPLAY_PERSISTENCE_TIMEOUT_MS\n\n let missing = Object.keys(expectedSpanCounts)\n while (true) {\n const status = await httpClient.getReplayStatus(\n experimentId,\n expectedSpanCounts,\n )\n const ready = status.traceIds ?? {}\n Object.assign(readBackTraceIds, ready)\n missing = Object.keys(expectedSpanCounts).filter(\n (traceId) => ready[traceId] === undefined,\n )\n if (missing.length === 0) {\n return readBackTraceIds\n }\n if (Date.now() >= deadline) {\n break\n }\n await sleepForReplayPersistence(\n Math.min(100, Math.max(0, deadline - Date.now())),\n )\n }\n\n for (const traceId of missing) {\n warn(\n unconfirmedReplayWarning(\n replayLabels[traceId] ?? traceId,\n REPLAY_PERSISTENCE_TIMEOUT_MS / 1000,\n flushed,\n ),\n )\n }\n return readBackTraceIds\n}\n\nfunction unconfirmedReplayWarning(\n label: string,\n seconds: number,\n flushed: boolean,\n): string {\n return (\n `[bitfab] replay ${label} could not confirm all spans reached Bitfab ` +\n `within ${seconds}s. The run continues; Bitfab will show this replay as ` +\n `capture incomplete.${flushed ? \"\" : \" Some spans likely never left this process.\"}`\n )\n}\n\n/** @internal Wait between replay persistence polls without releasing Node. */\nexport function sleepForReplayPersistence(ms: number): Promise<void> {\n return new Promise((resolve) => {\n // This timer is part of an awaited persistence barrier. It must keep a CLI\n // process alive until the server confirms the replay or the deadline fires.\n setTimeout(resolve, ms)\n })\n}\n\nasync function mapWithConcurrency<T>(\n tasks: Array<() => Promise<T>>,\n maxConcurrency: number,\n onSettled?: (result: T, index: number) => void | Promise<void>,\n onStarted?: (index: number) => void,\n shouldStop?: () => boolean,\n): Promise<T[]> {\n const results: T[] = new Array(tasks.length)\n let nextIndex = 0\n\n async function worker(): Promise<void> {\n while (nextIndex < tasks.length && shouldStop?.() !== true) {\n const index = nextIndex++\n onStarted?.(index)\n const result = await tasks[index]()\n results[index] = result\n await onSettled?.(result, index)\n }\n }\n\n const workers = Array.from(\n { length: Math.min(maxConcurrency, tasks.length) },\n () => worker(),\n )\n await Promise.all(workers)\n return results.slice(0, nextIndex)\n}\n\nexport const JUDGE_ASSERTIONS_DEPRECATION_WARNING =\n \"Bitfab: judgeAssertions is deprecated. Assertion judging is on by default; pass skipAssertionJudging: true (--skip-assertion-judging) to turn it off.\"\n\nexport function warnJudgeAssertionsDeprecated(\n write: (line: string) => void = console.warn,\n): void {\n writeOnce(\n \"judgeAssertions-deprecated\",\n JUDGE_ASSERTIONS_DEPRECATION_WARNING,\n write,\n )\n}\n\n/**\n * Replay historical traces through a function and create an experiment.\n *\n * @internal Called by Bitfab.replay, not part of the public API.\n */\nexport async function replay<TReturn>(\n httpClient: HttpClient,\n serviceUrl: string,\n traceFunctionKey: string,\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n options?: ReplayOptions,\n registeredOverrides: MockOverride[] = [],\n): Promise<ReplayResult<TReturn>> {\n if (options?.judgeAssertions !== undefined) {\n warnJudgeAssertionsDeprecated()\n }\n if (options?.resume !== undefined) {\n validateResume(options.resume, options)\n } else if (options?.force === true) {\n throw new BitfabError(\n \"force only applies when resuming an experiment. Pass it together with resume.\",\n )\n }\n if (\n options?.experimentGroupName !== undefined &&\n options.experimentGroupId === undefined\n ) {\n throw new BitfabError(\n \"experimentGroupName only applies with experimentGroupId. Pass it together with experimentGroupId.\",\n )\n }\n if (options?.experimentalSelectiveReplay !== undefined) {\n validateSelectiveReplayOptions(options.experimentalSelectiveReplay)\n if (\n (options.mock ?? \"marked\") !== \"marked\" ||\n normalizeMockOverrides(options.mockOverride).length > 0 ||\n registeredOverrides.length > 0\n ) {\n throw new BitfabError(\n \"experimentalSelectiveReplay requires mock: 'marked' and cannot be combined with mock overrides.\",\n )\n }\n }\n if (options?.traceIds !== undefined) {\n if (options.traceIds.length === 0) {\n throw new BitfabError(\"traceIds must contain at least one trace ID.\")\n }\n if (options.traceIds.length > 100) {\n throw new BitfabError(\n `traceIds supports at most 100 trace IDs per replay (got ${options.traceIds.length}).`,\n )\n }\n }\n const datasetIds = resolveDatasetIds(options)\n if (options?.limit !== undefined && options?.traceIds !== undefined) {\n try {\n console.warn(\n \"Bitfab: limit is ignored when traceIds is passed: the explicit trace ID list already determines how many traces replay.\",\n )\n } catch {\n // Never crash the host app\n }\n }\n const requestedAttempts = resolveAttempts(options?.attempts)\n const maxConcurrency = options?.maxConcurrency ?? 10\n if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1) {\n throw new BitfabError(\n `maxConcurrency must be a positive integer (got ${maxConcurrency}).`,\n )\n }\n await replayContextReady\n\n // Resolve the code change to attach to this experiment. codeChangeFiles is\n // the capture control: omitted auto-captures, an array wins, and null opts\n // out. A caller-supplied description is preserved when files are captured.\n let codeChangeDescription = options?.codeChangeDescription\n let codeChangeFiles = options?.codeChangeFiles\n if (codeChangeFiles === undefined) {\n const captured = await resolveAutoCodeChange(options?.name)\n if (captured) {\n codeChangeFiles = captured.files\n if (codeChangeDescription === undefined) {\n codeChangeDescription = captured.description\n }\n }\n }\n\n const includeDbBranchLease =\n dbBranchEnabled(options?.dbBranch) && options?.dryRun !== true\n let session: ReplaySession\n if (options?.resume === undefined) {\n const started = await httpClient.startReplay(\n traceFunctionKey,\n // limit is meaningless with explicit traceIds (the ID list determines\n // the count), so it's omitted from the request entirely.\n options?.traceIds ? undefined : (options?.limit ?? 5),\n options?.traceIds,\n options?.name,\n codeChangeDescription,\n codeChangeFiles,\n // A dry run executes nothing, so a branch would be provisioned (and billed)\n // for code that never runs, and a seeded source's refusal would fail the item\n // before it could report its resolved inputs.\n includeDbBranchLease,\n options?.experimentGroupId,\n datasetIds,\n options?.graderIds,\n resolveDbBranchSettings(options?.dbBranch),\n requestedAttempts,\n options?.adaptInputs !== undefined,\n options?.onlyWithAssertions,\n options?.skipAssertionJudging === true ||\n options?.judgeAssertions === false,\n options?.experimentalSelectiveReplay,\n options?.notes,\n options?.metadata,\n options?.dryRun === true,\n options?.experimentGroupName,\n safeReplayInvocation(() =>\n buildReplayInvocation(\n Object.entries(cliFlags(options) ?? explicitReplayOptions(options)),\n ),\n ),\n )\n\n // An empty selection is the common shape of \"the corpus was never seeded\".\n // The result still reports it faithfully (zero items), but a caller reading\n // only the exit path would otherwise see a clean run that did nothing.\n if (started.items.length === 0) {\n try {\n console.warn(\n `Bitfab: no traces matched \"${traceFunctionKey}\", so this replay ran nothing. Capture a trace, or seed one with seedTrace, before replaying.`,\n )\n } catch {\n // Never crash the host app\n }\n }\n session = {\n experimentId: started.experimentId,\n experimentUrl: started.experimentUrl,\n attempts: requestedAttempts,\n work: expandReplayWork(started.items, requestedAttempts),\n finished: [],\n includeDbBranchLease,\n dbBranchSettings: resolveDbBranchSettings(options?.dbBranch),\n }\n } else {\n session = await resumeReplaySession(\n httpClient,\n options.resume,\n traceFunctionKey,\n codeChangeFiles,\n options.force,\n options.dbBranch,\n )\n }\n const { experimentId } = session\n if (experimentId === null || session.experimentUrl === null) {\n // A dry run has no experiment to keep alive, interrupt, or complete.\n return runReplaySession(\n httpClient,\n fn,\n session,\n null,\n maxConcurrency,\n () => {},\n () => {},\n () => false,\n options,\n registeredOverrides,\n )\n }\n const fullExperimentUrl = `${serviceUrl}${session.experimentUrl}`\n const heartbeat = startReplayHeartbeat(() =>\n httpClient.heartbeatReplay(experimentId),\n )\n const interruptReplay = async (): Promise<boolean> => {\n await heartbeat.stop()\n return httpClient.interruptReplay(experimentId)\n }\n const interruptHandlers = installReplayInterruptHandlers({\n experimentId,\n experimentUrl: fullExperimentUrl,\n interrupt: interruptReplay,\n onInterrupt: options?.onInterrupt,\n })\n let completeReturned = false\n const markCompleteReturned = (): void => {\n completeReturned = true\n void heartbeat.stop()\n }\n try {\n return await runReplaySession(\n httpClient,\n fn,\n session,\n fullExperimentUrl,\n maxConcurrency,\n interruptHandlers.remove,\n markCompleteReturned,\n interruptHandlers.interrupted,\n options,\n registeredOverrides,\n )\n } catch (error) {\n if (!completeReturned && !interruptHandlers.interrupted()) {\n await interruptReplay()\n }\n throw error\n } finally {\n interruptHandlers.remove()\n await heartbeat.stop()\n }\n}\n\nfunction throwIfInterrupted<T>(\n interrupted: () => boolean,\n items: ReplayItem<T>[],\n experimentId: string,\n experimentUrl: string,\n): void {\n if (!interrupted()) {\n return\n }\n const cause = new BitfabError(\n `Experiment ${experimentId} was interrupted, so it was not completed or graded. Resume it by passing { resume: \"${experimentId}\" } to replay, or with bitfab-replay --resume ${experimentId}.`,\n experimentUrl,\n )\n throw new ReplayError(\n cause.message,\n items,\n experimentId,\n experimentUrl,\n cause,\n )\n}\n\nasync function runReplaySession<TReturn>(\n httpClient: HttpClient,\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n session: ReplaySession,\n fullExperimentUrl: string | null,\n maxConcurrency: number,\n stopInterruptingOnSignal: () => void,\n markCompleteReturned: () => void,\n interrupted: () => boolean,\n options: ReplayOptions | undefined,\n registeredOverrides: MockOverride[],\n): Promise<ReplayResult<TReturn>> {\n const { experimentId, attempts } = session\n const mockStrategy: MockStrategy = options?.mock ?? \"marked\"\n if (experimentId !== null && fullExperimentUrl !== null) {\n try {\n options?.onExperimentStart?.({\n experimentId,\n experimentUrl: fullExperimentUrl,\n })\n } catch {\n // A lifecycle callback must never crash the replay run.\n }\n }\n\n // Per-call overrides take precedence over registered ones: concatenating them\n // first means the first-match-wins scan hits per-call overrides before the\n // client-registered chain, and both before the base mock strategy.\n const resolvedOverrides = [\n ...normalizeMockOverrides(options?.mockOverride),\n ...registeredOverrides,\n ]\n\n // One client-side replay trace id per item. It tags that item's replay spans\n // during the run so the server can echo back the row id it minted for them\n // (resolved in the complete-replay mapping below). Kept out of the public\n // ReplayItem: it's a correlation handle, never an id callers use.\n const workItems = session.work\n const carriedOverItems = session.finished.map((finished) =>\n carriedOverReplayItem<TReturn>(finished),\n )\n const replayedTraceIds = workItems.map(() => randomUuid())\n // Declared before the first span is submitted: the transport records delivery\n // only for traces someone asked about, so anything submitted before this\n // would go untracked.\n httpClient.trackTraceDeliveries(replayedTraceIds)\n const tasks = workItems.map(\n ({ serverItem, attempt }, index) =>\n () =>\n processItem(\n httpClient,\n serverItem,\n fn,\n experimentId,\n mockStrategy,\n resolvedOverrides,\n replayedTraceIds[index],\n attempt,\n session.includeDbBranchLease,\n session.dbBranchSettings,\n options?.adaptInputs,\n options?.dryRun === true,\n options?.experimentalSelectiveReplay,\n ),\n )\n const total = tasks.length + carriedOverItems.length\n const onItemFinish = options?.onItemFinish ?? options?.onProgress\n let completed = carriedOverItems.length\n let started = carriedOverItems.length\n let errored = carriedOverItems.filter((item) => item.error !== null).length\n let succeeded = completed - errored\n\n // Flush an item's trace the moment it finishes, so its server traces.id is\n // read back off the ingest response and surfaced on the item as it settles,\n // instead of waiting for the end-of-run barrier. Waiting until the end is\n // worst at low concurrency: each trace is closed and ready when its item\n // finishes, but nothing fills a batch to force an export, so ready ids sit in\n // the queue for the whole run.\n //\n // Coalesced so a burst of concurrent finishes shares one flush: while a flush\n // runs, later finishers mark `pending` and await the same promise, which loops\n // once more to cover them. Every caller therefore waits for a flush that ran\n // after it asked, and low concurrency degrades to a clean flush per item.\n let flushInFlight: Promise<void> | null = null\n let flushPending = false\n const flushFinishedItemTrace = (): Promise<void> => {\n // Mark work waiting first, so a finisher that arrives mid-flush is always\n // picked up by another loop iteration. The runner clears `flushInFlight`\n // synchronously with the loop exit (no await between the `while` check and\n // the reset), so no caller can observe a stale in-flight promise.\n flushPending = true\n if (!flushInFlight) {\n flushInFlight = (async () => {\n try {\n while (flushPending) {\n flushPending = false\n await httpClient.settleDeferredWork(REPLAY_PERSISTENCE_TIMEOUT_MS)\n await flushTraces(REPLAY_PERSISTENCE_TIMEOUT_MS)\n }\n } finally {\n flushInFlight = null\n }\n })()\n }\n return flushInFlight\n }\n\n const ranItems = await mapWithConcurrency(\n tasks,\n maxConcurrency,\n async (item, index) => {\n // Deliver this item's trace now, then read its server id back off the\n // ingest response. A flush failure never crashes the run: the id degrades\n // to null and the end-of-run barrier stays the authority on persistence.\n // Done BEFORE touching the counters so the increment and emit below carry\n // no await between them: with items flushing concurrently, that keeps each\n // event's running totals a consistent snapshot.\n let serverTraceId: string | null = null\n try {\n await flushFinishedItemTrace()\n serverTraceId =\n httpClient.peekServerTraceId(replayedTraceIds[index]) ?? null\n } catch {\n // Best-effort: fall through with null; the barrier settles persistence.\n }\n item.traceId = serverTraceId\n completed += 1\n if (item.error === null) {\n succeeded += 1\n } else {\n errored += 1\n }\n try {\n onItemFinish?.({\n experimentId,\n testRunId: experimentId,\n completed,\n total,\n succeeded,\n errored,\n item: {\n // The server's assigned traces.id, read back off the ingest\n // response and surfaced as this item finishes. Null only if the\n // per-item flush could not confirm delivery in time; the end-of-run\n // barrier then fills the returned ReplayItem. The client-side\n // placeholder is never surfaced.\n traceId: serverTraceId,\n originalTraceId: item.originalTraceId ?? null,\n originalSpanId: item.originalSpanId ?? null,\n // Deprecated aliases for originalTraceId/originalSpanId.\n sourceTraceId: item.originalTraceId ?? null,\n sourceSpanId: item.originalSpanId ?? null,\n attempt: item.attempt,\n input: item.input,\n result: item.result,\n originalOutput: item.originalOutput,\n error: item.error,\n traceError: item.traceError,\n replayError: item.replayError,\n durationMs: item.durationMs,\n ...(item.selectiveReplay === undefined\n ? {}\n : { selectiveReplay: item.selectiveReplay }),\n originalDurationMs: item.originalDurationMs,\n originalTokens: item.originalTokens,\n originalModel: item.originalModel,\n ingestionType: item.ingestionType,\n tokens: item.tokens,\n model: item.model,\n dbSnapshotRef: item.dbSnapshotRef,\n dbBranchTimings: item.dbBranchTimings,\n },\n })\n } catch {\n // Progress UI must never crash the replay run.\n }\n },\n options?.onItemStart\n ? (index) => {\n started += 1\n const { serverItem, attempt } = workItems[index]\n const originalTraceId =\n serverItem.originalTraceId ?? serverItem.sourceTraceId\n const originalSpanId =\n serverItem.originalSpanId ?? serverItem.sourceSpanId\n try {\n options.onItemStart?.({\n type: \"started\",\n experimentId,\n testRunId: experimentId,\n started,\n completed,\n total,\n succeeded,\n errored,\n item: {\n originalTraceId,\n originalSpanId,\n sourceTraceId: originalTraceId,\n sourceSpanId: originalSpanId,\n attempt,\n },\n })\n } catch {\n // Progress UI must never crash the replay run.\n }\n }\n : undefined,\n interrupted,\n )\n const resultItems = [...carriedOverItems, ...ranItems]\n\n // Items submit their spans through the same batching transport live traffic\n // uses, so nothing here has waited on the network yet. Flush the transports,\n // then let the SERVER confirm each trace reached a final status with all of\n // its spans before finalizing: a drained queue is not proof that Bitfab\n // committed the data.\n // A dry run executed nothing, so it produced no spans and no traces. The\n // persistence barrier asserts the opposite (every completed item has a\n // persisted trace) and would fail the whole run, so it is skipped along with\n // the trace-id mapping it feeds. Current servers create no experiment for a\n // dry run. An older one still does, and that experiment is finalized so it\n // does not sit unfinished in the experiments list.\n if (\n options?.dryRun === true ||\n experimentId === null ||\n fullExperimentUrl === null\n ) {\n if (experimentId !== null && fullExperimentUrl !== null) {\n throwIfInterrupted(\n interrupted,\n resultItems,\n experimentId,\n fullExperimentUrl,\n )\n stopInterruptingOnSignal()\n await httpClient.completeReplay(experimentId).catch(() => undefined)\n markCompleteReturned()\n }\n const dryResult: ReplayResult<TReturn> = {\n items: resultItems,\n experimentId,\n experimentUrl: fullExperimentUrl,\n testRunId: experimentId,\n testRunUrl: fullExperimentUrl,\n attempts,\n }\n await writeReplayResultFile(dryResult)\n return dryResult\n }\n throwIfInterrupted(interrupted, resultItems, experimentId, fullExperimentUrl)\n\n const deliveredTraceIds = await preserveReplayFailure(\n () =>\n waitForReplayPersistence(\n httpClient,\n experimentId,\n replayedTraceIds,\n Object.fromEntries(\n workItems.map(({ serverItem, attempt }, index) => [\n replayedTraceIds[index],\n `${serverItem.originalTraceId ?? serverItem.sourceTraceId}#${attempt}`,\n ]),\n ),\n ),\n resultItems,\n experimentId,\n fullExperimentUrl,\n )\n\n // Primary source for item.traceId: the server's assigned traces.id, read back\n // per trace off the ingest response during the flush above (server-sourced, no\n // polling, already in hand before completeReplay). The completeReplay map below\n // remains the fallback for servers that don't return ids on ingest.\n for (let index = 0; index < ranItems.length; index += 1) {\n const localId = replayedTraceIds[index]\n const readBack = localId ? deliveredTraceIds[localId] : undefined\n if (readBack !== undefined) {\n ranItems[index].traceId = readBack\n }\n }\n\n // completeReplay finalizes the experiment and returns the token/diagnostic\n // mapping; its failures propagate loudly because a run that never completed\n // can't be finalized and callers must hear about it.\n throwIfInterrupted(interrupted, resultItems, experimentId, fullExperimentUrl)\n stopInterruptingOnSignal()\n const completeResult = await preserveReplayFailure(\n () => httpClient.completeReplay(experimentId),\n resultItems,\n experimentId,\n fullExperimentUrl,\n )\n markCompleteReturned()\n const serverTraceIds = completeResult.traceIds\n // Per-replay-trace token usage, keyed by server trace id. The REPLAYED run's\n // tokens (span-aggregated server-side), used below to fill each item.tokens.\n const replayTokens = completeResult.tokens\n\n // `serverTraceIds` maps each item's client-side replay trace id (its entry in\n // `replayedTraceIds`, which tagged that item's spans during the run) to the\n // server's trace row id. We use it to (a) write the real server replay trace\n // id into `item.traceId` now that the row exists, (b) attach each item's\n // server-aggregated token usage, and (c) detect a systemic upload failure\n // early. Verdict persistence does NOT use this map: it is keyed by the\n // original-trace lineage (`originalTraceId` + `experimentId`), which needs no\n // client-held server id. Older servers that omit the map yield no replay\n // tokens and leave `item.traceId` null.\n if (serverTraceIds !== undefined) {\n const missing: string[] = []\n let completedCount = 0\n for (let index = 0; index < ranItems.length; index += 1) {\n const item = ranItems[index]\n const localId = replayedTraceIds[index]\n const mapped = localId ? serverTraceIds[localId] : undefined\n // Fallback fill for servers that did not return ids on the ingest\n // response; the read-back loop above already set it when they did, so\n // never overwrite a resolved id with null here.\n item.traceId = item.traceId ?? mapped ?? null\n if (item.error === null) {\n completedCount += 1\n if (mapped === undefined) {\n missing.push(localId ?? item.originalTraceId)\n }\n }\n if (mapped !== undefined) {\n item.tokens = replayTokens?.[mapped] ?? null\n }\n }\n // ALL completed items missing → systemic (the replayed function isn't\n // wrapped with withSpan, or uploads are wholesale broken). Throw; the run's\n // traces never persisted, so nothing can be labeled and silence here is the\n // exact bug this guarantee exists to prevent.\n if (completedCount > 0 && missing.length === completedCount) {\n const serverCount =\n completeResult.traceCount !== undefined\n ? ` The server persisted ${completeResult.traceCount} trace(s) for this run.`\n : \"\"\n const cause = new BitfabError(\n `Replay completed but the server has no persisted trace for any of the ${completedCount} completed item(s) (experiment ${experimentId}).${serverCount} ` +\n `Trace uploads were awaited, so either the uploads failed (check for \"Bitfab: Failed to create\" errors above) or the replayed function is not wrapped with withSpan.`,\n )\n throw new ReplayError(\n cause.message,\n resultItems,\n experimentId,\n fullExperimentUrl,\n cause,\n )\n }\n // SOME completed items missing → per-item upload failure (transient blip,\n // one oversized payload). Log it, but return the run; the items that landed\n // can still be labeled via their lineage.\n if (missing.length > 0) {\n try {\n console.error(\n `Bitfab: server has no persisted trace for ${missing.length} of ${completedCount} completed replay item(s) (experiment ${experimentId}). Their replay token usage is unavailable and they cannot be labeled.`,\n )\n } catch {\n // Never crash the host app\n }\n }\n }\n\n const result: ReplayResult<TReturn> = {\n items: resultItems,\n experimentId,\n experimentUrl: fullExperimentUrl,\n testRunId: experimentId,\n testRunUrl: fullExperimentUrl,\n attempts,\n }\n // Persist the enriched result so the Bitfab plugin never has to parse the\n // replay's stdout, which a dependency's logging can corrupt.\n await writeReplayResultFile(result)\n // Preserve the legacy terminal event only for onProgress. onItemFinish is\n // strictly item-scoped, so every invocation always includes an item.\n if (!options?.onItemFinish) {\n try {\n options?.onProgress?.({\n type: \"complete\",\n experimentId,\n testRunId: experimentId,\n completed: total,\n total,\n succeeded,\n errored,\n result,\n })\n } catch {\n // A progress reporter must never crash the replay run.\n }\n }\n return result\n}\n\nasync function writeReplayResultFile(\n result: ReplayResult<unknown>,\n): Promise<void> {\n const resultPath =\n typeof process !== \"undefined\"\n ? process.env?.BITFAB_REPLAY_RESULT_PATH\n : undefined\n if (!resultPath) {\n return\n }\n\n try {\n const [{ dirname }, { mkdir, writeFile }] = await Promise.all([\n import(\"node:path\"),\n import(\"node:fs/promises\"),\n ])\n await mkdir(dirname(resultPath), { recursive: true })\n await writeFile(resultPath, `${serializeReplayResult(result)}\\n`)\n } catch (err) {\n try {\n console.warn(\n `Bitfab: failed to write replay result to BITFAB_REPLAY_RESULT_PATH (${resultPath}): ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n } catch {\n // Never crash the host app.\n }\n }\n}\n","import {\n type AsyncLocalStorageLike,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\nimport { isCaptureSuppressed } from \"./captureSuppression.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport interface AutoTraceFunctionDefinition {\n id: string\n name: string\n file: string\n line: number\n column: number\n async?: boolean\n wrapper?: boolean\n}\n\nexport interface AutoTraceNodeConfiguration {\n functionName: string\n name?: string\n type?: \"llm\" | \"agent\" | \"function\" | \"guardrail\" | \"handoff\" | \"custom\"\n capture: boolean\n experimentId?: string\n /** @deprecated Use experimentId. */\n testRunId?: string\n mockOnReplay?: boolean\n replayReusable?: boolean\n // biome-ignore lint/suspicious/noExplicitAny: node finalizers receive the configured function's result, whose type is owned by the caller\n finalize?: (result: any) => unknown | Promise<unknown>\n}\n\nexport interface NestedTraceLink {\n traceFunctionKey: string\n traceId?: string\n rootSpanId?: string\n}\n\nexport interface AutoTraceEntry {\n context: AutoTraceContext\n depth: number\n spanStack: unknown\n}\n\nexport interface AutoTraceContext {\n readonly traceFunctionKey: string\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n nodeConfiguration?: AutoTraceNodeConfiguration,\n ): T\n invokeNestedRoot<T>(\n name: string,\n functionName: string,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n link: NestedTraceLink | undefined,\n ): T\n}\n\ninterface AutoTraceRootFunction {\n name: string\n entering: boolean\n}\n\ninterface AutoTraceScope {\n entries: readonly AutoTraceEntry[]\n nodeConfiguration?: AutoTraceNodeConfiguration\n rootFunction?: AutoTraceRootFunction\n}\n\ninterface AutoTraceState {\n storage: AsyncLocalStorageLike<AutoTraceScope> | null\n browserScope: AutoTraceScope | undefined\n // Older SDK copies read this field when sharing the process-wide V4 state.\n capturePolicies: WeakMap<object, Map<string, ReadonlySet<string>>>\n activeRoots: number\n}\n\ninterface AutoTraceGlobal {\n __bitfabAutoTraceStateV4?: AutoTraceState\n __bitfab_auto_trace_transformed_v1__?: boolean\n}\n\ninterface AutoTraceAsyncGenerator {\n next(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n return(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n throw(error?: unknown): Promise<IteratorResult<unknown, unknown>>\n [Symbol.asyncIterator](): AutoTraceAsyncGenerator\n}\n\nconst autoTraceGlobal = globalThis as unknown as AutoTraceGlobal\nconst autoTraceState: AutoTraceState =\n autoTraceGlobal.__bitfabAutoTraceStateV4 ?? {\n storage: null,\n browserScope: undefined,\n capturePolicies: new WeakMap(),\n activeRoots: 0,\n }\nautoTraceGlobal.__bitfabAutoTraceStateV4 = autoTraceState\n\nfunction initializeAutoTraceStorage(): void {\n autoTraceState.storage ??= createAsyncLocalStorage<AutoTraceScope>()\n}\n\nfunction runWithAutoTraceScope<T>(scope: AutoTraceScope, fn: () => T): T {\n initializeAutoTraceStorage()\n if (autoTraceState.storage) {\n return autoTraceState.storage.run(scope, fn)\n }\n\n const previous = autoTraceState.browserScope\n autoTraceState.browserScope = scope\n try {\n return fn()\n } finally {\n autoTraceState.browserScope = previous\n }\n}\n\nexport function currentAutoTraceEntries(): readonly AutoTraceEntry[] {\n return currentAutoTraceScope()?.entries ?? []\n}\n\nfunction replaceEntry(\n entries: readonly AutoTraceEntry[],\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n): readonly AutoTraceEntry[] {\n return entries.map((entry) => (entry === previous ? updated : entry))\n}\n\nexport function runWithAutoTraceEntry<T>(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n fn: () => T,\n): T {\n const result = runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n fn,\n )\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceEntryAsyncGenerator(previous, updated, result) as T\n }\n return result\n}\n\nfunction wrapAutoTraceEntryAsyncGenerator(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n () => source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nexport function clearAutoTraceNodeConfiguration<T>(fn: () => T): T {\n return runWithAutoTraceScope({ entries: currentAutoTraceEntries() }, fn)\n}\n\nexport function runWithAutoTraceNodeConfiguration<T>(\n nodeConfiguration: AutoTraceNodeConfiguration,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0) {\n return fn()\n }\n\n const result = runWithAutoTraceScope({ ...scope, nodeConfiguration }, fn)\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceNodeAsyncGenerator(nodeConfiguration, result) as T\n }\n return result\n}\n\nexport function runAsAutoTraceRootFunction<T>(\n functionName: string,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || functionName === \"\") {\n return fn()\n }\n const rootFunction: AutoTraceRootFunction = {\n name: functionName,\n entering: true,\n }\n try {\n return runWithAutoTraceScope({ ...scope, rootFunction }, fn)\n } finally {\n rootFunction.entering = false\n }\n}\n\nfunction isRootFunctionEntry(\n scope: AutoTraceScope,\n simpleName: string | undefined,\n): boolean {\n const rootFunction = scope.rootFunction\n if (rootFunction === undefined || !rootFunction.entering) {\n return false\n }\n rootFunction.entering = false\n return rootFunction.name === simpleName\n}\n\nconst SUBTREE_TRACING_DOCS_URL =\n \"https://docs.bitfab.ai/typescript-sdk#experimental-subtree-tracing\"\n\nfunction noteTransformedModule(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = true\n}\n\nfunction transformInstalled(): boolean {\n return autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ === true\n}\n\nfunction runsOnNode(): boolean {\n return typeof process !== \"undefined\" && Boolean(process.versions?.node)\n}\n\nfunction closeAutoTraceRoot(): void {\n autoTraceState.activeRoots -= 1\n}\n\nfunction settleAutoTraceRoot(context: AutoTraceContext): void {\n closeAutoTraceRoot()\n if (transformInstalled() || !runsOnNode()) {\n return\n }\n warnOnce(\n \"auto-trace-transform-missing\",\n `trace root \"${context.traceFunctionKey}\" recorded only its own span. ` +\n \"No module in this build was compiled by @bitfab/sdk/transform, so calls \" +\n \"beneath the root were not discovered. Add the SDK's transform adapter \" +\n `to the server build: ${SUBTREE_TRACING_DOCS_URL}`,\n )\n}\n\nexport function runWithAutoTraceRootContext<T>(\n context: AutoTraceContext,\n spanStack: unknown,\n fn: () => T,\n): T {\n autoTraceState.activeRoots += 1\n const entries = [\n ...currentAutoTraceEntries(),\n { context, depth: 0, spanStack },\n ]\n let result: T\n try {\n result = runWithAutoTraceScope({ entries }, fn)\n } catch (error) {\n settleAutoTraceRoot(context)\n throw error\n }\n\n if (isAutoTraceAsyncGenerator(result)) {\n closeAutoTraceRoot()\n return wrapAutoTraceAsyncGenerator(context, spanStack, result) as T\n }\n\n if (result instanceof Promise) {\n return result.finally(() => {\n settleAutoTraceRoot(context)\n }) as T\n }\n\n settleAutoTraceRoot(context)\n return result\n}\n\nexport function invokeThroughAutoTraceEntries<T>(\n entries: readonly AutoTraceEntry[],\n step: (entry: AutoTraceEntry, next: () => T) => T,\n fn: () => T,\n): T {\n let run = fn\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index] as AutoTraceEntry\n const next = run\n run = () => step(entry, next)\n }\n return run()\n}\n\nfunction isAutoTraceAsyncGenerator(\n value: unknown,\n): value is AutoTraceAsyncGenerator {\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\nfunction wrapAutoTraceAsyncGenerator(\n context: AutoTraceContext,\n spanStack: unknown,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceRootContext(context, spanStack, () => source[method](value))\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction wrapAutoTraceNodeAsyncGenerator(\n nodeConfiguration: AutoTraceNodeConfiguration,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceNodeConfiguration(nodeConfiguration, () =>\n source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction shareFinalize(\n configuration: AutoTraceNodeConfiguration,\n): AutoTraceNodeConfiguration {\n const finalize = configuration.finalize\n if (finalize === undefined) {\n return configuration\n }\n let settled: Promise<unknown> | undefined\n return {\n ...configuration,\n finalize: (result: unknown) => {\n settled ??= Promise.resolve().then(() => finalize(result))\n return settled\n },\n }\n}\n\nexport function __bitfabAutoSpan<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n): T {\n noteTransformedModule()\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || isCaptureSuppressed()) {\n return fn()\n }\n const nameParts = definition.name.split(\".\")\n const simpleName = nameParts[nameParts.length - 1]\n if (isRootFunctionEntry(scope, simpleName)) {\n return fn()\n }\n const nodeConfiguration =\n simpleName === scope.nodeConfiguration?.functionName\n ? shareFinalize(scope.nodeConfiguration)\n : undefined\n return invokeThroughAutoTraceEntries(\n scope.entries,\n (entry, next) =>\n entry.context.invoke(definition, inputs, next, entry, nodeConfiguration),\n fn,\n )\n}\n\n/**\n * Preserve a function's original call arguments for transform cases where\n * parameter bindings discard them, such as destructured arrow parameters.\n *\n * This helper is internal transform/runtime protocol. The proxy preserves the\n * target's callability, arity, async identity, and non-constructibility while\n * only allocating a trace closure beneath an active automatic trace root.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoWrap<T extends (...args: never[]) => unknown>(\n definition: AutoTraceFunctionDefinition,\n fn: T,\n): T {\n noteTransformedModule()\n if (fn.name === \"\") {\n const nameParts = definition.name.split(\".\")\n const inferredName = nameParts[nameParts.length - 1]\n if (inferredName !== undefined) {\n Object.defineProperty(fn, \"name\", {\n configurable: true,\n value: inferredName,\n })\n }\n }\n\n const target = fn as unknown as (...args: unknown[]) => unknown\n return new Proxy(target, {\n apply(callTarget, thisArg, args) {\n if (!__bitfabAutoTraceActive()) {\n return Reflect.apply(callTarget, thisArg, args)\n }\n return __bitfabAutoSpan(definition, args, () =>\n Reflect.apply(callTarget, thisArg, args),\n )\n },\n }) as unknown as T\n}\n\n/**\n * Return whether the current call is inside an automatic trace root.\n *\n * Build transforms use this before allocating function metadata, captured\n * inputs, or an invocation closure. It is internal transform/runtime protocol,\n * not a supported application API.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoTraceActive(): boolean {\n if (autoTraceState.activeRoots === 0 || isCaptureSuppressed()) {\n return false\n }\n return currentAutoTraceEntries().length > 0\n}\n\nfunction currentAutoTraceScope(): AutoTraceScope | undefined {\n initializeAutoTraceStorage()\n return autoTraceState.storage?.getStore() ?? autoTraceState.browserScope\n}\n\nexport function _resetAutoTraceTransformDetection(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = undefined\n}\n","import { gitRunner } from \"./gitCommand.js\"\nimport { readEnv } from \"./readEnv.js\"\n\nexport interface CommitRef {\n sha: string\n branch: string | null\n dirty: boolean | null\n remote: string | null\n rootSha: string | null\n}\n\ntype EnvLookup = (name: string) => string | undefined\ntype RemoteReader = (env: EnvLookup) => string | null\n\nconst EXPLICIT_SHA_ENV = \"BITFAB_COMMIT_SHA\"\nconst DISABLE_ENV = \"BITFAB_DISABLE_COMMIT_REF\"\nconst GIT_TIMEOUT_MS = 2_000\nconst GIT_MAX_BUFFER = 1024 * 1024\n\nconst VERCEL_PROVIDER_HOSTS: Record<string, string> = {\n github: \"github.com\",\n gitlab: \"gitlab.com\",\n bitbucket: \"bitbucket.org\",\n}\n\nfunction read(env: EnvLookup, name: string | null): string | null {\n if (name === null) {\n return null\n }\n const value = env(name)?.trim()\n return value ? value : null\n}\n\nfunction remoteFrom(...names: string[]): RemoteReader {\n return (env) => {\n const parts = names.map((name) => read(env, name))\n if (parts.some((part) => part === null)) {\n return null\n }\n return normalizeRemote(parts.join(\"/\"))\n }\n}\n\nfunction vercelRemote(env: EnvLookup): string | null {\n const provider = read(env, \"VERCEL_GIT_PROVIDER\")?.toLowerCase() ?? \"\"\n const host = VERCEL_PROVIDER_HOSTS[provider]\n const owner = read(env, \"VERCEL_GIT_REPO_OWNER\")\n const slug = read(env, \"VERCEL_GIT_REPO_SLUG\")\n if (!host || !owner || !slug) {\n return null\n }\n return `${host}/${owner}/${slug}`\n}\n\nfunction noRemote(): string | null {\n return null\n}\n\nconst PLATFORM_ENVS: ReadonlyArray<\n readonly [sha: string, branch: string | null, remote: RemoteReader]\n> = [\n [\"VERCEL_GIT_COMMIT_SHA\", \"VERCEL_GIT_COMMIT_REF\", vercelRemote],\n [\n \"GITHUB_SHA\",\n \"GITHUB_REF_NAME\",\n remoteFrom(\"GITHUB_SERVER_URL\", \"GITHUB_REPOSITORY\"),\n ],\n [\"RAILWAY_GIT_COMMIT_SHA\", \"RAILWAY_GIT_BRANCH\", noRemote],\n [\"RENDER_GIT_COMMIT\", \"RENDER_GIT_BRANCH\", noRemote],\n [\"SOURCE_VERSION\", null, noRemote],\n [\"CF_PAGES_COMMIT_SHA\", \"CF_PAGES_BRANCH\", noRemote],\n [\"CI_COMMIT_SHA\", \"CI_COMMIT_REF_NAME\", remoteFrom(\"CI_REPOSITORY_URL\")],\n [\n \"BUILD_SOURCEVERSION\",\n \"BUILD_SOURCEBRANCHNAME\",\n remoteFrom(\"BUILD_REPOSITORY_URI\"),\n ],\n [\"CIRCLE_SHA1\", \"CIRCLE_BRANCH\", remoteFrom(\"CIRCLE_REPOSITORY_URL\")],\n]\n\nexport const COMMIT_REF_ENV_NAMES: readonly string[] = [\n EXPLICIT_SHA_ENV,\n DISABLE_ENV,\n ...PLATFORM_ENVS.flatMap(([sha, branch]) =>\n branch === null ? [sha] : [sha, branch],\n ),\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY\",\n \"CI_REPOSITORY_URL\",\n \"BUILD_REPOSITORY_URI\",\n \"CIRCLE_REPOSITORY_URL\",\n \"VERCEL_GIT_PROVIDER\",\n \"VERCEL_GIT_REPO_OWNER\",\n \"VERCEL_GIT_REPO_SLUG\",\n]\n\nexport function normalizeRemote(raw: string | null | undefined): string | null {\n const value = raw?.trim()\n if (!value) {\n return null\n }\n let host = \"\"\n let path = value\n if (value.includes(\"://\")) {\n try {\n const parsed = new URL(value)\n host = parsed.hostname\n path = parsed.pathname\n } catch {\n return null\n }\n } else {\n const separator = value.indexOf(\":\")\n if (separator !== -1) {\n const head = value.slice(0, separator)\n host = head.slice(head.lastIndexOf(\"@\") + 1)\n path = value.slice(separator + 1)\n }\n }\n path = path.replace(/^\\/+|\\/+$/g, \"\")\n if (path.endsWith(\".git\")) {\n path = path.slice(0, -\".git\".length).replace(/\\/+$/, \"\")\n }\n if (!host) {\n return path || null\n }\n return path ? `${host}/${path}` : host\n}\n\nexport function resolveCommitRefFromEnv(env: EnvLookup): CommitRef | null {\n const explicit = read(env, EXPLICIT_SHA_ENV)\n const platform = PLATFORM_ENVS.find(([sha]) => read(env, sha) !== null)\n if (!platform) {\n if (explicit === null) {\n return null\n }\n return {\n sha: explicit,\n branch: null,\n dirty: null,\n remote: null,\n rootSha: null,\n }\n }\n const [shaEnv, branchEnv, readRemote] = platform\n return {\n sha: explicit ?? (read(env, shaEnv) as string),\n branch: read(env, branchEnv),\n dirty: null,\n remote: readRemote(env),\n rootSha: null,\n }\n}\n\nexport async function resolveCommitRefFromGit(\n cwd: string,\n): Promise<CommitRef | null> {\n const git = await gitRunner({\n timeoutMs: GIT_TIMEOUT_MS,\n maxBuffer: GIT_MAX_BUFFER,\n keepProcessAlive: false,\n })\n if (!git) {\n return null\n }\n const run = async (args: string[]) => (await git(cwd, args))?.trim() ?? null\n const sha = await run([\"rev-parse\", \"HEAD\"])\n if (!sha) {\n return null\n }\n const [branch, status, remote, roots] = await Promise.all([\n run([\"symbolic-ref\", \"--short\", \"-q\", \"HEAD\"]),\n run([\"status\", \"--porcelain\"]),\n run([\"remote\", \"get-url\", \"origin\"]),\n run([\"rev-list\", \"--max-parents=0\", \"HEAD\"]),\n ])\n return {\n sha,\n branch: branch || null,\n dirty: status === null ? null : status.length > 0,\n remote: normalizeRemote(remote),\n rootSha: roots ? (roots.split(/\\s+/).sort()[0] ?? null) : null,\n }\n}\n\nexport function commitRefWire(ref: CommitRef): Record<string, unknown> {\n return {\n sha: ref.sha,\n branch: ref.branch,\n dirty: ref.dirty,\n remote: ref.remote,\n root_sha: ref.rootSha,\n }\n}\n\nlet resolved = false\nlet ref: CommitRef | null = null\nlet gitStarted = false\nlet settled: Promise<void> = Promise.resolve()\n\nexport function startCommitRefResolution(): void {\n if (resolved || gitStarted) {\n return\n }\n if (read(readEnv, DISABLE_ENV) !== null) {\n resolved = true\n return\n }\n const fromEnv = resolveCommitRefFromEnv(readEnv)\n if (fromEnv) {\n ref = fromEnv\n resolved = true\n return\n }\n gitStarted = true\n if (typeof process === \"undefined\") {\n resolved = true\n return\n }\n let cwd: string\n try {\n cwd = process.cwd?.() ?? \".\"\n } catch {\n resolved = true\n return\n }\n settled = resolveCommitRefFromGit(cwd).then(\n (fromGit) => {\n if (!resolved) {\n ref = fromGit\n resolved = true\n }\n },\n () => {\n resolved = true\n },\n )\n}\n\nexport function currentCommitRef(): CommitRef | null {\n startCommitRefResolution()\n return ref\n}\n\nexport function _commitRefSettled(): Promise<void> {\n return settled\n}\n\nexport function _resetCommitRef(): void {\n resolved = false\n ref = null\n gitStarted = false\n settled = Promise.resolve()\n}\n","const OPENAI_AGENTS_CONTEXT_STORAGE = Symbol.for(\n \"openai.agents.core.asyncLocalStorage\",\n)\nconst MAX_OPENAI_AGENTS_SPAN_CHAIN = 64\n\ninterface OpenAiAgentsSpanLike {\n spanId?: unknown\n traceId?: unknown\n previousSpan?: OpenAiAgentsSpanLike | null\n}\n\ninterface OpenAiAgentsContextStore {\n active?: unknown\n span?: OpenAiAgentsSpanLike | null\n}\n\ninterface OpenAiAgentsContextStorage {\n getStore(): OpenAiAgentsContextStore | undefined\n}\n\ninterface OpenAiAgentsSpanState {\n bitfabTraceIds: Map<string, string>\n endedSpanIds: Map<string, Set<string>>\n}\n\ninterface OpenAiAgentsSpanGlobal {\n __bitfabOpenAiAgentsSpansV1?: OpenAiAgentsSpanState\n}\n\nconst spanGlobal = globalThis as unknown as OpenAiAgentsSpanGlobal &\n Record<symbol, unknown>\nconst state: OpenAiAgentsSpanState = spanGlobal.__bitfabOpenAiAgentsSpansV1 ?? {\n bitfabTraceIds: new Map(),\n endedSpanIds: new Map(),\n}\nspanGlobal.__bitfabOpenAiAgentsSpansV1 = state\n\nexport function mapOpenAiAgentsTrace(\n agentsTraceId: string,\n bitfabTraceId: string,\n): void {\n state.bitfabTraceIds.set(agentsTraceId, bitfabTraceId)\n}\n\nexport function unmapOpenAiAgentsTrace(agentsTraceId: string): void {\n state.bitfabTraceIds.delete(agentsTraceId)\n state.endedSpanIds.delete(agentsTraceId)\n}\n\nexport function endOpenAiAgentsSpan(\n agentsTraceId: string,\n spanId: string,\n): void {\n if (!state.bitfabTraceIds.has(agentsTraceId)) {\n return\n }\n const ended = state.endedSpanIds.get(agentsTraceId) ?? new Set<string>()\n ended.add(spanId)\n state.endedSpanIds.set(agentsTraceId, ended)\n}\n\nfunction isOpenAiAgentsContextStorage(\n value: unknown,\n): value is OpenAiAgentsContextStorage {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as { getStore?: unknown }).getStore === \"function\"\n )\n}\n\nfunction currentOpenAiAgentsSpan(): OpenAiAgentsSpanLike | undefined {\n const storage = spanGlobal[OPENAI_AGENTS_CONTEXT_STORAGE]\n if (!isOpenAiAgentsContextStorage(storage)) {\n return undefined\n }\n try {\n const store = storage.getStore()\n return store?.active === true ? (store.span ?? undefined) : undefined\n } catch {\n return undefined\n }\n}\n\nfunction currentOpenAiAgentsSpans(): OpenAiAgentsSpanLike[] {\n const spans: OpenAiAgentsSpanLike[] = []\n let span = currentOpenAiAgentsSpan()\n while (span !== undefined && spans.length < MAX_OPENAI_AGENTS_SPAN_CHAIN) {\n spans.push(span)\n span = span.previousSpan ?? undefined\n }\n return spans\n}\n\nexport function openAiAgentsSpanChain(): string[] {\n if (state.bitfabTraceIds.size === 0) {\n return []\n }\n return currentOpenAiAgentsSpans()\n .map((span) => span.spanId)\n .filter((spanId): spanId is string => typeof spanId === \"string\")\n}\n\nexport function openAiAgentsParentSpanId(\n bitfabTraceId: string,\n enclosingSpanIds: readonly string[] | undefined,\n): string | undefined {\n if (state.bitfabTraceIds.size === 0) {\n return undefined\n }\n for (const span of currentOpenAiAgentsSpans()) {\n if (typeof span.spanId !== \"string\" || typeof span.traceId !== \"string\") {\n return undefined\n }\n if (state.bitfabTraceIds.get(span.traceId) !== bitfabTraceId) {\n return undefined\n }\n if (enclosingSpanIds?.includes(span.spanId)) {\n return undefined\n }\n if (!state.endedSpanIds.get(span.traceId)?.has(span.spanId)) {\n return span.spanId\n }\n }\n return undefined\n}\n","import {\n type AsyncLocalStorageLike,\n asyncStorageReady,\n createAsyncLocalStorage,\n isAsyncStorageInitDone,\n} from \"./asyncStorage.js\"\n\nexport interface RivetContextBinding<TContext extends object> {\n context: TContext\n fixtureContext: Record<string, unknown>\n recordedRoots: Set<string>\n proxy?: TContext\n}\n\nlet storage: AsyncLocalStorageLike<RivetContextBinding<object> | null> | null =\n null\nlet browserBinding: RivetContextBinding<object> | null = null\nconst STORAGE_SYMBOL = Symbol.for(\"bitfab.rivetContextStorage\")\n\nfunction initializeStorage(): void {\n if (storage) {\n return\n }\n const shared = globalThis as typeof globalThis & Record<symbol, unknown>\n const existing = shared[STORAGE_SYMBOL] as\n | AsyncLocalStorageLike<RivetContextBinding<object> | null>\n | undefined\n if (existing) {\n storage = existing\n return\n }\n const created = createAsyncLocalStorage<RivetContextBinding<object> | null>()\n if (created) {\n shared[STORAGE_SYMBOL] = created\n storage = created\n }\n}\n\nexport const rivetContextReady: Promise<void> = asyncStorageReady.then(() => {\n initializeStorage()\n})\n\nexport function getRivetContextBinding<TContext extends object>():\n | RivetContextBinding<TContext>\n | undefined {\n initializeStorage()\n return (storage?.getStore() ?? browserBinding ?? undefined) as\n | RivetContextBinding<TContext>\n | undefined\n}\n\nfunction runWithBrowserBinding<T>(\n binding: RivetContextBinding<object>,\n fn: () => T,\n): T {\n const previous = browserBinding\n browserBinding = binding\n try {\n const result = fn()\n if (result instanceof Promise) {\n return result.finally(() => {\n browserBinding = previous\n }) as T\n }\n browserBinding = previous\n return result\n } catch (error) {\n browserBinding = previous\n throw error\n }\n}\n\nexport function runWithRivetContext<T>(\n binding: RivetContextBinding<object>,\n fn: () => T,\n): T {\n initializeStorage()\n if (!storage && !isAsyncStorageInitDone()) {\n return rivetContextReady.then(() => runWithRivetContext(binding, fn)) as T\n }\n if (storage) {\n return storage.run(binding, fn)\n }\n return runWithBrowserBinding(binding, fn)\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 * 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 type AutoTraceContext,\n type AutoTraceEntry,\n type AutoTraceFunctionDefinition,\n type AutoTraceNodeConfiguration,\n clearAutoTraceNodeConfiguration,\n currentAutoTraceEntries,\n invokeThroughAutoTraceEntries,\n type NestedTraceLink,\n runAsAutoTraceRootFunction,\n runWithAutoTraceEntry,\n runWithAutoTraceNodeConfiguration,\n runWithAutoTraceRootContext,\n} from \"./autoTrace.js\"\nimport {\n type AllowedEnvVars,\n type ProviderDefinition,\n runFunctionWithBaml,\n} from \"./baml.js\"\nimport { validateSpanId, validateTraceId } from \"./bitfabIds.js\"\nimport { isCaptureSuppressed } from \"./captureSuppression.js\"\nimport type { CaptureSurface, SurfaceRequest } from \"./captureSurface.js\"\nimport {\n assertSurfacesCompatible,\n DEFAULT_SURFACE,\n mixedTracingError,\n resolveSurface,\n} from \"./captureSurface.js\"\nimport { CategoriesClient } from \"./categories.js\"\nimport { BitfabClaudeAgentHandler } from \"./claudeAgentSdk.js\"\nimport {\n commitRefWire,\n currentCommitRef,\n startCommitRefResolution,\n} from \"./commitRef.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 { ExperimentsClient } from \"./experiments.js\"\nimport { GradersClient } from \"./graders.js\"\nimport {\n BitfabError,\n type CapturedSpan,\n experimentIdWireFields,\n HttpClient,\n SPAN_TYPES,\n type SpanLookup,\n type SpanType,\n} from \"./http.js\"\nimport { LabelsClient } from \"./labels.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 {\n openAiAgentsParentSpanId,\n openAiAgentsSpanChain,\n} from \"./openaiAgentsSpanContext.js\"\nimport { importOptionalPeer } from \"./optionalPeer.js\"\nimport { OrganizationMembersClient } from \"./organizationMembers.js\"\nimport { randomUuid } from \"./randomUuid.js\"\nimport type {\n ReplayOptions,\n ReplayResult,\n TraceIngestionType,\n} from \"./replay.js\"\nimport { deserializeInputs } from \"./replay.js\"\nimport { ReplayBranch } from \"./replayBranch.js\"\nimport type { DbBranchTimings } from \"./replayContext.js\"\nimport { getReplayContext } from \"./replayContext.js\"\nimport {\n BitfabRivetIntegration,\n type RivetContextLike,\n type RivetEffectType,\n type RivetIntegrationOptions,\n} from \"./rivetIntegration.js\"\nimport {\n getSeedContext,\n inSeedScope,\n runWithSeedContext,\n seedContextReady,\n} from \"./seedContext.js\"\nimport { deserializeValue, serializeValue } from \"./serialize.js\"\nimport {\n CONTENT_OFF_KEY,\n DECLARED_NODE_FIELD,\n ROOT_TRACE_FUNCTION_KEY_FIELD,\n SimulationPlan,\n type SimulationPlanSubmit,\n} from \"./simulationPlan.js\"\nimport {\n isFrameworkInstrumentation,\n makeSpanOrigin,\n type SpanInstrumentation,\n} from \"./spanOrigin.js\"\nimport { SpansClient } from \"./spans.js\"\nimport { StreamFinalizationError } from \"./streamFinalizationError.js\"\nimport { nowIsoTimestamp } from \"./timestamp.js\"\nimport {\n callerTraceMetadata,\n recordCallerTraceMetadata,\n retireTraceMetadata,\n} from \"./traceMetadata.js\"\nimport { TracesClient } from \"./traces.js\"\nimport { BitfabOpenAITracingProcessor } from \"./tracing.js\"\nimport { BitfabVercelAiHandler } from \"./vercelAiSdk.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nfunction markTracedFunction<T extends (...args: never[]) => unknown>(\n target: T,\n traceFunctionKey: string,\n original: unknown,\n): T {\n Object.defineProperty(target, \"_bitfabTraceFunctionKey\", {\n value: traceFunctionKey,\n })\n Object.defineProperty(target, \"_bitfabWrappedFn\", { value: original })\n Object.defineProperty(target, \"bind\", {\n value(this: T, thisArg: unknown, ...boundArgs: unknown[]) {\n return markTracedFunction(\n Function.prototype.bind.call(this, thisArg, ...boundArgs) as T,\n traceFunctionKey,\n original,\n )\n },\n })\n return target\n}\n\nfunction resolveSpanExperimentId(\n options: Pick<SpanOptions, \"experimentId\" | \"testRunId\">,\n): string | undefined {\n const { experimentId, testRunId } = options\n if (\n experimentId !== undefined &&\n testRunId !== undefined &&\n experimentId !== testRunId\n ) {\n throw new BitfabError(\n `experimentId (\"${experimentId}\") and its deprecated alias testRunId (\"${testRunId}\") were both passed with different values. Pass only experimentId.`,\n )\n }\n return experimentId ?? testRunId\n}\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 traceFunctionKey?: string\n sessionId?: string\n name?: string\n contexts: ContextEntry[]\n startedAt: string\n experimentId?: 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 truncation?: TraceTruncation\n}\n\ntype TruncationLimit = \"max_depth\" | \"max_captured_subtree_spans\"\n\nconst TRUNCATION_LIMIT_ORDER: readonly TruncationLimit[] = [\n \"max_depth\",\n \"max_captured_subtree_spans\",\n]\n\ninterface TraceTruncation {\n limits: Set<TruncationLimit>\n droppedSpans: number\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 openAiAgentsSpanIds?: string[]\n spanName: string\n rootTraceFunctionKey: string\n instrumentation: SpanInstrumentation\n declaredNode: boolean\n isRoot: boolean\n}\n\n// Global map to track active trace states\nconst activeTraceStates = new Map<string, TraceState>()\n\nfunction truncationMetadata(\n truncation: TraceTruncation | undefined,\n): Record<string, unknown> | undefined {\n if (truncation === undefined || truncation.limits.size === 0) {\n return undefined\n }\n return {\n \"bitfab.truncated_by\": TRUNCATION_LIMIT_ORDER.filter((limit) =>\n truncation.limits.has(limit),\n ).join(\",\"),\n \"bitfab.dropped_spans\": truncation.droppedSpans,\n }\n}\n\nfunction rootTraceFunctionKeyOfTrace(\n traceId: string,\n fallback: string,\n): string {\n return activeTraceStates.get(traceId)?.traceFunctionKey ?? fallback\n}\n\nfunction rootTraceFunctionKeyOf(\n payload: Record<string, unknown>,\n): string | undefined {\n const captured = payload[ROOT_TRACE_FUNCTION_KEY_FIELD]\n if (typeof captured === \"string\") {\n return captured\n }\n const traceId = payload.traceId\n const live =\n typeof traceId === \"string\"\n ? activeTraceStates.get(traceId)?.traceFunctionKey\n : undefined\n if (typeof live === \"string\") {\n return live\n }\n const own = payload.traceFunctionKey\n return typeof own === \"string\" ? own : undefined\n}\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\nexport function _resolvedApiKey(client: Bitfab): string | null {\n const keyed = client as unknown as {\n findApiKey(callsKeyFunction: boolean): string | undefined\n }\n return keyed.findApiKey(true) ?? null\n}\n\nexport function _serviceUrl(client: Bitfab): string {\n return (client as unknown as { serviceUrl: string }).serviceUrl\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). Its methods\n * write whether or not capture is on.\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\nfunction isSpanType(value: unknown): value is SpanType {\n return SPAN_TYPES.some((spanType) => spanType === value)\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 recordCallerTraceMetadata(traceId, 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\nconst CAPTURE_ENABLED_ENV = \"BITFAB_CAPTURE_ENABLED\"\n\nconst REPLAY_API_KEY_ENV = \"BITFAB_REPLAY_BITFAB_API_KEY\"\n\nconst TRUE_ENV_VALUES = new Set([\"1\", \"true\", \"yes\"])\nconst FALSE_ENV_VALUES = new Set([\"0\", \"false\", \"no\"])\n\nfunction readBooleanEnv(name: string): boolean | undefined {\n const raw = readEnv(name)\n if (raw === undefined) {\n return undefined\n }\n const value = raw.trim().toLowerCase()\n if (value === \"\") {\n return undefined\n }\n if (TRUE_ENV_VALUES.has(value)) {\n return true\n }\n if (FALSE_ENV_VALUES.has(value)) {\n return false\n }\n warnOnce(\n `unrecognized-boolean-env:${name}`,\n `${name}=\"${raw}\" is not 0 or 1; ignoring it.`,\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 ReseedOptions {\n traceId: string\n}\n\nexport interface ReseedResult {\n traceId: string\n previousRunTraceId: 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 simulationPlan?: boolean\n}\n\nexport type { SpanType }\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 /**\n * Experimental selective-replay eligibility, recorded with this span.\n * Attests that the whole subtree is output-only with JSON value semantics:\n * no hidden mutable reads, required effects, input mutations, or reliance\n * on object identity. Include implementation/dependency changes in replay's\n * mustRun. Both capture-time and current declarations must allow reuse.\n * Does not affect ordinary replay or replace mockOnReplay safety protection.\n */\n replayReusable?: boolean\n /** Optional experiment ID included on the span and on the trace it starts. */\n experimentId?: string\n /**\n * @deprecated Use {@link experimentId}. Same meaning. Passing both with\n * different values throws.\n */\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 maxCapturedSubtreeSpans?: 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 EnclosingTrace {\n traceId: string\n spanId: string\n traceFunctionKey: string\n link: NestedTraceLink\n}\n\ninterface InternalSpanOptions extends SpanOptions {\n nameFor?: (receiver: unknown) => string\n instrumentation?: SpanInstrumentation\n functionId?: string\n captureContent?: boolean\n autoTraceDefinition?: AutoTraceFunctionDefinition\n declaredNode?: boolean\n surface?: SurfaceRequest\n nestedTrace?: NestedTraceLink\n enclosingTrace?: EnclosingTrace\n replayOutput?: () => unknown\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 AUTO_TRACE_NODE_FUNCTION_NAMES = new WeakMap<object, string>()\n\nfunction registerAutoTraceNode<T extends object>(\n configured: T,\n functionName: string,\n): T {\n AUTO_TRACE_NODE_FUNCTION_NAMES.set(configured, functionName)\n return configured\n}\nconst DEFAULT_AUTO_TRACE_MAX_DEPTH = 30\nconst DEFAULT_AUTO_TRACE_MAX_CAPTURED_SUBTREE_SPANS = 500\n\nfunction spanOwnerName(receiver: unknown): string | undefined {\n if (typeof receiver === \"function\") {\n return receiver.name !== \"\" ? receiver.name : undefined\n }\n if (typeof receiver !== \"object\" || receiver === null) {\n return undefined\n }\n const owner = (receiver as { constructor?: unknown }).constructor\n if (typeof owner !== \"function\" || owner === Object || owner.name === \"\") {\n return undefined\n }\n return owner.name\n}\n\nfunction qualifiedSpanName(\n receiver: unknown,\n functionName: string | undefined,\n): string | undefined {\n if (functionName === undefined) {\n return undefined\n }\n const owner = spanOwnerName(receiver)\n return owner === undefined ? functionName : `${owner}.${functionName}`\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\n// Re-export BitfabError for backwards compatibility\nexport { BitfabError, MixedTracingError }\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 captureConfiguredInCode: boolean | undefined\n private captureConfiguredFromEnv: boolean | undefined\n private readonly strict: boolean\n private readonly httpClient: HttpClient\n /** Dataset operations for the authenticated organization. */\n readonly datasets: DatasetsClient\n /** Organization-scoped groupings for assertions and scenarios. */\n readonly categories: CategoriesClient\n /** @deprecated Use {@link categories}. Same client. */\n readonly assertionCategories: CategoriesClient\n readonly organizationMembers: OrganizationMembersClient\n readonly traces: TracesClient\n readonly spans: SpansClient\n readonly labels: LabelsClient\n readonly graders: GradersClient\n readonly experiments: ExperimentsClient\n private readonly bamlClient: unknown\n private readonly dbSnapshot: DbSnapshotConfig | undefined\n private readonly simulationPlan: SimulationPlan\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.captureConfiguredInCode =\n config.captureEnabled === undefined && config.enabled === undefined\n ? undefined\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 startCommitRefResolution()\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.simulationPlan = new SimulationPlan(\n this.httpClient,\n config.simulationPlan ?? true,\n )\n this.httpClient.externalSpanTransform = (payload, submit, drop) =>\n this.applySimulationPlan(payload, submit, drop)\n this.httpClient.externalTraceTransform = (payload, submit) =>\n this.simulationPlan.sendTrace(payload, submit)\n this.httpClient.releaseHeldExternalSpans = (timeoutMs) =>\n this.simulationPlan.release(timeoutMs)\n this.httpClient.stopSimulationPlan = () => this.simulationPlan.stop()\n if (this.findApiKey(false) !== undefined) {\n this.simulationPlan.refresh()\n }\n this.datasets = new DatasetsClient(this.httpClient)\n this.categories = new CategoriesClient(this.httpClient)\n this.assertionCategories = this.categories\n this.organizationMembers = new OrganizationMembersClient(this.httpClient)\n this.traces = new TracesClient(this.httpClient)\n this.spans = new SpansClient(this.httpClient)\n this.labels = new LabelsClient(this.httpClient)\n this.graders = new GradersClient(this.httpClient)\n this.experiments = new ExperimentsClient(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. Source exclusions and sim-plan capture-off decisions are explicit\n * opt-outs from that default.\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 controls.\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. Source exclusions and sim-plan capture-off decisions are explicit\n * opt-outs from that default. Without a compatible transform, this still\n * records one normal rich root span and runs the function unchanged.\n *\n * @param traceFunctionKey - Groups traces and their capture controls.\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(\n traceFunctionKey,\n name,\n options,\n fn,\n AUTO_TRACE_NODE_FUNCTION_NAMES.get(fn) ?? fn.name.replace(/^bound /, \"\"),\n )\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 const experimentId = resolveSpanExperimentId(options)\n return {\n capture,\n type: options.type ?? \"custom\",\n ...(options.name !== undefined && { name: options.name }),\n ...(experimentId !== undefined && { experimentId }),\n ...(options.mockOnReplay !== undefined && {\n mockOnReplay: options.mockOnReplay,\n }),\n ...(options.replayReusable !== undefined && {\n replayReusable: options.replayReusable,\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 registerAutoTraceNode(function (\n this: This,\n ...args: TArgs\n ): 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 }, functionName)\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 rootFunctionName = \"\",\n ): (this: This, ...args: TArgs) => TReturn {\n const self = this\n self.simulationPlan.refresh()\n const runRootFunction = (receiver: This, args: TArgs): TReturn =>\n runAsAutoTraceRootFunction(rootFunctionName, () =>\n fn.apply(receiver, args),\n )\n const maxDepth = autoTraceLimit(\n options.maxDepth,\n DEFAULT_AUTO_TRACE_MAX_DEPTH,\n )\n const maxCapturedSubtreeSpans = autoTraceLimit(\n options.maxCapturedSubtreeSpans,\n DEFAULT_AUTO_TRACE_MAX_CAPTURED_SUBTREE_SPANS,\n )\n const rootIsAsync = fn.constructor.name === \"AsyncFunction\"\n const excluded = new Set(options.exclude ?? [])\n const includeWrappers = options.includeWrappers ?? false\n const rootNameFor = (receiver: unknown): string =>\n options.name ??\n (fn.name !== \"\" ? (qualifiedSpanName(receiver, name) ?? name) : name)\n const rootOptions: InternalSpanOptions = {\n name: options.name,\n nameFor: rootNameFor,\n type: options.type ?? \"custom\",\n surface: \"opt-out\",\n instrumentation: \"trace\",\n }\n const buildTracedRoot = (\n spanOptions: InternalSpanOptions,\n ): ((this: This, ...args: TArgs) => TReturn) =>\n this.withSpan(\n traceFunctionKey,\n spanOptions,\n function (this: This, ...args: TArgs): TReturn {\n self.simulationPlan.refresh()\n let capturedSubtreeCount = 0\n const rootSpanStack = getSpanStack()\n const rootSpan = rootSpanStack[rootSpanStack.length - 1]\n const rootTraceState =\n rootSpan === undefined\n ? undefined\n : activeTraceStates.get(rootSpan.traceId)\n const truncation: TraceTruncation = rootTraceState?.truncation ?? {\n limits: new Set(),\n droppedSpans: 0,\n }\n const truncate = (limit: TruncationLimit): void => {\n truncation.limits.add(limit)\n truncation.droppedSpans += 1\n warnOnce(\n `auto-trace-truncated:${traceFunctionKey}`,\n `\"${traceFunctionKey}\" hit an automatic subtree capture limit (maxDepth=${maxDepth}, maxCapturedSubtreeSpans=${maxCapturedSubtreeSpans}); its trace is incomplete. Raise the limits, declare the calls you need with node(), or narrow the subtree with exclude.`,\n )\n }\n if (rootTraceState !== undefined) {\n rootTraceState.truncation = truncation\n }\n const spanStackOf = (entry: AutoTraceEntry): SpanContext[] =>\n entry.spanStack as SpanContext[]\n const openChild = <T>(\n entry: AutoTraceEntry,\n childOptions: InternalSpanOptions,\n inputs: unknown[],\n isAsync: boolean,\n invokeFn: () => T,\n ): T => {\n const runInside = (): T =>\n runWithAutoTraceEntry(\n entry,\n {\n context: autoTraceContext,\n depth: entry.depth + 1,\n spanStack: getSpanStack(),\n },\n invokeFn,\n )\n return runWithSpanStack(spanStackOf(entry), () => {\n if (isAsync) {\n const tracedAsyncChild = self.withSpan(\n traceFunctionKey,\n childOptions,\n async (..._inputs: unknown[]) => await runInside(),\n )\n return tracedAsyncChild(...inputs) as T\n }\n const tracedChild = self.withSpan(\n traceFunctionKey,\n childOptions,\n (..._inputs: unknown[]): T => runInside(),\n )\n return tracedChild(...inputs)\n })\n }\n const rootTraceFunctionKeyOfEntry = (\n entry: AutoTraceEntry,\n ): string => {\n const stack = spanStackOf(entry)\n const innermost = stack[stack.length - 1]\n return innermost === undefined\n ? traceFunctionKey\n : rootTraceFunctionKeyOfTrace(innermost.traceId, traceFunctionKey)\n }\n const recordsSpan = (\n entry: AutoTraceEntry,\n spanName: string,\n declared: boolean,\n ): boolean => {\n const contentOff =\n !declared &&\n self.simulationPlan.contentOffNow(\n rootTraceFunctionKeyOfEntry(entry),\n spanName,\n )\n const countsTowardCapturedSubtree = !declared && !contentOff\n const refusedBy: TruncationLimit | undefined =\n entry.depth >= maxDepth\n ? \"max_depth\"\n : countsTowardCapturedSubtree &&\n capturedSubtreeCount >= maxCapturedSubtreeSpans\n ? \"max_captured_subtree_spans\"\n : undefined\n if (refusedBy !== undefined) {\n truncate(refusedBy)\n return false\n }\n if (countsTowardCapturedSubtree) {\n capturedSubtreeCount += 1\n }\n return true\n }\n const autoTraceContext: AutoTraceContext = {\n traceFunctionKey,\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n invokeFn: () => T,\n entry: AutoTraceEntry,\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 : clearAutoTraceNodeConfiguration(invokeFn)\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 clearAutoTraceNodeConfiguration(invokeFn)\n }\n const spanName = nodeConfiguration?.name ?? definition.name\n const declaredNode = nodeConfiguration !== undefined\n if (!recordsSpan(entry, spanName, declaredNode)) {\n return invokeWithoutNode()\n }\n const mockOnReplay =\n nodeConfiguration?.mockOnReplay ?? options.mockOnReplayDefault\n const nodeExperimentId =\n nodeConfiguration === undefined\n ? undefined\n : resolveSpanExperimentId(nodeConfiguration)\n const childOptions: InternalSpanOptions = {\n name: spanName,\n type: nodeConfiguration?.type ?? \"function\",\n captureWhen: \"nested\",\n surface: \"opt-out\",\n instrumentation: \"trace\",\n functionId: definition.id,\n captureContent: true,\n autoTraceDefinition: definition,\n ...(declaredNode && { declaredNode }),\n ...(nodeExperimentId !== undefined && {\n experimentId: nodeExperimentId,\n }),\n ...(mockOnReplay !== undefined && {\n mockOnReplay,\n }),\n ...(nodeConfiguration?.replayReusable !== undefined && {\n replayReusable: nodeConfiguration.replayReusable,\n }),\n ...(nodeConfiguration?.finalize !== undefined && {\n finalize: nodeConfiguration.finalize,\n }),\n }\n return openChild(\n entry,\n childOptions,\n inputs,\n definition.async === true,\n invokeFn,\n )\n },\n invokeNestedRoot<T>(\n nestedName: string,\n nestedFunctionName: string,\n inputs: unknown[],\n invokeFn: () => T,\n entry: AutoTraceEntry,\n link: NestedTraceLink | undefined,\n ): T {\n if (\n excluded.has(nestedName) ||\n excluded.has(nestedFunctionName) ||\n !recordsSpan(entry, nestedName, true)\n ) {\n return invokeFn()\n }\n const childOptions: InternalSpanOptions = {\n name: nestedName,\n type: \"function\",\n captureWhen: \"nested\",\n surface: \"opt-out\",\n instrumentation: \"trace\",\n captureContent: true,\n declaredNode: true,\n ...(link !== undefined && { nestedTrace: link }),\n }\n return openChild(entry, childOptions, inputs, false, invokeFn)\n },\n }\n\n return runWithAutoTraceRootContext(\n autoTraceContext,\n getSpanStack(),\n () => runRootFunction(this, args),\n )\n },\n )\n const tracedRoot = buildTracedRoot(rootOptions)\n const autoTraceRoot = function (this: This, ...args: TArgs): TReturn {\n if (!self.shouldRecord() || isCaptureSuppressed()) {\n return fn.apply(this, args)\n }\n const enclosing = currentAutoTraceEntries()\n if (enclosing.length === 0) {\n const firstPlanRead = rootIsAsync\n ? self.simulationPlan.waitForFirstRead()\n : undefined\n if (firstPlanRead !== undefined) {\n return firstPlanRead.then(() =>\n tracedRoot.apply(this, args),\n ) as TReturn\n }\n return tracedRoot.apply(this, args)\n }\n const link: NestedTraceLink | undefined =\n getReplayContext() || inSeedScope() ? undefined : { traceFunctionKey }\n const rootName = rootNameFor(this)\n return invokeThroughAutoTraceEntries(\n enclosing,\n (entry, next) =>\n entry.context.invokeNestedRoot(\n rootName,\n name,\n args,\n next,\n entry,\n link,\n ),\n () => {\n if (link === undefined) {\n return runRootFunction(this, args)\n }\n const innermost = enclosing[enclosing.length - 1] as AutoTraceEntry\n const innermostNow =\n currentAutoTraceEntries().find(\n (entry) => entry.context === innermost.context,\n ) ?? innermost\n const innermostStack = innermostNow.spanStack as SpanContext[]\n const copy = innermostStack[innermostStack.length - 1]\n const detachedRoot = buildTracedRoot({\n ...rootOptions,\n ...(copy !== undefined && {\n enclosingTrace: {\n traceId: copy.traceId,\n spanId: copy.spanId,\n traceFunctionKey: innermost.context.traceFunctionKey,\n link,\n },\n }),\n })\n return runWithSpanStack([], () => detachedRoot.apply(this, args))\n },\n )\n }\n return markTracedFunction(autoTraceRoot, traceFunctionKey, fn)\n }\n\n private applySimulationPlan(\n payload: Record<string, unknown>,\n submit: SimulationPlanSubmit,\n drop: () => void,\n ): void {\n this.simulationPlan.send(\n payload,\n rootTraceFunctionKeyOf(payload),\n submit,\n drop,\n )\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 findApiKey(callsKeyFunction: boolean): string | undefined {\n const replayKey = readEnv(REPLAY_API_KEY_ENV)\n if (replayKey && replayKey.trim() !== \"\") {\n return replayKey\n }\n if (this.resolvedApiKey !== undefined) {\n return this.resolvedApiKey\n }\n if (typeof this.apiKeyConfig === \"function\" && !callsKeyFunction) {\n return undefined\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 }\n return key\n }\n\n private resolveApiKey(): string | undefined {\n const key = this.findApiKey(true)\n if (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.isCaptureConfigured() && !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 isCaptureConfigured(): boolean {\n if (this.captureConfiguredInCode !== undefined) {\n return this.captureConfiguredInCode\n }\n if (this.captureConfiguredFromEnv === undefined) {\n this.captureConfiguredFromEnv =\n readBooleanEnv(CAPTURE_ENABLED_ENV) ?? true\n }\n return this.captureConfiguredFromEnv\n }\n\n private isCaptureEnabled(): boolean {\n if (!this.isCaptureConfigured()) {\n return false\n }\n return this.resolveApiKey() !== undefined\n }\n\n private shouldRecord(): boolean {\n if (!this.isCaptureConfigured() && !getReplayContext() && !inSeedScope()) {\n return false\n }\n return this.resolveApiKey() !== undefined\n }\n\n private prepareFrameworkIntegration(): void {\n if (this.isCaptureConfigured() && this.strict) {\n this.resolveApiKey()\n }\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 if (this.shouldRecord()) {\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\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 this.prepareFrameworkIntegration()\n return new BitfabOpenAITracingProcessor({\n serviceUrl: this.serviceUrl,\n shouldRecord: () => this.shouldRecord(),\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 this.prepareFrameworkIntegration()\n return new BitfabLangGraphCallbackHandler({\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n shouldRecord: () => this.shouldRecord(),\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 this.prepareFrameworkIntegration()\n const callbackHandler = new BitfabLangGraphCallbackHandler({\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n shouldRecord: () => this.shouldRecord(),\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 the first-class Rivet actor/workflow-context integration for an\n * existing trace root. The integration binds context and records effect\n * spans; it never creates another root.\n *\n * @param traceFunctionKey - Key used by the enclosing `withTrace()` root\n * @param options - Explicit per-context-path replay mocking policy\n * @experimental This API may change before it is stable.\n */\n getRivetIntegration<TContext extends object = RivetContextLike>(\n traceFunctionKey: string,\n options?: RivetIntegrationOptions,\n ): BitfabRivetIntegration<TContext> {\n return new BitfabRivetIntegration<TContext>(\n traceFunctionKey,\n {\n wrapEffect: <TArgs extends unknown[], TReturn>(\n effect: RivetEffectType,\n mockOnReplay: boolean,\n fn: (...args: TArgs) => TReturn,\n replayOutput?: () => unknown,\n ) => {\n const spanOptions: InternalSpanOptions = {\n name: effect,\n type: \"function\",\n captureWhen: \"nested\",\n mockOnReplay,\n surface: \"inherit\",\n instrumentation: \"rivet\",\n ...(replayOutput !== undefined && { replayOutput }),\n }\n return this.withSpan(traceFunctionKey, spanOptions, fn)\n },\n recordRootFixture: (context, recordedRoots) => {\n const root = getSpanStack()[0]\n if (!root) {\n return\n }\n const rootId = `${root.traceId}:${root.spanId}`\n if (recordedRoots.has(rootId)) {\n return\n }\n root.contexts.push(context)\n recordedRoots.add(rootId)\n },\n },\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 this.prepareFrameworkIntegration()\n return new BitfabClaudeAgentHandler({\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n shouldRecord: () => this.shouldRecord(),\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 this.simulationPlan.refresh()\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 const optionExperimentId = resolveSpanExperimentId(options)\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() || isCaptureSuppressed()) {\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 let startedSpan: { traceId: string; spanId: 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 openAiAgentsParent =\n parentContext !== undefined && options.instrumentation === \"trace\"\n ? openAiAgentsParentSpanId(\n parentContext.traceId,\n parentContext.openAiAgentsSpanIds,\n )\n : undefined\n const parentSpanId = openAiAgentsParent ?? parentContext?.spanId ?? null\n const isRootSpan = parentSpanId === null\n if (options.enclosingTrace !== undefined) {\n options.enclosingTrace.link.traceId = traceId\n options.enclosingTrace.link.rootSpanId = spanId\n }\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 const openAiAgentsSpanIds = openAiAgentsSpanChain()\n const functionNameAtOpen = fn.name !== \"\" ? fn.name : undefined\n const newContext: SpanContext = {\n traceId,\n spanId,\n contexts: [],\n spanName:\n options.name ??\n options.nameFor?.(this) ??\n qualifiedSpanName(this, functionNameAtOpen) ??\n traceFunctionKey,\n rootTraceFunctionKey: rootTraceFunctionKeyOfTrace(\n traceId,\n traceFunctionKey,\n ),\n instrumentation: options.instrumentation ?? \"span\",\n declaredNode: options.declaredNode === true,\n isRoot: isRootSpan,\n ...(surface !== undefined && { surface }),\n ...(openAiAgentsSpanIds.length > 0 && { openAiAgentsSpanIds }),\n }\n const nearestCapturedAncestorSpanId =\n self.nearestCapturedAncestorSpanIdOf(currentStack)\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 experimentId =\n replayCtxAtStart?.experimentId ?? optionExperimentId\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 self.simulationPlan.refresh()\n activeTraceStates.set(traceId, {\n traceId,\n traceFunctionKey,\n startedAt,\n contexts: [],\n ...(experimentId !== undefined && { experimentId }),\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 self.httpClient.traceCompletion.start(traceId, spanId)\n startedSpan = { traceId, spanId }\n const functionName = functionNameAtOpen\n const baseSpanParams = {\n traceFunctionKey,\n rootTraceFunctionKey: newContext.rootTraceFunctionKey,\n functionName,\n spanName: newContext.spanName,\n traceId,\n spanId,\n parentSpanId,\n nearestCapturedAncestorSpanId,\n inputs,\n startedAt,\n spanType: options.type ?? \"custom\",\n instrumentation: options.instrumentation ?? \"span\",\n functionId: options.functionId,\n captureContent: options.captureContent ?? true,\n replayReusable: options.replayReusable,\n autoTraceDefinition: options.autoTraceDefinition,\n declaredNode: options.declaredNode === true,\n nestedTrace: options.nestedTrace,\n enclosingTrace: options.enclosingTrace,\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 ...(experimentId !== undefined && { experimentId }),\n ...(replayCtx?.inputSourceSpanId && {\n inputSourceSpanId: replayCtx.inputSourceSpanId,\n }),\n })\n }\n\n if (isRootSpan) {\n const traceState = activeTraceStates.get(traceId)\n const truncated = truncationMetadata(traceState?.truncation)\n if (truncated !== undefined) {\n recordCallerTraceMetadata(traceId, truncated)\n }\n self.sendTraceCompletion({\n traceFunctionKey,\n traceId,\n startedAt: traceState?.startedAt ?? startedAt,\n endedAt,\n sessionId: traceState?.sessionId,\n name: traceState?.name,\n metadata: callerTraceMetadata(traceId),\n contexts: traceState?.contexts ?? [],\n experimentId: traceState?.experimentId,\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 retireTraceMetadata(traceId)\n }\n } catch {\n // Silently ignore - user's result/exception takes priority\n } finally {\n self.httpClient.traceCompletion.end(traceId, spanId)\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:\n error instanceof StreamFinalizationError\n ? error.output\n : undefined,\n error:\n error instanceof StreamFinalizationError\n ? error.message\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 const resolveMockOrAbort = async <T>(\n resolve: () => T | Promise<T>,\n ): Promise<T> => {\n try {\n return await resolve()\n } catch (error) {\n self.httpClient.traceCompletion.abort(traceId, spanId)\n throw error\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?.selectiveReplay) {\n const decision = replayCtxForMock.selectiveReplay.enter({\n traceFunctionKey,\n spanName: baseSpanParams.spanName ?? traceFunctionKey,\n spanId,\n parentSpanId,\n inputs: args,\n safetyMock: !isRootSpan && options.mockOnReplay === true,\n reuseAllowed: options.replayReusable === true,\n canReuseOutput:\n options.finalize === undefined &&\n options.replayOutput === undefined &&\n !fn.constructor.name.includes(\"Generator\"),\n })\n if (decision.mock) {\n void sendSpan({\n result: decision.output,\n mocked: true,\n mockTarget: \"output\",\n mockSource: \"recorded\",\n })\n return (\n fnReturnsPromise\n ? Promise.resolve(decision.output)\n : decision.output\n ) as TReturn\n }\n }\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 resolveMockOrAbort(() => 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 const resolveBaseOutput = (): unknown | Promise<unknown> =>\n options.replayOutput !== undefined\n ? options.replayOutput()\n : resolveRecordedOutput()\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 resolveMockOrAbort(() => 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 resolveMockOrAbort(() =>\n resolveBaseOutput(),\n )\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 = resolveBaseOutput()\n if (recorded instanceof Promise) {\n return emitMockAsync(recorded, \"recorded\")\n }\n return emitMock(recorded, \"recorded\")\n }\n }\n } catch (setupError) {\n if (startedSpan) {\n self.httpClient.traceCompletion.abort(\n startedSpan.traceId,\n startedSpan.spanId,\n )\n }\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 retireTraceMetadata(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 return markTracedFunction(wrappedFn, traceFunctionKey, fn)\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 (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 (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 (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 (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 * Look up by `id` alone, or by `name` and/or `type` (both must match when\n * both are given). Name and type lookups return the last matching span by\n * default. Pass `occurrence` as `\"first\"` or a zero-based index to select a\n * different match. Returns `null` when no span matches.\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 hasNameOrType = lookup.name !== undefined || lookup.type !== undefined\n if (hasId === hasNameOrType) {\n throw new BitfabError(\"Provide id, or name and/or type\")\n }\n if (hasId) {\n validateSpanId(lookup.id)\n } else {\n if (lookup.name !== undefined && lookup.name.length === 0) {\n throw new BitfabError(\"name must be a non-empty string\")\n }\n if (lookup.type !== undefined && !isSpanType(lookup.type)) {\n throw new BitfabError(`type must be one of ${SPAN_TYPES.join(\", \")}`)\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 async getSpan(spanId: string): Promise<CapturedSpan | null> {\n if (typeof spanId !== \"string\" || spanId.trim().length === 0) {\n throw new BitfabError(\"spanId must be a non-empty string\")\n }\n return this.httpClient.getSpan(spanId)\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 this.simulationPlan.refresh()\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 experimentId?: 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 const commitRef = currentCommitRef()\n if (commitRef) {\n rawTrace.commit_ref = commitRefWire(commitRef)\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.experimentId !== undefined &&\n experimentIdWireFields(params.experimentId)),\n })\n }\n\n private sendsSpanOnCompletion(context: SpanContext): boolean {\n return (\n context.isRoot ||\n context.declaredNode ||\n isFrameworkInstrumentation(context.instrumentation) ||\n !this.simulationPlan.contentOffNow(\n context.rootTraceFunctionKey,\n context.spanName,\n )\n )\n }\n\n private nearestCapturedAncestorSpanIdOf(stack: SpanContext[]): string | null {\n for (let index = stack.length - 1; index >= 0; index -= 1) {\n const candidate = stack[index]\n if (candidate !== undefined && this.sendsSpanOnCompletion(candidate)) {\n return candidate.spanId\n }\n }\n return null\n }\n\n private contentOffBySimulationPlan(params: {\n rootTraceFunctionKey?: string\n spanName: string\n instrumentation: SpanInstrumentation\n parentSpanId: string | null\n }): boolean {\n if (\n params.rootTraceFunctionKey === undefined ||\n isFrameworkInstrumentation(params.instrumentation)\n ) {\n return false\n }\n return (\n this.simulationPlan.contentOffNow(\n params.rootTraceFunctionKey,\n params.spanName,\n ) ||\n (params.parentSpanId !== null && this.simulationPlan.unavailableNow())\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 rootTraceFunctionKey?: 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 instrumentation: SpanInstrumentation\n contexts?: ContextEntry[]\n prompt?: string\n experimentId?: string\n inputSourceSpanId?: string\n mocked?: boolean\n mockTarget?: MockTarget\n mockSource?: MockSource\n functionId?: string\n captureContent: boolean\n nearestCapturedAncestorSpanId?: string | null\n replayReusable?: boolean\n autoTraceDefinition?: AutoTraceFunctionDefinition\n declaredNode?: boolean\n nestedTrace?: NestedTraceLink\n enclosingTrace?: EnclosingTrace\n }): void {\n const contentOff =\n params.declaredNode !== true && this.contentOffBySimulationPlan(params)\n const buildsContent = params.captureContent && !contentOff\n const serializedInputs = buildsContent\n ? serializeValue(params.inputs)\n : undefined\n const serializedResult = buildsContent\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_origin: makeSpanOrigin(params.instrumentation),\n span_data: {\n name: params.spanName,\n ...(params.replayReusable !== undefined && {\n replay_reusable: params.replayReusable,\n }),\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 ...(params.nestedTrace?.traceId !== undefined && {\n nested_trace_id: params.nestedTrace.traceId,\n nested_trace_function_key: params.nestedTrace.traceFunctionKey,\n nested_root_span_id: params.nestedTrace.rootSpanId,\n }),\n ...(params.enclosingTrace !== undefined && {\n enclosing_trace_id: params.enclosingTrace.traceId,\n enclosing_trace_function_key: params.enclosingTrace.traceFunctionKey,\n enclosing_span_id: params.enclosingTrace.spanId,\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 ...(buildsContent &&\n params.prompt !== undefined && { prompt: params.prompt }),\n ...(contentOff && { [CONTENT_OFF_KEY]: true }),\n },\n }\n\n // Add parent_id for nested spans\n if (params.parentSpanId) {\n externalSpan.parent_id = params.parentSpanId\n }\n if (\n params.nearestCapturedAncestorSpanId !== undefined &&\n params.nearestCapturedAncestorSpanId !== null &&\n params.nearestCapturedAncestorSpanId !== params.parentSpanId\n ) {\n externalSpan.nearest_captured_ancestor_id =\n params.nearestCapturedAncestorSpanId\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 ...(params.rootTraceFunctionKey !== undefined && {\n [ROOT_TRACE_FUNCTION_KEY_FIELD]: params.rootTraceFunctionKey,\n }),\n ...(params.declaredNode === true && { [DECLARED_NODE_FIELD]: true }),\n rawSpan: externalSpan,\n ...(params.experimentId !== undefined &&\n experimentIdWireFields(params.experimentId)),\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 an experiment.\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 experiment. 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, experimentId, and experimentUrl\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 if (options.metadata !== undefined) {\n recordCallerTraceMetadata(traceId, options.metadata)\n }\n activeTraceStates.set(traceId, {\n traceId,\n traceFunctionKey,\n startedAt,\n contexts: [],\n ingestionType: \"seeded\",\n ...(options.sessionId !== undefined && { sessionId: options.sessionId }),\n ...(options.name !== undefined && { name: options.name }),\n })\n\n try {\n this.sendWrapperSpan({\n traceFunctionKey,\n rootTraceFunctionKey: 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 instrumentation: \"span\",\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: callerTraceMetadata(traceId),\n contexts: [],\n ingestionType: \"seeded\",\n })\n } finally {\n activeTraceStates.delete(traceId)\n retireTraceMetadata(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 if (options?.metadata !== undefined) {\n recordCallerTraceMetadata(traceId, options.metadata)\n }\n activeTraceStates.set(traceId, {\n traceId,\n traceFunctionKey,\n startedAt: nowIsoTimestamp(),\n contexts: [],\n ingestionType: \"seeded\",\n ...(options?.sessionId !== undefined && { sessionId: options.sessionId }),\n ...(options?.name !== undefined && { name: options.name }),\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 retireTraceMetadata(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 reseedTrace(\n traceFunctionKey: string,\n // biome-ignore lint/suspicious/noExplicitAny: the recorded inputs are deserialized from the trace, typed args would be incorrect\n fn: (...args: any[]) => unknown,\n options: ReseedOptions,\n ): Promise<ReseedResult> {\n const source = await this.httpClient.getReseedSource(options.traceId)\n if (source.traceFunctionKey !== traceFunctionKey) {\n throw new BitfabError(\n `Trace ${options.traceId} belongs to '${source.traceFunctionKey}', not '${traceFunctionKey}'.`,\n )\n }\n const args = deserializeInputs({\n input: source.input,\n input_meta: source.inputMeta,\n })\n const runTraceId = await this.seedTraceByRunning(\n traceFunctionKey,\n fn as (...args: never[]) => unknown,\n {\n args: args as never[],\n metadata: source.metadata,\n ...(source.sessionId === null ? {} : { sessionId: source.sessionId }),\n ...(source.name === null ? {} : { name: source.name }),\n },\n )\n const adopted = await this.httpClient.reseedTrace(\n options.traceId,\n runTraceId,\n )\n return {\n traceId: adopted.traceId,\n previousRunTraceId: adopted.previousRunTraceId,\n }\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 * Wrap a function as an automatically expanded trace root bound to this\n * function's key.\n *\n * Equivalent to `client.withTrace(key, options, fn)` but reuses the key\n * bound on this handle.\n *\n * @param optionsOrFn - Trace options or the workflow entrypoint to wrap\n * @param maybeFn - Workflow entrypoint when options are provided\n * @returns A wrapped function with the same signature\n * @experimental Automatic child-call instrumentation is experimental.\n */\n withTrace<This, TArgs extends unknown[], TReturn>(\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn\n withTrace<This, TArgs extends unknown[], TReturn>(\n options: TraceOptions,\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn\n withTrace<This, TArgs extends unknown[], TReturn>(\n optionsOrFn: TraceOptions | ((this: This, ...args: TArgs) => TReturn),\n maybeFn?: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn {\n if (typeof optionsOrFn === \"function\") {\n return this.client.withTrace(this.traceFunctionKey, optionsOrFn)\n }\n if (!maybeFn) {\n throw new BitfabError(\"BitfabFunction.withTrace requires a function\")\n }\n return this.client.withTrace(this.traceFunctionKey, optionsOrFn, maybeFn)\n }\n\n /**\n * Create a trace method decorator bound to this function's key.\n *\n * Equivalent to `client.trace(key, options)` but reuses the key bound on\n * this handle.\n *\n * @param options - Trace configuration applied to the decorated method\n * @returns A method decorator configured for this key\n * @experimental Automatic child-call instrumentation is experimental.\n */\n trace(options: TraceOptions = {}): TraceMethodDecorator {\n return this.client.trace(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 * Get the first-class Rivet actor-context integration bound to this key.\n * Use its `bind()` or `withContext()` outside this handle's `withTrace()`\n * root, then call `getContext()` inside the root.\n *\n * @param options - Explicit per-context-path replay mocking policy\n * @experimental This API may change before it is stable.\n */\n getRivetIntegration<TContext extends object = RivetContextLike>(\n options?: RivetIntegrationOptions,\n ): BitfabRivetIntegration<TContext> {\n return this.client.getRivetIntegration<TContext>(\n this.traceFunctionKey,\n options,\n )\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","import type { ApprovalState } from \"./approval.js\"\nimport { _resolvedApiKey, _serviceUrl, 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 warnJudgeAssertionsDeprecated,\n} from \"./replay.js\"\nimport {\n describeReplayInterrupt,\n type ReplayInterruptSignal,\n} from \"./replayInterrupt.js\"\nimport { canonicalCliFlag, withCliFlags } from \"./replayInvocation.js\"\nimport { warnOnce } from \"./warnOnce.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\" | \"onExperimentStart\"\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 validateReplayRegistry(registry)\n return registry\n}\n\nconst REGISTRATION_FIELDS = new Set([\n \"client\",\n \"fn\",\n \"traceFunctionKey\",\n \"options\",\n \"optionsFactory\",\n])\n\nexport function validateReplayRegistry(registry: ReplayRegistry): void {\n for (const [pipeline, registration] of Object.entries(registry)) {\n if (typeof registration !== \"object\" || registration === null) {\n throw new BitfabError(\n `Replay registry entry '${pipeline}' must be an object with client and fn.`,\n )\n }\n const unknownFields = Object.keys(registration).filter(\n (field) => !REGISTRATION_FIELDS.has(field),\n )\n if (unknownFields.length > 0) {\n warnOnce(\n `replay-registry-unknown-fields:${pipeline}:${unknownFields.join(\",\")}`,\n `Replay registry entry '${pipeline}' has unknown field(s): ${unknownFields.join(\", \")}. ` +\n \"They are ignored. An entry takes client, fn, traceFunctionKey, options, and optionsFactory. \" +\n \"Put replay options such as adaptInputs, mock, and mockOverride inside options. \" +\n \"A later SDK release will reject unknown fields.\",\n )\n }\n }\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 notes?: string\n metadata?: Record<string, string>\n maxConcurrency?: number\n codeChangePath?: string\n experimentGroupId?: string\n experimentGroupName?: string\n datasetIds?: string[]\n graderIds?: string[]\n onlyWithAssertions?: boolean\n skipAssertionJudging?: boolean\n judgeAssertionsFlag?: boolean\n mock?: \"none\" | \"all\" | \"marked\"\n dbBranch?: boolean\n noCodeChange?: boolean\n dryRun?: boolean\n failOnError?: boolean\n paramsPath?: string\n params: string[]\n resume?: string\n force?: boolean\n flags: Record<string, unknown>\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 \"--notes\",\n \"--metadata\",\n \"--concurrency\",\n \"--max-concurrency\",\n \"--code-change\",\n \"--experiment-group-id\",\n \"--experiment-group-name\",\n \"--dataset-id\",\n \"--dataset-ids\",\n \"--grader-ids\",\n \"--mock\",\n \"--param\",\n \"--params\",\n \"--resume\",\n])\n\nconst BOOLEAN_FLAGS = new Set([\n \"--only-with-assertions\",\n \"--skip-assertion-judging\",\n \"--judge-assertions\",\n \"--db-branch\",\n \"--no-db-branch\",\n \"--no-code-change\",\n \"--dry-run\",\n \"--fail-on-error\",\n \"--force\",\n])\n\nconst HELP_FLAGS = new Set([\"--help\", \"-h\"])\n\nconst REPEATABLE_FLAGS = new Set([\"--metadata\", \"--param\"])\n\nfunction recordFlag(\n flags: Record<string, unknown>,\n flag: string,\n raw?: string,\n): void {\n const name = canonicalCliFlag(flag.slice(2))\n if (raw === undefined) {\n flags[name] = true\n return\n }\n const value = flag === \"--param\" ? raw.split(\"=\")[0] : raw\n if (REPEATABLE_FLAGS.has(flag)) {\n const previous = flags[name]\n flags[name] = [...(Array.isArray(previous) ? previous : []), value]\n return\n }\n flags[name] = value\n}\n\nconst MAX_ATTEMPTS = 100\n\nconst MAX_PINNED_TRACE_IDS = 100\n\nconst INTERRUPT_EXIT_CODES: Record<ReplayInterruptSignal, number> = {\n SIGINT: 130,\n SIGTERM: 143,\n}\n\nconst RESUME_CONFLICTING_FLAGS: ReadonlyArray<[keyof ReplayCliArgs, string]> = [\n [\"traceIds\", \"--trace-ids\"],\n [\"datasetIds\", \"--dataset-ids\"],\n [\"limit\", \"--limit\"],\n [\"attempts\", \"--attempts\"],\n [\"graderIds\", \"--grader-ids\"],\n [\"onlyWithAssertions\", \"--only-with-assertions\"],\n [\"dryRun\", \"--dry-run\"],\n]\n\nconst RESUME_CLEARED_OPTIONS: Partial<ReplayOptions> = {\n traceIds: undefined,\n limit: undefined,\n datasetId: undefined,\n datasetIds: undefined,\n attempts: undefined,\n graderIds: undefined,\n onlyWithAssertions: undefined,\n dryRun: undefined,\n}\n\nfunction hasApprovedAssertion(\n assertions: { approvalState: ApprovalState }[],\n): boolean {\n return assertions.some((assertion) => assertion.approvalState === \"approved\")\n}\n\nasync function boundTraceIds(\n client: Bitfab,\n traceIds: string[],\n limit: number,\n onlyWithAssertions: boolean,\n): Promise<string[]> {\n if (!Number.isInteger(limit) || limit < 1) {\n throw new BitfabError(\"Replay limit must be a positive integer.\")\n }\n if (!onlyWithAssertions || limit >= traceIds.length) {\n return traceIds.slice(0, limit)\n }\n const selected: string[] = []\n for (const traceId of traceIds) {\n const { assertions, inheritedFrom } =\n await client.traces.getAssertions(traceId)\n if (inheritedFrom === null && hasApprovedAssertion(assertions)) {\n selected.push(traceId)\n if (selected.length === limit) {\n break\n }\n }\n }\n if (selected.length === 0) {\n throw new BitfabError(\n \"No traces with approved assertions matched this replay selection.\",\n )\n }\n return selected\n}\n\nasync function pinnedDatasetMembers(\n client: Bitfab,\n datasetIds: string[],\n limit: number,\n onlyWithAssertions = false,\n): Promise<string[] | undefined> {\n const members = new Set<string>()\n for (const datasetId of datasetIds) {\n const { traceIds } = await client.datasets.listTraces(datasetId)\n for (const traceId of traceIds) {\n members.add(traceId)\n }\n }\n const ordered = [...members].sort()\n if (limit >= ordered.length) {\n return undefined\n }\n if (limit > MAX_PINNED_TRACE_IDS) {\n throw new BitfabError(\n `Bounding a dataset replay to ${limit} names one trace ID per replayed item, and a replay accepts at most ${MAX_PINNED_TRACE_IDS}. Drop the limit to replay every selected dataset in full.`,\n )\n }\n return boundTraceIds(client, ordered, limit, onlyWithAssertions)\n}\n\nfunction usage(registry: ReplayRegistry | undefined): string {\n const pipelines =\n registry === undefined ? \"pipeline\" : Object.keys(registry).join(\"|\")\n return `Usage: bitfab-replay --registry <path> <${pipelines}> [options]\\n\\nOptions:\\n --limit N (bounds a trace ID or dataset selection instead of replacing it)\\n --attempts N (replay each trace N times in this run, max ${MAX_ATTEMPTS})\\n --trace-ids id1,id2\\n --name NAME (what this run is testing, such as \"baseline\"; Bitfab already records the commit, branch, and datasets)\\n --notes TEXT (run conditions Bitfab cannot see, such as a forced feature flag)\\n --metadata key=value (repeatable; tags kept on the experiment, such as which schedule launched it, and filterable through client.experiments.list)\\n --concurrency N, --max-concurrency N\\n --code-change PATH, --no-code-change\\n --experiment-group-id UUID (join this experiment group; a new UUID creates the group)\\n --experiment-group-name NAME (name the group when this run creates it or it has no name yet; requires --experiment-group-id)\\n --dataset-ids uuid1,uuid2 (--dataset-id is the same flag)\\n --grader-ids id1,id2\\n --only-with-assertions (replay only traces carrying an approved assertion)\\n --skip-assertion-judging (don't judge approved assertions on each replay; judging is on by default and costs model calls)\\n --judge-assertions (deprecated: judging is on by default)\\n --mock none|all|marked\\n --db-branch, --no-db-branch\\n --dry-run (resolve inputs, run nothing)\\n --fail-on-error (exit 1 after printing the result when any replayed item errored; under --dry-run, items whose inputs failed to resolve count)\\n --resume EXPERIMENT_ID (finish an experiment that stopped partway, running only the items it did not finish, with the traces, attempts, and graders it started with)\\n --force (with --resume, resume even when the experiment may still be running or the code changed since it started)\\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\nexport interface ReseedRegistryResult {\n pipeline: string\n traceFunctionKey: string\n reseeded: { traceId: string; previousRunTraceId: string }[]\n}\n\nexport async function reseedFromRegistry(\n registry: ReplayRegistry,\n pipeline: string,\n traceIds: readonly string[],\n): Promise<ReseedRegistryResult> {\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 const reseeded: ReseedRegistryResult[\"reseeded\"] = []\n for (const traceId of traceIds) {\n reseeded.push(\n await registration.client.reseedTrace(traceFunctionKey, registration.fn, {\n traceId,\n }),\n )\n }\n return { pipeline, traceFunctionKey, reseeded }\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-seed --registry <path> <pipeline> --from-trace <id>[,<id>...]\\n bitfab-seed --registry <path> <pipeline> --cases <cases.jsonl> [--run]\\n\\n--from-trace re-seeds each trace: the registered function runs once on the trace\\'s recorded inputs and the result is recorded under the same trace id, with the previous run kept as history under a new id. Nothing is mocked and no experiment is created. Labels, assertions, and dataset membership stay on the trace.\\n\\n--cases seeds new cases. Each case is a JSON object with an \"input\" array, plus optional \"expected\", \"metadata\", and \"sessionId\"; a JSON array of those objects works too. Without --run, each case is written as a trace directly (\"input\" becomes the root span input and \"expected\" its output) and nothing executes. With --run, each case runs 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\\nbitfab-replay --registry <path> <pipeline> --seed <cases.jsonl> [--run] is the older spelling of --cases.'\n\nexport async function runSeedCli(\n registry: ReplayRegistry,\n argv: readonly string[],\n io: ReplayCliIo = {},\n): Promise<SeedResult | ReseedRegistryResult> {\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 fromTraceIndex = argv.indexOf(\"--from-trace\")\n if (fromTraceIndex !== -1) {\n const raw = argv[fromTraceIndex + 1]\n if (raw === undefined || raw.startsWith(\"--\")) {\n throw new BitfabError(\"--from-trace requires one or more trace ids.\")\n }\n const traceIds = commaSeparated(\"--from-trace\", raw)\n stderr(\n `[seed] Re-seeding ${traceIds.length} trace(s) through \"${pipeline}\"...`,\n )\n const result = await reseedFromRegistry(registry, pipeline, traceIds)\n for (const entry of result.reseeded) {\n stderr(\n `[seed] ${entry.traceId} now holds the fresh run; the previous run is kept as ${entry.previousRunTraceId}`,\n )\n }\n stdout(JSON.stringify(result, null, 2))\n return result\n }\n const casesFlagIndex = argv.indexOf(\"--cases\")\n const seedIndex =\n casesFlagIndex === -1 ? argv.indexOf(\"--seed\") : casesFlagIndex\n if (seedIndex === -1) {\n throw new BitfabError(SEED_USAGE)\n }\n const casesPath = argv[seedIndex + 1]\n if (casesPath === undefined || casesPath.startsWith(\"--\")) {\n throw new BitfabError(`${argv[seedIndex]} 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\nexport function checkReplayCliArgs(argv: readonly string[]): void {\n parseReplayCliArgs(undefined, argv)\n}\n\nfunction parseReplayCliArgs(\n registry: ReplayRegistry | undefined,\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 (\n pipeline === undefined ||\n (registry !== undefined && registry[pipeline] === undefined)\n ) {\n throw new BitfabError(usage(registry))\n }\n\n const parsed: ReplayCliArgs = { pipeline, params: [], flags: {} }\n for (let index = 1; index < argv.length; index += 1) {\n const flag = argv[index]\n if (BOOLEAN_FLAGS.has(flag)) {\n recordFlag(parsed.flags, 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 \"--only-with-assertions\":\n // Left undefined when absent, never set to false: absence means the\n // command line said nothing, so a registry that set the option keeps\n // it. Only a present flag speaks.\n parsed.onlyWithAssertions = true\n break\n case \"--skip-assertion-judging\":\n parsed.skipAssertionJudging = true\n break\n case \"--judge-assertions\":\n parsed.judgeAssertionsFlag = true\n break\n case \"--no-code-change\":\n parsed.noCodeChange = true\n break\n case \"--dry-run\":\n parsed.dryRun = true\n break\n case \"--fail-on-error\":\n parsed.failOnError = true\n break\n case \"--force\":\n parsed.force = 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 recordFlag(parsed.flags, flag, raw)\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 \"--notes\":\n parsed.notes = raw\n break\n case \"--metadata\": {\n const [key, value] = parseMetadataTag(raw)\n parsed.metadata = { ...parsed.metadata, [key]: value }\n break\n }\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 \"--experiment-group-name\":\n parsed.experimentGroupName = raw\n break\n case \"--dataset-id\":\n case \"--dataset-ids\":\n parsed.datasetIds = commaSeparated(flag, 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 case \"--resume\":\n parsed.resume = raw\n break\n }\n }\n if (parsed.force === true && parsed.resume === undefined) {\n throw new BitfabError(\"--force only applies with --resume <experimentId>.\")\n }\n if (parsed.resume !== undefined) {\n const conflicting = RESUME_CONFLICTING_FLAGS.filter(\n ([key]) => parsed[key] !== undefined,\n ).map(([, flag]) => flag)\n if (conflicting.length > 0) {\n throw new BitfabError(\n `--resume reuses the traces, attempts, and graders experiment ${parsed.resume} started with, so it cannot be combined with ${conflicting.join(\", \")}.`,\n )\n }\n }\n if (parsed.traceIds !== undefined && parsed.datasetIds !== undefined) {\n throw new BitfabError(\n \"--trace-ids and --dataset-ids 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 resolveRegistrationDatasetIds(\n options: ReplayRegistryOptions,\n): string[] | undefined {\n if (options.datasetId !== undefined && options.datasetIds !== undefined) {\n throw new BitfabError(\n \"Replay registry options datasetId and datasetIds are the same selector: set one of them.\",\n )\n }\n if (options.datasetId !== undefined) {\n return [options.datasetId]\n }\n return options.datasetIds\n}\n\nfunction describeSelection(options: ReplayOptions): string {\n if (options.traceIds !== undefined) {\n return `${options.traceIds.length} traces`\n }\n if (options.limit !== undefined) {\n return `${options.limit} traces`\n }\n const datasetCount = options.datasetIds?.length ?? 1\n return datasetCount > 1\n ? `${datasetCount} datasets' traces`\n : \"dataset traces\"\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 parseMetadataTag(raw: string): [string, string] {\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 --metadata '${raw}': expected a non-empty key=value pair.`,\n )\n }\n return [key, raw.slice(separator + 1)]\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 let carriedOver = 0\n\n for (const item of result.items) {\n if (item.carriedOver === true) {\n carriedOver += 1\n continue\n }\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 - carriedOver}`)\n if (carriedOver > 0) {\n stderr(` Carried over from the earlier run: ${carriedOver}`)\n }\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.experimentUrl}`)\n}\n\nfunction countErroredItems(result: ReplayResult<unknown>): {\n errored: number\n replayed: number\n} {\n const replayed = result.items.filter((item) => item.carriedOver !== true)\n return {\n errored: replayed.filter((item) => item.error !== null).length,\n replayed: replayed.length,\n }\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 // Current servers record no experiment for a dry run; an older one still does.\n if (result.experimentUrl !== null) {\n stderr(`\\n ${result.experimentUrl}`)\n }\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 shellQuote(value: string): string {\n return /^[\\w@%+=:,./-]+$/.test(value)\n ? value\n : `'${value.replace(/'/g, `'\"'\"'`)}'`\n}\n\nfunction resumeCommand(\n registryPath: string | undefined,\n args: ReplayCliArgs,\n experimentId: string,\n): string {\n const carried = [\n ...(args.mock === undefined ? [] : [\"--mock\", args.mock]),\n ...(args.paramsPath === undefined ? [] : [\"--params\", args.paramsPath]),\n ...args.params.flatMap((param) => [\"--param\", param]),\n ]\n return [\n \"Resume with: bitfab-replay --registry\",\n registryPath === undefined ? \"<path>\" : shellQuote(registryPath),\n ...[args.pipeline, ...carried, \"--resume\", experimentId].map(shellQuote),\n ].join(\" \")\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\nconst API_KEY_LINE_PREFIX = \"@@bitfab:api-key \"\n\nconst PRINT_API_KEY_FLAG = \"--print-api-key\"\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 registryPath?: string,\n): Promise<ReplayResult<unknown> | null> {\n const stdout = io.stdout ?? console.log\n const stderr = io.stderr ?? console.error\n const printApiKey = argv.includes(PRINT_API_KEY_FLAG)\n const args = parseReplayCliArgs(\n registry,\n argv.filter((arg) => arg !== PRINT_API_KEY_FLAG),\n )\n if (printApiKey) {\n const client = registry[args.pipeline].client\n const apiKey = _resolvedApiKey(client)\n const serviceUrl = _serviceUrl(client)\n stdout(`${API_KEY_LINE_PREFIX}${JSON.stringify({ apiKey, serviceUrl })}`)\n return null\n }\n if (args.judgeAssertionsFlag) {\n warnJudgeAssertionsDeprecated(stderr)\n }\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 const registrationDatasetIds =\n resolveRegistrationDatasetIds(registrationOptions)\n if (\n registrationOptions.traceIds !== undefined &&\n registrationDatasetIds !== undefined\n ) {\n throw new BitfabError(\n \"Replay registry options traceIds and datasetIds select different sources and cannot be used together.\",\n )\n }\n const selectedDatasetIds = args.datasetIds ?? registrationDatasetIds\n const codeChange = await loadCodeChange(args.codeChangePath, readFile)\n let startedExperimentId: string | undefined\n\n const options: ReplayOptions = {\n ...registrationOptions,\n ...(args.name === undefined ? {} : { name: args.name }),\n ...(args.notes === undefined ? {} : { notes: args.notes }),\n ...(args.metadata === undefined ? {} : { metadata: args.metadata }),\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.experimentGroupName === undefined\n ? {}\n : { experimentGroupName: args.experimentGroupName }),\n datasetId: undefined,\n datasetIds: selectedDatasetIds,\n ...(args.graderIds === undefined ? {} : { graderIds: args.graderIds }),\n ...(args.onlyWithAssertions === undefined\n ? {}\n : { onlyWithAssertions: args.onlyWithAssertions }),\n ...(args.skipAssertionJudging === undefined\n ? {}\n : { skipAssertionJudging: args.skipAssertionJudging }),\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 onExperimentStart: ({ experimentId, experimentUrl }) => {\n startedExperimentId = experimentId\n stderr(`[replay] Experiment ${experimentId}: ${experimentUrl}`)\n },\n onInterrupt: ({ experimentId, signal, markedInterrupted }) => {\n stderr(\n `${describeReplayInterrupt(experimentId, markedInterrupted)} ${resumeCommand(registryPath, args, experimentId)}`,\n )\n process.exit(INTERRUPT_EXIT_CODES[signal])\n },\n }\n withCliFlags(options, args.flags)\n\n if (args.resume !== undefined) {\n Object.assign(options, RESUME_CLEARED_OPTIONS, {\n resume: args.resume,\n ...(args.force === true ? { force: true } : {}),\n })\n stderr(\n `[replay] Resuming experiment ${args.resume} of \"${traceFunctionKey}\"...`,\n )\n } else {\n if (args.traceIds !== undefined) {\n options.traceIds = args.traceIds\n options.datasetIds = undefined\n } else if (args.datasetIds !== undefined) {\n options.traceIds = undefined\n }\n\n const bound = args.limit ?? registrationOptions.limit\n options.limit = undefined\n\n if (options.traceIds !== undefined) {\n if (bound !== undefined) {\n options.traceIds = await boundTraceIds(\n registration.client,\n options.traceIds,\n bound,\n options.onlyWithAssertions === true,\n )\n }\n } else if (options.datasetIds !== undefined) {\n if (bound !== undefined) {\n const pinned = await pinnedDatasetMembers(\n registration.client,\n options.datasetIds,\n bound,\n options.onlyWithAssertions === true,\n )\n if (pinned !== undefined) {\n options.traceIds = pinned\n }\n }\n } else {\n options.limit = bound ?? 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\"} ${describeSelection(options)} from \"${traceFunctionKey}\"${attemptsSuffix}...`,\n )\n }\n\n let result: ReplayResult<unknown>\n try {\n result = await registration.client.replay(\n traceFunctionKey,\n registration.fn,\n options,\n )\n } catch (error) {\n if (error instanceof ReplayError) {\n reportReplayError(error, stderr)\n }\n const experimentId =\n error instanceof ReplayError ? error.experimentId : startedExperimentId\n if (experimentId !== undefined) {\n stderr(resumeCommand(registryPath, args, experimentId))\n }\n throw error\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 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 if (args.failOnError === true) {\n const { errored, replayed } = countErroredItems(result)\n if (errored > 0) {\n throw new BitfabError(\n `[replay] ${errored} of ${replayed} ${args.dryRun === true ? \"resolved\" : \"replayed\"} items errored; exiting 1 because of --fail-on-error`,\n )\n }\n }\n return result\n}\n","import { register } from \"tsx/esm/api\"\nimport { BitfabError } from \"./errors.js\"\nimport { ReplayError } from \"./replay.js\"\nimport {\n ReplayCliHelp,\n type ReplayCliIo,\n type ReplayRegistry,\n validateReplayRegistry,\n} from \"./replayRegistry.js\"\n\nexport type RegistryImporter = (path: string) => Promise<unknown>\n\nlet isTypeScriptLoaderRegistered = false\n\nexport async function parseRegistryCommandArgs(\n argv: readonly string[],\n usage: string,\n): Promise<{ registryPath: string; commandArgs: string[] }> {\n if (\n argv.some((value) => value === \"--help\" || value === \"-h\") &&\n !argv.includes(\"--registry\")\n ) {\n throw new ReplayCliHelp(usage)\n }\n const registryFlagIndex = argv.indexOf(\"--registry\")\n const registryPath = argv[registryFlagIndex + 1]\n if (\n registryFlagIndex === -1 ||\n registryPath === undefined ||\n registryPath.startsWith(\"--\")\n ) {\n throw new BitfabError(usage)\n }\n\n const commandArgs = argv.filter(\n (_value, index) =>\n index !== registryFlagIndex && index !== registryFlagIndex + 1,\n )\n if (commandArgs.length === 0) {\n throw new BitfabError(usage)\n }\n const { resolve } = await import(\"node:path\")\n return { registryPath: resolve(registryPath), commandArgs }\n}\n\nexport async function importRegistry(path: string): Promise<unknown> {\n const { pathToFileURL } = await import(\"node:url\")\n if (!isTypeScriptLoaderRegistered) {\n register()\n isTypeScriptLoaderRegistered = true\n }\n try {\n return await import(pathToFileURL(path).href)\n } catch (error) {\n if (isModuleNotFoundError(error)) {\n throw new BitfabError(`${error.message}\\n\\n${registryImportHint(path)}`)\n }\n throw error\n }\n}\n\nfunction isModuleNotFoundError(error: unknown): error is Error {\n const code = (error as { code?: unknown } | null)?.code\n return (\n error instanceof Error &&\n (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\")\n )\n}\n\nfunction registryImportHint(path: string): string {\n return [\n `The replay registry '${path}' could not load one of its imports.`,\n \"A registry belongs in the package that builds the traced function's call and already depends on everything it imports (its tools, clients, and config), and bitfab-replay runs from that package's directory.\",\n \"When the traced function lives in a lower-level library that an app package calls, put the registry in the app package and add @bitfab/sdk to it. Copying the app's dependencies into the library is the wrong fix.\",\n `See \"When the traced function needs the app's dependencies\" at https://docs.bitfab.ai/typescript-sdk.`,\n ].join(\"\\n\")\n}\n\nexport function resolveRegistry(\n moduleValue: unknown,\n path: string,\n): ReplayRegistry {\n if (typeof moduleValue !== \"object\" || moduleValue === null) {\n throw new BitfabError(\n `Replay registry '${path}' must export a default registry.`,\n )\n }\n\n const registry = (moduleValue as { default?: unknown }).default\n if (typeof registry !== \"object\" || registry === null) {\n throw new BitfabError(\n `Replay registry '${path}' must export a default registry.`,\n )\n }\n validateReplayRegistry(registry as ReplayRegistry)\n return registry as ReplayRegistry\n}\n\nexport async function runRegistryMain(\n run: () => Promise<unknown>,\n io: ReplayCliIo = {},\n): Promise<number> {\n const stdout = io.stdout ?? console.log\n const stderr = io.stderr ?? console.error\n try {\n await run()\n return 0\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (error instanceof ReplayCliHelp) {\n stdout(message)\n return 0\n }\n if (error instanceof ReplayError) {\n stderr(`Experiment ${error.experimentId}: ${error.experimentUrl}`)\n }\n stderr(message)\n return 1\n }\n}\n\nasync function isEntrypoint(moduleUrl: string): Promise<boolean> {\n const executablePath = process.argv[1]\n if (executablePath === undefined) {\n return false\n }\n const [{ realpath }, { fileURLToPath }] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:url\"),\n ])\n return (\n (await realpath(executablePath)) ===\n (await realpath(fileURLToPath(moduleUrl)))\n )\n}\n\nexport function runIfEntrypoint(\n moduleUrl: string,\n main: () => Promise<number>,\n): void {\n void isEntrypoint(moduleUrl).then((entrypoint) => {\n if (entrypoint) {\n void main().then((exitCode) => {\n process.exitCode = exitCode\n })\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,IAAa,cAAb,cAAiC,MAAM;CACrC,YACE,SACA,KAOA,QAMA,cACA;EACA,MAAM,OAAO;EAfG,KAAA,MAAA;EAOA,KAAA,SAAA;EAMA,KAAA,eAAA;EAGhB,KAAK,OAAO;CACd;AACF;CCSE,OAAO,YAAY,eAAe,QAAQ,UAAU,OAKhD;;CAEE,CAAC,QAAQ,MAAM,CAAC,CAAC,KAAK,GAAG;CAC1B,CACE,MAAM,EAAE,WAAqB,CAW9B,CAAC,CAAC,CACD,YAAY,CAAC,CAAC,IACjB,QAAQ,QAAQ,EAAA,CACpB,WAAW,CAAC,CAAC;;;ACxBf,IAAI,yBACF;AAWF,SAAgB,+BACd,KACM;CACN,IAAI,CAAC,wBACH,yBAAyB;AAG7B;AAoBA,MAAa,qBACX,OAAO,YAAY,eAAe,QAAQ,UAAU;;AAKhD;;CAEE,CAAC,QAAQ,aAAa,CAAC,CAAC,KAAK,GAAG;CACjC,CACE,MACE,QAEK;CACJ,+BAA+B,IA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,IAAI;EACF,MAAM,IAAI;EACV,OAAO;CACT,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,IAAI,iBAAiB,eAAe;GAClC,OAAO,OAAO;GACd,OAAO;EACT;EACA,IAAI,iBAAiB,aACnB,OAAO,cAAc,MAAM,aAAa,IAAI,MAAM,eAAe;EAEnE,OAAO,OAAO;EACd,OAAO;CACT;AACF;AAEA,eAAe,aAAa,WAAqC;CAC/D,MAAM,iBAAiB,QAAQ,KAAK;CACpC,IAAI,mBAAmB,KAAA,GACrB,OAAO;CAET,MAAM,CAAC,EAAE,YAAY,EAAE,mBAAmB,MAAM,QAAQ,IAAI,CAC1D,OAAO,gBACP,OAAO,MACT,CAAC;CACD,OACG,MAAM,SAAS,cAAc,MAC7B,MAAM,SAAS,cAAc,SAAS,CAAC;AAE5C;AAEA,SAAgB,gBACd,WACA,MACM;CACN,aAAkB,SAAS,CAAC,CAAC,MAAM,eAAe;EAChD,IAAI,YACF,KAAU,CAAC,CAAC,MAAM,aAAa;GAC7B,QAAQ,WAAW;EACrB,CAAC;CAEL,CAAC;AACH"}
1
+ {"version":3,"file":"registryCommand-Di8x0YoJ.js","names":["DEFAULT_LIFECYCLE_TIMEOUT_MS","keyed"],"sources":["../src/errors.ts","../src/compress.ts","../src/asyncStorage.ts","../src/replayContext.ts","../src/captureSuppression.ts","../src/payloadBudget.ts","../src/warnOnce.ts","../src/spanOrigin.ts","../src/simulationPlan.ts","../src/unrefTimer.ts","../src/otel.ts","../src/transport.ts","../src/http.ts","../src/replayInterrupt.ts","../src/replayInvocation.ts","../src/replay.ts","../src/autoTrace.ts","../src/commitRef.ts","../src/openaiAgentsSpanContext.ts","../src/rivetContext.ts","../src/seedContext.ts","../src/client.ts","../src/replayRegistry.ts","../src/registryCommand.ts"],"sourcesContent":["/**\n * Shared error type for Bitfab SDK runtime errors. Lives in its own\n * module to avoid import cycles between `http.ts` and modules that need\n * to throw structured errors (e.g. `dbSnapshot.ts` validation).\n */\n\nexport class BitfabError extends Error {\n constructor(\n message: string,\n public readonly url?: string,\n /**\n * HTTP status the request failed with, when it failed with one. The\n * transport's retry policy needs the code itself (retry 408/425/429/5xx,\n * never a 4xx the server will reject again), which a formatted message\n * cannot supply. Absent for network failures and non-HTTP errors.\n */\n public readonly status?: number,\n /**\n * `Retry-After` in milliseconds, when the server sent one. A 429 or 503\n * carries the server's own instruction about when to come back; retrying\n * on our own schedule ignores it and keeps the pressure on.\n */\n public readonly retryAfterMs?: number,\n ) {\n super(message)\n this.name = \"BitfabError\"\n }\n}\n\nexport class MixedTracingError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"MixedTracingError\"\n }\n}\n","import { readEnv } from \"./readEnv.js\"\n\nconst DISABLE_COMPRESSION_ENV = \"BITFAB_DISABLE_COMPRESSION\"\n\n/**\n * Below this, compressing costs more than the saved bytes are worth, so small\n * requests (function lookups, replay status polls, single-span batches) ride\n * uncompressed.\n */\nconst MIN_COMPRESSED_BYTES = 8_192\n\nexport interface EncodedRequestBody {\n body: string | ArrayBuffer\n contentEncoding?: \"gzip\"\n rawBytes: number\n wireBytes: number\n}\n\n/**\n * Node's gzip, loaded dynamically so browser bundlers never have to resolve\n * `node:zlib`. Deliberately the async form: it runs on libuv's threadpool\n * rather than the event loop. Measured on 8 concurrent 1 MB bodies, the\n * synchronous form stalled the loop for 326ms and the async form for 1ms,\n * while also finishing 3.8x sooner because the threadpool compresses in\n * parallel. A tracing SDK must not block its host's event loop.\n */\nlet gzipNode: ((data: Uint8Array) => Promise<Uint8Array>) | undefined\n\ntype NodeZlib = {\n gzip: (\n data: Uint8Array,\n callback: (error: Error | null, result: Uint8Array) => void,\n ) => void\n}\n\nexport const _nodeGzipReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:zlib\" from static analysis so bundlers that\n // ban Node.js built-ins don't fail at build time. webpackIgnore tells\n // webpack/turbopack to emit a native import() so Node.js can resolve the\n // module at runtime. Same pattern as `asyncStorage.ts`.\n import(\n /* webpackIgnore: true */\n [\"node\", \"zlib\"].join(\":\")\n )\n .then(({ gzip }: NodeZlib) => {\n gzipNode = (data) =>\n new Promise((resolve, reject) => {\n gzip(data, (error, result) => {\n if (error) {\n reject(error)\n } else {\n resolve(result)\n }\n })\n })\n })\n .catch(() => {})\n : Promise.resolve()\n).then(() => {})\n\n/** Test seam for exercising the browser path on Node. */\nexport function _setNodeGzip(\n impl: ((data: Uint8Array) => Promise<Uint8Array>) | undefined,\n): void {\n gzipNode = impl\n}\n\nfunction toArrayBuffer(view: Uint8Array): ArrayBuffer {\n return view.buffer.slice(\n view.byteOffset,\n view.byteOffset + view.byteLength,\n ) as ArrayBuffer\n}\n\nfunction compressedRequest(\n body: string,\n rawBytes: number,\n compressed: Uint8Array | ArrayBuffer,\n): EncodedRequestBody {\n if (compressed.byteLength >= rawBytes) {\n return { body, rawBytes, wireBytes: rawBytes }\n }\n return {\n body:\n compressed instanceof Uint8Array ? toArrayBuffer(compressed) : compressed,\n contentEncoding: \"gzip\",\n rawBytes,\n wireBytes: compressed.byteLength,\n }\n}\n\nasync function gzipViaStream(bytes: Uint8Array): Promise<ArrayBuffer> {\n const stream = new Blob([bytes as BlobPart])\n .stream()\n .pipeThrough(new CompressionStream(\"gzip\"))\n return await new Response(stream).arrayBuffer()\n}\n\n/**\n * Compression is best-effort: any failure sends the original body rather than\n * dropping the span. `CompressionStream` is absent on older browsers, so its\n * presence is checked rather than assumed.\n *\n * Returns a plain value (not a promise) whenever it can, so a request still\n * reaches `fetch` in the caller's tick rather than one microtask later. Callers\n * await the union.\n */\nexport function encodeRequestBody(\n body: string,\n): EncodedRequestBody | Promise<EncodedRequestBody> {\n if (readEnv(DISABLE_COMPRESSION_ENV)) {\n const rawBytes = new TextEncoder().encode(body).byteLength\n return { body, rawBytes, wireBytes: rawBytes }\n }\n const bytes = new TextEncoder().encode(body)\n if (bytes.byteLength < MIN_COMPRESSED_BYTES) {\n return {\n body,\n rawBytes: bytes.byteLength,\n wireBytes: bytes.byteLength,\n }\n }\n if (gzipNode) {\n return gzipNode(bytes).then(\n (compressed) => compressedRequest(body, bytes.byteLength, compressed),\n () => ({\n body,\n rawBytes: bytes.byteLength,\n wireBytes: bytes.byteLength,\n }),\n )\n }\n if (typeof CompressionStream === \"undefined\") {\n return {\n body,\n rawBytes: bytes.byteLength,\n wireBytes: bytes.byteLength,\n }\n }\n return gzipViaStream(bytes).then(\n (compressed) => compressedRequest(body, bytes.byteLength, compressed),\n () => ({\n body,\n rawBytes: bytes.byteLength,\n wireBytes: bytes.byteLength,\n }),\n )\n}\n","/**\n * Shared AsyncLocalStorage loader.\n *\n * Provides two ways to initialize AsyncLocalStorage:\n *\n * 1. **Synchronous registration** (preferred for Node.js):\n * `asyncStorageNode.ts` calls `registerAsyncLocalStorageClass()` at module\n * evaluation time, so the class is available immediately - no async gap.\n * The `node.ts` entry point imports it before anything else.\n *\n * 2. **Async dynamic import** (fallback for the default entry point):\n * Loads `node:async_hooks` via a bundler-safe dynamic import. This is used\n * by the default `index.ts` entry point so the SDK works in browsers\n * (where the import silently fails) and in Node.js when imported via the\n * default entry point.\n *\n * ## Why the dynamic import looks like this\n *\n * We need to handle three environments:\n *\n * 1. **Pure Node.js** - `import(\"node:async_hooks\")` works natively.\n * 2. **Webpack/Turbopack (Next.js server)** - The bundler processes\n * `import()` calls at build time. The `webpackIgnore` magic comment tells\n * webpack (and turbopack) to emit a native `import()` call instead of\n * trying to resolve it, so Node.js handles it at runtime.\n * 3. **Browsers / Edge** - The `process.versions?.node` guard prevents\n * execution entirely. If it somehow runs, `.catch(() => {})` swallows\n * the failure.\n */\n\nexport interface AsyncLocalStorageLike<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\nlet AsyncLocalStorageClass: (new () => AsyncLocalStorageLike<unknown>) | null =\n null\nlet initDone = false\n\n/**\n * Register the AsyncLocalStorage class synchronously.\n *\n * Called by `asyncStorageNode.ts` at module evaluation time so the class\n * is available before any span is created - no async gap, no race condition.\n *\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport function registerAsyncLocalStorageClass(\n cls: new () => AsyncLocalStorageLike<unknown>,\n): void {\n if (!AsyncLocalStorageClass) {\n AsyncLocalStorageClass = cls\n }\n initDone = true\n}\n\n/**\n * Assert that AsyncLocalStorage was registered successfully.\n *\n * Called by `node.ts` after importing `asyncStorageNode.ts` to catch\n * import-order bugs at startup rather than silently degrading to the\n * browser fallback (flat spans with no nesting).\n *\n * This should ONLY be called from the Node.js entry point where we\n * know `node:async_hooks` must be available.\n */\nexport function assertAsyncStorageRegistered(): void {\n if (!AsyncLocalStorageClass) {\n console.warn(\n \"Bitfab: AsyncLocalStorage not available - nested span context will not propagate.\",\n )\n }\n}\n\nexport const asyncStorageReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:async_hooks\" from static analysis so\n // bundlers that ban Node.js built-ins don't fail at build time.\n // webpackIgnore tells webpack/turbopack to emit a native import()\n // so Node.js can resolve the module at runtime.\n import(\n /* webpackIgnore: true */\n [\"node\", \"async_hooks\"].join(\":\")\n )\n .then(\n (mod: {\n AsyncLocalStorage: new () => AsyncLocalStorageLike<unknown>\n }) => {\n registerAsyncLocalStorageClass(mod.AsyncLocalStorage)\n },\n )\n .catch(() => {})\n : Promise.resolve()\n).then(() => {\n initDone = true\n})\n\nexport function isAsyncStorageInitDone(): boolean {\n return initDone\n}\n\nexport function createAsyncLocalStorage<T>(): AsyncLocalStorageLike<T> | null {\n return AsyncLocalStorageClass\n ? (new AsyncLocalStorageClass() as AsyncLocalStorageLike<T>)\n : null\n}\n","/**\n * Replay context propagation via AsyncLocalStorage.\n *\n * When set, the withSpan wrapper injects experimentId into the span payload\n * so that new spans created during replay are linked to the experiment.\n * Optionally carries a mock tree so child spans can return historical\n * outputs instead of executing.\n */\n\nimport {\n type AsyncLocalStorageLike,\n asyncStorageReady,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\nimport type { MockOverride } from \"./mockOverride.js\"\nimport type { SelectiveReplayRuntime } from \"./selectiveReplayRuntime.js\"\n\n/**\n * A single span entry in the mock tree.\n *\n * Under the eager path (`mock: \"all\"`) `output`/`outputMeta` are populated\n * inline, even when overrides are present. Under a non-`all` path that needs a\n * tree (`marked`, or `none` with overrides), they are absent and the recorded\n * output is fetched on demand via `externalSpanId` - see\n * {@link ReplayContext.fetchSpanOutput}.\n */\nexport interface MockSpan {\n sourceSpanId: string\n /** Row id accepted by `getExternalSpan`, for the lazy per-span output fetch. */\n externalSpanId?: string\n output?: unknown\n outputMeta?: unknown\n}\n\n/**\n * Per-item DB branch resolved by the Bitfab service from the source\n * trace's `dbSnapshotRef`. Carried on the replay context so that\n * customer code reads `databaseUrl` through `getCurrentReplayBranch()`, and so\n * the process-isolated replay runner can materialize it into a `.env`\n * overlay file before customer code initializes its DB client.\n *\n * `neonBranchId` is the literal Neon branch id; passing it to\n * `releaseDbBranchLease` deletes that branch.\n */\nexport interface DbBranchLease {\n neonBranchId: string\n /** Env var name the customer's app reads, e.g. \"DATABASE_URL\". */\n envKey: string\n databaseUrl: string\n expiresAt: string\n /**\n * The instant the branch was pinned to (the source trace's wall clock).\n * Echoed back in `db_snapshot_usage` on the replayed trace's completion.\n */\n snapshotTimestamp?: string\n providerConsoleUrl?: string\n 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 runner elsewhere pays that round trip on every query.\n */\n region?: string\n}\n\n/**\n * How long each phase of provisioning one replay branch took, measured\n * server-side. A runner in another region sees these plus its own round trip.\n *\n * Durations, not instants: an instant is approximately `startedAt` plus the\n * running sum, and per-phase wall-clock stamps would make clock skew between\n * the server and your runner look like latency. Approximately, because\n * `totalMs` is the resolve's true wall time and covers a little work no phase\n * owns, so the phases account for it without summing to it exactly.\n *\n * `startedAt` and `totalMs` are always present. The phases are optional\n * because a failed resolve reports only the ones it reached, and `totalMs` is\n * then time-to-failure. On success every phase is present except `warmupMs`,\n * which is absent when no warm-up SQL was supplied.\n */\nexport interface DbBranchTimings {\n /** When the resolve began, ISO. */\n startedAt: string\n /** Resolving the project, plus its retention and region reads. */\n projectResolveMs?: number\n /** Creating the branch, through its provider operations reaching terminal. */\n branchCreateMs?: number\n /** Resolving the connection URI. 0 when the provider returns one inline. */\n connectionUriMs?: number\n /** The compute accepting a connection. */\n computeConnectMs?: number\n /** The branch answering a readiness query. */\n baseProbeMs?: number\n /** Your warm-up SQL. Absent when you supplied none. */\n warmupMs?: number\n /** The whole resolve, or time-to-failure when it threw. */\n totalMs: number\n}\n\n/**\n * Wire shape of the caller's `ReplayOptions.dbBranch`, sent to\n * `/api/sdk/replay/start` and applied per lease.\n */\nexport interface DbBranchSettings {\n minCu?: number\n maxCu?: number\n warmupSql?: string\n}\n\n/**\n * Pre-built lookup table of historical span outputs.\n * Keys are `${traceFunctionKey}:${spanName}:${callIndex}` so that repeated\n * calls with the same (key, name) are matched by call order, but spans\n * sharing only the traceFunctionKey (different name) do not collide.\n */\nexport interface MockTree {\n spans: Map<string, MockSpan>\n}\n\nexport interface ReplayContext {\n experimentId: string\n selectiveReplay?: SelectiveReplayRuntime\n traceId?: string\n inputSourceSpanId?: string\n /**\n * External trace ID from `external_traces.id`. Used for span-chain\n * lookup against the source platform's trace tree (Braintrust, etc.).\n * NOT the same as the Bitfab `traceId` - see `sourceBitfabTraceId`.\n */\n inputSourceTraceId?: string\n /**\n * The Bitfab `traces.id` of the historical trace that produced this\n * replay item's input. This is what customer-facing surfaces (e.g.\n * `ReplayBranch.traceId`) should expose, since it's the ID the\n * customer sees in the Bitfab dashboard.\n */\n sourceBitfabTraceId?: string\n replayAttempt?: number\n mockTree?: MockTree\n callCounters?: Map<string, number>\n mockStrategy?: \"none\" | \"all\" | \"marked\"\n /**\n * Resolved override chain for this replay, per-call overrides first then\n * registered ones (first matcher wins). Empty/absent when no overrides apply.\n */\n mockOverrides?: MockOverride[]\n /**\n * Memoized lazy fetch of a span's recorded output (deserialized), keyed by\n * `externalSpanId`. Present ONLY on a non-`all` path that needs a tree\n * (`marked`, or `none` with overrides); absent under `mock: \"all\"`, where\n * outputs are inline even when overrides are present. Its presence is the\n * signal that outputs must be fetched rather than read inline.\n */\n fetchSpanOutput?: (externalSpanId: string) => Promise<unknown>\n /** Internal framework state captured on the historical root span. */\n integrationFixtures?: Map<string, unknown>\n dbBranchLease?: DbBranchLease\n /**\n * Server-measured provisioning timings for this item's branch, echoed back\n * on the trace completion so the trace records what it cost to set up. Kept\n * off `ReplayBranch`: customer code reads that mid-replay to reach the\n * branch, and provisioning latency is a property of the run, not of the\n * connection.\n */\n dbBranchTimings?: DbBranchTimings\n /**\n * Set to true by `ReplayBranch` the first time customer code actually\n * obtains `databaseUrl` for this item. Reported on the trace completion inside\n * `db_snapshot_usage` so the server can distinguish \"branch was\n * provisioned and exposed\" from \"branch URL was actually consumed\".\n * Only an explicit `databaseUrl` read may set it. A path that hands the URL\n * over by other means (e.g. a process-isolated runner writing an env\n * overlay) must leave it alone: setting it there would make every such\n * replay report `accessed` for free, and the flag would stop separating\n * \"branch was used\" from \"branch was offered\".\n */\n dbSnapshotAccessed?: boolean\n}\n\nlet replayContextStorage: AsyncLocalStorageLike<ReplayContext | null> | null =\n null\nconst REPLAY_CONTEXT_STORAGE_SYMBOL = Symbol.for(\"bitfab.replayContextStorage\")\n\nexport const replayContextReady: Promise<void> = asyncStorageReady.then(() => {\n const shared = globalThis as typeof globalThis & Record<symbol, unknown>\n const existing = shared[REPLAY_CONTEXT_STORAGE_SYMBOL] as\n | AsyncLocalStorageLike<ReplayContext | null>\n | undefined\n if (existing) {\n replayContextStorage = existing\n return\n }\n const created = createAsyncLocalStorage<ReplayContext | null>()\n if (created) {\n shared[REPLAY_CONTEXT_STORAGE_SYMBOL] = created\n replayContextStorage = created\n }\n})\n\n/** Get the current replay context, if any. */\nexport function getReplayContext(): ReplayContext | null {\n return replayContextStorage?.getStore() ?? null\n}\n\n/** Run a function within a replay context. */\nexport function runWithReplayContext<T>(ctx: ReplayContext, fn: () => T): T {\n if (replayContextStorage) {\n return replayContextStorage.run(ctx, fn)\n }\n return fn()\n}\n","interface CaptureSuppressionState {\n depth: number\n}\n\ninterface CaptureSuppressionGlobal {\n __bitfabCaptureSuppressionV1?: CaptureSuppressionState\n}\n\nconst suppressionGlobal = globalThis as unknown as CaptureSuppressionGlobal\nconst suppressionState: CaptureSuppressionState =\n suppressionGlobal.__bitfabCaptureSuppressionV1 ?? { depth: 0 }\nsuppressionGlobal.__bitfabCaptureSuppressionV1 = suppressionState\n\nexport function isCaptureSuppressed(): boolean {\n return suppressionState.depth > 0\n}\n\nexport function runWithCaptureSuppressed<T>(fn: () => T): T {\n suppressionState.depth += 1\n try {\n return fn()\n } finally {\n suppressionState.depth -= 1\n }\n}\n","/**\n * The ceiling on a span's encoded carrier, and the trimming that enforces it.\n *\n * A span's whole payload (input, output, contexts, prompt, metadata) ships as\n * a single `bitfab.payload` string attribute, and the exporter drops any\n * carrier that exceeds the per-request byte ceiling outright rather than\n * trimming it. Capping each value on its own cannot prevent that: two values\n * that each fit can still add up to an undeliverable span. So the budget is\n * enforced on the whole span, and an oversized one ships with its largest\n * fields stubbed instead of vanishing.\n *\n * The budget is measured on the *carrier* (the payload re-escaped into the\n * OTLP attribute), not on the payload body, because the carrier is what the\n * exporter weighs. Bounding the body instead leaves escape-heavy content to\n * blow the request ceiling anyway: a body of escaped JSON, Windows paths, or\n * regexes is nearly all backslashes, and every one of them doubles. Measured\n * on a body sized exactly to a 2.4 MB cap, prose produced a 2.4 MB carrier but\n * backslash-dense content produced 4.8 MB, which the exporter dropped.\n *\n * The normal 2.8 MB fallback leaves room beneath the 3 MB wire target. Trace\n * transport may first preserve a carrier up to 7.8 MB when its single-span\n * request compresses below that wire target and remains below ingress's 8 MB\n * decompressed ceiling.\n */\nexport const MAX_SPAN_CARRIER_BYTES = 2_800_000\n\n/**\n * A larger carrier may still fit when its single-span request is compressed.\n * This leaves 200 kB beneath ingress's 8 MB decompressed-body ceiling for the\n * OTLP span and request envelopes.\n */\nexport const MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES = 7_800_000\n\nconst textEncoder =\n typeof TextEncoder !== \"undefined\" ? new TextEncoder() : null\n\nexport function byteLength(value: string): number {\n return textEncoder ? textEncoder.encode(value).length : value.length\n}\n\n/**\n * The byte length `body` occupies once re-escaped as a JSON string value.\n *\n * `body` is itself JSON text, so the first encode already replaced every\n * control character with a `\\uXXXX` sequence, leaving only `\"` and `\\` to\n * escape at one extra byte each.\n *\n * Counts UTF-8 width and escapes in the same pass and allocates nothing.\n * `TextEncoder.encode().length` would be the obvious way to get the byte count,\n * but it copies the entire body into a fresh array just to read its length,\n * which on a multi-megabyte span costs more than producing the body did.\n */\nexport function carrierByteLength(body: string): number {\n return carrierBytesOf(textEncoder ? textEncoder.encode(body) : null, body)\n}\n\n/**\n * Counts escapes over the UTF-8 bytes rather than the UTF-16 string. Bytes\n * `0x22` and `0x5c` are unambiguous there (a multi-byte sequence never uses a\n * byte below `0x80`), so a flat byte scan is exact, and it reuses the array the\n * byte count already had to produce instead of walking the string a second\n * time. Measured ~2x faster than the equivalent `charCodeAt` loop.\n */\nfunction carrierBytesOf(encoded: Uint8Array | null, body: string): number {\n if (!encoded) {\n // No TextEncoder (a browser old enough to lack it). Fall back to the string,\n // where `length` is the best available byte estimate.\n return body.length + 2\n }\n let extra = 2 // the quotes wrapping the attribute value\n for (let i = 0; i < encoded.length; i++) {\n const byte = encoded[i]\n if (byte === 34 || byte === 92) {\n extra += 1 // `\"` and `\\` take a leading backslash\n } else if (byte < 0x20) {\n extra +=\n byte === 8 || byte === 9 || byte === 10 || byte === 12 || byte === 13\n ? 1 // \\b \\f \\n \\r \\t\n : 5 // \\uXXXX\n }\n }\n return encoded.length + extra\n}\n\n/**\n * The most carrier bytes one UTF-16 code unit of a *JSON body* can become.\n *\n * A unit is at most 3 UTF-8 bytes, and the only characters that grow under\n * escaping are `\"` and `\\`, which are one byte and become two. A unit cannot be\n * both, so 3 is the ceiling. This holds because every caller passes the output\n * of a JSON encoder, which by specification never emits a raw control character\n * (the case that would otherwise expand to a 6-byte `\\uXXXX`); the invariant is\n * pinned by a test so a future caller that broke it would fail loudly rather\n * than silently ship an oversized carrier.\n */\nconst MAX_BYTES_PER_UNIT = 3\n\n/**\n * Whether `body` fits the carrier budget, escalating only as far as it must.\n *\n * `body.length` is O(1) and brackets the answer for both ordinary spans (far\n * under the budget) and hopeless ones (already past it on raw length alone),\n * which is every span in normal traffic: neither case touches the string. Only\n * a body near the budget is measured exactly, and that costs one encode plus\n * one byte scan.\n */\nexport function fitsCarrierBudget(\n body: string,\n maxBytes: number = MAX_SPAN_CARRIER_BYTES,\n): boolean {\n const units = body.length\n if (units * MAX_BYTES_PER_UNIT + 2 <= maxBytes) {\n return true\n }\n if (units + 2 > maxBytes) {\n return false\n }\n return carrierByteLength(body) <= maxBytes\n}\n\n/**\n * Span fields that identify the span rather than carry user data. Trimming one\n * would leave a span that no longer says what it is, so they stay whatever the\n * payload costs.\n */\nconst STRUCTURAL_SPAN_KEYS = new Set([\n \"name\",\n \"type\",\n \"function_name\",\n \"error_source\",\n])\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\ninterface Candidate {\n container: Record<string, unknown>\n key: string\n size: number\n}\n\n/**\n * The records holding user data, cloned so trimming never mutates the caller's\n * objects. Returns the payload copy to encode plus the containers to trim.\n */\nfunction cloneTrimmable(payload: Record<string, unknown>): {\n copy: Record<string, unknown>\n containers: Record<string, unknown>[]\n} {\n const copy = { ...payload }\n const containers: Record<string, unknown>[] = []\n\n const spanData = asRecord(copy.span_data)\n if (spanData) {\n const clone = { ...spanData }\n copy.span_data = clone\n containers.push(clone)\n }\n\n const rawSpan = asRecord(copy.rawSpan)\n const rawSpanData = rawSpan && asRecord(rawSpan.span_data)\n if (rawSpan && rawSpanData) {\n const clone = { ...rawSpanData }\n copy.rawSpan = { ...rawSpan, span_data: clone }\n containers.push(clone)\n }\n\n // No span_data anywhere: a trace-level or otherwise unfamiliar payload. Trim\n // its own fields rather than give up, so an oversized body still ships.\n if (containers.length === 0) {\n containers.push(copy)\n }\n\n return { copy, containers }\n}\n\nfunction collectCandidates(containers: Record<string, unknown>[]): Candidate[] {\n const candidates: Candidate[] = []\n for (const container of containers) {\n for (const [key, value] of Object.entries(container)) {\n if (STRUCTURAL_SPAN_KEYS.has(key) || value == null) {\n continue\n }\n let size: number\n try {\n size = byteLength(JSON.stringify(value) ?? \"\")\n } catch {\n continue\n }\n candidates.push({ container, key, size })\n }\n }\n return candidates.sort((a, b) => b.size - a.size)\n}\n\n/**\n * Stub the largest payload fields until the encoded body fits the budget.\n *\n * Returns the trimmed payload and the names of the fields that were stubbed, or\n * `undefined` when nothing could be trimmed (the caller then ships the\n * oversized body and lets the exporter report the drop, which is still better\n * than silently emptying a span).\n */\nexport function trimPayloadToBudget(\n payload: Record<string, unknown>,\n encode: (value: Record<string, unknown>) => string,\n maxBytes: number = MAX_SPAN_CARRIER_BYTES,\n): { value: Record<string, unknown>; trimmed: string[] } | undefined {\n const { copy, containers } = cloneTrimmable(payload)\n const candidates = collectCandidates(containers)\n if (candidates.length === 0) {\n return undefined\n }\n\n const trimmed: string[] = []\n for (const candidate of candidates) {\n candidate.container[candidate.key] =\n `<unserializable: too_large_${candidate.size}_bytes>`\n trimmed.push(candidate.key)\n let body: string\n try {\n body = encode(copy)\n } catch {\n return undefined\n }\n if (fitsCarrierBudget(body, maxBytes)) {\n return { value: copy, trimmed }\n }\n }\n return undefined\n}\n\n/**\n * Record a trim in the payload's own `errors`, which is what the server reads\n * to flag a trace as incomplete.\n */\nexport function markPayloadTrimmed(\n value: Record<string, unknown>,\n trimmed: string[],\n maxBytes: number = MAX_SPAN_CARRIER_BYTES,\n): void {\n const existing = Array.isArray(value.errors) ? value.errors : []\n value.errors = [\n ...existing,\n {\n source: \"sdk\",\n step: \"payload_budget\",\n error: `trimmed oversized field(s) to fit the ${maxBytes}-byte span carrier budget: ${[\n ...new Set(trimmed),\n ].join(\", \")}`,\n },\n ]\n}\n","/**\n * Emit a `console.warn` at most once per distinct `key` for the life of the\n * process.\n *\n * The SDK must NEVER crash a host app, so every failure on the user's path\n * degrades silently (a span is dropped, a call runs untraced, a payload is\n * stubbed). Silent is safe but undebuggable: a user who suddenly has no traces,\n * or sees `<unserializable>` in a span, has no signal as to why. A one-time\n * warning per distinct issue restores that signal without spamming the console\n * from a hot path.\n *\n * Keys should identify the specific degradation (e.g. include the traced\n * function key) so each distinct issue warns once, not just the first one seen.\n */\nconst warned = new Set<string>()\n\nexport function warn(message: string): void {\n try {\n console.warn(`[bitfab] ${message}`)\n } catch {\n // Logging must never crash the host app (e.g. a closed/replaced console).\n }\n}\n\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n warn(message)\n}\n\nexport function writeOnce(\n key: string,\n line: string,\n write: (line: string) => void = console.warn,\n): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n try {\n write(line)\n } catch {}\n}\n\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n","import { __version__ } from \"./constants.js\"\n\nexport const SPAN_ORIGIN_NAME = \"bitfab.sdk.typescript\"\n\nexport const SPAN_INSTRUMENTATIONS = [\n \"span\",\n \"trace\",\n \"openai-agents\",\n \"langgraph\",\n \"claude-agent-sdk\",\n \"vercel-ai\",\n \"rivet\",\n] as const\n\nexport type SpanInstrumentation = (typeof SPAN_INSTRUMENTATIONS)[number]\n\nexport const FRAMEWORK_INSTRUMENTATIONS: readonly SpanInstrumentation[] = [\n \"openai-agents\",\n \"langgraph\",\n \"claude-agent-sdk\",\n \"vercel-ai\",\n \"rivet\",\n]\n\nconst FRAMEWORK_INSTRUMENTATION_SET: ReadonlySet<string> = new Set(\n FRAMEWORK_INSTRUMENTATIONS,\n)\n\nexport function isFrameworkInstrumentation(value: unknown): boolean {\n return typeof value === \"string\" && FRAMEWORK_INSTRUMENTATION_SET.has(value)\n}\n\nexport interface SpanOrigin {\n name: string\n version: string\n instrumentation: { name: SpanInstrumentation }\n}\n\nexport function makeSpanOrigin(\n instrumentation: SpanInstrumentation,\n): SpanOrigin {\n return {\n name: SPAN_ORIGIN_NAME,\n version: __version__,\n instrumentation: { name: instrumentation },\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nexport function spanOriginOf(\n payload: Record<string, unknown>,\n): SpanOrigin | undefined {\n const rawSpan = payload.rawSpan\n if (!isRecord(rawSpan)) {\n return undefined\n }\n const origin = rawSpan.span_origin\n if (!isRecord(origin) || !isRecord(origin.instrumentation)) {\n return undefined\n }\n const { name, version } = origin\n const instrumentation = origin.instrumentation.name\n if (\n typeof name !== \"string\" ||\n typeof version !== \"string\" ||\n typeof instrumentation !== \"string\" ||\n !(SPAN_INSTRUMENTATIONS as readonly string[]).includes(instrumentation)\n ) {\n return undefined\n }\n return {\n name,\n version,\n instrumentation: { name: instrumentation as SpanInstrumentation },\n }\n}\n\nexport function spanInstrumentationOf(\n payload: Record<string, unknown>,\n): SpanInstrumentation | undefined {\n return spanOriginOf(payload)?.instrumentation.name\n}\n\nexport function recordedByFramework(payload: Record<string, unknown>): boolean {\n return isFrameworkInstrumentation(spanInstrumentationOf(payload))\n}\n","import { BitfabError } from \"./errors.js\"\nimport { PolicyRefresh } from \"./policyRefresh.js\"\nimport { readEnv } from \"./readEnv.js\"\nimport { recordedByFramework, spanInstrumentationOf } from \"./spanOrigin.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport const SIMULATION_PLAN_REFRESH_MS = 60_000\nexport const SIMULATION_PLAN_RETRY_MS = 10_000\nexport const SIMULATION_PLAN_READ_TIMEOUT_MS = 5_000\nexport const SIMULATION_PLAN_MAX_HELD = 1_000\nexport const DISABLE_SIMULATION_PLAN_ENV = \"BITFAB_DISABLE_SIM_PLAN\"\nexport const NO_API_KEY_FOR_SIMULATION_PLAN = \"no API key is set\"\nexport const ROOT_TRACE_FUNCTION_KEY_FIELD = \"rootTraceFunctionKey\"\nexport const DECLARED_NODE_FIELD = \"declaredNode\"\n\nexport const CONTENT_OFF_KEY = \"content_off_by_simulation_plan\"\nconst CONTENT_KEYS = [\n \"input\",\n \"input_meta\",\n \"output\",\n \"output_meta\",\n \"replay_recording\",\n \"prompt\",\n] as const\n\nexport interface SimulationPlanNode {\n traceFunctionKey: string\n name: string\n captureContent: boolean\n}\n\nexport interface SimulationPlanResponse {\n nodes: SimulationPlanNode[]\n}\n\ninterface SimulationPlanSource {\n getSimulationPlan(): Promise<SimulationPlanResponse>\n canRead?(): boolean\n}\n\nexport type SimulationPlanSubmit = (payload: Record<string, unknown>) => void\n\ninterface HeldEntry {\n payload: Record<string, unknown>\n traceFunctionKey: string | undefined\n submit: SimulationPlanSubmit\n drop?: () => void\n}\n\nexport function planWaitSliceMs(timeoutMs: number): number {\n return Math.min(SIMULATION_PLAN_READ_TIMEOUT_MS, Math.max(timeoutMs, 0) / 2)\n}\n\nexport function parseSimulationPlan(\n body: unknown,\n): Map<string, Set<string>> | null {\n if (typeof body !== \"object\" || body === null) {\n return null\n }\n const nodes = (body as { nodes?: unknown }).nodes\n if (!Array.isArray(nodes)) {\n return null\n }\n const contentOff = new Map<string, Set<string>>()\n for (const node of nodes) {\n if (typeof node !== \"object\" || node === null) {\n continue\n }\n const { traceFunctionKey, name, captureContent } = node as Record<\n string,\n unknown\n >\n if (\n typeof traceFunctionKey !== \"string\" ||\n typeof name !== \"string\" ||\n typeof captureContent !== \"boolean\"\n ) {\n continue\n }\n if (captureContent) {\n continue\n }\n const names = contentOff.get(traceFunctionKey) ?? new Set<string>()\n names.add(name)\n contentOff.set(traceFunctionKey, names)\n }\n return contentOff\n}\n\nexport function traceIdOf(\n payload: Record<string, unknown>,\n): string | undefined {\n const traceId = payload.traceId\n if (typeof traceId === \"string\") {\n return traceId\n }\n const id = payload.id\n return typeof id === \"string\" ? id : undefined\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null\n}\n\nfunction rawSpanOf(\n payload: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n return isRecord(payload.rawSpan) ? payload.rawSpan : undefined\n}\n\nfunction spanDataOf(\n payload: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const spanData = rawSpanOf(payload)?.span_data\n return isRecord(spanData) ? spanData : undefined\n}\n\nexport function spanNameOf(\n payload: Record<string, unknown>,\n): string | undefined {\n const name = spanDataOf(payload)?.name\n return typeof name === \"string\" ? name : undefined\n}\n\nexport function stripContent(\n payload: Record<string, unknown>,\n): Record<string, unknown> {\n const rawSpan = rawSpanOf(payload)\n const spanData = spanDataOf(payload)\n if (rawSpan === undefined || spanData === undefined) {\n return payload\n }\n const kept: Record<string, unknown> = { ...spanData }\n for (const key of CONTENT_KEYS) {\n delete kept[key]\n }\n kept[CONTENT_OFF_KEY] = true\n return { ...payload, rawSpan: { ...rawSpan, span_data: kept } }\n}\n\nfunction simulationPlanEnvDisabled(): boolean {\n const value = readEnv(DISABLE_SIMULATION_PLAN_ENV)\n return typeof value === \"string\" && value.trim() !== \"\"\n}\n\nfunction missingSimulationPlanEndpoint(error: unknown): boolean {\n return error instanceof BitfabError && error.status === 404\n}\n\nfunction isTraceRootSpan(payload: Record<string, unknown>): boolean {\n const parentId = rawSpanOf(payload)?.parent_id\n return parentId === undefined || parentId === null\n}\n\nfunction declaredInCode(payload: Record<string, unknown>): boolean {\n return payload[DECLARED_NODE_FIELD] === true\n}\n\nfunction recordedError(payload: Record<string, unknown>): boolean {\n const error = spanDataOf(payload)?.error\n return error !== undefined && error !== null\n}\n\nexport class SimulationPlan {\n private contentOffByKey: Map<string, Set<string>> | undefined\n private readonly policyRefresh = new PolicyRefresh()\n private resolveLoaded: (() => void) | undefined\n private readonly loaded: Promise<void>\n private firstReadOver = false\n private resolveFirstReadEnded: (() => void) | undefined\n private readonly firstReadEnded: Promise<void>\n private rootWaitOver = false\n private rootWait: Promise<void> | undefined\n private resolveRootWait: (() => void) | undefined\n private rootWaitTimer: ReturnType<typeof setTimeout> | undefined\n private held: HeldEntry[] = []\n private stopped = false\n private readStarted = false\n\n constructor(\n private readonly source: SimulationPlanSource,\n private readonly enabled: boolean = true,\n ) {\n this.loaded = new Promise((resolve) => {\n this.resolveLoaded = resolve\n })\n this.firstReadEnded = new Promise((resolve) => {\n this.resolveFirstReadEnded = resolve\n })\n }\n\n disabled(): boolean {\n return !this.enabled || simulationPlanEnvDisabled()\n }\n\n private idle(): boolean {\n return !this.readStarted && this.source.canRead?.() === false\n }\n\n refresh(): void {\n if (this.idle()) {\n return\n }\n this.read()\n }\n\n private read(): void {\n if (this.stopped || this.disabled()) {\n return\n }\n this.readStarted = true\n this.policyRefresh.run(\n () => this.source.getSimulationPlan(),\n (body) => {\n const parsed = parseSimulationPlan(body)\n if (parsed === null) {\n this.scheduleRetry(\n \"sim-plan-unreadable\",\n \"the sim plan response was not understood\",\n )\n } else {\n this.markLoaded(parsed)\n }\n this.endFirstRead()\n },\n (error: unknown) => {\n if (missingSimulationPlanEndpoint(error)) {\n this.markLoaded(new Map())\n } else {\n this.scheduleRetry(\n \"sim-plan-unavailable\",\n `could not read the sim plan: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n this.endFirstRead()\n },\n )\n }\n\n private markLoaded(parsed: Map<string, Set<string>>): void {\n if (this.stopped) {\n return\n }\n this.contentOffByKey = parsed\n this.policyRefresh.hold(SIMULATION_PLAN_REFRESH_MS)\n this.resolveLoaded?.()\n this.resolveLoaded = undefined\n }\n\n private scheduleRetry(warnKey: string, reason: string): void {\n if (this.stopped) {\n return\n }\n this.policyRefresh.hold(SIMULATION_PLAN_RETRY_MS)\n if (this.contentOffByKey !== undefined) {\n return\n }\n warnOnce(\n warnKey,\n `${reason}. Until a read succeeds, spans are sent without their inputs and outputs, except each trace's root span and spans recorded by a framework integration. The read is retried on the next span after ${SIMULATION_PLAN_RETRY_MS / 1000}s.`,\n )\n }\n\n private endFirstRead(): void {\n this.endRootWait()\n if (!this.firstReadOver) {\n this.firstReadOver = true\n this.resolveFirstReadEnded?.()\n this.resolveFirstReadEnded = undefined\n }\n this.releaseHeld()\n }\n\n private endRootWait(): void {\n this.rootWaitOver = true\n if (this.rootWaitTimer !== undefined) {\n clearTimeout(this.rootWaitTimer)\n this.rootWaitTimer = undefined\n }\n this.resolveRootWait?.()\n this.resolveRootWait = undefined\n }\n\n waitForFirstRead(): Promise<void> | undefined {\n this.refresh()\n if (\n this.rootWaitOver ||\n this.disabled() ||\n this.idle() ||\n !this.holdingForFirstRead()\n ) {\n return undefined\n }\n if (this.rootWait === undefined) {\n this.rootWait = new Promise<void>((resolve) => {\n this.resolveRootWait = resolve\n })\n this.rootWaitTimer = setTimeout(\n () => this.endRootWait(),\n SIMULATION_PLAN_READ_TIMEOUT_MS,\n )\n }\n return this.rootWait\n }\n\n private holdingForFirstRead(): boolean {\n return (\n this.contentOffByKey === undefined && !this.firstReadOver && !this.stopped\n )\n }\n\n unavailableNow(): boolean {\n return (\n !this.disabled() &&\n this.contentOffByKey === undefined &&\n this.firstReadOver\n )\n }\n\n firstLoad(): Promise<void> | undefined {\n if (\n this.contentOffByKey !== undefined ||\n this.stopped ||\n this.disabled() ||\n this.idle()\n ) {\n return undefined\n }\n return this.loaded\n }\n\n send(\n payload: Record<string, unknown>,\n traceFunctionKey: string | undefined,\n submit: SimulationPlanSubmit,\n drop?: () => void,\n ): void {\n this.read()\n if (\n this.disabled() ||\n traceFunctionKey === undefined ||\n spanNameOf(payload) === undefined ||\n recordedByFramework(payload)\n ) {\n submit(payload)\n return\n }\n const entry = { payload, traceFunctionKey, submit, drop }\n if (this.holdingForFirstRead()) {\n this.hold(entry)\n return\n }\n this.submitEntry(entry)\n }\n\n sendTrace(\n payload: Record<string, unknown>,\n submit: SimulationPlanSubmit,\n ): void {\n this.read()\n if (\n this.disabled() ||\n !this.holdingForFirstRead() ||\n !this.holdsSpanOfTrace(traceIdOf(payload))\n ) {\n submit(payload)\n return\n }\n this.hold({ payload, traceFunctionKey: undefined, submit })\n }\n\n private holdsSpanOfTrace(traceId: string | undefined): boolean {\n if (traceId === undefined) {\n return false\n }\n return this.held.some(\n (entry) =>\n entry.traceFunctionKey !== undefined &&\n traceIdOf(entry.payload) === traceId,\n )\n }\n\n private hold(entry: HeldEntry): void {\n this.held.push(entry)\n let overflowed = false\n while (this.held.length > SIMULATION_PLAN_MAX_HELD) {\n const oldest = this.held.shift() as HeldEntry\n this.submitEntry(oldest)\n overflowed = true\n }\n if (overflowed) {\n warnOnce(\n \"sim-plan-held-overflow\",\n `more than ${SIMULATION_PLAN_MAX_HELD} records were waiting for the sim plan, so the oldest were sent without their inputs and outputs.`,\n )\n }\n }\n\n private payloadToSend(entry: HeldEntry): Record<string, unknown> {\n if (entry.traceFunctionKey === undefined || declaredInCode(entry.payload)) {\n return entry.payload\n }\n if (this.contentOffByKey !== undefined) {\n return this.apply(entry.payload, entry.traceFunctionKey)\n }\n if (recordedByFramework(entry.payload) || isTraceRootSpan(entry.payload)) {\n return entry.payload\n }\n return stripContent(entry.payload)\n }\n\n private submitEntry(entry: HeldEntry): void {\n if (\n entry.traceFunctionKey !== undefined &&\n this.skipsSpan(entry.payload, entry.traceFunctionKey)\n ) {\n entry.drop?.()\n return\n }\n try {\n entry.submit(this.payloadToSend(entry))\n } catch (error) {\n entry.drop?.()\n warnOnce(\n \"sim-plan-held-span-dropped\",\n `a span held for the sim plan was dropped when released: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n private releaseHeld(): void {\n const held = this.held\n this.held = []\n for (const entry of held) {\n this.submitEntry(entry)\n }\n }\n\n private releaseHeldWithoutPlan(): void {\n if (this.held.length === 0) {\n return\n }\n if (this.contentOffByKey === undefined) {\n warnOnce(\n \"sim-plan-not-loaded-at-release\",\n `${this.held.length} record(s) were sent without their inputs and outputs because the sim plan had not loaded`,\n )\n }\n this.releaseHeld()\n }\n\n async release(timeoutMs: number): Promise<void> {\n this.refresh()\n if (this.held.length > 0) {\n await this.waitForFirstReadEnd(timeoutMs)\n }\n this.releaseHeldWithoutPlan()\n }\n\n private waitForFirstReadEnd(timeoutMs: number): Promise<void> {\n if (this.firstReadOver) {\n return Promise.resolve()\n }\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, Math.max(timeoutMs, 0))\n void this.firstReadEnded.then(() => {\n clearTimeout(timer)\n resolve()\n })\n })\n }\n\n stop(): void {\n if (this.stopped) {\n return\n }\n this.releaseHeldWithoutPlan()\n this.stopped = true\n this.endFirstRead()\n }\n\n contentOff(traceFunctionKey: string, spanName: string): boolean {\n return this.contentOffByKey?.get(traceFunctionKey)?.has(spanName) === true\n }\n\n contentOffNow(traceFunctionKey: string, spanName: string): boolean {\n return (\n !this.stopped &&\n !this.disabled() &&\n this.contentOff(traceFunctionKey, spanName)\n )\n }\n\n private skipsSpan(\n payload: Record<string, unknown>,\n traceFunctionKey: string,\n ): boolean {\n const name = spanNameOf(payload)\n return (\n name !== undefined &&\n this.contentOff(traceFunctionKey, name) &&\n !isTraceRootSpan(payload) &&\n !declaredInCode(payload) &&\n spanInstrumentationOf(payload) !== undefined &&\n !recordedByFramework(payload) &&\n !recordedError(payload)\n )\n }\n\n apply(\n payload: Record<string, unknown>,\n traceFunctionKey: string,\n ): Record<string, unknown> {\n if (recordedByFramework(payload) || declaredInCode(payload)) {\n return payload\n }\n const name = spanNameOf(payload)\n if (name === undefined || !this.contentOff(traceFunctionKey, name)) {\n return payload\n }\n return stripContent(payload)\n }\n}\n","/**\n * Best-effort `unref()` on a timer handle so a pending timeout never keeps the\n * Node.js event loop alive on its own. An un-unref'd timeout would delay\n * process exit, prolong a serverless function's billed lifetime, and hang test\n * runners until it fires.\n *\n * In the browser `setTimeout` returns a number with no `unref`, so this is a\n * no-op there. Callers should still `clearTimeout` the handle once the work it\n * guards has settled.\n */\nexport function unrefTimer(timer: ReturnType<typeof setTimeout>): void {\n const handle = timer as { unref?: () => void }\n if (typeof handle.unref === \"function\") {\n handle.unref()\n }\n}\n","/**\n * OpenTelemetry transport for Bitfab spans and trace completions.\n *\n * OTel is used here as a queueing, batching, and delivery engine only. Bitfab\n * keeps ownership of logical trace identity: every payload travels inside an\n * internal *carrier* span whose `bitfab.payload` attribute holds the encoded\n * Bitfab body, and the server reconstructs the stored tree from that payload\n * rather than from the carrier's OTel topology. The provider and processor are\n * private to each client, so an application's own OTel traces are never mixed\n * into Bitfab traces and the global provider is never replaced.\n */\n\nimport { type Span, SpanStatusCode, type Tracer } from \"@opentelemetry/api\"\nimport {\n type ExportResult,\n ExportResultCode,\n type InstrumentationScope,\n} from \"@opentelemetry/core\"\nimport { resourceFromAttributes } from \"@opentelemetry/resources\"\nimport {\n AlwaysOnSampler,\n BasicTracerProvider,\n BatchSpanProcessor,\n type ReadableSpan,\n type SpanExporter,\n} from \"@opentelemetry/sdk-trace-base\"\nimport { type EncodedRequestBody, encodeRequestBody } from \"./compress.js\"\nimport { __version__ } from \"./constants.js\"\nimport { BitfabError } from \"./errors.js\"\nimport {\n byteLength,\n MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES,\n MAX_SPAN_CARRIER_BYTES,\n} from \"./payloadBudget.js\"\nimport { readEnv } from \"./readEnv.js\"\nimport { serializePayloadBody } from \"./serializePayload.js\"\nimport type {\n CarrierMeta,\n CarrierRef,\n DirectBatchSender,\n TraceOperation,\n TraceTransport,\n} from \"./transportTypes.js\"\nimport { DeliveryError } from \"./transportTypes.js\"\nimport { unrefTimer } from \"./unrefTimer.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nconst OPERATION_ATTRIBUTE = \"bitfab.operation\"\nconst PAYLOAD_ATTRIBUTE = \"bitfab.payload\"\nconst MAX_EXPORT_REQUEST_BYTES = 3_000_000\nconst MAX_DECOMPRESSED_REQUEST_BYTES = 8_000_000\nconst MAX_REQUEST_BYTES_ENV = \"BITFAB_OTEL_MAX_REQUEST_BYTES\"\nconst EXPORT_CONCURRENCY_ENV = \"BITFAB_OTEL_EXPORT_CONCURRENCY\"\nconst MAX_QUEUE_SIZE = 16_384\nconst DIRECT_MAX_EXPORT_BATCH_SIZE = 512\nconst DIRECT_MAX_REQUEST_BATCH_SIZE = 256\nconst DEFAULT_EXPORT_CONCURRENCY = 32\nconst MAX_EXPORT_CONCURRENCY = 64\nconst SCHEDULE_DELAY_MILLIS = 5_000\nconst EXPORT_TIMEOUT_MILLIS = 30_000\nconst RETRY_BASE_DELAY_MILLIS = 100\n// Ceiling on the exponential growth of our OWN backoff. It does not bound a\n// wait the server asked for: OTLP says to honor Retry-After, and warns that a\n// delay big enough to make the client drop data is the server's mistake to\n// avoid, not the client's cue to discard. What bounds an honored wait is the\n// export budget below, since a wait outliving the export cannot be served.\nconst RETRY_BACKOFF_CEILING_MILLIS = 5_000\nconst MAX_SEND_ATTEMPTS = 3\nconst DEFAULT_LIFECYCLE_TIMEOUT_MS = 30_000\n\nconst liveTransports = new Set<OtelBatchTransport>()\n\n// Keyed by the carrier span object so a dropped span needs no cleanup. The ref\n// cannot ride on the span as an attribute: `spanLimits` caps carriers at two,\n// and `bitfab.operation` and `bitfab.payload` hold both.\nconst carrierRefs = new WeakMap<object, CarrierRef>()\n\nfunction readBoundedIntEnv(\n name: string,\n max: number,\n fallback: number,\n warnKey: string,\n): number {\n const raw = readEnv(name)\n if (raw === undefined) {\n return fallback\n }\n const value = Number(raw)\n if (Number.isInteger(value) && value > 0 && value <= max) {\n return value\n }\n warnOnce(\n warnKey,\n `${name} must be a positive integer no greater than ${max}; using ${fallback}`,\n )\n return fallback\n}\n\nfunction logError(message: string, error?: unknown): void {\n try {\n if (error === undefined) {\n console.error(`[bitfab] ${message}`)\n } else {\n console.error(`[bitfab] ${message}`, error)\n }\n } catch {\n // Logging must never crash the host app.\n }\n}\n\nfunction otlpValue(value: unknown): Record<string, unknown> {\n if (typeof value === \"boolean\") {\n return { boolValue: value }\n }\n if (typeof value === \"number\") {\n return Number.isInteger(value)\n ? { intValue: String(value) }\n : { doubleValue: value }\n }\n if (typeof value === \"string\") {\n return { stringValue: value }\n }\n if (Array.isArray(value)) {\n return { arrayValue: { values: value.map(otlpValue) } }\n }\n return { stringValue: String(value) }\n}\n\nfunction otlpAttributes(\n attributes: Record<string, unknown> | undefined,\n): Record<string, unknown>[] {\n if (!attributes) {\n return []\n }\n return Object.entries(attributes)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => ({ key, value: otlpValue(value) }))\n}\n\n/**\n * Nanoseconds since the epoch as a decimal string. Built by concatenation\n * rather than arithmetic because the value exceeds `Number.MAX_SAFE_INTEGER`,\n * so multiplying seconds out would silently lose the low digits.\n */\nfunction hrTimeToNanoString(time: [number, number] | undefined): string {\n if (!time) {\n return \"0\"\n }\n return `${time[0]}${String(time[1]).padStart(9, \"0\")}`\n}\n\nfunction spanToOtlp(span: ReadableSpan): Record<string, unknown> {\n const spanContext = span.spanContext()\n const result: Record<string, unknown> = {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n name: span.name,\n kind: span.kind + 1,\n startTimeUnixNano: hrTimeToNanoString(span.startTime),\n endTimeUnixNano: hrTimeToNanoString(span.endTime),\n attributes: otlpAttributes(span.attributes as Record<string, unknown>),\n droppedAttributesCount: span.droppedAttributesCount,\n droppedEventsCount: span.droppedEventsCount,\n droppedLinksCount: span.droppedLinksCount,\n status: {\n code: span.status.code,\n ...(span.status.message ? { message: span.status.message } : {}),\n },\n flags: spanContext.traceFlags,\n }\n const parentSpanId = span.parentSpanContext?.spanId\n if (parentSpanId) {\n result.parentSpanId = parentSpanId\n }\n if (spanContext.traceState) {\n result.traceState = spanContext.traceState.serialize()\n }\n return result\n}\n\n/**\n * A span encoded exactly as it will appear on the wire, carrying its own byte\n * count. Encoding once and remembering the size is what keeps request packing\n * linear: sizing a candidate batch by re-encoding the whole request re-escapes\n * every carrier's `bitfab.payload` string on every span considered.\n */\ninterface EncodedSpan {\n json: string\n size: number\n ref?: CarrierRef\n}\n\ninterface RequestBatch {\n spans: EncodedSpan[]\n size: number\n}\n\n/**\n * The invariant head and tail of an OTLP request for one export window. Key\n * order matches what `JSON.stringify` emits for the equivalent object, so a\n * body assembled by concatenation is byte-identical to encoding that object.\n */\ninterface RequestEnvelope {\n head: string\n tail: string\n size: number\n}\n\n/** The comma `join` puts between adjacent spans in the request's span list. */\nconst SPAN_SEPARATOR_BYTES = 1\n\nfunction encodeSpan(span: ReadableSpan): EncodedSpan {\n const json = JSON.stringify(spanToOtlp(span))\n return {\n json,\n size: byteLength(json),\n ref: carrierRefs.get(span),\n }\n}\n\nfunction trimEncodedSpan(span: EncodedSpan): EncodedSpan | undefined {\n try {\n const carrier = JSON.parse(span.json) as {\n attributes?: Array<{\n key?: string\n value?: { stringValue?: string }\n }>\n }\n const attribute = carrier.attributes?.find(\n (entry) => entry.key === PAYLOAD_ATTRIBUTE,\n )\n const payloadBody = attribute?.value?.stringValue\n if (!attribute?.value || payloadBody === undefined) {\n return undefined\n }\n const payload = JSON.parse(payloadBody) as Record<string, unknown>\n attribute.value.stringValue = serializePayloadBody(\n payload,\n MAX_SPAN_CARRIER_BYTES,\n ).body\n const json = JSON.stringify(carrier)\n return { json, size: byteLength(json) }\n } catch {\n return undefined\n }\n}\n\nasync function prepareRequest(body: string): Promise<EncodedRequestBody> {\n const prepared = encodeRequestBody(body)\n return prepared instanceof Promise ? await prepared : prepared\n}\n\nfunction requestEnvelope(first: ReadableSpan): RequestEnvelope {\n const scope = first.instrumentationScope as InstrumentationScope\n const resource = JSON.stringify({\n attributes: otlpAttributes(\n first.resource.attributes as Record<string, unknown>,\n ),\n })\n const scopeJson = JSON.stringify({\n name: scope.name,\n version: scope.version ?? \"\",\n })\n const head = `{\"resourceSpans\":[{\"resource\":${resource},\"scopeSpans\":[{\"scope\":${scopeJson},\"spans\":[`\n const tail = \"]}]}]}\"\n return { head, tail, size: byteLength(head) + byteLength(tail) }\n}\n\nfunction encodeRequest(\n envelope: RequestEnvelope,\n spans: EncodedSpan[],\n): string {\n return (\n envelope.head + spans.map((span) => span.json).join(\",\") + envelope.tail\n )\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms)\n unrefTimer(timer)\n })\n}\n\n/**\n * Race `work` against `timeoutMs`. Resolves `false` when the deadline wins, so\n * a wedged export can never hold a flush or shutdown open past its budget.\n */\nasync function withDeadline(\n work: Promise<boolean>,\n timeoutMs: number,\n): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n work,\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs))\n unrefTimer(timer)\n }),\n ])\n } finally {\n if (timer) {\n clearTimeout(timer)\n }\n }\n}\n\n/** Run `task` over `items` with at most `limit` in flight at any moment. */\nasync function mapWithConcurrency<T, R>(\n items: T[],\n limit: number,\n task: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length)\n let next = 0\n const workers = Array.from(\n { length: Math.min(Math.max(limit, 1), items.length) },\n async () => {\n while (next < items.length) {\n const index = next\n next += 1\n results[index] = await task(items[index])\n }\n },\n )\n await Promise.all(workers)\n return results\n}\n\n/**\n * Only what the sender classified. Anything else reaching here is a fault in\n * the sender itself, and retrying a deterministic bug just delays it.\n */\nfunction isRetryable(error: unknown): boolean {\n return error instanceof DeliveryError && error.retryable\n}\n\nfunction isOversized(error: unknown): boolean {\n return error instanceof DeliveryError && error.oversized\n}\n\n/**\n * How long to wait before the next send attempt, or `null` to stop trying.\n *\n * A server that sent `Retry-After` has told us when it wants us back, so that\n * wait is honored exactly. Clamping it would return early, which is the single\n * thing the server asked us not to do; when the wait is longer than we are\n * willing to hold a batch, the honest answer is to give up rather than come\n * back sooner and add load to something already struggling.\n *\n * Absent an instruction, back off exponentially so a struggling server is not\n * hit on a fixed cadence, and jitter it so every client in a fleet does not\n * return in lockstep.\n */\n/**\n * How long to wait before the next attempt, or null when the wait cannot be\n * served inside `remainingMillis` and the batch has to be given up.\n *\n * A server that sent Retry-After told us when it wants us back, so that wait is\n * honored whole rather than shortened: coming back early is the one thing it\n * asked us not to do. It is refused only when it outlasts the export budget,\n * where waiting would mean being killed mid-wait and losing the batch anyway.\n *\n * Absent an instruction, back off exponentially so a struggling server is not\n * hit on a fixed cadence, and jitter it so a fleet does not return in lockstep.\n */\nfunction retryWaitMillis(\n error: unknown,\n attempt: number,\n remainingMillis: number,\n): number | null {\n const requested =\n error instanceof DeliveryError ? error.retryAfterMs : undefined\n // Half the remaining budget, not all of it: a wait is only worth taking if\n // what is left afterwards can still carry the request. Spending the whole\n // budget waiting means being killed mid-wait, which loses the batch AND holds\n // an export slot for the duration.\n const affordable = remainingMillis / 2\n if (requested !== undefined) {\n return requested < affordable ? requested : null\n }\n const backoff = Math.min(\n RETRY_BASE_DELAY_MILLIS * 2 ** attempt,\n RETRY_BACKOFF_CEILING_MILLIS,\n )\n const jittered = backoff / 2 + Math.random() * (backoff / 2)\n return jittered < affordable ? jittered : null\n}\n\n/**\n * Direct delivery to Bitfab's OTLP/JSON ingress.\n *\n * OTel hands this exporter one batch as a candidate window. The window is\n * repacked into requests bounded by both a carrier count and the exact encoded\n * request size, and those complete requests are sent concurrently. That keeps\n * OTel's queue, scheduling, force-flush and shutdown while restoring the small\n * independent requests Bitfab's serverless ingress is built to scale.\n */\nexport class BitfabSpanExporter implements SpanExporter {\n constructor(\n private readonly directSender: DirectBatchSender,\n private readonly maxRequestBytes: number,\n private readonly maxRequestBatchSize: number,\n private readonly exportConcurrency: number,\n private readonly onDelivered?: (refs: CarrierRef[]) => void,\n // The same budget the processor enforces around this export. Waits are\n // measured against it, so a configured timeout and the deadline a wait is\n // judged by can never drift apart.\n private readonly exportTimeoutMillis: number = EXPORT_TIMEOUT_MILLIS,\n ) {}\n\n /** Epoch ms until which the server has asked this exporter to stay away. */\n private throttledUntil = 0\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): void {\n void this.exportAsync(spans).then(\n (succeeded) => {\n resultCallback({\n code: succeeded ? ExportResultCode.SUCCESS : ExportResultCode.FAILED,\n })\n },\n (error) => {\n resultCallback({ code: ExportResultCode.FAILED, error })\n },\n )\n }\n\n private async exportAsync(spans: ReadableSpan[]): Promise<boolean> {\n if (spans.length === 0) {\n return true\n }\n let encoded: EncodedSpan[]\n let envelope: RequestEnvelope\n try {\n encoded = spans.map(encodeSpan)\n envelope = requestEnvelope(spans[0])\n } catch (error) {\n logError(\"failed to encode an OpenTelemetry span batch\", error)\n return false\n }\n\n const batches = this.buildRequestBatches(envelope, encoded)\n const results = await mapWithConcurrency(\n batches,\n this.exportConcurrency,\n (batch) => this.send(envelope, batch),\n )\n return results.every(Boolean)\n }\n\n private buildRequestBatches(\n envelope: RequestEnvelope,\n spans: EncodedSpan[],\n ): RequestBatch[] {\n const batches: RequestBatch[] = []\n let current: EncodedSpan[] = []\n let size = envelope.size\n\n for (const span of spans) {\n const addition =\n span.size + (current.length > 0 ? SPAN_SEPARATOR_BYTES : 0)\n if (\n current.length > 0 &&\n (current.length >= this.maxRequestBatchSize ||\n size + addition > this.maxRequestBytes)\n ) {\n batches.push({ spans: current, size })\n current = []\n size = envelope.size\n }\n current.push(span)\n size += span.size + (current.length > 1 ? SPAN_SEPARATOR_BYTES : 0)\n }\n\n if (current.length > 0) {\n batches.push({ spans: current, size })\n }\n return batches\n }\n\n private async send(\n envelope: RequestEnvelope,\n batch: RequestBatch,\n ): Promise<boolean> {\n try {\n let requestSpans = batch.spans\n let requestRawBytes = batch.size\n let alreadyTrimmed = false\n while (true) {\n if (requestRawBytes <= MAX_DECOMPRESSED_REQUEST_BYTES) {\n const prepared = await prepareRequest(\n encodeRequest(envelope, requestSpans),\n )\n if (prepared.wireBytes <= this.maxRequestBytes) {\n await this.sendWithRetries(prepared)\n // Refs come from the batch, not the possibly-trimmed request:\n // trimming rebuilds a span without its ref, and a trimmed carrier\n // still reached the server under its original identity.\n this.reportDelivered(batch.spans)\n return true\n }\n }\n\n if (batch.spans.length !== 1) {\n logError(\n \"an OpenTelemetry span batch exceeded the configured request-size target and could not be exported\",\n )\n return false\n }\n if (alreadyTrimmed) {\n logError(\n \"a single OpenTelemetry span exceeded the configured request-size target after trimming\",\n )\n return false\n }\n const trimmed = trimEncodedSpan(batch.spans[0])\n if (!trimmed) {\n logError(\n \"a single OpenTelemetry span exceeded the configured request-size target and could not be trimmed\",\n )\n return false\n }\n requestSpans = [trimmed]\n requestRawBytes = envelope.size + trimmed.size\n alreadyTrimmed = true\n }\n } catch (error) {\n if (isOversized(error)) {\n logError(\n batch.spans.length === 1\n ? \"a single OpenTelemetry span exceeded the ingestion request limit and could not be exported\"\n : \"an OpenTelemetry span batch exceeded the ingestion request limit and could not be exported\",\n )\n return false\n }\n logError(\"failed to export an OpenTelemetry span batch\", error)\n return false\n }\n }\n\n /**\n * Retries transient failures. Span and trace-completion carriers are safe to\n * retry: the server keys them idempotently on `sourceSpanId`/`sourceTraceId`,\n * so a duplicate delivery cannot create a duplicate row.\n *\n * KNOWN LIMITATION: an `internal_trace` (a `call()` BAML trace) carries no\n * such key, so retrying a batch that holds one can create a duplicate trace -\n * including when a request times out client-side but the server goes on to\n * persist it. Accepted deliberately for now, matching the other SDKs, rather\n * than skipping retries for a whole batch or inventing an idempotency scheme\n * the server does not yet understand. The fix is a client-supplied\n * idempotency key that ingestion dedupes on.\n */\n /**\n * Remember a throttle the server asked for, so the requests fanned out\n * alongside this one respect it too. Delaying only the request that was\n * refused leaves the other seven in the window hitting a server that just\n * asked for room.\n */\n private recordThrottle(error: unknown): void {\n const requested =\n error instanceof DeliveryError ? error.retryAfterMs : undefined\n if (requested !== undefined) {\n this.throttledUntil = Math.max(\n this.throttledUntil,\n Date.now() + requested,\n )\n }\n }\n\n /**\n * Waits out an active throttle, or reports the batch undeliverable when the\n * throttle outlasts what we are willing to hold it for. Either way nothing is\n * sent while the server has asked us to stay away.\n */\n private async awaitThrottle(deadline: number): Promise<void> {\n const remaining = this.throttledUntil - Date.now()\n if (remaining <= 0) {\n return\n }\n // Waited out, not refused: OTLP asks the client to hold off until the\n // window passes, and treats data dropped while throttled as the outcome to\n // avoid. Only a throttle outliving the export budget is refused, because\n // the processor would kill the wait before it could send anyway.\n if (remaining >= (deadline - Date.now()) / 2) {\n throw new DeliveryError(\n `OTLP ingestion is throttled for another ${remaining}ms, longer than the export budget`,\n )\n }\n await delay(remaining)\n }\n\n private async sendWithRetries(request: EncodedRequestBody): Promise<void> {\n // One budget for the whole exchange, waits included: the processor kills\n // the export at this deadline, so a wait past it cannot be served.\n const deadline = Date.now() + this.exportTimeoutMillis\n for (let attempt = 0; attempt < MAX_SEND_ATTEMPTS; attempt += 1) {\n try {\n await this.awaitThrottle(deadline)\n await this.directSender(request, Math.max(0, deadline - Date.now()))\n return\n } catch (error) {\n if (isOversized(error)) {\n throw error\n }\n this.recordThrottle(error)\n if (attempt === MAX_SEND_ATTEMPTS - 1 || !isRetryable(error)) {\n throw error\n }\n const wait = retryWaitMillis(error, attempt, deadline - Date.now())\n if (wait === null) {\n throw error\n }\n await delay(wait)\n }\n }\n }\n\n /**\n * Announce the carriers a request delivered. Wrapped because a listener that\n * throws must never turn a delivered batch into a failed export.\n */\n private reportDelivered(spans: EncodedSpan[]): void {\n if (this.onDelivered === undefined) {\n return\n }\n const refs = spans\n .map((span) => span.ref)\n .filter((ref): ref is CarrierRef => ref !== undefined)\n if (refs.length === 0) {\n return\n }\n try {\n this.onDelivered(refs)\n } catch (error) {\n logError(\"a delivery listener threw\", error)\n }\n }\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\n/**\n * Counts export failures so `flush` can answer \"was this delivered?\" instead of\n * only \"did the processor queue drain?\". Without it a flush would report\n * success for a batch the exporter dropped, and replay would finalize a run\n * whose traces never landed.\n */\nclass DeliveryTrackingExporter implements SpanExporter {\n // Deliberately unscoped, matching the Python SDK. An export can outlive\n // OTel's export timeout and report failure after the flush that was waiting\n // on it already returned, so that failure surfaces on the NEXT flush instead.\n // That over-reports: a good flush can inherit an older failure. The\n // alternative - discarding failures from completed flush windows - under-\n // reports, and `BatchSpanProcessor` also runs scheduled exports that belong\n // to no flush at all, so their failures would vanish entirely. For a\n // telemetry SDK a false \"flush failed\" is investigable; a false \"flush\n // succeeded\" silently loses traces. We take the noisy direction on purpose.\n private failedExports = 0\n\n constructor(private readonly exporter: SpanExporter) {}\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void,\n ): void {\n try {\n this.exporter.export(spans, (result) => {\n if (result.code !== ExportResultCode.SUCCESS) {\n this.failedExports += 1\n }\n resultCallback(result)\n })\n } catch (error) {\n this.failedExports += 1\n resultCallback({ code: ExportResultCode.FAILED, error: error as Error })\n }\n }\n\n takeFailedExports(): number {\n const failed = this.failedExports\n this.failedExports = 0\n return failed\n }\n\n shutdown(): Promise<void> {\n return this.exporter.shutdown()\n }\n\n forceFlush(): Promise<void> {\n return this.exporter.forceFlush?.() ?? Promise.resolve()\n }\n}\n\nexport interface OtelBatchTransportOptions {\n directSender: DirectBatchSender\n /** Called with the refs of every carrier a request delivered. */\n onDelivered?: (refs: CarrierRef[]) => void\n maxExportBatchSize?: number\n maxRequestBatchSize?: number\n maxQueueSize?: number\n exportConcurrency?: number\n maxRequestBytes?: number\n /** Overridable so tests can drive OTel's export-timeout path in ms, not 30s. */\n exportTimeoutMillis?: number\n}\n\nexport class OtelBatchTransport implements TraceTransport {\n private readonly provider: BasicTracerProvider\n private readonly processor: BatchSpanProcessor\n private readonly deliveryTracker: DeliveryTrackingExporter\n private readonly tracer: Tracer\n private closed = false\n private pendingFlush: Promise<boolean> | undefined\n\n constructor(options: OtelBatchTransportOptions) {\n const maxRequestBytes = options.maxRequestBytes ?? MAX_EXPORT_REQUEST_BYTES\n const maxRequestBatchSize =\n options.maxRequestBatchSize ?? DIRECT_MAX_REQUEST_BATCH_SIZE\n if (maxRequestBatchSize <= 0) {\n throw new BitfabError(\"maxRequestBatchSize must be a positive integer\")\n }\n\n this.deliveryTracker = new DeliveryTrackingExporter(\n new BitfabSpanExporter(\n options.directSender,\n maxRequestBytes,\n maxRequestBatchSize,\n options.exportConcurrency ?? DEFAULT_EXPORT_CONCURRENCY,\n options.onDelivered,\n options.exportTimeoutMillis ?? EXPORT_TIMEOUT_MILLIS,\n ),\n )\n\n this.processor = new BatchSpanProcessor(this.deliveryTracker, {\n maxQueueSize: options.maxQueueSize ?? MAX_QUEUE_SIZE,\n maxExportBatchSize:\n options.maxExportBatchSize ?? DIRECT_MAX_EXPORT_BATCH_SIZE,\n scheduledDelayMillis: SCHEDULE_DELAY_MILLIS,\n exportTimeoutMillis: options.exportTimeoutMillis ?? EXPORT_TIMEOUT_MILLIS,\n })\n\n // Every option is passed explicitly: `BasicTracerProvider` otherwise reads\n // OTEL_* defaults, so a host application's sampler or attribute-length\n // limit would silently drop or truncate Bitfab payloads.\n this.provider = new BasicTracerProvider({\n sampler: new AlwaysOnSampler(),\n resource: resourceFromAttributes({\n \"service.name\": \"bitfab-typescript-sdk\",\n \"service.version\": __version__,\n }),\n spanLimits: {\n attributeCountLimit: 2,\n attributeValueLengthLimit: Number.POSITIVE_INFINITY,\n },\n spanProcessors: [this.processor],\n })\n this.tracer = this.provider.getTracer(\"bitfab\", __version__)\n liveTransports.add(this)\n }\n\n submit(\n operation: TraceOperation,\n payload: Record<string, unknown>,\n meta: CarrierMeta = {},\n ): void {\n if (this.closed) {\n warnOnce(\n \"otel-submit-after-shutdown\",\n \"OpenTelemetry transport is shut down; dropping spans\",\n )\n return\n }\n try {\n // Not a bare JSON.stringify: contexts, metadata and `call()` inputs\n // never pass through `serializeValue`, so one stray value here would\n // throw and drop the whole span rather than being stubbed. This is the\n // same backstop the pre-transport HTTP path applied.\n const { body, dropped } = serializePayloadBody(\n payload,\n MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES,\n )\n if (dropped.length > 0) {\n warnOnce(\n \"otel-carrier-payload-stubbed\",\n `a span payload held non-serializable value(s) (${[\n ...new Set(dropped),\n ].join(\", \")}); they were stubbed so the span still ships, but the ` +\n \"trace may be incomplete or not replayable.\",\n )\n }\n const span = this.tracer.startSpan(meta.name ?? `bitfab.${operation}`, {\n attributes: {\n [OPERATION_ATTRIBUTE]: operation,\n [PAYLOAD_ATTRIBUTE]: body,\n },\n startTime: meta.startTime,\n })\n if (meta.ref !== undefined) {\n carrierRefs.set(span, meta.ref)\n }\n if (meta.errored === true) {\n span.setStatus({ code: SpanStatusCode.ERROR })\n }\n endSpan(span, meta.endTime)\n } catch (error) {\n logError(\"failed to queue an OpenTelemetry span\", error)\n }\n }\n\n async flush(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n ): Promise<boolean> {\n // Serialized: two concurrent force-flushes would race for the same\n // delivery counter and one would report the other's failures as success.\n const pending = (this.pendingFlush ?? Promise.resolve(true)).then(() =>\n this.forceFlushOnce(),\n )\n this.pendingFlush = pending.catch(() => false)\n return withDeadline(pending, timeoutMs)\n }\n\n private async forceFlushOnce(): Promise<boolean> {\n try {\n await this.processor.forceFlush()\n } catch (error) {\n logError(\"failed to flush OpenTelemetry spans\", error)\n this.deliveryTracker.takeFailedExports()\n return false\n }\n return this.deliveryTracker.takeFailedExports() === 0\n }\n\n async shutdown(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n ): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n this.closed = true\n const flushed = await this.flush(Math.max(0, deadline - Date.now()))\n liveTransports.delete(this)\n const shutdownCompleted = await withDeadline(\n this.provider\n .shutdown()\n .then(() => true)\n .catch((error) => {\n logError(\"failed to shut down the OpenTelemetry transport\", error)\n return false\n }),\n Math.max(0, deadline - Date.now()),\n )\n return flushed && shutdownCompleted\n }\n}\n\nfunction endSpan(span: Span, endTime: number | undefined): void {\n span.end(endTime)\n}\n\nexport function createOtelTransport(options: {\n directSender: DirectBatchSender\n onDelivered?: (refs: CarrierRef[]) => void\n}): OtelBatchTransport {\n return new OtelBatchTransport({\n ...options,\n exportConcurrency: readBoundedIntEnv(\n EXPORT_CONCURRENCY_ENV,\n MAX_EXPORT_CONCURRENCY,\n DEFAULT_EXPORT_CONCURRENCY,\n \"otel-export-concurrency-invalid\",\n ),\n maxRequestBytes: readBoundedIntEnv(\n MAX_REQUEST_BYTES_ENV,\n MAX_EXPORT_REQUEST_BYTES,\n MAX_EXPORT_REQUEST_BYTES,\n \"otel-max-request-bytes-invalid\",\n ),\n })\n}\n\nasync function forEachLiveTransport(\n timeoutMs: number,\n run: (transport: OtelBatchTransport, remainingMs: number) => Promise<boolean>,\n): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n let succeeded = true\n for (const transport of [...liveTransports]) {\n succeeded =\n (await run(transport, Math.max(0, deadline - Date.now()))) && succeeded\n }\n return succeeded\n}\n\nexport function flushOtelTransports(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n): Promise<boolean> {\n return forEachLiveTransport(timeoutMs, (transport, remaining) =>\n transport.flush(remaining),\n )\n}\n\nexport function shutdownOtelTransports(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n): Promise<boolean> {\n return forEachLiveTransport(timeoutMs, (transport, remaining) =>\n transport.shutdown(remaining),\n )\n}\n","/**\n * The single seam between the HTTP client and whichever transport implements\n * span delivery. Keeping the factory here (rather than importing `otel.ts`\n * from `http.ts` directly) is what lets the OpenTelemetry implementation\n * depend on `HttpClient`'s request path without an import cycle.\n */\n\nimport {\n createOtelTransport,\n flushOtelTransports,\n shutdownOtelTransports,\n} from \"./otel.js\"\nimport type {\n CarrierRef,\n DirectBatchSender,\n TraceTransport,\n} from \"./transportTypes.js\"\n\nexport function createTraceTransport(options: {\n directSender: DirectBatchSender\n onDelivered?: (refs: CarrierRef[]) => void\n}): TraceTransport {\n return createOtelTransport(options)\n}\n\nexport function flushTraceTransports(timeoutMs?: number): Promise<boolean> {\n return flushOtelTransports(timeoutMs)\n}\n\nexport function shutdownTraceTransports(timeoutMs?: number): Promise<boolean> {\n return shutdownOtelTransports(timeoutMs)\n}\n","import { TraceCompletion } from \"./traceCompletion.js\"\n/**\n * HTTP client utilities for Bitfab API requests.\n *\n * This module provides:\n * - HttpClient class for making API requests\n * - awaitOnExit helper so deferred span work still gates process exit\n */\n\nimport { type EncodedRequestBody, encodeRequestBody } from \"./compress.js\"\nimport { __packageName__, __version__ } from \"./constants.js\"\nimport type { DbSnapshotRef } from \"./dbSnapshot.js\"\nimport { BitfabError } from \"./errors.js\"\nimport { isEmptyGitState, resolvedGitState } from \"./gitState.js\"\nimport {\n type DbBranchLease,\n type DbBranchSettings,\n type DbBranchTimings,\n replayContextReady,\n} from \"./replayContext.js\"\nimport type { ReplayInvocation } from \"./replayInvocation.js\"\nimport { serializePayloadBody } from \"./serializePayload.js\"\nimport {\n DECLARED_NODE_FIELD,\n NO_API_KEY_FOR_SIMULATION_PLAN,\n planWaitSliceMs,\n ROOT_TRACE_FUNCTION_KEY_FIELD,\n SIMULATION_PLAN_READ_TIMEOUT_MS,\n type SimulationPlanResponse,\n type SimulationPlanSubmit,\n} from \"./simulationPlan.js\"\nimport { mergeCallerMetadataIntoTracePayload } from \"./traceMetadata.js\"\nimport {\n createTraceTransport,\n flushTraceTransports,\n shutdownTraceTransports,\n} from \"./transport.js\"\nimport {\n type CarrierMeta,\n type CarrierRef,\n DeliveryError,\n type TraceOperation,\n type TraceTransport,\n} from \"./transportTypes.js\"\nimport { unrefTimer } from \"./unrefTimer.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\n// BitfabError lives in `errors.ts` to break the http ↔ dbSnapshot import\n// cycle. Re-exported here for backwards compatibility with existing\n// callers that import it from \"./http.js\".\nexport { BitfabError, serializePayloadBody }\n\nconst REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS = 300_000\nconst REPLAY_COMPLETE_REQUEST_TIMEOUT_MS = 120_000\nconst REPLAY_INTERRUPT_REQUEST_TIMEOUT_MS = 5_000\nconst REPLAY_HEARTBEAT_REQUEST_TIMEOUT_MS = 5_000\nconst OTLP_TRACES_ENDPOINT = \"/api/sdk/otel/v1/traces\"\n// OTLP's retryable set, plus 500. Every other 4xx is the server's verdict on\n// the payload and will be the same next time.\n//\n// 500 is a deliberate deviation: OTLP treats it as the app being broken, which\n// assumes a collector that fails deterministically. Bitfab ingestion answers\n// every unhandled error with 500, so a connection blip or a cold start arrives\n// here indistinguishable from a real fault, and giving up on the first one\n// drops spans that a second attempt would have delivered.\nconst RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504])\nconst EXIT_FLUSH_TIMEOUT_MS = 5_000\nconst DEFAULT_LIFECYCLE_TIMEOUT_MS = 30_000\n\nconst pendingTracePromises = new Set<Promise<unknown>>()\n\nconst liveHttpClients = new Set<HttpClient>()\n\nasync function releaseHeldExternalSpans(timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n let released = true\n for (const client of [...liveHttpClients]) {\n const result = await client.releaseHeldExternalSpans?.(\n Math.max(0, deadline - Date.now()),\n )\n released = result !== false && released\n }\n return released\n}\n\nfunction stopSimulationPlans(): void {\n for (const client of [...liveHttpClients]) {\n client.stopSimulationPlan?.()\n }\n}\n\n/**\n * Track a promise so `flushTraces()` and the exit hook wait for it.\n *\n * Exactly one caller remains: the deferred `finalize` chain, which hands its\n * span to the transport only after finalize settles. Everything else submits\n * synchronously, so the transport's own queue is the complete picture. Python\n * has no equivalent because its finalize runs inline.\n *\n * @param promise - The promise to track\n * @returns The same promise (for chaining)\n */\nexport function awaitOnExit<T>(promise: Promise<T>): Promise<T> {\n pendingTracePromises.add(promise)\n // Use void to prevent unhandled rejection warnings from the .finally() chain\n // The actual error handling is done by the caller's .catch() on the returned promise\n void promise\n .finally(() => {\n pendingTracePromises.delete(promise)\n })\n .catch(() => {\n // Swallow rejection in this chain - the caller handles errors via their own .catch()\n })\n return promise\n}\n\n/**\n * Wait for pending fire-and-forget requests AND every live span transport to\n * deliver, within one total deadline. Useful in tests and scripts to ensure all\n * data has been sent before asserting or exiting.\n *\n * Returns `false` when delivery failed or the deadline expired, so a caller\n * that depends on persistence (replay does) can react instead of assuming a\n * drained queue means the server has the data.\n *\n * @param timeoutMs - Maximum total time to wait in milliseconds (default: 5000)\n */\nexport async function flushTraces(timeoutMs: number = 5000): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n const released = await releaseHeldExternalSpans(planWaitSliceMs(timeoutMs))\n const requestsFlushed = await awaitPendingRequests(\n Math.max(0, deadline - Date.now()),\n )\n const releasedAfterDeferred = await releaseHeldExternalSpans(0)\n const transportsFlushed = await flushTraceTransports(\n Math.max(0, deadline - Date.now()),\n )\n return (\n released && releasedAfterDeferred && requestsFlushed && transportsFlushed\n )\n}\n\n/**\n * Wait for in-flight fire-and-forget requests and deferred span work, WITHOUT\n * flushing the transports.\n *\n * Replay needs this half on its own: a `finalize` span reaches the transport\n * only after its deferred chain settles, so the expected-span tally has to be\n * read after that work lands but before a flush is issued (which would be\n * wasted, and would emit a request, when the run submitted nothing).\n */\nexport async function awaitPendingRequests(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n): Promise<boolean> {\n // Async-context storage loads asynchronously, and spans traced before it\n // resolves have their recording deferred behind it. Without this, a script\n // that traces and immediately flushes or closes races its own first spans.\n await replayContextReady.catch(() => {})\n return waitForPromises(Array.from(pendingTracePromises), timeoutMs)\n}\n\n/**\n * Await `promises` within `timeoutMs`, reporting whether they all settled in\n * time rather than throwing. Rejections count as settled: a failed span upload\n * is already reported by its own catch handler, and the caller is asking about\n * completion, not success.\n */\nasync function waitForPromises(\n promises: Promise<unknown>[],\n timeoutMs: number,\n): Promise<boolean> {\n if (promises.length === 0) {\n return true\n }\n // Clear and unref the timeout so the loser of the race never leaves a\n // dangling timer holding the event loop open after flush resolves.\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n Promise.allSettled(promises).then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs)\n unrefTimer(timer)\n }),\n ])\n } finally {\n if (timer) {\n clearTimeout(timer)\n }\n }\n}\n\n// Register beforeExit handler to wait for pending traces (Node.js only)\n// This ensures traces are sent before the process exits (for scripts).\n// The transport is included: its batch worker sits on an unref'd timer, so a\n// script that ends without an explicit flush would otherwise exit with a queue\n// of spans still waiting on the scheduled delay.\nif (\n typeof process !== \"undefined\" &&\n process.versions != null &&\n process.versions.node != null\n) {\n let isFlushing = false\n process.on(\"beforeExit\", () => {\n if (isFlushing) {\n return\n }\n isFlushing = true\n const planWaitMs = SIMULATION_PLAN_READ_TIMEOUT_MS\n const stopFlushing = () => {\n isFlushing = false\n }\n const deadline = setTimeout(\n stopFlushing,\n EXIT_FLUSH_TIMEOUT_MS + planWaitMs,\n )\n unrefTimer(deadline)\n void releaseHeldExternalSpans(planWaitMs)\n .catch(() => {})\n .then(() => {\n stopSimulationPlans()\n })\n .then(() =>\n Promise.allSettled([\n ...Array.from(pendingTracePromises).map((p) => p.catch(() => {})),\n shutdownTraceTransports(EXIT_FLUSH_TIMEOUT_MS).catch(() => false),\n ]),\n )\n .then(() => {\n clearTimeout(deadline)\n stopFlushing()\n })\n })\n}\n\n/**\n * How the API key is supplied internally: either a literal string or a\n * function resolved each time the key is needed (at request/send time). The\n * function form is what defers key resolution past module-load construction\n * so an env var loaded after the client is built (the ESM dotenv-hoisting\n * case) is still picked up.\n */\nexport type ApiKeyInput = string | (() => string | undefined)\n\nexport interface HttpClientConfig {\n apiKey?: ApiKeyInput\n serviceUrl: string\n timeout?: number\n}\n\nexport type SpanOccurrence = \"first\" | \"last\" | number\n\nexport const SPAN_TYPES = [\n \"llm\",\n \"agent\",\n \"function\",\n \"guardrail\",\n \"handoff\",\n \"custom\",\n] as const\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 = (typeof SPAN_TYPES)[number]\n\n/**\n * Which span `getTraceSpan` returns: `id` alone, or `name` and/or `type`\n * with an optional `occurrence` (`\"first\"`, `\"last\"` by default, or a\n * zero-based index into the matches in the order they ran).\n */\nexport type SpanLookup =\n | { id: string; name?: never; type?: never; occurrence?: never }\n | { name: string; type?: SpanType; id?: never; occurrence?: SpanOccurrence }\n | { type: SpanType; name?: string; id?: never; occurrence?: SpanOccurrence }\n\nexport interface CapturedSpan {\n id: string\n traceId: string\n parentSpanId: string | null\n name: string | null\n type: string\n input: unknown\n output: unknown\n contexts: Record<string, unknown>[]\n prompt: string | null\n metadata: Record<string, unknown>\n metrics: Record<string, unknown> | null\n errors: unknown\n startedAt: string | null\n endedAt: string | null\n}\n\n/**\n * HTTP client for Bitfab API requests.\n *\n * Provides methods for different API endpoints with proper error handling,\n * timeouts, and authentication.\n */\n/**\n * `Retry-After` as milliseconds. The header is either a delay in seconds or an\n * HTTP date; both forms appear in the wild, so both are read. Anything else, or\n * a date already in the past, yields `undefined` so the caller falls back to\n * its own backoff.\n */\n/**\n * Read one response header without letting it break delivery. `Response.headers`\n * is always present from a real `fetch`, but polyfills and doubles are looser,\n * and an optional header must never be the reason a batch fails to send.\n */\nfunction readHeader(response: Response, name: string): string | null {\n try {\n return response.headers?.get(name) ?? null\n } catch {\n return null\n }\n}\n\nexport function parseRetryAfterMs(header: string | null): number | undefined {\n // Trimmed and emptiness-checked before Number(), which reads \"\" and \" \" as\n // 0 and would turn a blank header into \"retry immediately\", skipping the\n // backoff entirely. The other SDKs treat a blank header as no instruction.\n const value = header?.trim()\n if (!value) {\n return undefined\n }\n const seconds = Number(value)\n if (Number.isFinite(seconds)) {\n return seconds >= 0 ? seconds * 1_000 : undefined\n }\n const at = Date.parse(value)\n if (Number.isNaN(at)) {\n return undefined\n }\n return Math.max(0, at - Date.now())\n}\n\n/**\n * The delivery identity of a carrier, read from the payload here because this\n * is where the payload shape is owned. The transport is handed the result and\n * never looks inside a payload itself.\n */\n/**\n * Everything the transport needs to know about a carrier, derived here because\n * this is where the payload shape is owned. The transport applies these and\n * never looks inside a payload itself.\n */\nfunction carrierMeta(\n operation: TraceOperation,\n payload: Record<string, unknown>,\n ref: CarrierRef | undefined,\n): CarrierMeta {\n return {\n ref,\n name: carrierName(operation, payload),\n startTime: payloadTimestamp(payload, \"started_at\"),\n endTime: payloadTimestamp(payload, \"ended_at\"),\n errored: payloadHasError(payload),\n }\n}\n\nfunction carrierName(\n operation: TraceOperation,\n payload: Record<string, unknown>,\n): string {\n if (operation === \"external_span\") {\n const spanData = asPayloadRecord(\n asPayloadRecord(payload.rawSpan)?.span_data,\n )\n if (typeof spanData?.name === \"string\") {\n return spanData.name\n }\n }\n if (typeof payload.traceFunctionKey === \"string\") {\n return payload.traceFunctionKey\n }\n return `bitfab.${operation}`\n}\n\n/**\n * Milliseconds since the epoch for a payload timestamp, or `undefined` to let\n * OTel stamp the carrier with the current time.\n */\nfunction payloadTimestamp(\n payload: Record<string, unknown>,\n field: string,\n): number | undefined {\n const rawSpan = asPayloadRecord(payload.rawSpan)\n const rawTrace =\n asPayloadRecord(payload.externalTrace) ?? asPayloadRecord(payload.rawTrace)\n const raw = rawSpan?.[field] ?? rawTrace?.[field]\n if (typeof raw !== \"string\") {\n return undefined\n }\n const parsed = Date.parse(raw)\n return Number.isNaN(parsed) ? undefined : parsed\n}\n\nfunction payloadHasError(payload: Record<string, unknown>): boolean {\n const spanData = asPayloadRecord(asPayloadRecord(payload.rawSpan)?.span_data)\n if (spanData?.error != null) {\n return true\n }\n const errors = payload.errors\n return Array.isArray(errors) ? errors.length > 0 : Boolean(errors)\n}\n\nfunction asPayloadRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/** What a caller learns about one tracked trace once it takes it back. */\nexport interface DeliveryReport {\n spanCount: number\n /** A closing carrier was submitted, so the expected set is final. */\n closed: boolean\n /** Every carrier submitted under this trace came back accepted. */\n delivered: boolean\n /**\n * The server's assigned `traces.id`, read back from the OTLP ingest response.\n * Absent when talking to a server that predates this field, or before any\n * carrier for the trace has been acked.\n */\n serverTraceId?: string\n}\n\ninterface TraceDelivery {\n submittedSpanIds: Set<string>\n ackedSpanIds: Set<string>\n closed: boolean\n closingAcked: boolean\n serverTraceId?: string\n}\n\nfunction carrierRef(payload: Record<string, unknown>): CarrierRef | undefined {\n const traceId = sourceTraceIdOf(payload)\n if (traceId === undefined) {\n return undefined\n }\n const rawSpan = payload.rawSpan\n if (rawSpan === undefined) {\n return { traceId }\n }\n const spanId = (rawSpan as Record<string, unknown>)?.id\n return {\n traceId,\n spanId: typeof spanId === \"string\" ? spanId : `submission-${++carrierSeq}`,\n }\n}\n\nfunction sourceTraceIdOf(payload: Record<string, unknown>): string | undefined {\n if (typeof payload.sourceTraceId === \"string\") {\n return payload.sourceTraceId\n }\n const rawTrace = (payload.externalTrace ?? payload.rawTrace) as\n | Record<string, unknown>\n | undefined\n const id = rawTrace?.id\n return typeof id === \"string\" ? id : undefined\n}\n\nlet carrierSeq = 0\n\nfunction describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction warnDroppedExternalSpan(error: unknown): void {\n warnOnce(\n \"external-span-dropped\",\n `a span was dropped because the send step failed: ${describeError(error)}`,\n )\n}\n\nfunction warnDroppedExternalTrace(error: unknown): void {\n warnOnce(\n \"external-trace-dropped\",\n `a trace was dropped because the send step failed: ${describeError(error)}`,\n )\n}\n\nexport class HttpClient {\n private readonly apiKey: ApiKeyInput | undefined\n private readonly serviceUrl: string\n private readonly timeout: number\n private traceTransport: TraceTransport | undefined\n // Only traces a caller asked about are tracked, so ordinary tracing stores\n // nothing here.\n private readonly traceDeliveries = new Map<string, TraceDelivery>()\n // Deferred span work owned by THIS client. The module-global set backs the\n // process-wide `flushTraces()` and the exit hook, but per-client lifecycle\n // must not wait on another client's slow finalize: a false `close()` failure\n // caused by unrelated work is worse than no signal at all.\n private readonly deferredWork = new Set<Promise<unknown>>()\n readonly traceCompletion = new TraceCompletion()\n private closed = false\n private closing: Promise<boolean> | undefined\n externalSpanTransform:\n | ((\n payload: Record<string, unknown>,\n submit: SimulationPlanSubmit,\n drop: () => void,\n ) => void)\n | undefined\n externalTraceTransform:\n | ((payload: Record<string, unknown>, submit: SimulationPlanSubmit) => void)\n | undefined\n releaseHeldExternalSpans:\n | ((timeoutMs: number) => Promise<boolean> | Promise<void>)\n | undefined\n stopSimulationPlan: (() => void) | undefined\n\n constructor(config: HttpClientConfig) {\n this.apiKey = config.apiKey\n this.serviceUrl = config.serviceUrl\n this.timeout = config.timeout ?? 120000\n liveHttpClients.add(this)\n }\n\n /**\n * Resolve the API key at the moment it is needed (request time), invoking\n * the function form if one was supplied. Never read at construction.\n */\n private resolveApiKey(): string | undefined {\n return typeof this.apiKey === \"function\" ? this.apiKey() : this.apiKey\n }\n\n /** @internal Whether this client currently has credentials for trace delivery. */\n hasApiKey(): boolean {\n try {\n const apiKey = this.resolveApiKey()\n return apiKey !== undefined && apiKey.trim() !== \"\"\n } catch {\n return false\n }\n }\n\n /**\n * This client's span transport, built on first use.\n *\n * Lazy on purpose: a client that never sends a span must never start a batch\n * worker. Every framework integration created from a `Bitfab` client shares\n * the owning client's `HttpClient`, so handlers reuse this one worker instead\n * of each spinning up their own.\n */\n private getTraceTransport(): TraceTransport | undefined {\n if (this.closed) {\n warnOnce(\n \"http-client-closed\",\n \"the Bitfab client is closed; dropping spans\",\n )\n return undefined\n }\n if (!this.traceTransport) {\n this.traceTransport = createTraceTransport({\n directSender: (request, timeoutMs) =>\n this.deliverCarriers(request, timeoutMs),\n onDelivered: (refs) => this.recordDeliveredCarriers(refs),\n })\n }\n return this.traceTransport\n }\n\n /**\n * Post one encoded batch and decide what the server's answer means, so the\n * transport never reads a response. Rejections and permanent statuses come\n * back as a non-retryable {@link DeliveryError}; anything the server might\n * still accept on a second try comes back retryable.\n */\n private async deliverCarriers(\n request: EncodedRequestBody,\n timeoutMs: number,\n ): Promise<void> {\n let response: Record<string, unknown>\n try {\n // sendPrepared, not sendEncoded: the exporter already encoded this batch\n // to size the request, and re-encoding here would do that work twice.\n response = await this.sendPrepared<Record<string, unknown>>(\n OTLP_TRACES_ENDPOINT,\n request,\n { timeout: timeoutMs },\n )\n } catch (error) {\n const status = error instanceof BitfabError ? error.status : undefined\n if (status === undefined) {\n // No verdict from the server (a network fault): worth another attempt.\n throw new DeliveryError(`OTLP ingestion failed: ${String(error)}`, {\n retryable: true,\n })\n }\n throw new DeliveryError(`OTLP ingestion failed with HTTP ${status}`, {\n retryable: RETRYABLE_STATUSES.has(status),\n oversized: status === 413,\n ...(error instanceof BitfabError && error.retryAfterMs !== undefined\n ? { retryAfterMs: error.retryAfterMs }\n : {}),\n })\n }\n\n const serverTraceIds = asPayloadRecord(response?.traceIds)\n if (serverTraceIds !== undefined) {\n this.recordServerTraceIds(serverTraceIds)\n }\n\n const partialSuccess = asPayloadRecord(response?.partialSuccess)\n const rejected = partialSuccess?.rejectedSpans\n if (rejected !== undefined && rejected !== \"0\" && rejected !== 0) {\n // The server's verdict on the payload, not a transient fault.\n throw new DeliveryError(\n `OTLP ingestion rejected ${rejected} span(s): ${\n partialSuccess?.errorMessage ?? \"no reason provided\"\n }`,\n )\n }\n }\n\n /**\n * Start tracking delivery for `traceIds`. Nothing is recorded for a trace\n * that was never tracked, so ordinary tracing costs no bookkeeping at all.\n */\n trackTraceDeliveries(traceIds: string[]): void {\n for (const traceId of traceIds) {\n if (!this.traceDeliveries.has(traceId)) {\n this.traceDeliveries.set(traceId, {\n submittedSpanIds: new Set(),\n ackedSpanIds: new Set(),\n closed: false,\n closingAcked: false,\n })\n }\n }\n }\n\n /**\n * The server's assigned `traces.id` for a tracked trace if it has already\n * been read back off an ingest response, without stopping tracking. Lets a\n * replay surface the id mid-run for items whose spans already landed.\n */\n peekServerTraceId(traceId: string): string | undefined {\n return this.traceDeliveries.get(traceId)?.serverTraceId\n }\n\n /** Whether any tracked trace has had its closing carrier submitted. */\n hasClosedDeliveries(traceIds: string[]): boolean {\n return traceIds.some((traceId) => this.traceDeliveries.get(traceId)?.closed)\n }\n\n /**\n * Report what each tracked trace submitted and whether the server confirmed\n * it, and stop tracking them. Every id passed is freed, so a caller cannot\n * leak a record for a trace that never closed.\n *\n * `delivered` is only meaningful once a flush has settled: acks land before\n * an export resolves, so a flush that reported success has already collected\n * every ack it is going to collect.\n */\n takeTraceDeliveries(traceIds: string[]): Record<string, DeliveryReport> {\n const reports: Record<string, DeliveryReport> = {}\n for (const traceId of traceIds) {\n const delivery = this.traceDeliveries.get(traceId)\n if (delivery === undefined) {\n continue\n }\n this.traceDeliveries.delete(traceId)\n reports[traceId] = {\n spanCount: delivery.submittedSpanIds.size,\n closed: delivery.closed,\n delivered:\n delivery.closingAcked &&\n [...delivery.submittedSpanIds].every((spanId) =>\n delivery.ackedSpanIds.has(spanId),\n ),\n serverTraceId: delivery.serverTraceId,\n }\n }\n return reports\n }\n\n /** Build a carrier's meta and record what it adds to its trace's expected set. */\n private recordedMeta(\n operation: TraceOperation,\n payload: Record<string, unknown>,\n ref: CarrierRef | undefined,\n ): CarrierMeta {\n this.recordSubmittedCarrier(ref)\n return carrierMeta(operation, payload, ref)\n }\n\n private recordSubmittedCarrier(ref: CarrierRef | undefined): void {\n if (ref === undefined) {\n return\n }\n const delivery = this.traceDeliveries.get(ref.traceId)\n if (delivery === undefined) {\n return\n }\n if (ref.spanId === undefined) {\n delivery.closed = true\n } else {\n delivery.submittedSpanIds.add(ref.spanId)\n }\n }\n\n /**\n * Ingestion commits every carrier in a request before it answers, so a\n * delivered ref is proof its row exists: the same fact the replay status\n * endpoint would report, already in hand.\n */\n /**\n * Record the server's assigned `traces.id` for each tracked source trace,\n * read back from the OTLP ingest response. Keyed by source trace id, the same\n * key the delivery ledger uses. Untracked ids are ignored.\n */\n private recordServerTraceIds(map: Record<string, unknown>): void {\n for (const [sourceTraceId, serverTraceId] of Object.entries(map)) {\n if (typeof serverTraceId !== \"string\") {\n continue\n }\n const delivery = this.traceDeliveries.get(sourceTraceId)\n if (delivery === undefined) {\n continue\n }\n delivery.serverTraceId = serverTraceId\n }\n }\n\n private recordDeliveredCarriers(refs: CarrierRef[]): void {\n for (const ref of refs) {\n const delivery = this.traceDeliveries.get(ref.traceId)\n if (delivery === undefined) {\n continue\n }\n if (ref.spanId === undefined) {\n delivery.closingAcked = true\n } else {\n delivery.ackedSpanIds.add(ref.spanId)\n }\n }\n }\n\n /**\n * Track deferred span work so this client's own lifecycle waits for it, and\n * so the process-wide flush and exit hook do too.\n */\n trackDeferred<T>(promise: Promise<T>): Promise<T> {\n this.deferredWork.add(promise)\n void promise\n .finally(() => this.deferredWork.delete(promise))\n .catch(() => {})\n return awaitOnExit(promise)\n }\n\n /**\n * Settle only THIS client's deferred span work. Scoped deliberately: the\n * global set can contain another client's long-running finalize, and\n * attributing its timeout here would fail a client whose own work succeeded.\n */\n async settleDeferredWork(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n ): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n const released = await this.releaseHeldExternalSpans?.(\n planWaitSliceMs(timeoutMs),\n )\n await replayContextReady.catch(() => {})\n const settled = await waitForPromises(\n Array.from(this.deferredWork),\n Math.max(0, deadline - Date.now()),\n )\n const releasedAfterDeferred = await this.releaseHeldExternalSpans?.(0)\n return released !== false && releasedAfterDeferred !== false && settled\n }\n\n /**\n * Wait for spans queued by this client to be delivered, within one deadline.\n * Returns false on delivery failure or timeout.\n */\n async waitForPendingRequests(\n timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS,\n ): Promise<boolean> {\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n const settled = await this.settleDeferredWork(\n Math.max(0, deadline - Date.now()),\n )\n const flushed =\n (await this.traceTransport?.flush(Math.max(0, deadline - Date.now()))) ??\n true\n return settled && flushed\n }\n\n /**\n * Flush and permanently close this client's tracing transport. Idempotent:\n * a second call joins the first rather than tearing down a pipeline the\n * first call already owns.\n */\n close(timeoutMs: number = DEFAULT_LIFECYCLE_TIMEOUT_MS): Promise<boolean> {\n if (this.closing) {\n return this.closing\n }\n const deadline = Date.now() + Math.max(timeoutMs, 0)\n this.closing = (async () => {\n liveHttpClients.delete(this)\n const settled = await this.settleDeferredWork(\n Math.max(0, deadline - Date.now()),\n )\n this.stopSimulationPlan?.()\n this.closed = true\n this.externalSpanTransform = undefined\n this.externalTraceTransform = undefined\n this.releaseHeldExternalSpans = undefined\n this.stopSimulationPlan = undefined\n const transport = this.traceTransport\n this.traceTransport = undefined\n const shutdownOk =\n (await transport?.shutdown(Math.max(0, deadline - Date.now()))) ?? true\n return settled && shutdownOk\n })()\n return this.closing\n }\n\n /**\n * Make an HTTP request to the Bitfab API. Defaults to POST; pass\n * `options.method` to use a different verb (e.g. \"PATCH\").\n *\n * @param endpoint - The API endpoint (without base URL)\n * @param payload - The request body\n * @param options - Optional request options\n * @returns The parsed JSON response\n * @throws {BitfabError} If the request fails\n */\n async request<T>(\n endpoint: string,\n payload: Record<string, unknown>,\n options?: {\n timeout?: number\n method?: \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\"\n },\n ): Promise<T> {\n // Serialize the payload so a stray non-serializable value (BigInt,\n // function, circular ref, a class instance that slipped past upstream\n // serialization) can never abort the send and silently drop the span.\n // Strays are stubbed in place, preserving span content, and a degraded\n // payload warns loudly.\n const { body, dropped } = serializePayloadBody(payload)\n if (dropped.length > 0) {\n try {\n console.warn(\n `Bitfab: request body to ${endpoint} held ${dropped.length} ` +\n `non-serializable value(s) (${[...new Set(dropped)].join(\", \")}); ` +\n \"they were stubbed so the span still sends, but the trace may be \" +\n \"incomplete or not replayable. Capture a JSON-safe projection of \" +\n \"this input to make it replayable.\",\n )\n } catch {}\n }\n return this.sendEncoded<T>(endpoint, body, options)\n }\n\n /**\n * POST an already-encoded body. The span transport encodes its own batches,\n * so routing them back through {@link HttpClient.request} would encode the\n * same data twice.\n */\n async sendEncoded<T>(\n endpoint: string,\n body: string,\n options?: {\n timeout?: number\n method?: \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\"\n },\n ): Promise<T> {\n // Awaited only when compression actually runs, so an uncompressed request\n // still calls `fetch` synchronously the way it did before compression.\n const prepared = encodeRequestBody(body)\n const encoded = prepared instanceof Promise ? await prepared : prepared\n return this.sendPrepared<T>(endpoint, encoded, options)\n }\n\n private async sendPrepared<T>(\n endpoint: string,\n encoded: EncodedRequestBody,\n options?: {\n timeout?: number\n method?: \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\"\n },\n ): Promise<T> {\n const url = `${this.serviceUrl}${endpoint}`\n const timeout = options?.timeout ?? this.timeout\n const method = options?.method ?? \"POST\"\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.resolveApiKey() ?? \"\"}`,\n }\n if (encoded.contentEncoding) {\n headers[\"Content-Encoding\"] = encoded.contentEncoding\n }\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body: encoded.body,\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new BitfabError(\n `HTTP ${response.status}: ${errorText.slice(0, 500)}`,\n undefined,\n response.status,\n parseRetryAfterMs(readHeader(response, \"retry-after\")),\n )\n }\n\n const result = await response.json()\n\n // Check for errors in the response\n if (result.error) {\n if (result.url) {\n throw new BitfabError(\n `${result.error} Configure it at: ${this.serviceUrl}${result.url}`,\n result.url,\n )\n }\n throw new BitfabError(result.error)\n }\n\n return result as T\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new BitfabError(`Request timed out after ${timeout}ms`)\n }\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred\")\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /**\n * Look up a function by name.\n * Blocks until complete - needed for function execution.\n */\n async lookupFunction<T>(name: string): Promise<T> {\n return this.request<T>(\"/api/sdk/functions/lookup\", { name })\n }\n\n async getSimulationPlan(): Promise<SimulationPlanResponse> {\n // Without a key the server answers 401, so skip the request entirely.\n if (!this.hasApiKey()) {\n throw new BitfabError(NO_API_KEY_FOR_SIMULATION_PLAN)\n }\n return this.get<SimulationPlanResponse>(\n \"/api/sdk/sim-plan\",\n SIMULATION_PLAN_READ_TIMEOUT_MS,\n )\n }\n\n async getTraceSpan(\n traceId: string,\n lookup: SpanLookup,\n ): Promise<CapturedSpan | null> {\n const searchParams = new URLSearchParams()\n if (lookup.id !== undefined) {\n searchParams.set(\"id\", lookup.id)\n } else {\n if (lookup.name !== undefined) {\n searchParams.set(\"name\", lookup.name)\n }\n if (lookup.type !== undefined) {\n searchParams.set(\"type\", lookup.type)\n }\n searchParams.set(\"occurrence\", String(lookup.occurrence ?? \"last\"))\n }\n\n const endpoint = `/api/sdk/traces/${encodeURIComponent(traceId)}/span?${searchParams.toString()}`\n const response = await this.get<{ span: CapturedSpan | null }>(endpoint)\n return response.span\n }\n\n async getSpan(spanId: string): Promise<CapturedSpan | null> {\n const response = await this.get<{ span: CapturedSpan | null }>(\n `/api/sdk/spans/${encodeURIComponent(spanId)}`,\n )\n return response.span\n }\n\n /**\n * GET a JSON endpoint on the service with the client's API key. Throws a\n * `BitfabError` carrying the status text for any non-2xx response.\n */\n async get<T>(\n endpoint: string,\n timeoutMs?: number,\n extraHeaders?: Record<string, string>,\n ): Promise<T> {\n const url = `${this.serviceUrl}${endpoint}`\n const timeout = timeoutMs ?? this.timeout\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${this.resolveApiKey() ?? \"\"}`,\n ...extraHeaders,\n },\n signal: controller.signal,\n })\n if (!response.ok) {\n const errorText = await response.text()\n throw new BitfabError(\n `HTTP ${response.status}: ${errorText.slice(0, 500)}`,\n undefined,\n response.status,\n parseRetryAfterMs(readHeader(response, \"retry-after\")),\n )\n }\n return (await response.json()) as T\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new BitfabError(`Request timed out after ${timeout}ms`)\n }\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred\")\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /**\n * Queue an internal trace (from local BAML execution via `call()`) onto this\n * client's batching transport. `functionId` moves into the payload because\n * the OTLP carrier has no path to carry it.\n */\n sendInternalTrace(\n functionId: string,\n payload: Record<string, unknown>,\n ): void {\n const body = {\n ...payload,\n functionId,\n sdkPackage: __packageName__,\n sdkVersion: __version__,\n }\n this.getTraceTransport()?.submit(\n \"internal_trace\",\n body,\n carrierMeta(\"internal_trace\", body, undefined),\n )\n }\n\n sendExternalSpan(payload: Record<string, unknown>): void {\n const ref = carrierRef(payload)\n if (ref?.spanId !== undefined) {\n this.traceCompletion.record(ref.traceId, ref.spanId)\n }\n const drop = (): void => {\n if (ref?.spanId !== undefined) {\n this.traceCompletion.abort(ref.traceId, ref.spanId)\n }\n }\n const gate = this.externalSpanTransform\n if (gate === undefined) {\n this.submitExternalSpan(payload)\n return\n }\n try {\n gate(payload, (ready) => this.submitExternalSpan(ready), drop)\n } catch (error) {\n drop()\n warnDroppedExternalSpan(error)\n }\n }\n\n submitExternalSpan(payload: Record<string, unknown>): void {\n const body: Record<string, unknown> = {\n ...payload,\n sdkVersion: __version__,\n }\n delete body[ROOT_TRACE_FUNCTION_KEY_FIELD]\n delete body[DECLARED_NODE_FIELD]\n this.getTraceTransport()?.submit(\n \"external_span\",\n body,\n this.recordedMeta(\"external_span\", payload, carrierRef(payload)),\n )\n }\n\n /**\n * Queue an external trace completion (from OpenAI tracing) onto this\n * client's batching transport. Fire-and-forget for the same reason as\n * {@link HttpClient.sendExternalSpan}; replay confirms persistence with the\n * server-authoritative barrier in `replay.ts`, not by awaiting this call.\n */\n sendExternalTrace(rawPayload: Record<string, unknown>): void {\n const payload = mergeCallerMetadataIntoTracePayload(rawPayload)\n const traceId = sourceTraceIdOf(payload)\n if (payload.completed === true && traceId !== undefined) {\n this.traceCompletion.close(\n traceId,\n (expectedSpanCount) =>\n this.sendCountedExternalTrace({ ...payload, expectedSpanCount }),\n payload.dropped === true,\n )\n return\n }\n if (traceId !== undefined) {\n this.traceCompletion.open(traceId)\n }\n this.sendCountedExternalTrace(payload)\n }\n\n private sendCountedExternalTrace(payload: Record<string, unknown>): void {\n try {\n const gate = this.externalTraceTransform\n if (gate === undefined) {\n this.submitExternalTrace(payload)\n } else {\n gate(payload, (ready) => this.submitExternalTrace(ready))\n }\n } catch (error) {\n warnDroppedExternalTrace(error)\n }\n }\n\n submitExternalTrace(payload: Record<string, unknown>): void {\n this.getTraceTransport()?.submit(\n \"external_trace\",\n {\n ...payload,\n sdkPackage: __packageName__,\n sdkVersion: __version__,\n },\n this.recordedMeta(\n \"external_trace\",\n payload,\n payload.completed === true ? carrierRef(payload) : undefined,\n ),\n )\n }\n\n /**\n * Partial update of an existing trace identified by its Bitfab trace ID.\n * Used by the detached `client.getTrace(id)` handle.\n *\n * Blocking, like the other trace-API calls: it resolves once the server has\n * applied the change and rejects if the server refused it. A patch targets a\n * trace that is already closed, so there is no batch for it to ride along\n * with and no later signal that would reveal a silent failure.\n */\n async patchTrace(\n traceId: string,\n payload: {\n appendContexts?: Record<string, unknown>[]\n mergeMetadata?: Record<string, unknown>\n setSessionId?: string\n setName?: string\n },\n ): Promise<void> {\n const endpoint = `/api/sdk/traces/${encodeURIComponent(traceId)}`\n await this.request(endpoint, payload, { method: \"PATCH\" })\n }\n\n /**\n * Start a replay session by fetching historical traces.\n * Blocking call - creates an experiment and returns lightweight item references.\n */\n async startReplay(\n traceFunctionKey: string,\n limit: number | undefined,\n traceIds?: string[],\n name?: string,\n codeChangeDescription?: string | null,\n codeChangeFiles?: CodeChangeFile[] | null,\n includeDbBranchLease?: boolean,\n experimentGroupId?: string,\n datasetIds?: string[],\n graderIds?: string[],\n dbBranchSettings?: DbBranchSettings,\n attempts?: number,\n includeOriginalMetadata?: boolean,\n onlyWithAssertions?: boolean,\n skipAssertionJudging?: boolean,\n experimentalSelectiveReplay?: import(\"./selectiveReplay.js\").SelectiveReplayOptions,\n notes?: string,\n metadata?: Record<string, string>,\n dryRun?: boolean,\n experimentGroupName?: string,\n invocation?: ReplayInvocation,\n ): Promise<StartReplayResponse> {\n // limit is only meaningful without traceIds (an explicit ID list\n // already determines the count), so it's omitted when undefined.\n const payload: Record<string, unknown> = { traceFunctionKey }\n if (experimentalSelectiveReplay !== undefined) {\n payload.experimentalSelectiveReplay = experimentalSelectiveReplay\n }\n if (limit !== undefined) {\n payload.limit = limit\n }\n if (traceIds) {\n payload.traceIds = traceIds\n }\n if (name !== undefined) {\n payload.name = name\n }\n if (notes !== undefined) {\n payload.notes = notes\n }\n if (metadata !== undefined) {\n payload.metadata = metadata\n }\n if (codeChangeDescription !== undefined) {\n payload.codeChangeDescription = codeChangeDescription\n }\n if (codeChangeFiles !== undefined) {\n payload.codeChangeFiles = codeChangeFiles\n }\n if (includeDbBranchLease) {\n payload.includeDbBranchLease = true\n payload.lazyDbBranchLease = true\n }\n if (experimentGroupId !== undefined) {\n payload.experimentGroupId = experimentGroupId\n }\n if (experimentGroupName !== undefined) {\n payload.experimentGroupName = experimentGroupName\n }\n if (datasetIds !== undefined) {\n if (datasetIds.length === 1) {\n payload.datasetId = datasetIds[0]\n } else {\n payload.datasetIds = datasetIds\n }\n }\n if (graderIds !== undefined) {\n payload.graderIds = graderIds\n }\n if (dbBranchSettings !== undefined) {\n payload.dbBranchSettings = dbBranchSettings\n }\n if (attempts !== undefined && attempts > 1) {\n payload.attempts = attempts\n }\n if (includeOriginalMetadata) {\n payload.includeOriginalMetadata = true\n }\n if (onlyWithAssertions) {\n payload.onlyWithAssertions = true\n }\n if (skipAssertionJudging !== true) {\n payload.judgeAssertions = true\n }\n if (dryRun) {\n payload.dryRun = true\n }\n if (invocation !== undefined) {\n payload.invocation = invocation\n }\n const git = await resolvedGitState()\n if (git && !isEmptyGitState(git)) {\n payload.git = git\n }\n // When DB branching is on, the server resolves a Neon preview branch\n // per item (snapshot + restore + poll), which can run ~5-10s each, and\n // runs any `warmupSql` against each branch on a 240s budget of its own.\n // The server gives up at 280s and answers, so this is a backstop for a\n // reply that never comes rather than the thing that normally fires; it\n // sits above the server's own ceiling so the server's error is the one\n // callers see. Not raisable in practice either: undici's default\n // `headersTimeout` is also 300s and `fetch` cannot override it per\n // request.\n const timeout = includeDbBranchLease\n ? REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS\n : 30_000\n const response = await this.request<StartReplayWireResponse>(\n \"/api/sdk/replay/start\",\n payload,\n { timeout },\n )\n const { testRunId, testRunUrl, ...rest } = response\n const experimentId = response.experimentId ?? testRunId\n const experimentUrl = response.experimentUrl ?? testRunUrl\n // A dry run is the one start the server answers without an experiment.\n if (dryRun && response.experimentId === null) {\n return { ...rest, experimentId: null, experimentUrl: null }\n }\n if (\n experimentId === undefined ||\n experimentId === null ||\n experimentUrl === undefined ||\n experimentUrl === null\n ) {\n throw new BitfabError(\n \"Replay start response is missing the experiment ID or URL.\",\n )\n }\n return { ...rest, experimentId, experimentUrl }\n }\n\n async resumeReplay(\n experimentId: string,\n traceFunctionKey: string,\n codeChangeFiles?: CodeChangeFile[] | null,\n force?: boolean,\n ): Promise<ResumeReplayResponse> {\n const payload: Record<string, unknown> = {\n experimentId,\n traceFunctionKey,\n lazyDbBranchLease: true,\n }\n if (force === true) {\n payload.force = true\n }\n if (codeChangeFiles !== undefined) {\n payload.codeChangeFiles = codeChangeFiles\n }\n const git = await resolvedGitState()\n if (git && !isEmptyGitState(git)) {\n payload.git = git\n }\n const response = await this.request<ResumeReplayWireResponse>(\n \"/api/sdk/replay/resume\",\n payload,\n { timeout: REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS },\n )\n const { testRunId, testRunUrl, ...rest } = response\n const resumedExperimentId = response.experimentId ?? testRunId\n const experimentUrl = response.experimentUrl ?? testRunUrl\n if (resumedExperimentId === undefined || experimentUrl === undefined) {\n throw new BitfabError(\n \"Replay resume response is missing the experiment ID or URL.\",\n )\n }\n return {\n ...rest,\n experimentId: resumedExperimentId,\n experimentUrl,\n work: rest.work ?? [],\n finished: rest.finished ?? [],\n skippedOriginalTraceIds: rest.skippedOriginalTraceIds ?? [],\n includeDbBranchLease: rest.includeDbBranchLease ?? false,\n dbBranchSettings: rest.dbBranchSettings ?? null,\n }\n }\n\n /**\n * Fetch an external span by ID.\n * Blocking GET request.\n * The replay view limits rawData to input/output serialization fields.\n */\n async getExternalSpan(\n spanId: string,\n options?: { view?: \"full\" | \"replay\" },\n ): Promise<ExternalSpanResponse> {\n const query = options?.view === \"replay\" ? \"?view=replay\" : \"\"\n const url = `${this.serviceUrl}/api/sdk/externalSpans/${spanId}${query}`\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), 30_000)\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.resolveApiKey() ?? \"\"}` },\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new BitfabError(\n `HTTP ${response.status}: ${errorText.slice(0, 500)}`,\n )\n }\n\n return (await response.json()) as ExternalSpanResponse\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new BitfabError(\"Request timed out after 30000ms\")\n }\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred\")\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /**\n * Fetch the span tree for a root span.\n * Blocking GET request.\n *\n * Pass `includeOutputs: false` for a payload-free tree (structure +\n * `externalSpanId` only), so recorded outputs are fetched lazily per mocked\n * span instead of all up front. Omit it (default eager) for `mock: \"all\"`.\n * Pass `includeRootOutput: false` when the root was already fetched.\n */\n async getSpanTree(\n externalSpanId: string,\n options?: { includeOutputs?: boolean; includeRootOutput?: boolean },\n ): Promise<SpanTreeResponse> {\n const searchParams = new URLSearchParams()\n if (options?.includeOutputs === false) {\n searchParams.set(\"includeOutputs\", \"false\")\n }\n if (options?.includeRootOutput === false) {\n searchParams.set(\"includeRootOutput\", \"false\")\n }\n const encodedQuery = searchParams.toString()\n const query = encodedQuery ? `?${encodedQuery}` : \"\"\n const url = `${this.serviceUrl}/api/sdk/replay/spanTree/${externalSpanId}${query}`\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), 30_000)\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.resolveApiKey() ?? \"\"}` },\n signal: controller.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new BitfabError(\n `HTTP ${response.status}: ${errorText.slice(0, 500)}`,\n )\n }\n\n return (await response.json()) as SpanTreeResponse\n } catch (error) {\n if (error instanceof BitfabError) {\n throw error\n }\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n throw new BitfabError(\"Request timed out after 30000ms\")\n }\n throw new BitfabError(error.message)\n }\n throw new BitfabError(\"Unknown error occurred\")\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /**\n * Read which of a replay run's traces the server has fully persisted.\n *\n * With `expectedSpanCounts`, a trace appears in the response only once it\n * has a final status AND at least that many persisted spans, which is what\n * makes this a real barrier rather than a \"the row exists\" check.\n */\n async getReplayStatus(\n experimentId: string,\n expectedSpanCounts: Record<string, number>,\n ): Promise<ReplayStatusResponse> {\n return this.request<ReplayStatusResponse>(\n \"/api/sdk/replay/status\",\n { ...experimentIdWireFields(experimentId), expectedSpanCounts },\n { timeout: 30_000 },\n )\n }\n\n /**\n * Mark a replay experiment as completed.\n * Blocking call.\n */\n async completeReplay(experimentId: string): Promise<CompleteReplayResponse> {\n return this.request<CompleteReplayResponse>(\n \"/api/sdk/replay/complete\",\n experimentIdWireFields(experimentId),\n { timeout: REPLAY_COMPLETE_REQUEST_TIMEOUT_MS },\n )\n }\n\n async interruptReplay(experimentId: string): Promise<boolean> {\n try {\n await this.request<unknown>(\n \"/api/sdk/replay/interrupt\",\n experimentIdWireFields(experimentId),\n { timeout: REPLAY_INTERRUPT_REQUEST_TIMEOUT_MS },\n )\n return true\n } catch {\n return false\n }\n }\n\n async heartbeatReplay(experimentId: string): Promise<void> {\n try {\n await this.request<unknown>(\n \"/api/sdk/replay/heartbeat\",\n experimentIdWireFields(experimentId),\n { timeout: REPLAY_HEARTBEAT_REQUEST_TIMEOUT_MS },\n )\n } catch {}\n }\n\n async getReseedSource(traceId: string): Promise<ReseedSourceResponse> {\n return this.get<ReseedSourceResponse>(\n `/api/sdk/traces/${encodeURIComponent(traceId)}/reseedSource`,\n )\n }\n\n async reseedTrace(\n traceId: string,\n runTraceId: string,\n ): Promise<ReseedTraceResponse> {\n return this.request<ReseedTraceResponse>(\n `/api/sdk/traces/${encodeURIComponent(traceId)}/reseed`,\n { runTraceId },\n { timeout: 30_000 },\n )\n }\n\n /**\n * Ask the server to materialize a per-trace DB branch lease from a\n * captured `dbSnapshotRef`. Blocking - the resolver creates a Neon\n * snapshot + preview branch and polls operations to readiness, which\n * can take seconds.\n */\n async resolveDbBranchLease(\n experimentId: string,\n traceId: string,\n dbBranchSettings?: DbBranchSettings,\n attempt?: number,\n ): Promise<{\n dbSnapshotRef: DbSnapshotRef | null\n lease: DbBranchLease | null\n leaseError: { code: string; message: string } | null\n timings: DbBranchTimings | null\n }> {\n return this.request<{\n dbSnapshotRef: DbSnapshotRef | null\n lease: DbBranchLease | null\n leaseError: { code: string; message: string } | null\n timings: DbBranchTimings | null\n }>(\n \"/api/sdk/replay/resolveDbBranchLease\",\n {\n ...experimentIdWireFields(experimentId),\n traceId,\n dbBranchSettings,\n ...(attempt !== undefined && attempt > 0 ? { attempt } : {}),\n },\n { timeout: REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS },\n )\n }\n\n /** Release a previously-resolved DB branch by deleting its Neon branch. Idempotent server-side. */\n async releaseDbBranchLease(neonBranchId: string): Promise<void> {\n await this.request<{ released: true }>(\n \"/api/sdk/replay/releaseDbBranchLease\",\n { neonBranchId },\n { timeout: 30_000 },\n )\n }\n}\n\nexport interface TokenUsage {\n input: number | null\n output: number | null\n cached: number | null\n total: number | null\n}\n\n/**\n * Describes a single file edited as part of a code change.\n *\n * - `path`: file path (relative to the repo root, or any consistent root)\n * - `before`: file contents before the change (\"\" for newly created files)\n * - `after`: file contents after the change (\"\" for deleted files)\n */\nexport interface CodeChangeFile {\n path: string\n before: string\n after: string\n}\n\nexport function experimentIdWireFields(experimentId: string): {\n experimentId: string\n testRunId: string\n} {\n return { experimentId, testRunId: experimentId }\n}\n\ntype StartReplayWireResponse = Omit<\n StartReplayResponse,\n \"experimentId\" | \"experimentUrl\"\n> & {\n experimentId?: string | null\n experimentUrl?: string | null\n testRunId?: string | null\n testRunUrl?: string | null\n}\n\nexport interface StartReplayResponse {\n /** Null for a dry run, which the server records no experiment for. */\n experimentId: string | null\n experimentUrl: string | null\n attempts?: number\n items: Array<{\n selectiveReplayPlan?: import(\"./selectiveReplay.js\").SelectiveReplayPlan\n /** Bitfab trace ID of the original (historical) trace being replayed. */\n originalTraceId?: string\n /** External span ID the recorded inputs were read from (the original root span). */\n originalSpanId?: string\n /** @deprecated alias for `originalTraceId`; the only key emitted by servers that predate the rename. */\n sourceTraceId: string\n /** @deprecated alias for `originalSpanId`; the only key emitted by servers that predate the rename. */\n sourceSpanId: string\n durationMs: number | null\n tokens: TokenUsage | null\n model: string | null\n /**\n * The DB snapshot ref captured by the SDK at trace open. Surfaced so\n * the SDK can pass it to the lease-resolver step (or report when no\n * snapshot was captured for this trace).\n */\n dbSnapshotRef?: DbSnapshotRef\n /**\n * Populated once the server-side resolver has materialized a per-item\n * branch from `dbSnapshotRef`. The SDK exposes this to customer code\n * via `getCurrentReplayBranch()`. Absent until the resolver lands.\n */\n dbBranchLease?: DbBranchLease\n /**\n * Why the branch could not be resolved, when one was requested and the\n * attempt failed. Distinct from both fields being absent, which means the\n * trace carried no snapshot ref so nothing was attempted.\n */\n dbBranchLeaseError?: { code: string; message: string }\n /**\n * How long provisioning took, per phase. Sits beside the two fields above\n * rather than inside either: it is reported on both outcomes, complete on\n * success and partial up to the failing phase on error. Absent from\n * servers that predate it.\n */\n dbBranchTimings?: DbBranchTimings\n originalMetadata?: Record<string, unknown>\n }>\n}\n\nexport type StartReplayItem = StartReplayResponse[\"items\"][number]\n\nexport interface ResumeReplayWorkPair {\n itemIndex: number\n attempt: number\n}\n\nexport interface ResumeReplayFinishedItem {\n originalTraceId: string\n attempt: number\n traceId: string\n hasError: boolean\n}\n\nexport interface ResumeReplayResponse {\n experimentId: string\n experimentUrl: string\n attempts: number\n items: StartReplayItem[]\n work: ResumeReplayWorkPair[]\n finished: ResumeReplayFinishedItem[]\n skippedOriginalTraceIds: string[]\n includeDbBranchLease: boolean\n dbBranchSettings: DbBranchSettings | null\n}\n\ntype ResumeReplayWireResponse = Omit<\n ResumeReplayResponse,\n | \"experimentId\"\n | \"experimentUrl\"\n | \"work\"\n | \"finished\"\n | \"skippedOriginalTraceIds\"\n | \"includeDbBranchLease\"\n | \"dbBranchSettings\"\n> & {\n experimentId?: string\n experimentUrl?: string\n testRunId?: string\n testRunUrl?: string\n work?: ResumeReplayWorkPair[]\n finished?: ResumeReplayFinishedItem[]\n skippedOriginalTraceIds?: string[]\n includeDbBranchLease?: boolean\n dbBranchSettings?: DbBranchSettings | null\n}\n\nexport interface ExternalSpanResponse {\n id: string\n externalTraceId: string\n rawData: {\n span_data: {\n input: unknown\n output: unknown\n input_meta?: unknown\n output_meta?: unknown\n input_serialized?: { json: unknown; meta: unknown }\n output_serialized?: { json: unknown; meta: unknown }\n }\n }\n}\n\nexport interface ReplayStatusResponse {\n /**\n * Local replay trace id -> server trace row id, for the traces the server\n * considers fully persisted. Traces still short of their expected span count\n * are simply absent.\n */\n traceIds?: Record<string, string>\n}\n\nexport interface CompleteReplayResponse {\n id: string\n status: string\n traceIds?: Record<string, string>\n /**\n * Per-replay-trace token usage, keyed by the server trace id (the values of\n * `traceIds`). Aggregated server-side from the freshly-uploaded replay spans,\n * so it's the REPLAYED run's tokens (the same source the dashboard reads), not the\n * original trace's. The SDK maps each item onto this to set\n * `ReplayItem.tokens`. Absent on servers that predate this field.\n */\n tokens?: Record<string, TokenUsage | null>\n /**\n * Number of traces the server has persisted for this experiment at\n * completion time. Lets the SDK distinguish \"uploads failed\" from\n * \"server never saw them\" when the trace-ID mapping is incomplete.\n */\n traceCount?: number\n}\n\nexport interface ReseedSourceResponse {\n traceId: string\n traceFunctionKey: string\n ingestionType: string\n name: string | null\n sessionId: string | null\n metadata: Record<string, unknown>\n input: unknown\n inputMeta: unknown\n inputSerialized: unknown\n}\n\nexport interface ReseedTraceResponse {\n traceId: string\n previousRunTraceId: string\n}\n\nexport interface SpanTreeNode {\n /** Upstream platform span id. Stable structural identity; NOT the row id. */\n sourceSpanId: string\n /**\n * The `externalSpans` row id, accepted by {@link HttpClient.getExternalSpan}.\n * Distinct from `sourceSpanId`; used to lazily fetch this node's output when\n * the tree was fetched with `includeOutputs: false`. Optional so trees from\n * older servers (which omit it) still deserialize.\n */\n externalSpanId?: string\n traceFunctionKey: string\n spanName: string\n type: string\n /** Omitted when the tree was fetched payload-free (`includeOutputs: false`). */\n output?: unknown\n outputMeta?: unknown\n children: SpanTreeNode[]\n}\n\nexport interface SpanTreeResponse {\n root: SpanTreeNode\n}\n","export type ReplayInterruptSignal = \"SIGINT\" | \"SIGTERM\"\n\nexport interface ReplayInterrupt {\n experimentId: string\n experimentUrl: string\n signal: ReplayInterruptSignal\n markedInterrupted: boolean\n}\n\ninterface ReplayInterruptTarget {\n experimentId: string\n experimentUrl: string\n interrupt: () => Promise<boolean>\n onInterrupt?: (interrupt: ReplayInterrupt) => void\n}\n\nconst REPLAY_INTERRUPT_SIGNALS: readonly ReplayInterruptSignal[] = [\n \"SIGINT\",\n \"SIGTERM\",\n]\n\nconst replayListeners = new Set<unknown>()\n\nfunction signalCapableProcess(): NodeJS.Process | undefined {\n if (typeof process === \"undefined\" || typeof process.on !== \"function\") {\n return undefined\n }\n return process\n}\n\nexport function describeReplayInterrupt(\n experimentId: string,\n markedInterrupted: boolean,\n): string {\n if (markedInterrupted) {\n return `[replay] Experiment ${experimentId} interrupted.`\n }\n return `[replay] Experiment ${experimentId} stopped, but Bitfab could not mark it interrupted. It will be marked interrupted within 15 minutes. A resume in the next two minutes may be refused as still running.`\n}\n\nfunction reportInterrupted(\n experimentId: string,\n markedInterrupted: boolean,\n): void {\n try {\n console.error(describeReplayInterrupt(experimentId, markedInterrupted))\n } catch {}\n}\n\nexport interface ReplayInterruptHandlers {\n remove: () => void\n interrupted: () => boolean\n}\n\nexport function installReplayInterruptHandlers(\n target: ReplayInterruptTarget,\n): ReplayInterruptHandlers {\n const host = signalCapableProcess()\n if (host === undefined) {\n return { remove: () => {}, interrupted: () => false }\n }\n const handlers = new Map<ReplayInterruptSignal, () => void>()\n const removeHandlers = (): void => {\n for (const [signal, handler] of handlers) {\n host.removeListener(signal, handler)\n replayListeners.delete(handler)\n }\n handlers.clear()\n }\n let interrupting = false\n const handleSignal = async (signal: ReplayInterruptSignal): Promise<void> => {\n const hostHandlesSignal = host\n .listeners(signal)\n .some((listener) => !replayListeners.has(listener))\n const markedInterrupted = await target.interrupt()\n removeHandlers()\n if (target.onInterrupt !== undefined) {\n try {\n target.onInterrupt({\n experimentId: target.experimentId,\n experimentUrl: target.experimentUrl,\n signal,\n markedInterrupted,\n })\n } catch {}\n return\n }\n reportInterrupted(target.experimentId, markedInterrupted)\n if (!hostHandlesSignal) {\n host.kill(host.pid, signal)\n }\n }\n for (const signal of REPLAY_INTERRUPT_SIGNALS) {\n const handler = (): void => {\n if (interrupting) {\n return\n }\n interrupting = true\n void handleSignal(signal)\n }\n handlers.set(signal, handler)\n replayListeners.add(handler)\n host.on(signal, handler)\n }\n return { remove: removeHandlers, interrupted: () => interrupting }\n}\n","import { __version__ } from \"./constants.js\"\nimport { readEnv } from \"./readEnv.js\"\n\nconst REPLAY_EXECUTION_TARGET_ENV = \"BITFAB_REPLAY_EXECUTION_TARGET\"\nconst HOSTED_EXECUTION_TARGET = \"hosted\"\nconst CI_ENV = \"CI\"\nconst CI_TRUE_VALUES = new Set([\"true\", \"1\"])\nconst CI_PRESENCE_ENV_VARS = [\n \"GITHUB_ACTIONS\",\n \"GITLAB_CI\",\n \"CIRCLECI\",\n \"BUILDKITE\",\n \"JENKINS_URL\",\n \"TF_BUILD\",\n] as const\nconst MAX_FLAGS = 100\nconst MAX_FLAG_NAME_LENGTH = 100\nconst MAX_FLAG_STRING_LENGTH = 1_000\nconst MAX_FLAG_LIST_LENGTH = 100\nconst SECRET_FLAG_NAME = /key|token|secret|password/i\nconst CLI_FLAGS = Symbol(\"bitfab.replayCliFlags\")\nconst METADATA_FLAG = \"metadata\"\nconst CLI_FLAG_ALIASES: Record<string, string> = {\n \"max-concurrency\": \"concurrency\",\n \"dataset-id\": \"dataset-ids\",\n}\nconst OPTION_FLAG_NAMES: Record<string, string> = {\n maxConcurrency: \"concurrency\",\n datasetId: \"dataset-ids\",\n datasetIds: \"dataset-ids\",\n}\n\ntype FlagScalar = string | number | boolean | null\ntype FlagValue = FlagScalar | FlagScalar[]\n\ntype ReplayEnvironment = \"local\" | \"ci\" | \"cloud_replay\"\n\nexport interface ReplayInvocation {\n flags: Record<string, FlagValue>\n sdk: { language: \"typescript\"; version: string }\n environment: ReplayEnvironment\n}\n\nexport function replayEnvironment(): ReplayEnvironment {\n if (readEnv(REPLAY_EXECUTION_TARGET_ENV) === HOSTED_EXECUTION_TARGET) {\n return \"cloud_replay\"\n }\n if (CI_TRUE_VALUES.has((readEnv(CI_ENV) ?? \"\").toLowerCase())) {\n return \"ci\"\n }\n if (CI_PRESENCE_ENV_VARS.some((name) => (readEnv(name) ?? \"\") !== \"\")) {\n return \"ci\"\n }\n return \"local\"\n}\n\nfunction flagScalar(value: unknown): FlagScalar | undefined {\n if (typeof value === \"string\") {\n return value.slice(0, MAX_FLAG_STRING_LENGTH)\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : undefined\n }\n if (typeof value === \"boolean\" || value === null) {\n return value\n }\n return undefined\n}\n\nfunction flagValue(value: unknown): FlagValue {\n if (Array.isArray(value)) {\n const items = value.slice(0, MAX_FLAG_LIST_LENGTH).map(flagScalar)\n return items.every((item) => item !== undefined)\n ? (items as FlagScalar[])\n : true\n }\n const scalar = flagScalar(value)\n return scalar === undefined ? true : scalar\n}\n\nexport function canonicalCliFlag(name: string): string {\n return CLI_FLAG_ALIASES[name] ?? name\n}\n\nexport function optionFlagName(option: string): string {\n return (\n OPTION_FLAG_NAMES[option] ??\n option.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)\n )\n}\n\nfunction metadataKeys(value: unknown): string[] | true {\n const keys = Array.isArray(value)\n ? value.map((pair) => String(pair).split(\"=\")[0])\n : typeof value === \"object\" && value !== null\n ? Object.keys(value)\n : undefined\n return keys === undefined ? true : [...new Set(keys)].sort()\n}\n\nexport function invocationFlags(\n entries: Iterable<readonly [string, unknown]>,\n): Record<string, FlagValue> {\n const flags: Record<string, FlagValue> = {}\n const seen = new Set<string>()\n for (const [name, value] of entries) {\n if (seen.size >= MAX_FLAGS) {\n break\n }\n if (\n value === undefined ||\n seen.has(name) ||\n name.length === 0 ||\n name.length > MAX_FLAG_NAME_LENGTH ||\n SECRET_FLAG_NAME.test(name)\n ) {\n continue\n }\n flags[name] = flagValue(\n name === METADATA_FLAG ? metadataKeys(value) : value,\n )\n seen.add(name)\n }\n return flags\n}\n\nexport function buildReplayInvocation(\n entries: Iterable<readonly [string, unknown]> = [],\n): ReplayInvocation {\n return {\n flags: invocationFlags(entries),\n sdk: { language: \"typescript\", version: __version__ },\n environment: replayEnvironment(),\n }\n}\n\nexport function safeReplayInvocation(\n build: () => ReplayInvocation,\n): ReplayInvocation | undefined {\n try {\n return build()\n } catch {\n return undefined\n }\n}\n\nexport function withCliFlags<T extends object>(\n options: T,\n flags: Record<string, unknown>,\n): T {\n Object.defineProperty(options, CLI_FLAGS, {\n value: flags,\n enumerable: false,\n })\n return options\n}\n\nexport function cliFlags(\n options: object | undefined,\n): Record<string, unknown> | undefined {\n return (options as { [CLI_FLAGS]?: Record<string, unknown> } | undefined)?.[\n CLI_FLAGS\n ]\n}\n","/**\n * Replay historical traces through a function and create an experiment.\n *\n * The replay flow has three phases:\n * 1. Start: fetches historical traces from the server and creates an experiment\n * 2. Execute: re-runs each trace's inputs through the provided function locally\n * 3. Complete: marks the experiment as completed on the server\n */\n\nimport { resolveAutoCodeChange } from \"./codeChange.js\"\nimport type { DbSnapshotRef } from \"./dbSnapshot.js\"\nimport { BitfabError } from \"./errors.js\"\nimport {\n type CodeChangeFile,\n flushTraces,\n type HttpClient,\n type ResumeReplayFinishedItem,\n type SpanTreeNode,\n type StartReplayItem,\n type TokenUsage,\n} from \"./http.js\"\nimport { extractIntegrationFixtures } from \"./integrationFixture.js\"\nimport type { MockOverride, MockOverrideInput } from \"./mockOverride.js\"\nimport { normalizeMockOverrides } from \"./mockOverride.js\"\nimport { randomUuid } from \"./randomUuid.js\"\nimport type {\n DbBranchLease,\n DbBranchSettings,\n DbBranchTimings,\n MockSpan,\n MockTree,\n} from \"./replayContext.js\"\nimport { replayContextReady, runWithReplayContext } from \"./replayContext.js\"\nimport { startReplayHeartbeat } from \"./replayHeartbeat.js\"\nimport {\n installReplayInterruptHandlers,\n type ReplayInterrupt,\n} from \"./replayInterrupt.js\"\nimport {\n buildReplayInvocation,\n cliFlags,\n optionFlagName,\n safeReplayInvocation,\n} from \"./replayInvocation.js\"\nimport type {\n SelectiveReplayOptions,\n SelectiveReplayPlan,\n SelectiveReplayReport,\n} from \"./selectiveReplay.js\"\nimport {\n SelectiveReplayRuntime,\n validateSelectiveReplayOptions,\n} from \"./selectiveReplayRuntime.js\"\nimport { deserializeValue } from \"./serialize.js\"\nimport { writeOnce } from \"./warnOnce.js\"\n\nexport type MockStrategy = \"none\" | \"all\" | \"marked\"\n\nexport type TraceIngestionType = \"captured\" | \"seeded\"\n\nconst REPLAY_PERSISTENCE_TIMEOUT_MS = 30_000\nconst MAX_REPLAY_ATTEMPTS = 100\n\nfunction expandReplayWork<T>(\n serverItems: T[],\n attempts: number,\n): Array<{ serverItem: T; attempt: number }> {\n return Array.from({ length: attempts }, (_, attempt) =>\n serverItems.map((serverItem) => ({ serverItem, attempt })),\n ).flat()\n}\n\nconst RESUME_CONFLICTING_OPTIONS = [\n \"traceIds\",\n \"limit\",\n \"datasetId\",\n \"datasetIds\",\n \"attempts\",\n \"graderIds\",\n \"onlyWithAssertions\",\n \"dryRun\",\n \"experimentalSelectiveReplay\",\n] as const satisfies ReadonlyArray<keyof ReplayOptions>\n\nconst CARRIED_OVER_ERROR =\n \"This item errored in an earlier run of this experiment, before it was resumed.\"\n\ninterface ReplaySession {\n /** Null for a dry run: the server creates no experiment for one. */\n experimentId: string | null\n experimentUrl: string | null\n attempts: number\n work: Array<{ serverItem: StartReplayItem; attempt: number }>\n finished: ResumeReplayFinishedItem[]\n includeDbBranchLease: boolean\n dbBranchSettings: DbBranchSettings | undefined\n}\n\nfunction validateResume(resume: string, options: ReplayOptions): void {\n if (resume.trim().length === 0) {\n throw new BitfabError(\"resume must be the ID of the experiment to resume.\")\n }\n const conflicting = RESUME_CONFLICTING_OPTIONS.filter(\n (name) => options[name] !== undefined && options[name] !== false,\n )\n if (conflicting.length > 0) {\n throw new BitfabError(\n `resume continues experiment ${resume} with the traces, attempts, and graders it started with, so it cannot be combined with ${conflicting.join(\", \")}. Drop those options, or start a new replay without resume.`,\n )\n }\n}\n\nasync function resumeReplaySession(\n httpClient: HttpClient,\n experimentId: string,\n traceFunctionKey: string,\n codeChangeFiles: CodeChangeFile[] | null | undefined,\n force: boolean | undefined,\n requestedDbBranch: DbBranchOptions | boolean | undefined,\n): Promise<ReplaySession> {\n const response = await httpClient.resumeReplay(\n experimentId,\n traceFunctionKey,\n codeChangeFiles,\n force,\n )\n const work = response.work.map(({ itemIndex, attempt }) => {\n const serverItem = response.items[itemIndex]\n if (serverItem === undefined) {\n throw new BitfabError(\n `Replay resume for experiment ${response.experimentId} named item ${itemIndex}, but the server returned only ${response.items.length} item(s).`,\n )\n }\n return { serverItem, attempt }\n })\n if (response.skippedOriginalTraceIds.length > 0) {\n try {\n console.warn(\n `Bitfab: ${response.skippedOriginalTraceIds.length} trace(s) selected when experiment ${response.experimentId} started no longer exist, so resume skips them: ${response.skippedOriginalTraceIds.join(\", \")}`,\n )\n } catch {}\n }\n if (\n requestedDbBranch !== undefined &&\n dbBranchEnabled(requestedDbBranch) !== response.includeDbBranchLease\n ) {\n try {\n console.warn(\n `Bitfab: experiment ${response.experimentId} started with database branching ${response.includeDbBranchLease ? \"on\" : \"off\"}, so resume keeps it ${response.includeDbBranchLease ? \"on\" : \"off\"} and ignores the dbBranch option passed here.`,\n )\n } catch {}\n }\n return {\n experimentId: response.experimentId,\n experimentUrl: response.experimentUrl,\n attempts: response.attempts,\n work,\n finished: response.finished,\n includeDbBranchLease: response.includeDbBranchLease,\n dbBranchSettings: response.dbBranchSettings ?? undefined,\n }\n}\n\nfunction carriedOverReplayItem<T>(\n finished: ResumeReplayFinishedItem,\n): ReplayItem<T> {\n return {\n traceId: finished.traceId,\n originalTraceId: finished.originalTraceId,\n originalSpanId: \"\",\n sourceTraceId: finished.originalTraceId,\n sourceSpanId: \"\",\n attempt: finished.attempt,\n input: [],\n result: undefined,\n originalOutput: undefined,\n error: finished.hasError ? CARRIED_OVER_ERROR : null,\n traceError: null,\n replayError: null,\n durationMs: null,\n originalDurationMs: null,\n originalTokens: null,\n originalModel: null,\n tokens: null,\n model: null,\n dbSnapshotRef: null,\n dbBranchTimings: null,\n carriedOver: true,\n }\n}\n\nfunction resolveAttempts(attempts: number | undefined): number {\n if (attempts === undefined) {\n return 1\n }\n if (\n !Number.isInteger(attempts) ||\n attempts < 1 ||\n attempts > MAX_REPLAY_ATTEMPTS\n ) {\n throw new BitfabError(\n `attempts must be an integer from 1 to ${MAX_REPLAY_ATTEMPTS} (got ${attempts}).`,\n )\n }\n return attempts\n}\n\n/**\n * How the DB-snapshot branch each replay item runs against is sized and warmed.\n *\n * Every field is optional, so this object is only worth passing when you want\n * to override the mirror project's own sizing. To branch with those defaults,\n * pass `dbBranch: true` instead of an empty object.\n */\nexport interface DbBranchOptions {\n /**\n * Autoscaling floor for the branch's compute, in Neon Compute Units (0.25 to\n * 56). Omit to keep the mirror project's own default. Raise it when the\n * mirror is provisioned smaller than the database it stands in for, so\n * replay latency reflects your code rather than a cold, undersized branch.\n */\n minCu?: number\n /**\n * Autoscaling ceiling for the branch's compute, in Neon Compute Units.\n * Setting it equal to `minCu` pins the size, which keeps items comparable:\n * otherwise a later item can run against an endpoint that has already\n * scaled up and post a better number for the same code.\n */\n maxCu?: number\n /**\n * SQL that warms the branch's cache. The server appends it to the branch's\n * readiness check, so it runs BEFORE your function sees the branch and its\n * time is not charged to the replayed call. Invalid SQL fails the branch\n * rather than silently leaving it cold.\n */\n warmupSql?: string\n}\n\n/**\n * Whether the caller asked for database branching. `true` and a settings object\n * both turn it on; `false` and omission leave it off. Kept separate from\n * `resolveDbBranchSettings` because `dbBranch: true` enables branching while\n * contributing no settings, so presence of settings can't stand in for the\n * switch.\n */\nfunction resolveDatasetIds(\n options: Pick<ReplayOptions, \"datasetId\" | \"datasetIds\"> | undefined,\n): string[] | undefined {\n if (options?.datasetId !== undefined && options?.datasetIds !== undefined) {\n throw new BitfabError(\n \"datasetId and datasetIds are the same selector: pass one dataset through datasetId, or several through datasetIds.\",\n )\n }\n if (options?.datasetId !== undefined) {\n return [options.datasetId]\n }\n if (options?.datasetIds === undefined) {\n return undefined\n }\n if (options.datasetIds.length === 0) {\n throw new BitfabError(\"datasetIds must contain at least one dataset ID.\")\n }\n return [...new Set(options.datasetIds)]\n}\n\nfunction dbBranchEnabled(\n dbBranch: DbBranchOptions | boolean | undefined,\n): boolean {\n return dbBranch !== undefined && dbBranch !== false\n}\n\n/**\n * Narrow the caller's branch options to the wire shape, dropping the object\n * entirely when nothing was set so the request stays byte-identical to what\n * older SDKs send. Booleans carry no settings: they only move the switch.\n */\nfunction resolveDbBranchSettings(\n dbBranch: DbBranchOptions | boolean | undefined,\n): DbBranchSettings | undefined {\n if (!dbBranch || dbBranch === true) {\n return undefined\n }\n const { minCu, maxCu, warmupSql } = dbBranch\n const settings: DbBranchSettings = {\n ...(minCu === undefined ? {} : { minCu }),\n ...(maxCu === undefined ? {} : { maxCu }),\n ...(warmupSql === undefined ? {} : { warmupSql }),\n }\n return Object.keys(settings).length === 0 ? undefined : settings\n}\n\nexport interface ReplayOptions {\n /**\n * Experimental selective replay. Explicit required nodes\n * always execute; eligible output-only nodes reuse JSON recordings only\n * when runtime inputs match. Requires a compatible server, mock: \"marked\",\n * and no mock overrides or resume. Does not infer changes from codeChangeFiles.\n * The server reads active/inherited assertions and protects their scoped\n * execution evidence. Coverage in item.selectiveReplay is not a verdict.\n */\n experimentalSelectiveReplay?: SelectiveReplayOptions\n /**\n * Maximum number of traces to replay (1-5,000, default 5). Ignored when\n * `traceIds` is passed (with a warning), or when `datasetId` / `datasetIds`\n * is passed, because either source already determines how many traces replay.\n * To replay part of a dataset selection, name the members to run in\n * `traceIds` rather than bounding it here.\n */\n limit?: number\n attempts?: number\n /**\n * Optional list of specific trace IDs to replay (max 100). Passed alongside\n * `datasetId` or `datasetIds` it pins which members of that selection replay,\n * and the server rejects any ID none of those datasets contains. On its own\n * it selects by ID with no dataset attribution.\n */\n traceIds?: string[]\n /**\n * What this run is testing, in a few words, such as 'baseline' or 'shorter\n * system prompt'. Bitfab records the commit, branch, tree state, datasets,\n * and who ran it with every experiment, so do not repeat them here.\n */\n name?: string\n /**\n * Run conditions Bitfab cannot see on its own, such as an environment\n * override or a forced feature flag. Kept on the experiment next to its name.\n */\n notes?: string\n metadata?: Record<string, string>\n /** Positive integer limiting parallel items. Set to 1 for sequential. Default 10. */\n maxConcurrency?: number\n /**\n * Description of the code change being tested in this replay. Stored on\n * the resulting experiment so the change can be reviewed alongside results.\n * Supplying a description without `codeChangeFiles` preserves this text\n * while the SDK automatically captures the files.\n * Pass `null` when the replay should have no description; use\n * `codeChangeFiles: null` to suppress automatic file capture.\n */\n codeChangeDescription?: string | null\n /**\n * Files edited as part of this code change. Each entry holds the file path\n * and the full `before`/`after` contents. The agent reads each file before\n * and after editing and passes the two strings. Use `\"\"` for newly created\n * files (`before`) or deleted files (`after`). Omit this field to capture\n * automatically, or pass `null` to suppress file capture for this replay.\n */\n codeChangeFiles?: CodeChangeFile[] | null\n /**\n * Mock strategy for child spans during replay.\n * - \"marked\": only spans tagged with { mockOnReplay: true } in SpanOptions are mocked (default)\n * - \"none\": everything runs real code\n * - \"all\": every matched recorded child withSpan returns historical output;\n * a missing occurrence fails the replay item closed\n */\n mock?: MockStrategy\n /**\n * Selective mock overrides: inject custom values into specific spans during\n * replay, so downstream real code runs against the substituted output. Each\n * Pass `{ match, value }` pairs, or one resolver invoked for every child span.\n * A resolver can route on `ctx.node.traceFunctionKey` and return\n * `NO_MOCK_OVERRIDE` to continue to the next override and base strategy.\n * Per-call overrides take precedence over registrations on the client.\n */\n mockOverride?: MockOverrideInput | MockOverrideInput[]\n /**\n * Run each item against a database branch restored to the state its source\n * trace saw. Pass `true` to branch with the mirror project's own sizing, or a\n * {@link DbBranchOptions} object to tune how each branch is sized and warmed.\n * `false` and omission leave branching off. Inside `fn`, read the resolved\n * branch with `getCurrentReplayBranch()`.\n *\n * Items whose source trace carried no DB snapshot reference get no branch and\n * use the app's normal database path. Unsafe calls on that path still require\n * replay mocking. An item whose branch was requested but could not be resolved\n * fails instead of running, so replay never silently reports a result that did\n * not use the historical data you asked for.\n */\n dbBranch?: DbBranchOptions | boolean\n /**\n * Experiment group this replay joins, shown together on the experiments\n * page. An ID with no group yet creates the group.\n */\n experimentGroupId?: string\n /**\n * Name for the experiment group in `experimentGroupId`. Applied when this\n * replay creates the group, or when the group exists without a name. A group\n * that already has a name keeps it. Requires `experimentGroupId`.\n */\n experimentGroupName?: string\n /**\n * Dataset this replay runs against. Mutually exclusive with `datasetIds`.\n * Alone it replays the dataset's full membership, and with `traceIds` it\n * replays only those members. When set, the resulting experiment is\n * durably attributed to the dataset (stored on the experiment), so it appears\n * under the dataset's experiments even if the trace lineage can't be\n * reconstructed. Validated server-side against the org.\n */\n datasetId?: string\n datasetIds?: string[]\n /**\n * Graders to attach directly to this experiment, independent of any\n * graders already on the dataset. The resulting experiment is graded by the\n * union of these and the dataset's runnable graders at completion, so use this\n * to grade a single run with a check you don't want to add to the dataset\n * permanently. Each id must be an active/live grader belonging to the same\n * organization and trace function, otherwise the server rejects the replay.\n */\n graderIds?: string[]\n /**\n * Replay only the selected traces that carry at least one approved assertion.\n *\n * Narrows whatever `limit`, `traceIds` or `datasetIds` selected, so a run that\n * measures assertion outcomes does not pay to re-execute traces nothing can\n * grade. The server applies it as part of selection, which is what makes it\n * compose with `limit`: `{ limit: 10, onlyWithAssertions: true }` is the ten\n * most recent traces that HAVE approved assertions, not the ten most recent\n * filtered down to however few do. An archived assertion does not count, and\n * neither does one still awaiting review: a replay is only ever judged\n * against assertions a person has approved, so a trace carrying nothing but\n * drafts has nothing here to measure. A selection that narrows to nothing\n * replays nothing.\n */\n onlyWithAssertions?: boolean\n skipAssertionJudging?: boolean\n judgeAssertions?: boolean\n /**\n * Reshape recorded inputs before they are spread into `fn`.\n *\n * Replay pulls each trace's inputs exactly as they were captured against the\n * function's signature AT TRACE TIME. When the function's shape has since\n * changed (params renamed, reordered, collapsed into an options object, etc.),\n * the recorded inputs no longer line up and `fn(...inputs)` throws. This hook\n * lets a caller map the recorded inputs onto the current signature so replay\n * can still run.\n *\n * Receives the deserialized recorded inputs and a per-trace {@link AdaptContext}\n * (so a table-driven adapter can look up the adapted inputs by `traceId`), and\n * returns the array actually spread into `fn`. The returned array is also what\n * `ReplayItem.input` reports, so the experiment shows what was really run.\n *\n * Runs per item, inside the same try/catch as `fn`: if the adapter throws, the\n * failure is surfaced on that item's `error` rather than crashing the run.\n * Omit it to spread the recorded inputs unchanged.\n */\n adaptInputs?: (inputs: unknown[], ctx: AdaptContext) => unknown[]\n /**\n * Resolve every item's inputs and stop, without calling the function.\n *\n * Selection, span fetch, deserialization, and `adaptInputs` all run, so each\n * item reports the exact arguments the function would have received. Nothing\n * executes and no replay traces are produced, which is the cheap way to check\n * that recorded inputs still fit the current signature. No experiment is\n * created either, so the result's `experimentId` and `experimentUrl` are null\n * and `onExperimentStart` is not called.\n */\n dryRun?: boolean\n /**\n * Called once per item as it finishes, in completion order (not input\n * order), with running totals for the whole run. Use it to render replay\n * progress, for example a terminal progress bar. Replay does not know\n * pass/fail at this point (verdicts are assigned later), so the totals only\n * distinguish items whose function ran (`succeeded`) from items that threw\n * (`errored`).\n *\n * Invoked synchronously right after each item finishes, so keep it cheap. A\n * throwing callback never crashes the run: the error is swallowed so progress\n * UI can't break replay.\n */\n onItemFinish?: (progress: ReplayItemFinishProgress) => void\n /**\n * @deprecated Use {@link onItemFinish}. This compatibility callback receives\n * the same per-item finish events plus the legacy whole-run `\"complete\"`\n * event. It is ignored when `onItemFinish` is also provided.\n */\n onProgress?: (progress: ReplayProgress) => void\n /**\n * Called once when each replay item begins processing, before input loading,\n * mock preparation, database branching, or the customer function runs. Use\n * it with {@link onItemFinish} to distinguish queued items from items that\n * are still in flight. A throwing callback never crashes the run.\n */\n onItemStart?: (progress: ReplayItemStartProgress) => void\n /**\n * Called once, right after the server creates the experiment and before any\n * item runs, with the experiment ID and its dashboard URL. Use it to show\n * where results will appear while the replay is still running. A throwing\n * callback never crashes the run.\n */\n onExperimentStart?: (experiment: ReplayExperiment) => void\n onInterrupt?: (interrupt: ReplayInterrupt) => void\n resume?: string\n force?: boolean\n}\n\nconst REPLAY_OPTION_NAMES = [\n \"experimentalSelectiveReplay\",\n \"limit\",\n \"attempts\",\n \"traceIds\",\n \"name\",\n \"notes\",\n \"metadata\",\n \"maxConcurrency\",\n \"codeChangeDescription\",\n \"codeChangeFiles\",\n \"mock\",\n \"mockOverride\",\n \"dbBranch\",\n \"experimentGroupId\",\n \"experimentGroupName\",\n \"datasetId\",\n \"datasetIds\",\n \"graderIds\",\n \"onlyWithAssertions\",\n \"skipAssertionJudging\",\n \"judgeAssertions\",\n \"adaptInputs\",\n \"dryRun\",\n \"onItemFinish\",\n \"onProgress\",\n \"onItemStart\",\n \"onExperimentStart\",\n \"onInterrupt\",\n \"resume\",\n \"force\",\n] as const satisfies readonly (keyof ReplayOptions)[]\n\nfunction explicitReplayOptions(\n options: ReplayOptions | undefined,\n): Record<string, unknown> {\n const explicit: Record<string, unknown> = {}\n for (const name of REPLAY_OPTION_NAMES) {\n if (options?.[name] !== undefined) {\n explicit[optionFlagName(name)] ??= options[name]\n }\n }\n return explicit\n}\n\n/** The experiment a replay records into, passed to {@link ReplayOptions.onExperimentStart}. */\nexport interface ReplayExperiment {\n /** Experiment ID created for this replay. */\n experimentId: string\n /** Full URL to view the experiment in the dashboard. */\n experimentUrl: string\n}\n\n/** Emitted through {@link ReplayOptions.onItemStart} when a worker starts an item. */\nexport interface ReplayItemStartProgress {\n type: \"started\"\n /** Experiment ID created for this replay. Null for a dry run, which creates none. */\n experimentId: string | null\n /** @deprecated Use {@link experimentId}. Same value. */\n testRunId: string | null\n /** Items whose processing has started so far. */\n started: number\n /** Items that have finished so far, whether they succeeded or errored. */\n completed: number\n /** Total number of items in this replay run. */\n total: number\n /** Of the completed items, how many finished without a code or replay error. */\n succeeded: number\n /** Of the completed items, how many finished with an error. */\n errored: number\n /** The historical trace and span whose replay processing just started. */\n item: {\n originalTraceId: string\n originalSpanId: string\n /** @deprecated alias for `originalTraceId`. */\n sourceTraceId: string\n /** @deprecated alias for `originalSpanId`. */\n sourceSpanId: string\n attempt: number\n }\n}\n\n/** Running totals reported to {@link ReplayOptions.onItemFinish} as replay proceeds. */\nexport interface ReplayItemFinishProgress {\n /** Event kind, omitted for backward-compatible per-item events. */\n type?: \"item\"\n /** Experiment ID created for this replay. Null for a dry run, which creates none. */\n experimentId: string | null\n /** @deprecated Use {@link experimentId}. Same value. */\n testRunId: string | null\n /** Items that have finished so far, whether they succeeded or errored. */\n completed: number\n /** Total number of items in this replay run. */\n total: number\n /** Of the completed items, how many finished without a code or replay error. */\n succeeded: number\n /** Of the completed items, how many have `item.error` set. */\n errored: number\n /**\n * The single item that just finished to produce this event. Field-for-field\n * the same shape and meaning as {@link ReplayItem}, so a progress UI and a\n * final-result UI read one contract. `traceId` is null at this stage (the\n * server replay id arrives at completion), and `tokens` is null for the same\n * reason: the replayed run's usage is aggregated server-side by\n * completeReplay. `durationMs` is how long this item took to replay; the\n * `original*` fields describe the trace it replayed.\n */\n item: ReplayProgressItem\n}\n\n/** See {@link ReplayItemFinishProgress.item}. Mirrors {@link ReplayItem}. */\nexport interface ReplayProgressItem {\n selectiveReplay?: SelectiveReplayReport\n /** Trace ID of the new replay trace (null during the run; the server id arrives at completion). */\n traceId?: string | null\n /** Bitfab trace ID of the original (historical) trace being replayed. */\n originalTraceId: string | null\n /** External span ID the recorded inputs were read from (the original root span). */\n originalSpanId?: string | null\n /** @deprecated alias for `originalTraceId`. */\n sourceTraceId: string | null\n /** @deprecated alias for `originalSpanId`. */\n sourceSpanId?: string | null\n attempt: number\n /** Deserialized inputs from the original trace. */\n input?: unknown[]\n /** The result returned by the replayed function, or undefined on error. */\n result?: unknown\n /** The original output from the historical trace. */\n originalOutput?: unknown\n /** Backward-compatible message for either error kind. */\n error: string | null\n /** The actual value thrown by the replayed customer function. */\n traceError?: unknown | null\n /** The actual value thrown while Bitfab prepared this replay item. */\n replayError?: unknown | null\n /** How long the replayed function took on this run. */\n durationMs?: number | null\n /** The original trace's duration, tokens, and model. */\n originalDurationMs?: number | null\n originalTokens?: TokenUsage | null\n originalModel?: string | null\n ingestionType?: TraceIngestionType\n /** Always null here: the replayed run's usage is only known at completion. */\n tokens?: TokenUsage | null\n /** @deprecated renamed to `originalModel`. */\n model?: string | null\n dbSnapshotRef?: DbSnapshotRef | null\n dbBranchTimings?: DbBranchTimings | null\n}\n\n/**\n * @deprecated Use {@link ReplayItemFinishProgress}. This legacy shape also\n * represents the item-less terminal `\"complete\"` event emitted by\n * {@link ReplayOptions.onProgress}.\n */\nexport interface ReplayProgress {\n type?: \"item\" | \"complete\"\n result?: ReplayResult<unknown>\n /** Null for a dry run, which creates no experiment. */\n experimentId?: string | null\n /** @deprecated Use {@link experimentId}. Same value. */\n testRunId?: string | null\n completed: number\n total: number\n succeeded: number\n errored: number\n item?: ReplayItemFinishProgress[\"item\"]\n}\n\n/**\n * Wire prefix the Bitfab plugin scans for. Each line {@link reportReplayProgress}\n * writes is this prefix followed by the JSON of the running totals (plus the\n * finished `item`). The plugin polls these lines to report live progress while a\n * replay runs in the background; keep the SDK emitter and the plugin parser in\n * sync.\n */\nexport const BITFAB_PROGRESS_PREFIX = \"@@bitfab:progress \"\n\n/**\n * A ready-made replay lifecycle callback for replay scripts.\n * Pass it straight in:\n *\n * ```ts\n * await bitfab.replay(\"my-fn\", fn, {\n * limit,\n * onItemStart: reportReplayProgress,\n * onItemFinish: reportReplayProgress,\n * })\n * ```\n *\n * It writes `@@bitfab:progress` lines to stderr, which the Bitfab plugin polls\n * to report in-flight and finished items while replay runs in the background,\n * so scripts never hand-format the wire protocol.\n * stdout is left untouched for direct-run ReplayResult JSON. Outside Node (no\n * `process.stderr`, e.g. a browser) it is a no-op, and a write failure is\n * swallowed so progress can never crash a run.\n */\nexport function reportReplayProgress(\n progress: ReplayItemFinishProgress | ReplayItemStartProgress | ReplayProgress,\n): void {\n const stderr = typeof process !== \"undefined\" ? process.stderr : undefined\n if (!stderr) {\n return\n }\n try {\n stderr.write(\n `${BITFAB_PROGRESS_PREFIX}${JSON.stringify(progress, replayJsonReplacer)}\\n`,\n )\n } catch {\n // A progress reporter must never crash the replay run.\n }\n}\n\n/** Per-trace context passed to {@link ReplayOptions.adaptInputs}. */\nexport interface AdaptContext {\n /** Bitfab trace ID of the original (historical) trace being replayed. */\n originalTraceId: string\n /** External span ID the recorded inputs were read from. */\n originalSpanId: string\n /** @deprecated alias for {@link AdaptContext.originalTraceId}. */\n sourceTraceId: string\n /** @deprecated alias for {@link AdaptContext.originalSpanId}. */\n sourceSpanId: string\n metadata: Record<string, unknown>\n}\n\n/**\n * The shape an adapter module must export as `adaptInputs`.\n *\n * Author an adapter in its own file (e.g. `scripts/replay-adapters/<name>.ts`),\n * import it in your replay script, and pass it to `replay({ adaptInputs })`:\n *\n * ```ts\n * import type { AdaptInputsFn } from \"@bitfab/sdk\"\n * export const adaptInputs: AdaptInputsFn = (inputs, ctx) => [reshape(inputs)]\n * ```\n */\nexport type AdaptInputsFn = (inputs: unknown[], ctx: AdaptContext) => unknown[]\n\nexport interface ReplayItem<T> {\n /** Decisions and changed-code coverage for experimental selective replay. */\n selectiveReplay?: SelectiveReplayReport\n /**\n * Server trace ID of the new replay trace this item produced. Written in by\n * `replay()` from the complete-replay response once the server has minted the\n * trace row; the client-side id used to correlate spans during the run is\n * never surfaced here. Null until completion, on older servers that omit the\n * mapping, or if the item produced no trace. Not the verdict-persistence key:\n * that is the original-trace lineage (`originalTraceId` + `experimentId`).\n */\n traceId: string | null\n /** Bitfab trace ID of the original (historical) trace being replayed. */\n originalTraceId: string\n /** External span ID the recorded inputs were read from (the original root span). */\n originalSpanId: string\n /** @deprecated alias for {@link ReplayItem.originalTraceId}. */\n sourceTraceId: string\n /** @deprecated alias for {@link ReplayItem.originalSpanId}. */\n sourceSpanId: string\n attempt: number\n /** Deserialized inputs from the original trace. */\n input: unknown[]\n /** The result returned by the function during replay, or undefined on error. */\n result: T | undefined\n originalOutput: unknown\n /**\n * How the source trace came to exist. Absent on servers that predate the\n * field, which only ever served captured traces.\n */\n ingestionType?: TraceIngestionType\n /**\n * Backward-compatible message for either error kind. Prefer `traceError` and\n * `replayError` when callers need the original exception and its source.\n */\n error: string | null\n /** The actual value thrown by the replayed customer function. */\n traceError: unknown | null\n /**\n * The actual value thrown by replay setup before the customer function ran,\n * such as database warmup, input hydration, or mock preparation.\n */\n replayError: unknown | null\n /**\n * How long the replayed function took on this run, in ms. Null if the item\n * failed before it ran. Compare against\n * {@link ReplayItem.originalDurationMs} for the before/after.\n */\n durationMs: number | null\n /** The original trace's duration in ms, or null if its timestamps are missing. */\n originalDurationMs: number | null\n /**\n * Token usage recorded on the original trace, or null if it captured none.\n * The \"old\" side of a token delta; {@link ReplayItem.tokens} is the new one.\n */\n originalTokens: TokenUsage | null\n /** Model name from the original trace, or null if not captured. */\n originalModel: string | null\n /**\n * Token usage from the REPLAYED run (this item's new execution), aggregated\n * server-side from the spans it produced, or null if the run captured no\n * token data. Compare against {@link ReplayItem.originalTokens} to see how\n * the code change moved cost. Matches what the experiments page shows.\n *\n * Unprefixed because the replay is this item's subject: anything describing\n * the trace being replayed carries `original`.\n */\n tokens: TokenUsage | null\n /** @deprecated renamed to {@link ReplayItem.originalModel}. */\n model: string | null\n /**\n * The DB snapshot ref the SDK captured at trace open. Useful for debugging\n * (\"what state was this trace pinned to?\") and for customers building\n * their own resolvers. Undefined when the source trace was captured\n * without `dbSnapshot` configured.\n */\n dbSnapshotRef: DbSnapshotRef | null\n /**\n * How long this item's DB branch took to provision, per phase, measured\n * server-side. Present whenever a branch was attempted, on both outcomes:\n * complete on success, partial up to the failing phase when the resolve\n * failed. Null when no branch was asked for, when the source trace carried\n * no snapshot ref, or against a server that predates timings.\n */\n dbBranchTimings: DbBranchTimings | null\n carriedOver?: boolean\n}\n\nexport type { CodeChangeFile, TokenUsage }\n\nexport interface ReplayResult<T> {\n /** Individual replay items with inputs, results, and comparison data. */\n items: ReplayItem<T>[]\n /**\n * The experiment ID created on the server. Null for a dry run, which\n * executes nothing and so creates no experiment.\n */\n experimentId: string | null\n /** Full URL to view the experiment in the dashboard. Null for a dry run. */\n experimentUrl: string | null\n /** @deprecated Use {@link experimentId}. Same value. */\n testRunId: string | null\n /** @deprecated Use {@link experimentUrl}. Same value. */\n testRunUrl: string | null\n attempts: number\n}\n\n/**\n * Whole-run replay failure that preserves every item collected before the run\n * failed. The original whole-run exception is available as `cause`.\n */\nexport class ReplayError<T = unknown> extends BitfabError {\n /** @deprecated Use {@link experimentId}. Same value. */\n public readonly testRunId: string\n /** @deprecated Use {@link experimentUrl}. Same value. */\n public readonly testRunUrl: string\n\n constructor(\n message: string,\n public readonly items: ReplayItem<T>[],\n public readonly experimentId: string,\n public readonly experimentUrl: string,\n public readonly cause: unknown,\n ) {\n super(message, experimentUrl)\n this.name = \"ReplayError\"\n this.testRunId = experimentId\n this.testRunUrl = experimentUrl\n }\n}\n\n/**\n * A database branch requested for one replay item could not be resolved.\n *\n * The server's resolver code and message are retained as structured fields so\n * callers can handle failures such as `branch_create_failed` and\n * `snapshot_from_replaced_origin` without parsing the compatible `item.error`\n * string.\n */\nexport class DbBranchReplayError extends BitfabError {\n constructor(\n public readonly code: string,\n message: string,\n public readonly originalTraceId: string,\n public readonly cause?: unknown,\n ) {\n super(message)\n this.name = \"DbBranchReplayError\"\n }\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction replayItemErrorMessage(error: unknown): string {\n if (error instanceof DbBranchReplayError) {\n return `Replay requested a database branch for trace ${error.originalTraceId} but it could not be resolved (${error.code}): ${error.message}. The function was not run, because replaying it against the live database would produce a result that looks valid but did not use the historical data you asked for.`\n }\n return errorMessage(error)\n}\n\nfunction replayJsonReplacer(_key: string, value: unknown): unknown {\n if (value instanceof Error) {\n const serialized: Record<string, unknown> = {\n name: value.name,\n message: value.message,\n stack: value.stack,\n }\n if (value instanceof DbBranchReplayError) {\n serialized.code = value.code\n serialized.originalTraceId = value.originalTraceId\n if (value.cause !== undefined) {\n serialized.cause = value.cause\n }\n }\n return serialized\n }\n return value\n}\n\n/**\n * Serialize a replay result as JSON while retaining structured trace and replay\n * errors. Use this for direct-run stdout instead of raw `JSON.stringify`, which\n * drops the useful fields on JavaScript `Error` objects.\n */\nexport function serializeReplayResult<T>(result: ReplayResult<T>): string {\n return JSON.stringify(result, replayJsonReplacer, 2)\n}\n\nasync function preserveReplayFailure<T, TItem>(\n operation: () => Promise<T>,\n items: ReplayItem<TItem>[],\n experimentId: string,\n experimentUrl: string,\n): Promise<T> {\n try {\n return await operation()\n } catch (cause) {\n if (cause instanceof ReplayError) {\n throw cause\n }\n throw new ReplayError(\n errorMessage(cause),\n items,\n experimentId,\n experimentUrl,\n cause,\n )\n }\n}\n\n/**\n * Deserialize inputs from a historical span's rawData.\n *\n * Prefers superjson-serialized `input_meta` for type preservation,\n * falls back to the raw `input` field.\n */\nexport function deserializeInputs(\n spanData: Record<string, unknown>,\n): unknown[] {\n const inputMeta = spanData.input_meta as unknown\n const rawInput = spanData.input\n\n // If superjson meta is available, deserialize with type reconstruction\n if (inputMeta !== undefined && inputMeta !== null) {\n const deserialized = deserializeValue({ json: rawInput, meta: inputMeta })\n if (Array.isArray(deserialized)) {\n return deserialized\n }\n return deserialized !== undefined && deserialized !== null\n ? [deserialized]\n : []\n }\n\n // Fall back to raw input\n if (Array.isArray(rawInput)) {\n return rawInput\n }\n return rawInput !== undefined && rawInput !== null ? [rawInput] : []\n}\n\n/**\n * Deserialize the original output from a historical span's rawData.\n */\nfunction deserializeOutput(spanData: Record<string, unknown>): unknown {\n const outputMeta = spanData.output_meta as unknown\n const rawOutput = spanData.output\n\n if (outputMeta !== undefined && outputMeta !== null) {\n return deserializeValue({ json: rawOutput, meta: outputMeta })\n }\n\n return rawOutput\n}\n\n/**\n * Walk the children of a root span tree node in depth-first order and build\n * a MockTree keyed by `${traceFunctionKey}:${spanName}:${callIndex}`.\n *\n * The historical root itself is NOT walked. At replay time the runtime root\n * span has `isRootSpan === true` and never queries the mockTree (mock\n * interception is skipped for root spans by design), so the root has nothing\n * to look up. Walking it would just leave an unreachable entry in the table.\n *\n * The (key, name) compound match is what disambiguates same-key spans:\n * - A wrapped function's children commonly share its traceFunctionKey via\n * the fluent `getFunction(key).withSpan({ name }, ...)` pattern. They\n * disambiguate by `name`, never colliding with each other.\n * - Recursion: same (key, name) at every depth. callIndex per (key, name)\n * orders them correctly without leaking the historical root into the\n * nested call's slot.\n * - Outer-wrapper replay scripts: the outer wrapper's `name` is distinct\n * from anything in the historical tree (it only exists at replay), so\n * its presence never disturbs counters or lookups for spans that do\n * exist in the historical tree.\n */\nfunction buildMockTree(rootNode: SpanTreeNode): MockTree {\n const spans = new Map<string, MockSpan>()\n const counters = new Map<string, number>()\n\n function walk(node: SpanTreeNode): void {\n const key = node.traceFunctionKey\n if (key) {\n const name = node.spanName || key\n const counterKey = `${key}:${name}`\n const index = counters.get(counterKey) ?? 0\n counters.set(counterKey, index + 1)\n // `output`/`outputMeta` are undefined on a payload-free (lazy) tree;\n // `externalSpanId` is what the lazy path fetches them by. Both are copied\n // verbatim so eager and lazy trees build through the same walk.\n spans.set(`${counterKey}:${index}`, {\n sourceSpanId: node.sourceSpanId,\n externalSpanId: node.externalSpanId,\n output: node.output,\n outputMeta: node.outputMeta,\n })\n }\n for (const child of node.children) {\n walk(child)\n }\n }\n\n for (const child of rootNode.children) {\n walk(child)\n }\n\n return { spans }\n}\n\n/**\n * Execute a single replay item: fetch span data, deserialize inputs, call\n * the function within a replay context that injects experimentId into new spans.\n */\nasync function processItem<TReturn>(\n httpClient: HttpClient,\n serverItem: {\n originalTraceId?: string\n originalSpanId?: string\n /** @deprecated alias emitted by servers that predate the originalTraceId rename. */\n sourceTraceId: string\n /** @deprecated alias emitted by servers that predate the originalSpanId rename. */\n sourceSpanId: string\n originalDurationMs?: number | null\n originalTokens?: TokenUsage | null\n originalModel?: string | null\n originalMetadata?: Record<string, unknown>\n selectiveReplayPlan?: SelectiveReplayPlan\n ingestionType?: TraceIngestionType\n /** @deprecated unprefixed aliases emitted by servers that predate the rename.\n * `tokens` here is the ORIGINAL trace's usage: the start item has never\n * carried the replay's, which only exists after completeReplay. */\n durationMs: number | null\n tokens?: TokenUsage | null\n model: string | null\n dbSnapshotRef?: DbSnapshotRef\n dbBranchLease?: DbBranchLease\n dbBranchLeaseError?: { code: string; message: string }\n dbBranchTimings?: DbBranchTimings\n },\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n experimentId: string | null,\n mockStrategy: MockStrategy,\n resolvedOverrides: MockOverride[],\n replayedTraceId: string,\n attempt: number,\n includeDbBranchLease: boolean,\n dbBranchSettings: DbBranchSettings | undefined,\n adaptInputs:\n | ((inputs: unknown[], ctx: AdaptContext) => unknown[])\n | undefined,\n dryRun: boolean,\n selectiveOptions?: SelectiveReplayOptions,\n): Promise<ReplayItem<TReturn>> {\n // The server-side resolver materializes a Neon preview branch per item\n // during `/api/sdk/replay/start` (when the customer passed `dbBranch`,\n // which triggers `includeDbBranchLease: true`). The lease arrives on the\n // server item; we just attach it to the replay context and release the\n // branch in `finally` so any throw (in fetch, mock-tree build, or the\n // customer fn) frees the Neon resource. Items whose source trace had no\n // snapshot ref arrive without a lease; `getCurrentReplayBranch()` returns\n // null for those, and the app uses its normal DB path. Unsafe calls on that\n // path still require replay mocking.\n let lease = includeDbBranchLease ? serverItem.dbBranchLease : undefined\n // A resolve that was attempted and FAILED is different: the caller asked for\n // a branch, so running their function against live data would produce a\n // result that looks valid and isn't. Fail this item instead, loudly.\n let leaseError = includeDbBranchLease\n ? serverItem.dbBranchLeaseError\n : undefined\n let dbSnapshotRef = serverItem.dbSnapshotRef\n // Reported whichever way the resolve went, so it is tracked separately from\n // both the lease and the error rather than hanging off either.\n let dbBranchTimings = includeDbBranchLease\n ? serverItem.dbBranchTimings\n : undefined\n\n let inputs: unknown[] = []\n let originalOutput: unknown\n let result: TReturn | undefined\n let error: string | null = null\n let traceError: unknown | null = null\n let replayError: unknown | null = null\n // Timed around the replayed function only, so it is comparable to\n // originalDurationMs (that same function's wall time on the original run)\n // rather than to the span fetches and persistence around it.\n let replayDurationMs: number | null = null\n // Null until the replayed function actually starts, so an item that fails in\n // the span fetch or mock-tree build reports no replay duration rather than\n // timing work that was not the function.\n let replayStarted: number | null = null\n let selectiveReplay: SelectiveReplayRuntime | undefined\n\n // The ORIGINAL (historical) trace/span this item replays. Canonical server\n // keys are originalTraceId/originalSpanId; older servers only send the\n // deprecated sourceTraceId/sourceSpanId aliases.\n const originalTraceId = serverItem.originalTraceId ?? serverItem.sourceTraceId\n const originalSpanId = serverItem.originalSpanId ?? serverItem.sourceSpanId\n\n try {\n if (\n includeDbBranchLease &&\n experimentId !== null &&\n !lease &&\n !leaseError\n ) {\n let resolved: Awaited<ReturnType<HttpClient[\"resolveDbBranchLease\"]>>\n try {\n resolved = await httpClient.resolveDbBranchLease(\n experimentId,\n originalTraceId,\n dbBranchSettings,\n attempt,\n )\n } catch (cause) {\n throw new DbBranchReplayError(\n \"lease_request_failed\",\n `Bitfab could not request the database branch: ${errorMessage(cause)}`,\n originalTraceId,\n cause,\n )\n }\n lease = resolved.lease ?? undefined\n leaseError = resolved.leaseError ?? undefined\n dbSnapshotRef = resolved.dbSnapshotRef ?? dbSnapshotRef\n dbBranchTimings = resolved.timings ?? dbBranchTimings\n }\n\n if (leaseError) {\n throw new DbBranchReplayError(\n leaseError.code,\n leaseError.message,\n originalTraceId,\n )\n }\n\n if (selectiveOptions !== undefined) {\n if (serverItem.selectiveReplayPlan === undefined) {\n throw new BitfabError(\n \"Server did not return a selective replay plan. Update the server or disable experimentalSelectiveReplay.\",\n )\n }\n selectiveReplay = new SelectiveReplayRuntime(\n serverItem.selectiveReplayPlan,\n selectiveOptions,\n )\n }\n\n const span = await httpClient.getExternalSpan(originalSpanId, {\n view: \"replay\",\n })\n const spanData = (span.rawData?.span_data ?? {}) as Record<string, unknown>\n\n inputs = deserializeInputs(spanData)\n originalOutput = deserializeOutput(spanData)\n const integrationFixtures = extractIntegrationFixtures(spanData)\n\n // Reshape the recorded inputs onto the current signature when an adapter\n // is supplied. Runs before the mock tree / fn call so the adapted array is\n // what fn receives and what `item.input` reports.\n if (adaptInputs) {\n const originalMetadata = serverItem.originalMetadata\n inputs = adaptInputs(inputs, {\n originalTraceId,\n originalSpanId,\n // Deprecated aliases for originalTraceId/originalSpanId.\n sourceTraceId: originalTraceId,\n sourceSpanId: originalSpanId,\n metadata: isPlainRecord(originalMetadata)\n ? { ...originalMetadata }\n : {},\n })\n }\n\n // Build the mock tree whenever mocking could apply: any non-\"none\" strategy,\n // OR overrides are present (overrides substitute even under \"none\" - the\n // \"run real code but replace node X\" case). Only \"all\" needs outputs inline;\n // Non-\"all\" runs that need a tree (\"marked\", or \"none\" with overrides)\n // keep it payload-free and pull outputs lazily, so we never drag down every\n // span's recorded output when only a few get mocked.\n const hasOverrides = resolvedOverrides.length > 0\n const needTree =\n selectiveReplay === undefined &&\n (mockStrategy === \"all\" || mockStrategy === \"marked\" || hasOverrides)\n const includeOutputs = mockStrategy === \"all\"\n\n let mockTree: MockTree | undefined\n if (needTree) {\n try {\n const treeResponse = await httpClient.getSpanTree(originalSpanId, {\n includeOutputs,\n includeRootOutput: false,\n })\n if (!treeResponse.root) {\n throw new BitfabError(\n `Replay mock strategy \"${mockStrategy}\"${hasOverrides ? \" with overrides\" : \"\"} requires a span tree root for original span ${originalSpanId}.`,\n )\n }\n mockTree = buildMockTree(treeResponse.root)\n } catch (error) {\n if (mockStrategy !== \"marked\" || hasOverrides) {\n throw error\n }\n // The root still runs under \"marked\". An empty active tree lets an\n // unmarked-only root proceed, while any selected child fails closed at\n // its call site instead of executing the real span.\n mockTree = { spans: new Map() }\n }\n }\n\n // Lazy per-span output fetch, memoized per item so a span read twice (once\n // as a marked mock, once via an override's getOriginalOutput) fetches once.\n // Present only when outputs were NOT fetched inline (not the eager \"all\"\n // path); its presence signals the mock path to fetch on demand.\n const outputCache = new Map<string, Promise<unknown>>()\n const fetchSpanOutput =\n mockTree && !includeOutputs\n ? (externalSpanId: string): Promise<unknown> => {\n let pending = outputCache.get(externalSpanId)\n if (!pending) {\n pending = httpClient\n .getExternalSpan(externalSpanId, { view: \"replay\" })\n .then((s) =>\n deserializeOutput(\n (s.rawData?.span_data ?? {}) as Record<string, unknown>,\n ),\n )\n outputCache.set(externalSpanId, pending)\n }\n return pending\n }\n : undefined\n\n if (dryRun || experimentId === null) {\n return {\n traceId: null,\n originalTraceId,\n originalSpanId,\n sourceTraceId: originalTraceId,\n sourceSpanId: originalSpanId,\n attempt,\n input: inputs,\n result: undefined,\n originalOutput,\n ...(serverItem.ingestionType && {\n ingestionType: serverItem.ingestionType,\n }),\n error: null,\n traceError: null,\n replayError: null,\n durationMs: null,\n originalDurationMs:\n serverItem.originalDurationMs ?? serverItem.durationMs ?? null,\n originalTokens: serverItem.originalTokens ?? serverItem.tokens ?? null,\n originalModel: serverItem.originalModel ?? serverItem.model ?? null,\n tokens: null,\n model: serverItem.originalModel ?? serverItem.model ?? null,\n dbSnapshotRef: dbSnapshotRef ?? null,\n dbBranchTimings: dbBranchTimings ?? null,\n }\n }\n\n try {\n replayStarted = performance.now()\n const maybePromise = runWithReplayContext(\n {\n experimentId,\n traceId: replayedTraceId,\n inputSourceSpanId: span.id,\n inputSourceTraceId: span.externalTraceId,\n sourceBitfabTraceId: originalTraceId,\n replayAttempt: attempt,\n mockTree,\n selectiveReplay,\n callCounters: mockTree ? new Map() : undefined,\n mockStrategy,\n mockOverrides: hasOverrides ? resolvedOverrides : undefined,\n fetchSpanOutput,\n integrationFixtures,\n dbBranchLease: lease,\n dbBranchTimings,\n },\n () => fn(...inputs),\n )\n result =\n maybePromise instanceof Promise ? await maybePromise : maybePromise\n selectiveReplay?.assertNoSafetyConflict()\n replayDurationMs = Math.round(performance.now() - replayStarted)\n } catch (e) {\n // The function ran and threw, so it still has a duration worth reporting.\n if (replayStarted !== null) {\n replayDurationMs = Math.round(performance.now() - replayStarted)\n }\n traceError = e\n error = errorMessage(e)\n }\n } catch (e) {\n // Replay setup failed. replayStarted is null unless the customer function\n // had already begun, so this leaves durationMs null for a genuine\n // setup failure rather than timing work that was not the function.\n if (replayStarted !== null) {\n replayDurationMs = Math.round(performance.now() - replayStarted)\n }\n replayError = e\n error = replayItemErrorMessage(e)\n } finally {\n if (lease) {\n try {\n await httpClient.releaseDbBranchLease(lease.neonBranchId)\n } catch (e) {\n try {\n console.warn(\n `Bitfab: failed to release DB branch ${lease.neonBranchId} (TTL janitor will catch it): ${\n e instanceof Error ? e.message : String(e)\n }`,\n )\n } catch {\n // Never crash the host\n }\n }\n }\n }\n\n // Canonical names first, falling back to the unprefixed ones a server that\n // predates the rename sends.\n const originalDurationMs =\n serverItem.originalDurationMs ?? serverItem.durationMs ?? null\n const originalModel = serverItem.originalModel ?? serverItem.model ?? null\n return {\n // Written in by replay() from the complete-replay response once the server\n // has minted this replay trace's row. Null until then: the client-side\n // correlation id (replayedTraceId) is never surfaced as the item's traceId.\n traceId: null,\n originalTraceId,\n originalSpanId,\n // Deprecated aliases for originalTraceId/originalSpanId.\n sourceTraceId: originalTraceId,\n sourceSpanId: originalSpanId,\n attempt,\n input: inputs,\n result,\n originalOutput,\n ...(serverItem.ingestionType && {\n ingestionType: serverItem.ingestionType,\n }),\n error,\n traceError,\n replayError,\n durationMs: replayDurationMs,\n ...(selectiveReplay === undefined\n ? {}\n : { selectiveReplay: selectiveReplay.report() }),\n originalDurationMs,\n originalTokens: serverItem.originalTokens ?? serverItem.tokens ?? null,\n originalModel,\n // Filled in by replay() from the complete-replay response once the\n // replay traces are persisted and their spans aggregated server-side.\n // Null here (and on older servers) means \"replay tokens not known\".\n tokens: null,\n model: originalModel,\n dbSnapshotRef: dbSnapshotRef ?? null,\n dbBranchTimings: dbBranchTimings ?? null,\n }\n}\n\n/**\n * Block until the server has fully persisted every replay trace this run\n * submitted, or warn about each one it never confirmed and carry on.\n *\n * `completeReplay` reads at a single instant: it mints the trace-ID mapping and\n * aggregates each trace's tokens from its spans. Run it while spans are still\n * in flight and `item.traceId` comes back null with undercounted tokens.\n *\n * In the normal case the verdict is local: ingestion commits a request's\n * carriers before it answers, so a flush that delivered every carrier has\n * already proven the traces are whole and polling only asked the server to\n * repeat itself. Acks cannot settle a request that timed out client-side after\n * the server committed, so anything short of fully delivered falls through to\n * the server poll, which stays the authority there.\n */\nexport async function waitForReplayPersistence(\n httpClient: HttpClient,\n experimentId: string,\n replayedTraceIds: string[],\n replayLabels: Record<string, string> = {},\n warn: (line: string) => void = console.warn,\n): Promise<Record<string, string>> {\n // Settle deferred submissions before counting. A `finalize` root span only\n // reaches the transport once its finalize chain resolves, so tallying first\n // would under-count and let the barrier pass on a trace that is still short.\n // This waits for that work WITHOUT flushing: a run that submitted nothing\n // must not emit an export request just to discover it has nothing to wait on.\n const deferredSettled = await httpClient.settleDeferredWork(\n REPLAY_PERSISTENCE_TIMEOUT_MS,\n )\n\n // Checked BEFORE the tally: deferred work that never landed means no\n // completion may have registered at all, and an empty tally would then look\n // like \"nothing to wait for\" and finalize the run with root spans pending.\n if (!deferredSettled) {\n // Freed before throwing: every other exit releases these, and a retained\n // record would carry this run's submitted-but-unacked spans into the next\n // replay of the same trace ids.\n httpClient.takeTraceDeliveries(replayedTraceIds)\n throw new BitfabError(\n `Replay could not settle deferred span work before the deadline, so the ` +\n `expected span counts are incomplete (experiment ${experimentId}).`,\n )\n }\n\n // Peeked before flushing: a run whose traces never closed submitted nothing\n // to wait on, and must not emit an export request just to discover that.\n if (!httpClient.hasClosedDeliveries(replayedTraceIds)) {\n httpClient.takeTraceDeliveries(replayedTraceIds)\n return {}\n }\n\n // A failed flush is a hint, not a verdict. It means delivery was not\n // CONFIRMED within the deadline, which is not the same as lost: the export\n // timeout can fire while requests are still in flight and the server goes on\n // to persist every one of them. Throwing here failed runs whose data had\n // fully landed.\n const flushed = await flushTraces(REPLAY_PERSISTENCE_TIMEOUT_MS)\n\n const deliveries = httpClient.takeTraceDeliveries(replayedTraceIds)\n const expectedSpanCounts: Record<string, number> = {}\n const readBackTraceIds: Record<string, string> = {}\n let allDelivered = true\n for (const [traceId, delivery] of Object.entries(deliveries)) {\n if (delivery.serverTraceId !== undefined) {\n readBackTraceIds[traceId] = delivery.serverTraceId\n }\n if (!delivery.closed) {\n continue\n }\n expectedSpanCounts[traceId] = delivery.spanCount\n allDelivered = allDelivered && delivery.delivered\n }\n if (allDelivered) {\n return readBackTraceIds\n }\n\n // Unacked is not unpersisted: a request that timed out client-side may have\n // committed anyway, and an export the flush deadline abandoned may still be\n // in flight. Neither is knowable here, so from this point the server is the\n // only authority and the run polls it until it answers or the budget ends.\n //\n // The poll gets its own budget. Sharing one deadline with the flush meant a\n // flush that used it all left zero polling window, so the barrier failed\n // after a single not-ready answer - exactly the case where the export is\n // still in flight and about to persist.\n const deadline = Date.now() + REPLAY_PERSISTENCE_TIMEOUT_MS\n\n let missing = Object.keys(expectedSpanCounts)\n while (true) {\n const status = await httpClient.getReplayStatus(\n experimentId,\n expectedSpanCounts,\n )\n const ready = status.traceIds ?? {}\n Object.assign(readBackTraceIds, ready)\n missing = Object.keys(expectedSpanCounts).filter(\n (traceId) => ready[traceId] === undefined,\n )\n if (missing.length === 0) {\n return readBackTraceIds\n }\n if (Date.now() >= deadline) {\n break\n }\n await sleepForReplayPersistence(\n Math.min(100, Math.max(0, deadline - Date.now())),\n )\n }\n\n for (const traceId of missing) {\n warn(\n unconfirmedReplayWarning(\n replayLabels[traceId] ?? traceId,\n REPLAY_PERSISTENCE_TIMEOUT_MS / 1000,\n flushed,\n ),\n )\n }\n return readBackTraceIds\n}\n\nfunction unconfirmedReplayWarning(\n label: string,\n seconds: number,\n flushed: boolean,\n): string {\n return (\n `[bitfab] replay ${label} could not confirm all spans reached Bitfab ` +\n `within ${seconds}s. The run continues; Bitfab will show this replay as ` +\n `capture incomplete.${flushed ? \"\" : \" Some spans likely never left this process.\"}`\n )\n}\n\n/** @internal Wait between replay persistence polls without releasing Node. */\nexport function sleepForReplayPersistence(ms: number): Promise<void> {\n return new Promise((resolve) => {\n // This timer is part of an awaited persistence barrier. It must keep a CLI\n // process alive until the server confirms the replay or the deadline fires.\n setTimeout(resolve, ms)\n })\n}\n\nasync function mapWithConcurrency<T>(\n tasks: Array<() => Promise<T>>,\n maxConcurrency: number,\n onSettled?: (result: T, index: number) => void | Promise<void>,\n onStarted?: (index: number) => void,\n shouldStop?: () => boolean,\n): Promise<T[]> {\n const results: T[] = new Array(tasks.length)\n let nextIndex = 0\n\n async function worker(): Promise<void> {\n while (nextIndex < tasks.length && shouldStop?.() !== true) {\n const index = nextIndex++\n onStarted?.(index)\n const result = await tasks[index]()\n results[index] = result\n await onSettled?.(result, index)\n }\n }\n\n const workers = Array.from(\n { length: Math.min(maxConcurrency, tasks.length) },\n () => worker(),\n )\n await Promise.all(workers)\n return results.slice(0, nextIndex)\n}\n\nexport const JUDGE_ASSERTIONS_DEPRECATION_WARNING =\n \"Bitfab: judgeAssertions is deprecated. Assertion judging is on by default; pass skipAssertionJudging: true (--skip-assertion-judging) to turn it off.\"\n\nexport function warnJudgeAssertionsDeprecated(\n write: (line: string) => void = console.warn,\n): void {\n writeOnce(\n \"judgeAssertions-deprecated\",\n JUDGE_ASSERTIONS_DEPRECATION_WARNING,\n write,\n )\n}\n\n/**\n * Replay historical traces through a function and create an experiment.\n *\n * @internal Called by Bitfab.replay, not part of the public API.\n */\nexport async function replay<TReturn>(\n httpClient: HttpClient,\n serviceUrl: string,\n traceFunctionKey: string,\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n options?: ReplayOptions,\n registeredOverrides: MockOverride[] = [],\n): Promise<ReplayResult<TReturn>> {\n if (options?.judgeAssertions !== undefined) {\n warnJudgeAssertionsDeprecated()\n }\n if (options?.resume !== undefined) {\n validateResume(options.resume, options)\n } else if (options?.force === true) {\n throw new BitfabError(\n \"force only applies when resuming an experiment. Pass it together with resume.\",\n )\n }\n if (\n options?.experimentGroupName !== undefined &&\n options.experimentGroupId === undefined\n ) {\n throw new BitfabError(\n \"experimentGroupName only applies with experimentGroupId. Pass it together with experimentGroupId.\",\n )\n }\n if (options?.experimentalSelectiveReplay !== undefined) {\n validateSelectiveReplayOptions(options.experimentalSelectiveReplay)\n if (\n (options.mock ?? \"marked\") !== \"marked\" ||\n normalizeMockOverrides(options.mockOverride).length > 0 ||\n registeredOverrides.length > 0\n ) {\n throw new BitfabError(\n \"experimentalSelectiveReplay requires mock: 'marked' and cannot be combined with mock overrides.\",\n )\n }\n }\n if (options?.traceIds !== undefined) {\n if (options.traceIds.length === 0) {\n throw new BitfabError(\"traceIds must contain at least one trace ID.\")\n }\n if (options.traceIds.length > 100) {\n throw new BitfabError(\n `traceIds supports at most 100 trace IDs per replay (got ${options.traceIds.length}).`,\n )\n }\n }\n const datasetIds = resolveDatasetIds(options)\n if (options?.limit !== undefined && options?.traceIds !== undefined) {\n try {\n console.warn(\n \"Bitfab: limit is ignored when traceIds is passed: the explicit trace ID list already determines how many traces replay.\",\n )\n } catch {\n // Never crash the host app\n }\n }\n const requestedAttempts = resolveAttempts(options?.attempts)\n const maxConcurrency = options?.maxConcurrency ?? 10\n if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1) {\n throw new BitfabError(\n `maxConcurrency must be a positive integer (got ${maxConcurrency}).`,\n )\n }\n await replayContextReady\n\n // Resolve the code change to attach to this experiment. codeChangeFiles is\n // the capture control: omitted auto-captures, an array wins, and null opts\n // out. A caller-supplied description is preserved when files are captured.\n let codeChangeDescription = options?.codeChangeDescription\n let codeChangeFiles = options?.codeChangeFiles\n if (codeChangeFiles === undefined) {\n const captured = await resolveAutoCodeChange(options?.name)\n if (captured) {\n codeChangeFiles = captured.files\n if (codeChangeDescription === undefined) {\n codeChangeDescription = captured.description\n }\n }\n }\n\n const includeDbBranchLease =\n dbBranchEnabled(options?.dbBranch) && options?.dryRun !== true\n let session: ReplaySession\n if (options?.resume === undefined) {\n const started = await httpClient.startReplay(\n traceFunctionKey,\n // limit is meaningless with explicit traceIds (the ID list determines\n // the count), so it's omitted from the request entirely.\n options?.traceIds ? undefined : (options?.limit ?? 5),\n options?.traceIds,\n options?.name,\n codeChangeDescription,\n codeChangeFiles,\n // A dry run executes nothing, so a branch would be provisioned (and billed)\n // for code that never runs, and a seeded source's refusal would fail the item\n // before it could report its resolved inputs.\n includeDbBranchLease,\n options?.experimentGroupId,\n datasetIds,\n options?.graderIds,\n resolveDbBranchSettings(options?.dbBranch),\n requestedAttempts,\n options?.adaptInputs !== undefined,\n options?.onlyWithAssertions,\n options?.skipAssertionJudging === true ||\n options?.judgeAssertions === false,\n options?.experimentalSelectiveReplay,\n options?.notes,\n options?.metadata,\n options?.dryRun === true,\n options?.experimentGroupName,\n safeReplayInvocation(() =>\n buildReplayInvocation(\n Object.entries(cliFlags(options) ?? explicitReplayOptions(options)),\n ),\n ),\n )\n\n // An empty selection is the common shape of \"the corpus was never seeded\".\n // The result still reports it faithfully (zero items), but a caller reading\n // only the exit path would otherwise see a clean run that did nothing.\n if (started.items.length === 0) {\n try {\n console.warn(\n `Bitfab: no traces matched \"${traceFunctionKey}\", so this replay ran nothing. Capture a trace, or seed one with seedTrace, before replaying.`,\n )\n } catch {\n // Never crash the host app\n }\n }\n session = {\n experimentId: started.experimentId,\n experimentUrl: started.experimentUrl,\n attempts: requestedAttempts,\n work: expandReplayWork(started.items, requestedAttempts),\n finished: [],\n includeDbBranchLease,\n dbBranchSettings: resolveDbBranchSettings(options?.dbBranch),\n }\n } else {\n session = await resumeReplaySession(\n httpClient,\n options.resume,\n traceFunctionKey,\n codeChangeFiles,\n options.force,\n options.dbBranch,\n )\n }\n const { experimentId } = session\n if (experimentId === null || session.experimentUrl === null) {\n // A dry run has no experiment to keep alive, interrupt, or complete.\n return runReplaySession(\n httpClient,\n fn,\n session,\n null,\n maxConcurrency,\n () => {},\n () => {},\n () => false,\n options,\n registeredOverrides,\n )\n }\n const fullExperimentUrl = `${serviceUrl}${session.experimentUrl}`\n const heartbeat = startReplayHeartbeat(() =>\n httpClient.heartbeatReplay(experimentId),\n )\n const interruptReplay = async (): Promise<boolean> => {\n await heartbeat.stop()\n return httpClient.interruptReplay(experimentId)\n }\n const interruptHandlers = installReplayInterruptHandlers({\n experimentId,\n experimentUrl: fullExperimentUrl,\n interrupt: interruptReplay,\n onInterrupt: options?.onInterrupt,\n })\n let completeReturned = false\n const markCompleteReturned = (): void => {\n completeReturned = true\n void heartbeat.stop()\n }\n try {\n return await runReplaySession(\n httpClient,\n fn,\n session,\n fullExperimentUrl,\n maxConcurrency,\n interruptHandlers.remove,\n markCompleteReturned,\n interruptHandlers.interrupted,\n options,\n registeredOverrides,\n )\n } catch (error) {\n if (!completeReturned && !interruptHandlers.interrupted()) {\n await interruptReplay()\n }\n throw error\n } finally {\n interruptHandlers.remove()\n await heartbeat.stop()\n }\n}\n\nfunction throwIfInterrupted<T>(\n interrupted: () => boolean,\n items: ReplayItem<T>[],\n experimentId: string,\n experimentUrl: string,\n): void {\n if (!interrupted()) {\n return\n }\n const cause = new BitfabError(\n `Experiment ${experimentId} was interrupted, so it was not completed or graded. Resume it by passing { resume: \"${experimentId}\" } to replay, or with bitfab-replay --resume ${experimentId}.`,\n experimentUrl,\n )\n throw new ReplayError(\n cause.message,\n items,\n experimentId,\n experimentUrl,\n cause,\n )\n}\n\nasync function runReplaySession<TReturn>(\n httpClient: HttpClient,\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n session: ReplaySession,\n fullExperimentUrl: string | null,\n maxConcurrency: number,\n stopInterruptingOnSignal: () => void,\n markCompleteReturned: () => void,\n interrupted: () => boolean,\n options: ReplayOptions | undefined,\n registeredOverrides: MockOverride[],\n): Promise<ReplayResult<TReturn>> {\n const { experimentId, attempts } = session\n const mockStrategy: MockStrategy = options?.mock ?? \"marked\"\n if (experimentId !== null && fullExperimentUrl !== null) {\n try {\n options?.onExperimentStart?.({\n experimentId,\n experimentUrl: fullExperimentUrl,\n })\n } catch {\n // A lifecycle callback must never crash the replay run.\n }\n }\n\n // Per-call overrides take precedence over registered ones: concatenating them\n // first means the first-match-wins scan hits per-call overrides before the\n // client-registered chain, and both before the base mock strategy.\n const resolvedOverrides = [\n ...normalizeMockOverrides(options?.mockOverride),\n ...registeredOverrides,\n ]\n\n // One client-side replay trace id per item. It tags that item's replay spans\n // during the run so the server can echo back the row id it minted for them\n // (resolved in the complete-replay mapping below). Kept out of the public\n // ReplayItem: it's a correlation handle, never an id callers use.\n const workItems = session.work\n const carriedOverItems = session.finished.map((finished) =>\n carriedOverReplayItem<TReturn>(finished),\n )\n const replayedTraceIds = workItems.map(() => randomUuid())\n // Declared before the first span is submitted: the transport records delivery\n // only for traces someone asked about, so anything submitted before this\n // would go untracked.\n httpClient.trackTraceDeliveries(replayedTraceIds)\n const tasks = workItems.map(\n ({ serverItem, attempt }, index) =>\n () =>\n processItem(\n httpClient,\n serverItem,\n fn,\n experimentId,\n mockStrategy,\n resolvedOverrides,\n replayedTraceIds[index],\n attempt,\n session.includeDbBranchLease,\n session.dbBranchSettings,\n options?.adaptInputs,\n options?.dryRun === true,\n options?.experimentalSelectiveReplay,\n ),\n )\n const total = tasks.length + carriedOverItems.length\n const onItemFinish = options?.onItemFinish ?? options?.onProgress\n let completed = carriedOverItems.length\n let started = carriedOverItems.length\n let errored = carriedOverItems.filter((item) => item.error !== null).length\n let succeeded = completed - errored\n\n // Flush an item's trace the moment it finishes, so its server traces.id is\n // read back off the ingest response and surfaced on the item as it settles,\n // instead of waiting for the end-of-run barrier. Waiting until the end is\n // worst at low concurrency: each trace is closed and ready when its item\n // finishes, but nothing fills a batch to force an export, so ready ids sit in\n // the queue for the whole run.\n //\n // Coalesced so a burst of concurrent finishes shares one flush: while a flush\n // runs, later finishers mark `pending` and await the same promise, which loops\n // once more to cover them. Every caller therefore waits for a flush that ran\n // after it asked, and low concurrency degrades to a clean flush per item.\n let flushInFlight: Promise<void> | null = null\n let flushPending = false\n const flushFinishedItemTrace = (): Promise<void> => {\n // Mark work waiting first, so a finisher that arrives mid-flush is always\n // picked up by another loop iteration. The runner clears `flushInFlight`\n // synchronously with the loop exit (no await between the `while` check and\n // the reset), so no caller can observe a stale in-flight promise.\n flushPending = true\n if (!flushInFlight) {\n flushInFlight = (async () => {\n try {\n while (flushPending) {\n flushPending = false\n await httpClient.settleDeferredWork(REPLAY_PERSISTENCE_TIMEOUT_MS)\n await flushTraces(REPLAY_PERSISTENCE_TIMEOUT_MS)\n }\n } finally {\n flushInFlight = null\n }\n })()\n }\n return flushInFlight\n }\n\n const ranItems = await mapWithConcurrency(\n tasks,\n maxConcurrency,\n async (item, index) => {\n // Deliver this item's trace now, then read its server id back off the\n // ingest response. A flush failure never crashes the run: the id degrades\n // to null and the end-of-run barrier stays the authority on persistence.\n // Done BEFORE touching the counters so the increment and emit below carry\n // no await between them: with items flushing concurrently, that keeps each\n // event's running totals a consistent snapshot.\n let serverTraceId: string | null = null\n try {\n await flushFinishedItemTrace()\n serverTraceId =\n httpClient.peekServerTraceId(replayedTraceIds[index]) ?? null\n } catch {\n // Best-effort: fall through with null; the barrier settles persistence.\n }\n item.traceId = serverTraceId\n completed += 1\n if (item.error === null) {\n succeeded += 1\n } else {\n errored += 1\n }\n try {\n onItemFinish?.({\n experimentId,\n testRunId: experimentId,\n completed,\n total,\n succeeded,\n errored,\n item: {\n // The server's assigned traces.id, read back off the ingest\n // response and surfaced as this item finishes. Null only if the\n // per-item flush could not confirm delivery in time; the end-of-run\n // barrier then fills the returned ReplayItem. The client-side\n // placeholder is never surfaced.\n traceId: serverTraceId,\n originalTraceId: item.originalTraceId ?? null,\n originalSpanId: item.originalSpanId ?? null,\n // Deprecated aliases for originalTraceId/originalSpanId.\n sourceTraceId: item.originalTraceId ?? null,\n sourceSpanId: item.originalSpanId ?? null,\n attempt: item.attempt,\n input: item.input,\n result: item.result,\n originalOutput: item.originalOutput,\n error: item.error,\n traceError: item.traceError,\n replayError: item.replayError,\n durationMs: item.durationMs,\n ...(item.selectiveReplay === undefined\n ? {}\n : { selectiveReplay: item.selectiveReplay }),\n originalDurationMs: item.originalDurationMs,\n originalTokens: item.originalTokens,\n originalModel: item.originalModel,\n ingestionType: item.ingestionType,\n tokens: item.tokens,\n model: item.model,\n dbSnapshotRef: item.dbSnapshotRef,\n dbBranchTimings: item.dbBranchTimings,\n },\n })\n } catch {\n // Progress UI must never crash the replay run.\n }\n },\n options?.onItemStart\n ? (index) => {\n started += 1\n const { serverItem, attempt } = workItems[index]\n const originalTraceId =\n serverItem.originalTraceId ?? serverItem.sourceTraceId\n const originalSpanId =\n serverItem.originalSpanId ?? serverItem.sourceSpanId\n try {\n options.onItemStart?.({\n type: \"started\",\n experimentId,\n testRunId: experimentId,\n started,\n completed,\n total,\n succeeded,\n errored,\n item: {\n originalTraceId,\n originalSpanId,\n sourceTraceId: originalTraceId,\n sourceSpanId: originalSpanId,\n attempt,\n },\n })\n } catch {\n // Progress UI must never crash the replay run.\n }\n }\n : undefined,\n interrupted,\n )\n const resultItems = [...carriedOverItems, ...ranItems]\n\n // Items submit their spans through the same batching transport live traffic\n // uses, so nothing here has waited on the network yet. Flush the transports,\n // then let the SERVER confirm each trace reached a final status with all of\n // its spans before finalizing: a drained queue is not proof that Bitfab\n // committed the data.\n // A dry run executed nothing, so it produced no spans and no traces. The\n // persistence barrier asserts the opposite (every completed item has a\n // persisted trace) and would fail the whole run, so it is skipped along with\n // the trace-id mapping it feeds. Current servers create no experiment for a\n // dry run. An older one still does, and that experiment is finalized so it\n // does not sit unfinished in the experiments list.\n if (\n options?.dryRun === true ||\n experimentId === null ||\n fullExperimentUrl === null\n ) {\n if (experimentId !== null && fullExperimentUrl !== null) {\n throwIfInterrupted(\n interrupted,\n resultItems,\n experimentId,\n fullExperimentUrl,\n )\n stopInterruptingOnSignal()\n await httpClient.completeReplay(experimentId).catch(() => undefined)\n markCompleteReturned()\n }\n const dryResult: ReplayResult<TReturn> = {\n items: resultItems,\n experimentId,\n experimentUrl: fullExperimentUrl,\n testRunId: experimentId,\n testRunUrl: fullExperimentUrl,\n attempts,\n }\n await writeReplayResultFile(dryResult)\n return dryResult\n }\n throwIfInterrupted(interrupted, resultItems, experimentId, fullExperimentUrl)\n\n const deliveredTraceIds = await preserveReplayFailure(\n () =>\n waitForReplayPersistence(\n httpClient,\n experimentId,\n replayedTraceIds,\n Object.fromEntries(\n workItems.map(({ serverItem, attempt }, index) => [\n replayedTraceIds[index],\n `${serverItem.originalTraceId ?? serverItem.sourceTraceId}#${attempt}`,\n ]),\n ),\n ),\n resultItems,\n experimentId,\n fullExperimentUrl,\n )\n\n // Primary source for item.traceId: the server's assigned traces.id, read back\n // per trace off the ingest response during the flush above (server-sourced, no\n // polling, already in hand before completeReplay). The completeReplay map below\n // remains the fallback for servers that don't return ids on ingest.\n for (let index = 0; index < ranItems.length; index += 1) {\n const localId = replayedTraceIds[index]\n const readBack = localId ? deliveredTraceIds[localId] : undefined\n if (readBack !== undefined) {\n ranItems[index].traceId = readBack\n }\n }\n\n // completeReplay finalizes the experiment and returns the token/diagnostic\n // mapping; its failures propagate loudly because a run that never completed\n // can't be finalized and callers must hear about it.\n throwIfInterrupted(interrupted, resultItems, experimentId, fullExperimentUrl)\n stopInterruptingOnSignal()\n const completeResult = await preserveReplayFailure(\n () => httpClient.completeReplay(experimentId),\n resultItems,\n experimentId,\n fullExperimentUrl,\n )\n markCompleteReturned()\n const serverTraceIds = completeResult.traceIds\n // Per-replay-trace token usage, keyed by server trace id. The REPLAYED run's\n // tokens (span-aggregated server-side), used below to fill each item.tokens.\n const replayTokens = completeResult.tokens\n\n // `serverTraceIds` maps each item's client-side replay trace id (its entry in\n // `replayedTraceIds`, which tagged that item's spans during the run) to the\n // server's trace row id. We use it to (a) write the real server replay trace\n // id into `item.traceId` now that the row exists, (b) attach each item's\n // server-aggregated token usage, and (c) detect a systemic upload failure\n // early. Verdict persistence does NOT use this map: it is keyed by the\n // original-trace lineage (`originalTraceId` + `experimentId`), which needs no\n // client-held server id. Older servers that omit the map yield no replay\n // tokens and leave `item.traceId` null.\n if (serverTraceIds !== undefined) {\n const missing: string[] = []\n let completedCount = 0\n for (let index = 0; index < ranItems.length; index += 1) {\n const item = ranItems[index]\n const localId = replayedTraceIds[index]\n const mapped = localId ? serverTraceIds[localId] : undefined\n // Fallback fill for servers that did not return ids on the ingest\n // response; the read-back loop above already set it when they did, so\n // never overwrite a resolved id with null here.\n item.traceId = item.traceId ?? mapped ?? null\n if (item.error === null) {\n completedCount += 1\n if (mapped === undefined) {\n missing.push(localId ?? item.originalTraceId)\n }\n }\n if (mapped !== undefined) {\n item.tokens = replayTokens?.[mapped] ?? null\n }\n }\n // ALL completed items missing → systemic (the replayed function isn't\n // wrapped with withSpan, or uploads are wholesale broken). Throw; the run's\n // traces never persisted, so nothing can be labeled and silence here is the\n // exact bug this guarantee exists to prevent.\n if (completedCount > 0 && missing.length === completedCount) {\n const serverCount =\n completeResult.traceCount !== undefined\n ? ` The server persisted ${completeResult.traceCount} trace(s) for this run.`\n : \"\"\n const cause = new BitfabError(\n `Replay completed but the server has no persisted trace for any of the ${completedCount} completed item(s) (experiment ${experimentId}).${serverCount} ` +\n `Trace uploads were awaited, so either the uploads failed (check for \"Bitfab: Failed to create\" errors above) or the replayed function is not wrapped with withSpan.`,\n )\n throw new ReplayError(\n cause.message,\n resultItems,\n experimentId,\n fullExperimentUrl,\n cause,\n )\n }\n // SOME completed items missing → per-item upload failure (transient blip,\n // one oversized payload). Log it, but return the run; the items that landed\n // can still be labeled via their lineage.\n if (missing.length > 0) {\n try {\n console.error(\n `Bitfab: server has no persisted trace for ${missing.length} of ${completedCount} completed replay item(s) (experiment ${experimentId}). Their replay token usage is unavailable and they cannot be labeled.`,\n )\n } catch {\n // Never crash the host app\n }\n }\n }\n\n const result: ReplayResult<TReturn> = {\n items: resultItems,\n experimentId,\n experimentUrl: fullExperimentUrl,\n testRunId: experimentId,\n testRunUrl: fullExperimentUrl,\n attempts,\n }\n // Persist the enriched result so the Bitfab plugin never has to parse the\n // replay's stdout, which a dependency's logging can corrupt.\n await writeReplayResultFile(result)\n // Preserve the legacy terminal event only for onProgress. onItemFinish is\n // strictly item-scoped, so every invocation always includes an item.\n if (!options?.onItemFinish) {\n try {\n options?.onProgress?.({\n type: \"complete\",\n experimentId,\n testRunId: experimentId,\n completed: total,\n total,\n succeeded,\n errored,\n result,\n })\n } catch {\n // A progress reporter must never crash the replay run.\n }\n }\n return result\n}\n\nasync function writeReplayResultFile(\n result: ReplayResult<unknown>,\n): Promise<void> {\n const resultPath =\n typeof process !== \"undefined\"\n ? process.env?.BITFAB_REPLAY_RESULT_PATH\n : undefined\n if (!resultPath) {\n return\n }\n\n try {\n const [{ dirname }, { mkdir, writeFile }] = await Promise.all([\n import(\"node:path\"),\n import(\"node:fs/promises\"),\n ])\n await mkdir(dirname(resultPath), { recursive: true })\n await writeFile(resultPath, `${serializeReplayResult(result)}\\n`)\n } catch (err) {\n try {\n console.warn(\n `Bitfab: failed to write replay result to BITFAB_REPLAY_RESULT_PATH (${resultPath}): ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n } catch {\n // Never crash the host app.\n }\n }\n}\n","import {\n type AsyncLocalStorageLike,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\nimport { isCaptureSuppressed } from \"./captureSuppression.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport interface AutoTraceFunctionDefinition {\n id: string\n name: string\n file: string\n line: number\n column: number\n async?: boolean\n wrapper?: boolean\n}\n\nexport interface AutoTraceNodeConfiguration {\n functionName: string\n name?: string\n type?: \"llm\" | \"agent\" | \"function\" | \"guardrail\" | \"handoff\" | \"custom\"\n capture: boolean\n experimentId?: string\n /** @deprecated Use experimentId. */\n testRunId?: string\n mockOnReplay?: boolean\n replayReusable?: boolean\n // biome-ignore lint/suspicious/noExplicitAny: node finalizers receive the configured function's result, whose type is owned by the caller\n finalize?: (result: any) => unknown | Promise<unknown>\n}\n\nexport interface NestedTraceLink {\n traceFunctionKey: string\n traceId?: string\n rootSpanId?: string\n}\n\nexport interface SpanDetails {\n contexts: Record<string, unknown>[]\n prompt?: string\n}\n\nexport interface AutoTraceEntry {\n context: AutoTraceContext\n depth: number\n spanStack: unknown\n}\n\nexport interface AutoTraceContext {\n readonly traceFunctionKey: string\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n spanDetails: SpanDetails,\n nodeConfiguration?: AutoTraceNodeConfiguration,\n ): T\n invokeNestedRoot<T>(\n name: string,\n functionName: string,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n link: NestedTraceLink | undefined,\n spanDetails: SpanDetails,\n ): T\n}\n\ninterface AutoTraceRootFunction {\n name: string\n entering: boolean\n}\n\ninterface AutoTraceScope {\n entries: readonly AutoTraceEntry[]\n nodeConfiguration?: AutoTraceNodeConfiguration\n rootFunction?: AutoTraceRootFunction\n}\n\ninterface AutoTraceState {\n storage: AsyncLocalStorageLike<AutoTraceScope> | null\n browserScope: AutoTraceScope | undefined\n // Older SDK copies read this field when sharing the process-wide V4 state.\n capturePolicies: WeakMap<object, Map<string, ReadonlySet<string>>>\n activeRoots: number\n}\n\ninterface AutoTraceGlobal {\n __bitfabAutoTraceStateV4?: AutoTraceState\n __bitfab_auto_trace_transformed_v1__?: boolean\n}\n\ninterface AutoTraceAsyncGenerator {\n next(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n return(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n throw(error?: unknown): Promise<IteratorResult<unknown, unknown>>\n [Symbol.asyncIterator](): AutoTraceAsyncGenerator\n}\n\nconst autoTraceGlobal = globalThis as unknown as AutoTraceGlobal\nconst autoTraceState: AutoTraceState =\n autoTraceGlobal.__bitfabAutoTraceStateV4 ?? {\n storage: null,\n browserScope: undefined,\n capturePolicies: new WeakMap(),\n activeRoots: 0,\n }\nautoTraceGlobal.__bitfabAutoTraceStateV4 = autoTraceState\n\nfunction initializeAutoTraceStorage(): void {\n autoTraceState.storage ??= createAsyncLocalStorage<AutoTraceScope>()\n}\n\nfunction runWithAutoTraceScope<T>(scope: AutoTraceScope, fn: () => T): T {\n initializeAutoTraceStorage()\n if (autoTraceState.storage) {\n return autoTraceState.storage.run(scope, fn)\n }\n\n const previous = autoTraceState.browserScope\n autoTraceState.browserScope = scope\n try {\n return fn()\n } finally {\n autoTraceState.browserScope = previous\n }\n}\n\nexport function currentAutoTraceEntries(): readonly AutoTraceEntry[] {\n return currentAutoTraceScope()?.entries ?? []\n}\n\nfunction replaceEntry(\n entries: readonly AutoTraceEntry[],\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n): readonly AutoTraceEntry[] {\n return entries.map((entry) => (entry === previous ? updated : entry))\n}\n\nexport function runWithAutoTraceEntry<T>(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n fn: () => T,\n): T {\n const result = runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n fn,\n )\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceEntryAsyncGenerator(previous, updated, result) as T\n }\n return result\n}\n\nfunction wrapAutoTraceEntryAsyncGenerator(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n () => source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nexport function clearAutoTraceNodeConfiguration<T>(fn: () => T): T {\n return runWithAutoTraceScope({ entries: currentAutoTraceEntries() }, fn)\n}\n\nexport function runWithAutoTraceNodeConfiguration<T>(\n nodeConfiguration: AutoTraceNodeConfiguration,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0) {\n return fn()\n }\n\n const result = runWithAutoTraceScope({ ...scope, nodeConfiguration }, fn)\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceNodeAsyncGenerator(nodeConfiguration, result) as T\n }\n return result\n}\n\nexport function runAsAutoTraceRootFunction<T>(\n functionName: string,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || functionName === \"\") {\n return fn()\n }\n const rootFunction: AutoTraceRootFunction = {\n name: functionName,\n entering: true,\n }\n try {\n return runWithAutoTraceScope({ ...scope, rootFunction }, fn)\n } finally {\n rootFunction.entering = false\n }\n}\n\nfunction isRootFunctionEntry(\n scope: AutoTraceScope,\n simpleName: string | undefined,\n): boolean {\n const rootFunction = scope.rootFunction\n if (rootFunction === undefined || !rootFunction.entering) {\n return false\n }\n rootFunction.entering = false\n return rootFunction.name === simpleName\n}\n\nconst SUBTREE_TRACING_DOCS_URL =\n \"https://docs.bitfab.ai/typescript-sdk#experimental-subtree-tracing\"\n\nfunction noteTransformedModule(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = true\n}\n\nfunction transformInstalled(): boolean {\n return autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ === true\n}\n\nfunction runsOnNode(): boolean {\n return typeof process !== \"undefined\" && Boolean(process.versions?.node)\n}\n\nfunction closeAutoTraceRoot(): void {\n autoTraceState.activeRoots -= 1\n}\n\nfunction settleAutoTraceRoot(context: AutoTraceContext): void {\n closeAutoTraceRoot()\n if (transformInstalled() || !runsOnNode()) {\n return\n }\n warnOnce(\n \"auto-trace-transform-missing\",\n `trace root \"${context.traceFunctionKey}\" recorded only its own span. ` +\n \"No module in this build was compiled by @bitfab/sdk/transform, so calls \" +\n \"beneath the root were not discovered. Add the SDK's transform adapter \" +\n `to the server build: ${SUBTREE_TRACING_DOCS_URL}`,\n )\n}\n\nexport function runWithAutoTraceRootContext<T>(\n context: AutoTraceContext,\n spanStack: unknown,\n fn: () => T,\n): T {\n autoTraceState.activeRoots += 1\n const entries = [\n ...currentAutoTraceEntries(),\n { context, depth: 0, spanStack },\n ]\n let result: T\n try {\n result = runWithAutoTraceScope({ entries }, fn)\n } catch (error) {\n settleAutoTraceRoot(context)\n throw error\n }\n\n if (isAutoTraceAsyncGenerator(result)) {\n closeAutoTraceRoot()\n return wrapAutoTraceAsyncGenerator(context, spanStack, result) as T\n }\n\n if (result instanceof Promise) {\n return result.finally(() => {\n settleAutoTraceRoot(context)\n }) as T\n }\n\n settleAutoTraceRoot(context)\n return result\n}\n\nexport function invokeThroughAutoTraceEntries<T>(\n entries: readonly AutoTraceEntry[],\n step: (entry: AutoTraceEntry, next: () => T) => T,\n fn: () => T,\n): T {\n let run = fn\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index] as AutoTraceEntry\n const next = run\n run = () => step(entry, next)\n }\n return run()\n}\n\nfunction isAutoTraceAsyncGenerator(\n value: unknown,\n): value is AutoTraceAsyncGenerator {\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\nfunction wrapAutoTraceAsyncGenerator(\n context: AutoTraceContext,\n spanStack: unknown,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceRootContext(context, spanStack, () => source[method](value))\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction wrapAutoTraceNodeAsyncGenerator(\n nodeConfiguration: AutoTraceNodeConfiguration,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceNodeConfiguration(nodeConfiguration, () =>\n source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction shareFinalize(\n configuration: AutoTraceNodeConfiguration,\n): AutoTraceNodeConfiguration {\n const finalize = configuration.finalize\n if (finalize === undefined) {\n return configuration\n }\n let settled: Promise<unknown> | undefined\n return {\n ...configuration,\n finalize: (result: unknown) => {\n settled ??= Promise.resolve().then(() => finalize(result))\n return settled\n },\n }\n}\n\nexport function __bitfabAutoSpan<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n): T {\n noteTransformedModule()\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || isCaptureSuppressed()) {\n return fn()\n }\n const nameParts = definition.name.split(\".\")\n const simpleName = nameParts[nameParts.length - 1]\n if (isRootFunctionEntry(scope, simpleName)) {\n return fn()\n }\n const nodeConfiguration =\n simpleName === scope.nodeConfiguration?.functionName\n ? shareFinalize(scope.nodeConfiguration)\n : undefined\n const spanDetails: SpanDetails = { contexts: [] }\n return invokeThroughAutoTraceEntries(\n scope.entries,\n (entry, next) =>\n entry.context.invoke(\n definition,\n inputs,\n next,\n entry,\n spanDetails,\n nodeConfiguration,\n ),\n fn,\n )\n}\n\n/**\n * Preserve a function's original call arguments for transform cases where\n * parameter bindings discard them, such as destructured arrow parameters.\n *\n * This helper is internal transform/runtime protocol. The proxy preserves the\n * target's callability, arity, async identity, and non-constructibility while\n * only allocating a trace closure beneath an active automatic trace root.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoWrap<T extends (...args: never[]) => unknown>(\n definition: AutoTraceFunctionDefinition,\n fn: T,\n): T {\n noteTransformedModule()\n if (fn.name === \"\") {\n const nameParts = definition.name.split(\".\")\n const inferredName = nameParts[nameParts.length - 1]\n if (inferredName !== undefined) {\n Object.defineProperty(fn, \"name\", {\n configurable: true,\n value: inferredName,\n })\n }\n }\n\n const target = fn as unknown as (...args: unknown[]) => unknown\n return new Proxy(target, {\n apply(callTarget, thisArg, args) {\n if (!__bitfabAutoTraceActive()) {\n return Reflect.apply(callTarget, thisArg, args)\n }\n return __bitfabAutoSpan(definition, args, () =>\n Reflect.apply(callTarget, thisArg, args),\n )\n },\n }) as unknown as T\n}\n\n/**\n * Return whether the current call is inside an automatic trace root.\n *\n * Build transforms use this before allocating function metadata, captured\n * inputs, or an invocation closure. It is internal transform/runtime protocol,\n * not a supported application API.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoTraceActive(): boolean {\n if (autoTraceState.activeRoots === 0 || isCaptureSuppressed()) {\n return false\n }\n return currentAutoTraceEntries().length > 0\n}\n\nfunction currentAutoTraceScope(): AutoTraceScope | undefined {\n initializeAutoTraceStorage()\n return autoTraceState.storage?.getStore() ?? autoTraceState.browserScope\n}\n\nexport function _resetAutoTraceTransformDetection(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = undefined\n}\n","import { gitRunner } from \"./gitCommand.js\"\nimport { readEnv } from \"./readEnv.js\"\n\nexport interface CommitRef {\n sha: string\n branch: string | null\n dirty: boolean | null\n remote: string | null\n rootSha: string | null\n}\n\ntype EnvLookup = (name: string) => string | undefined\ntype RemoteReader = (env: EnvLookup) => string | null\n\nconst EXPLICIT_SHA_ENV = \"BITFAB_COMMIT_SHA\"\nconst DISABLE_ENV = \"BITFAB_DISABLE_COMMIT_REF\"\nconst GIT_TIMEOUT_MS = 2_000\nconst GIT_MAX_BUFFER = 1024 * 1024\n\nconst VERCEL_PROVIDER_HOSTS: Record<string, string> = {\n github: \"github.com\",\n gitlab: \"gitlab.com\",\n bitbucket: \"bitbucket.org\",\n}\n\nfunction read(env: EnvLookup, name: string | null): string | null {\n if (name === null) {\n return null\n }\n const value = env(name)?.trim()\n return value ? value : null\n}\n\nfunction remoteFrom(...names: string[]): RemoteReader {\n return (env) => {\n const parts = names.map((name) => read(env, name))\n if (parts.some((part) => part === null)) {\n return null\n }\n return normalizeRemote(parts.join(\"/\"))\n }\n}\n\nfunction vercelRemote(env: EnvLookup): string | null {\n const provider = read(env, \"VERCEL_GIT_PROVIDER\")?.toLowerCase() ?? \"\"\n const host = VERCEL_PROVIDER_HOSTS[provider]\n const owner = read(env, \"VERCEL_GIT_REPO_OWNER\")\n const slug = read(env, \"VERCEL_GIT_REPO_SLUG\")\n if (!host || !owner || !slug) {\n return null\n }\n return `${host}/${owner}/${slug}`\n}\n\nfunction noRemote(): string | null {\n return null\n}\n\nconst PLATFORM_ENVS: ReadonlyArray<\n readonly [sha: string, branch: string | null, remote: RemoteReader]\n> = [\n [\"VERCEL_GIT_COMMIT_SHA\", \"VERCEL_GIT_COMMIT_REF\", vercelRemote],\n [\n \"GITHUB_SHA\",\n \"GITHUB_REF_NAME\",\n remoteFrom(\"GITHUB_SERVER_URL\", \"GITHUB_REPOSITORY\"),\n ],\n [\"RAILWAY_GIT_COMMIT_SHA\", \"RAILWAY_GIT_BRANCH\", noRemote],\n [\"RENDER_GIT_COMMIT\", \"RENDER_GIT_BRANCH\", noRemote],\n [\"SOURCE_VERSION\", null, noRemote],\n [\"CF_PAGES_COMMIT_SHA\", \"CF_PAGES_BRANCH\", noRemote],\n [\"CI_COMMIT_SHA\", \"CI_COMMIT_REF_NAME\", remoteFrom(\"CI_REPOSITORY_URL\")],\n [\n \"BUILD_SOURCEVERSION\",\n \"BUILD_SOURCEBRANCHNAME\",\n remoteFrom(\"BUILD_REPOSITORY_URI\"),\n ],\n [\"CIRCLE_SHA1\", \"CIRCLE_BRANCH\", remoteFrom(\"CIRCLE_REPOSITORY_URL\")],\n]\n\nexport const COMMIT_REF_ENV_NAMES: readonly string[] = [\n EXPLICIT_SHA_ENV,\n DISABLE_ENV,\n ...PLATFORM_ENVS.flatMap(([sha, branch]) =>\n branch === null ? [sha] : [sha, branch],\n ),\n \"GITHUB_SERVER_URL\",\n \"GITHUB_REPOSITORY\",\n \"CI_REPOSITORY_URL\",\n \"BUILD_REPOSITORY_URI\",\n \"CIRCLE_REPOSITORY_URL\",\n \"VERCEL_GIT_PROVIDER\",\n \"VERCEL_GIT_REPO_OWNER\",\n \"VERCEL_GIT_REPO_SLUG\",\n]\n\nexport function normalizeRemote(raw: string | null | undefined): string | null {\n const value = raw?.trim()\n if (!value) {\n return null\n }\n let host = \"\"\n let path = value\n if (value.includes(\"://\")) {\n try {\n const parsed = new URL(value)\n host = parsed.hostname\n path = parsed.pathname\n } catch {\n return null\n }\n } else {\n const separator = value.indexOf(\":\")\n if (separator !== -1) {\n const head = value.slice(0, separator)\n host = head.slice(head.lastIndexOf(\"@\") + 1)\n path = value.slice(separator + 1)\n }\n }\n path = path.replace(/^\\/+|\\/+$/g, \"\")\n if (path.endsWith(\".git\")) {\n path = path.slice(0, -\".git\".length).replace(/\\/+$/, \"\")\n }\n if (!host) {\n return path || null\n }\n return path ? `${host}/${path}` : host\n}\n\nexport function resolveCommitRefFromEnv(env: EnvLookup): CommitRef | null {\n const explicit = read(env, EXPLICIT_SHA_ENV)\n const platform = PLATFORM_ENVS.find(([sha]) => read(env, sha) !== null)\n if (!platform) {\n if (explicit === null) {\n return null\n }\n return {\n sha: explicit,\n branch: null,\n dirty: null,\n remote: null,\n rootSha: null,\n }\n }\n const [shaEnv, branchEnv, readRemote] = platform\n return {\n sha: explicit ?? (read(env, shaEnv) as string),\n branch: read(env, branchEnv),\n dirty: null,\n remote: readRemote(env),\n rootSha: null,\n }\n}\n\nexport async function resolveCommitRefFromGit(\n cwd: string,\n): Promise<CommitRef | null> {\n const git = await gitRunner({\n timeoutMs: GIT_TIMEOUT_MS,\n maxBuffer: GIT_MAX_BUFFER,\n keepProcessAlive: false,\n })\n if (!git) {\n return null\n }\n const run = async (args: string[]) => (await git(cwd, args))?.trim() ?? null\n const sha = await run([\"rev-parse\", \"HEAD\"])\n if (!sha) {\n return null\n }\n const [branch, status, remote, roots] = await Promise.all([\n run([\"symbolic-ref\", \"--short\", \"-q\", \"HEAD\"]),\n run([\"status\", \"--porcelain\"]),\n run([\"remote\", \"get-url\", \"origin\"]),\n run([\"rev-list\", \"--max-parents=0\", \"HEAD\"]),\n ])\n return {\n sha,\n branch: branch || null,\n dirty: status === null ? null : status.length > 0,\n remote: normalizeRemote(remote),\n rootSha: roots ? (roots.split(/\\s+/).sort()[0] ?? null) : null,\n }\n}\n\nexport function commitRefWire(ref: CommitRef): Record<string, unknown> {\n return {\n sha: ref.sha,\n branch: ref.branch,\n dirty: ref.dirty,\n remote: ref.remote,\n root_sha: ref.rootSha,\n }\n}\n\nlet resolved = false\nlet ref: CommitRef | null = null\nlet gitStarted = false\nlet settled: Promise<void> = Promise.resolve()\n\nexport function startCommitRefResolution(): void {\n if (resolved || gitStarted) {\n return\n }\n if (read(readEnv, DISABLE_ENV) !== null) {\n resolved = true\n return\n }\n const fromEnv = resolveCommitRefFromEnv(readEnv)\n if (fromEnv) {\n ref = fromEnv\n resolved = true\n return\n }\n gitStarted = true\n if (typeof process === \"undefined\") {\n resolved = true\n return\n }\n let cwd: string\n try {\n cwd = process.cwd?.() ?? \".\"\n } catch {\n resolved = true\n return\n }\n settled = resolveCommitRefFromGit(cwd).then(\n (fromGit) => {\n if (!resolved) {\n ref = fromGit\n resolved = true\n }\n },\n () => {\n resolved = true\n },\n )\n}\n\nexport function currentCommitRef(): CommitRef | null {\n startCommitRefResolution()\n return ref\n}\n\nexport function _commitRefSettled(): Promise<void> {\n return settled\n}\n\nexport function _resetCommitRef(): void {\n resolved = false\n ref = null\n gitStarted = false\n settled = Promise.resolve()\n}\n","const OPENAI_AGENTS_CONTEXT_STORAGE = Symbol.for(\n \"openai.agents.core.asyncLocalStorage\",\n)\nconst MAX_OPENAI_AGENTS_SPAN_CHAIN = 64\n\ninterface OpenAiAgentsSpanLike {\n spanId?: unknown\n traceId?: unknown\n previousSpan?: OpenAiAgentsSpanLike | null\n}\n\ninterface OpenAiAgentsContextStore {\n active?: unknown\n span?: OpenAiAgentsSpanLike | null\n}\n\ninterface OpenAiAgentsContextStorage {\n getStore(): OpenAiAgentsContextStore | undefined\n}\n\ninterface OpenAiAgentsSpanState {\n bitfabTraceIds: Map<string, string>\n endedSpanIds: Map<string, Set<string>>\n}\n\ninterface OpenAiAgentsSpanGlobal {\n __bitfabOpenAiAgentsSpansV1?: OpenAiAgentsSpanState\n}\n\nconst spanGlobal = globalThis as unknown as OpenAiAgentsSpanGlobal &\n Record<symbol, unknown>\nconst state: OpenAiAgentsSpanState = spanGlobal.__bitfabOpenAiAgentsSpansV1 ?? {\n bitfabTraceIds: new Map(),\n endedSpanIds: new Map(),\n}\nspanGlobal.__bitfabOpenAiAgentsSpansV1 = state\n\nexport function mapOpenAiAgentsTrace(\n agentsTraceId: string,\n bitfabTraceId: string,\n): void {\n state.bitfabTraceIds.set(agentsTraceId, bitfabTraceId)\n}\n\nexport function unmapOpenAiAgentsTrace(agentsTraceId: string): void {\n state.bitfabTraceIds.delete(agentsTraceId)\n state.endedSpanIds.delete(agentsTraceId)\n}\n\nexport function endOpenAiAgentsSpan(\n agentsTraceId: string,\n spanId: string,\n): void {\n if (!state.bitfabTraceIds.has(agentsTraceId)) {\n return\n }\n const ended = state.endedSpanIds.get(agentsTraceId) ?? new Set<string>()\n ended.add(spanId)\n state.endedSpanIds.set(agentsTraceId, ended)\n}\n\nfunction isOpenAiAgentsContextStorage(\n value: unknown,\n): value is OpenAiAgentsContextStorage {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as { getStore?: unknown }).getStore === \"function\"\n )\n}\n\nfunction currentOpenAiAgentsSpan(): OpenAiAgentsSpanLike | undefined {\n const storage = spanGlobal[OPENAI_AGENTS_CONTEXT_STORAGE]\n if (!isOpenAiAgentsContextStorage(storage)) {\n return undefined\n }\n try {\n const store = storage.getStore()\n return store?.active === true ? (store.span ?? undefined) : undefined\n } catch {\n return undefined\n }\n}\n\nfunction currentOpenAiAgentsSpans(): OpenAiAgentsSpanLike[] {\n const spans: OpenAiAgentsSpanLike[] = []\n let span = currentOpenAiAgentsSpan()\n while (span !== undefined && spans.length < MAX_OPENAI_AGENTS_SPAN_CHAIN) {\n spans.push(span)\n span = span.previousSpan ?? undefined\n }\n return spans\n}\n\nexport function openAiAgentsSpanChain(): string[] {\n if (state.bitfabTraceIds.size === 0) {\n return []\n }\n return currentOpenAiAgentsSpans()\n .map((span) => span.spanId)\n .filter((spanId): spanId is string => typeof spanId === \"string\")\n}\n\nexport function openAiAgentsParentSpanId(\n bitfabTraceId: string,\n enclosingSpanIds: readonly string[] | undefined,\n): string | undefined {\n if (state.bitfabTraceIds.size === 0) {\n return undefined\n }\n for (const span of currentOpenAiAgentsSpans()) {\n if (typeof span.spanId !== \"string\" || typeof span.traceId !== \"string\") {\n return undefined\n }\n if (state.bitfabTraceIds.get(span.traceId) !== bitfabTraceId) {\n return undefined\n }\n if (enclosingSpanIds?.includes(span.spanId)) {\n return undefined\n }\n if (!state.endedSpanIds.get(span.traceId)?.has(span.spanId)) {\n return span.spanId\n }\n }\n return undefined\n}\n","import {\n type AsyncLocalStorageLike,\n asyncStorageReady,\n createAsyncLocalStorage,\n isAsyncStorageInitDone,\n} from \"./asyncStorage.js\"\n\nexport interface RivetContextBinding<TContext extends object> {\n context: TContext\n fixtureContext: Record<string, unknown>\n recordedRoots: Set<string>\n proxy?: TContext\n}\n\nlet storage: AsyncLocalStorageLike<RivetContextBinding<object> | null> | null =\n null\nlet browserBinding: RivetContextBinding<object> | null = null\nconst STORAGE_SYMBOL = Symbol.for(\"bitfab.rivetContextStorage\")\n\nfunction initializeStorage(): void {\n if (storage) {\n return\n }\n const shared = globalThis as typeof globalThis & Record<symbol, unknown>\n const existing = shared[STORAGE_SYMBOL] as\n | AsyncLocalStorageLike<RivetContextBinding<object> | null>\n | undefined\n if (existing) {\n storage = existing\n return\n }\n const created = createAsyncLocalStorage<RivetContextBinding<object> | null>()\n if (created) {\n shared[STORAGE_SYMBOL] = created\n storage = created\n }\n}\n\nexport const rivetContextReady: Promise<void> = asyncStorageReady.then(() => {\n initializeStorage()\n})\n\nexport function getRivetContextBinding<TContext extends object>():\n | RivetContextBinding<TContext>\n | undefined {\n initializeStorage()\n return (storage?.getStore() ?? browserBinding ?? undefined) as\n | RivetContextBinding<TContext>\n | undefined\n}\n\nfunction runWithBrowserBinding<T>(\n binding: RivetContextBinding<object>,\n fn: () => T,\n): T {\n const previous = browserBinding\n browserBinding = binding\n try {\n const result = fn()\n if (result instanceof Promise) {\n return result.finally(() => {\n browserBinding = previous\n }) as T\n }\n browserBinding = previous\n return result\n } catch (error) {\n browserBinding = previous\n throw error\n }\n}\n\nexport function runWithRivetContext<T>(\n binding: RivetContextBinding<object>,\n fn: () => T,\n): T {\n initializeStorage()\n if (!storage && !isAsyncStorageInitDone()) {\n return rivetContextReady.then(() => runWithRivetContext(binding, fn)) as T\n }\n if (storage) {\n return storage.run(binding, fn)\n }\n return runWithBrowserBinding(binding, fn)\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 * 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 type AutoTraceContext,\n type AutoTraceEntry,\n type AutoTraceFunctionDefinition,\n type AutoTraceNodeConfiguration,\n clearAutoTraceNodeConfiguration,\n currentAutoTraceEntries,\n invokeThroughAutoTraceEntries,\n type NestedTraceLink,\n runAsAutoTraceRootFunction,\n runWithAutoTraceEntry,\n runWithAutoTraceNodeConfiguration,\n runWithAutoTraceRootContext,\n type SpanDetails,\n} from \"./autoTrace.js\"\nimport {\n type AllowedEnvVars,\n type ProviderDefinition,\n runFunctionWithBaml,\n} from \"./baml.js\"\nimport { validateSpanId, validateTraceId } from \"./bitfabIds.js\"\nimport { isCaptureSuppressed } from \"./captureSuppression.js\"\nimport type { CaptureSurface, SurfaceRequest } from \"./captureSurface.js\"\nimport {\n assertSurfacesCompatible,\n DEFAULT_SURFACE,\n mixedTracingError,\n resolveSurface,\n} from \"./captureSurface.js\"\nimport { CategoriesClient } from \"./categories.js\"\nimport { BitfabClaudeAgentHandler } from \"./claudeAgentSdk.js\"\nimport {\n commitRefWire,\n currentCommitRef,\n startCommitRefResolution,\n} from \"./commitRef.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 { ExperimentsClient } from \"./experiments.js\"\nimport { GradersClient } from \"./graders.js\"\nimport {\n BitfabError,\n type CapturedSpan,\n experimentIdWireFields,\n HttpClient,\n SPAN_TYPES,\n type SpanLookup,\n type SpanType,\n} from \"./http.js\"\nimport { LabelsClient } from \"./labels.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 {\n openAiAgentsParentSpanId,\n openAiAgentsSpanChain,\n} from \"./openaiAgentsSpanContext.js\"\nimport { importOptionalPeer } from \"./optionalPeer.js\"\nimport { OrganizationMembersClient } from \"./organizationMembers.js\"\nimport { randomUuid } from \"./randomUuid.js\"\nimport type {\n ReplayOptions,\n ReplayResult,\n TraceIngestionType,\n} from \"./replay.js\"\nimport { deserializeInputs } from \"./replay.js\"\nimport { ReplayBranch } from \"./replayBranch.js\"\nimport type { DbBranchTimings } from \"./replayContext.js\"\nimport { getReplayContext } from \"./replayContext.js\"\nimport {\n BitfabRivetIntegration,\n type RivetContextLike,\n type RivetEffectType,\n type RivetIntegrationOptions,\n} from \"./rivetIntegration.js\"\nimport {\n getSeedContext,\n inSeedScope,\n runWithSeedContext,\n seedContextReady,\n} from \"./seedContext.js\"\nimport { deserializeValue, serializeValue } from \"./serialize.js\"\nimport {\n CONTENT_OFF_KEY,\n DECLARED_NODE_FIELD,\n ROOT_TRACE_FUNCTION_KEY_FIELD,\n SimulationPlan,\n type SimulationPlanSubmit,\n} from \"./simulationPlan.js\"\nimport {\n isFrameworkInstrumentation,\n makeSpanOrigin,\n type SpanInstrumentation,\n} from \"./spanOrigin.js\"\nimport { SpansClient } from \"./spans.js\"\nimport { StreamFinalizationError } from \"./streamFinalizationError.js\"\nimport { nowIsoTimestamp } from \"./timestamp.js\"\nimport {\n callerTraceMetadata,\n recordCallerTraceMetadata,\n retireTraceMetadata,\n} from \"./traceMetadata.js\"\nimport { TracesClient } from \"./traces.js\"\nimport { BitfabOpenAITracingProcessor } from \"./tracing.js\"\nimport { BitfabVercelAiHandler } from \"./vercelAiSdk.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nfunction markTracedFunction<T extends (...args: never[]) => unknown>(\n target: T,\n traceFunctionKey: string,\n original: unknown,\n): T {\n Object.defineProperty(target, \"_bitfabTraceFunctionKey\", {\n value: traceFunctionKey,\n })\n Object.defineProperty(target, \"_bitfabWrappedFn\", { value: original })\n Object.defineProperty(target, \"bind\", {\n value(this: T, thisArg: unknown, ...boundArgs: unknown[]) {\n return markTracedFunction(\n Function.prototype.bind.call(this, thisArg, ...boundArgs) as T,\n traceFunctionKey,\n original,\n )\n },\n })\n return target\n}\n\nfunction resolveSpanExperimentId(\n options: Pick<SpanOptions, \"experimentId\" | \"testRunId\">,\n): string | undefined {\n const { experimentId, testRunId } = options\n if (\n experimentId !== undefined &&\n testRunId !== undefined &&\n experimentId !== testRunId\n ) {\n throw new BitfabError(\n `experimentId (\"${experimentId}\") and its deprecated alias testRunId (\"${testRunId}\") were both passed with different values. Pass only experimentId.`,\n )\n }\n return experimentId ?? testRunId\n}\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 traceFunctionKey?: string\n sessionId?: string\n name?: string\n contexts: ContextEntry[]\n startedAt: string\n experimentId?: 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 truncation?: TraceTruncation\n}\n\ntype TruncationLimit = \"max_depth\" | \"max_captured_subtree_spans\"\n\nconst TRUNCATION_LIMIT_ORDER: readonly TruncationLimit[] = [\n \"max_depth\",\n \"max_captured_subtree_spans\",\n]\n\ninterface TraceTruncation {\n limits: Set<TruncationLimit>\n droppedSpans: number\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 details: SpanDetails\n surface?: CaptureSurface\n openAiAgentsSpanIds?: string[]\n spanName: string\n rootTraceFunctionKey: string\n instrumentation: SpanInstrumentation\n declaredNode: boolean\n isRoot: boolean\n}\n\n// Global map to track active trace states\nconst activeTraceStates = new Map<string, TraceState>()\n\nfunction truncationMetadata(\n truncation: TraceTruncation | undefined,\n): Record<string, unknown> | undefined {\n if (truncation === undefined || truncation.limits.size === 0) {\n return undefined\n }\n return {\n \"bitfab.truncated_by\": TRUNCATION_LIMIT_ORDER.filter((limit) =>\n truncation.limits.has(limit),\n ).join(\",\"),\n \"bitfab.dropped_spans\": truncation.droppedSpans,\n }\n}\n\nfunction rootTraceFunctionKeyOfTrace(\n traceId: string,\n fallback: string,\n): string {\n return activeTraceStates.get(traceId)?.traceFunctionKey ?? fallback\n}\n\nfunction rootTraceFunctionKeyOf(\n payload: Record<string, unknown>,\n): string | undefined {\n const captured = payload[ROOT_TRACE_FUNCTION_KEY_FIELD]\n if (typeof captured === \"string\") {\n return captured\n }\n const traceId = payload.traceId\n const live =\n typeof traceId === \"string\"\n ? activeTraceStates.get(traceId)?.traceFunctionKey\n : undefined\n if (typeof live === \"string\") {\n return live\n }\n const own = payload.traceFunctionKey\n return typeof own === \"string\" ? own : undefined\n}\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\nexport function _resolvedApiKey(client: Bitfab): string | null {\n const keyed = client as unknown as {\n findApiKey(callsKeyFunction: boolean): string | undefined\n }\n return keyed.findApiKey(true) ?? null\n}\n\nexport function _serviceUrl(client: Bitfab): string {\n return (client as unknown as { serviceUrl: string }).serviceUrl\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). Its methods\n * write whether or not capture is on.\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\nfunction isSpanType(value: unknown): value is SpanType {\n return SPAN_TYPES.some((spanType) => spanType === value)\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.details.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.details.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 recordCallerTraceMetadata(traceId, 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\nconst CAPTURE_ENABLED_ENV = \"BITFAB_CAPTURE_ENABLED\"\n\nconst REPLAY_API_KEY_ENV = \"BITFAB_REPLAY_BITFAB_API_KEY\"\n\nconst TRUE_ENV_VALUES = new Set([\"1\", \"true\", \"yes\"])\nconst FALSE_ENV_VALUES = new Set([\"0\", \"false\", \"no\"])\n\nfunction readBooleanEnv(name: string): boolean | undefined {\n const raw = readEnv(name)\n if (raw === undefined) {\n return undefined\n }\n const value = raw.trim().toLowerCase()\n if (value === \"\") {\n return undefined\n }\n if (TRUE_ENV_VALUES.has(value)) {\n return true\n }\n if (FALSE_ENV_VALUES.has(value)) {\n return false\n }\n warnOnce(\n `unrecognized-boolean-env:${name}`,\n `${name}=\"${raw}\" is not 0 or 1; ignoring it.`,\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 ReseedOptions {\n traceId: string\n}\n\nexport interface ReseedResult {\n traceId: string\n previousRunTraceId: 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 simulationPlan?: boolean\n}\n\nexport type { SpanType }\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 /**\n * Experimental selective-replay eligibility, recorded with this span.\n * Attests that the whole subtree is output-only with JSON value semantics:\n * no hidden mutable reads, required effects, input mutations, or reliance\n * on object identity. Include implementation/dependency changes in replay's\n * mustRun. Both capture-time and current declarations must allow reuse.\n * Does not affect ordinary replay or replace mockOnReplay safety protection.\n */\n replayReusable?: boolean\n /** Optional experiment ID included on the span and on the trace it starts. */\n experimentId?: string\n /**\n * @deprecated Use {@link experimentId}. Same meaning. Passing both with\n * different values throws.\n */\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 maxCapturedSubtreeSpans?: 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 EnclosingTrace {\n traceId: string\n spanId: string\n traceFunctionKey: string\n link: NestedTraceLink\n}\n\ninterface InternalSpanOptions extends SpanOptions {\n nameFor?: (receiver: unknown) => string\n instrumentation?: SpanInstrumentation\n functionId?: string\n captureContent?: boolean\n autoTraceDefinition?: AutoTraceFunctionDefinition\n declaredNode?: boolean\n surface?: SurfaceRequest\n nestedTrace?: NestedTraceLink\n enclosingTrace?: EnclosingTrace\n spanDetails?: SpanDetails\n replayOutput?: () => unknown\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 AUTO_TRACE_NODE_FUNCTION_NAMES = new WeakMap<object, string>()\n\nfunction registerAutoTraceNode<T extends object>(\n configured: T,\n functionName: string,\n): T {\n AUTO_TRACE_NODE_FUNCTION_NAMES.set(configured, functionName)\n return configured\n}\nconst DEFAULT_AUTO_TRACE_MAX_DEPTH = 30\nconst DEFAULT_AUTO_TRACE_MAX_CAPTURED_SUBTREE_SPANS = 500\n\nfunction spanOwnerName(receiver: unknown): string | undefined {\n if (typeof receiver === \"function\") {\n return receiver.name !== \"\" ? receiver.name : undefined\n }\n if (typeof receiver !== \"object\" || receiver === null) {\n return undefined\n }\n const owner = (receiver as { constructor?: unknown }).constructor\n if (typeof owner !== \"function\" || owner === Object || owner.name === \"\") {\n return undefined\n }\n return owner.name\n}\n\nfunction qualifiedSpanName(\n receiver: unknown,\n functionName: string | undefined,\n): string | undefined {\n if (functionName === undefined) {\n return undefined\n }\n const owner = spanOwnerName(receiver)\n return owner === undefined ? functionName : `${owner}.${functionName}`\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\n// Re-export BitfabError for backwards compatibility\nexport { BitfabError, MixedTracingError }\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 captureConfiguredInCode: boolean | undefined\n private captureConfiguredFromEnv: boolean | undefined\n private readonly strict: boolean\n private readonly httpClient: HttpClient\n /** Dataset operations for the authenticated organization. */\n readonly datasets: DatasetsClient\n /** Organization-scoped groupings for assertions and scenarios. */\n readonly categories: CategoriesClient\n /** @deprecated Use {@link categories}. Same client. */\n readonly assertionCategories: CategoriesClient\n readonly organizationMembers: OrganizationMembersClient\n readonly traces: TracesClient\n readonly spans: SpansClient\n readonly labels: LabelsClient\n readonly graders: GradersClient\n readonly experiments: ExperimentsClient\n private readonly bamlClient: unknown\n private readonly dbSnapshot: DbSnapshotConfig | undefined\n private readonly simulationPlan: SimulationPlan\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.captureConfiguredInCode =\n config.captureEnabled === undefined && config.enabled === undefined\n ? undefined\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 startCommitRefResolution()\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.simulationPlan = new SimulationPlan(\n {\n getSimulationPlan: () => this.httpClient.getSimulationPlan(),\n canRead: () => this.canReadSimulationPlan(),\n },\n config.simulationPlan ?? true,\n )\n this.httpClient.externalSpanTransform = (payload, submit, drop) =>\n this.applySimulationPlan(payload, submit, drop)\n this.httpClient.externalTraceTransform = (payload, submit) =>\n this.simulationPlan.sendTrace(payload, submit)\n this.httpClient.releaseHeldExternalSpans = (timeoutMs) =>\n this.simulationPlan.release(timeoutMs)\n this.httpClient.stopSimulationPlan = () => this.simulationPlan.stop()\n if (this.findApiKey(false) !== undefined) {\n this.simulationPlan.refresh()\n }\n this.datasets = new DatasetsClient(this.httpClient)\n this.categories = new CategoriesClient(this.httpClient)\n this.assertionCategories = this.categories\n this.organizationMembers = new OrganizationMembersClient(this.httpClient)\n this.traces = new TracesClient(this.httpClient)\n this.spans = new SpansClient(this.httpClient)\n this.labels = new LabelsClient(this.httpClient)\n this.graders = new GradersClient(this.httpClient)\n this.experiments = new ExperimentsClient(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. Source exclusions and sim-plan capture-off decisions are explicit\n * opt-outs from that default.\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 controls.\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. Source exclusions and sim-plan capture-off decisions are explicit\n * opt-outs from that default. Without a compatible transform, this still\n * records one normal rich root span and runs the function unchanged.\n *\n * @param traceFunctionKey - Groups traces and their capture controls.\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(\n traceFunctionKey,\n name,\n options,\n fn,\n AUTO_TRACE_NODE_FUNCTION_NAMES.get(fn) ?? fn.name.replace(/^bound /, \"\"),\n )\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 const experimentId = resolveSpanExperimentId(options)\n return {\n capture,\n type: options.type ?? \"custom\",\n ...(options.name !== undefined && { name: options.name }),\n ...(experimentId !== undefined && { experimentId }),\n ...(options.mockOnReplay !== undefined && {\n mockOnReplay: options.mockOnReplay,\n }),\n ...(options.replayReusable !== undefined && {\n replayReusable: options.replayReusable,\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 registerAutoTraceNode(function (\n this: This,\n ...args: TArgs\n ): 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 }, functionName)\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 rootFunctionName = \"\",\n ): (this: This, ...args: TArgs) => TReturn {\n const self = this\n self.simulationPlan.refresh()\n const runRootFunction = (receiver: This, args: TArgs): TReturn =>\n runAsAutoTraceRootFunction(rootFunctionName, () =>\n fn.apply(receiver, args),\n )\n const maxDepth = autoTraceLimit(\n options.maxDepth,\n DEFAULT_AUTO_TRACE_MAX_DEPTH,\n )\n const maxCapturedSubtreeSpans = autoTraceLimit(\n options.maxCapturedSubtreeSpans,\n DEFAULT_AUTO_TRACE_MAX_CAPTURED_SUBTREE_SPANS,\n )\n const rootIsAsync = fn.constructor.name === \"AsyncFunction\"\n const excluded = new Set(options.exclude ?? [])\n const includeWrappers = options.includeWrappers ?? false\n const rootNameFor = (receiver: unknown): string =>\n options.name ??\n (fn.name !== \"\" ? (qualifiedSpanName(receiver, name) ?? name) : name)\n const rootOptions: InternalSpanOptions = {\n name: options.name,\n nameFor: rootNameFor,\n type: options.type ?? \"custom\",\n surface: \"opt-out\",\n instrumentation: \"trace\",\n }\n const buildTracedRoot = (\n spanOptions: InternalSpanOptions,\n ): ((this: This, ...args: TArgs) => TReturn) =>\n this.withSpan(\n traceFunctionKey,\n spanOptions,\n function (this: This, ...args: TArgs): TReturn {\n self.simulationPlan.refresh()\n let capturedSubtreeCount = 0\n const rootSpanStack = getSpanStack()\n const rootSpan = rootSpanStack[rootSpanStack.length - 1]\n const rootTraceState =\n rootSpan === undefined\n ? undefined\n : activeTraceStates.get(rootSpan.traceId)\n const truncation: TraceTruncation = rootTraceState?.truncation ?? {\n limits: new Set(),\n droppedSpans: 0,\n }\n const truncate = (limit: TruncationLimit): void => {\n truncation.limits.add(limit)\n truncation.droppedSpans += 1\n warnOnce(\n `auto-trace-truncated:${traceFunctionKey}`,\n `\"${traceFunctionKey}\" hit an automatic subtree capture limit (maxDepth=${maxDepth}, maxCapturedSubtreeSpans=${maxCapturedSubtreeSpans}); its trace is incomplete. Raise the limits, declare the calls you need with node(), or narrow the subtree with exclude.`,\n )\n }\n if (rootTraceState !== undefined) {\n rootTraceState.truncation = truncation\n }\n const spanStackOf = (entry: AutoTraceEntry): SpanContext[] =>\n entry.spanStack as SpanContext[]\n const openChild = <T>(\n entry: AutoTraceEntry,\n childOptions: InternalSpanOptions,\n inputs: unknown[],\n isAsync: boolean,\n invokeFn: () => T,\n ): T => {\n const runInside = (): T =>\n runWithAutoTraceEntry(\n entry,\n {\n context: autoTraceContext,\n depth: entry.depth + 1,\n spanStack: getSpanStack(),\n },\n invokeFn,\n )\n return runWithSpanStack(spanStackOf(entry), () => {\n if (isAsync) {\n const tracedAsyncChild = self.withSpan(\n traceFunctionKey,\n childOptions,\n async (..._inputs: unknown[]) => await runInside(),\n )\n return tracedAsyncChild(...inputs) as T\n }\n const tracedChild = self.withSpan(\n traceFunctionKey,\n childOptions,\n (..._inputs: unknown[]): T => runInside(),\n )\n return tracedChild(...inputs)\n })\n }\n const rootTraceFunctionKeyOfEntry = (\n entry: AutoTraceEntry,\n ): string => {\n const stack = spanStackOf(entry)\n const innermost = stack[stack.length - 1]\n return innermost === undefined\n ? traceFunctionKey\n : rootTraceFunctionKeyOfTrace(innermost.traceId, traceFunctionKey)\n }\n const recordsSpan = (\n entry: AutoTraceEntry,\n spanName: string,\n declared: boolean,\n ): boolean => {\n const contentOff =\n !declared &&\n self.simulationPlan.contentOffNow(\n rootTraceFunctionKeyOfEntry(entry),\n spanName,\n )\n const countsTowardCapturedSubtree = !declared && !contentOff\n const refusedBy: TruncationLimit | undefined =\n entry.depth >= maxDepth\n ? \"max_depth\"\n : countsTowardCapturedSubtree &&\n capturedSubtreeCount >= maxCapturedSubtreeSpans\n ? \"max_captured_subtree_spans\"\n : undefined\n if (refusedBy !== undefined) {\n truncate(refusedBy)\n return false\n }\n if (countsTowardCapturedSubtree) {\n capturedSubtreeCount += 1\n }\n return true\n }\n const autoTraceContext: AutoTraceContext = {\n traceFunctionKey,\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n invokeFn: () => T,\n entry: AutoTraceEntry,\n spanDetails: SpanDetails,\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 : clearAutoTraceNodeConfiguration(invokeFn)\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 clearAutoTraceNodeConfiguration(invokeFn)\n }\n const spanName = nodeConfiguration?.name ?? definition.name\n const declaredNode = nodeConfiguration !== undefined\n if (!recordsSpan(entry, spanName, declaredNode)) {\n return invokeWithoutNode()\n }\n const mockOnReplay =\n nodeConfiguration?.mockOnReplay ?? options.mockOnReplayDefault\n const nodeExperimentId =\n nodeConfiguration === undefined\n ? undefined\n : resolveSpanExperimentId(nodeConfiguration)\n const childOptions: InternalSpanOptions = {\n name: spanName,\n type: nodeConfiguration?.type ?? \"function\",\n captureWhen: \"nested\",\n surface: \"opt-out\",\n instrumentation: \"trace\",\n functionId: definition.id,\n captureContent: true,\n autoTraceDefinition: definition,\n spanDetails,\n ...(declaredNode && { declaredNode }),\n ...(nodeExperimentId !== undefined && {\n experimentId: nodeExperimentId,\n }),\n ...(mockOnReplay !== undefined && {\n mockOnReplay,\n }),\n ...(nodeConfiguration?.replayReusable !== undefined && {\n replayReusable: nodeConfiguration.replayReusable,\n }),\n ...(nodeConfiguration?.finalize !== undefined && {\n finalize: nodeConfiguration.finalize,\n }),\n }\n return openChild(\n entry,\n childOptions,\n inputs,\n definition.async === true,\n invokeFn,\n )\n },\n invokeNestedRoot<T>(\n nestedName: string,\n nestedFunctionName: string,\n inputs: unknown[],\n invokeFn: () => T,\n entry: AutoTraceEntry,\n link: NestedTraceLink | undefined,\n spanDetails: SpanDetails,\n ): T {\n if (\n excluded.has(nestedName) ||\n excluded.has(nestedFunctionName) ||\n !recordsSpan(entry, nestedName, true)\n ) {\n return invokeFn()\n }\n const childOptions: InternalSpanOptions = {\n name: nestedName,\n type: \"function\",\n captureWhen: \"nested\",\n surface: \"opt-out\",\n instrumentation: \"trace\",\n captureContent: true,\n declaredNode: true,\n spanDetails,\n ...(link !== undefined && { nestedTrace: link }),\n }\n return openChild(entry, childOptions, inputs, false, invokeFn)\n },\n }\n\n return runWithAutoTraceRootContext(\n autoTraceContext,\n getSpanStack(),\n () => runRootFunction(this, args),\n )\n },\n )\n const tracedRoot = buildTracedRoot(rootOptions)\n const autoTraceRoot = function (this: This, ...args: TArgs): TReturn {\n if (!self.shouldRecord() || isCaptureSuppressed()) {\n return fn.apply(this, args)\n }\n const enclosing = currentAutoTraceEntries()\n if (enclosing.length === 0) {\n const firstPlanRead = rootIsAsync\n ? self.simulationPlan.waitForFirstRead()\n : undefined\n if (firstPlanRead !== undefined) {\n return firstPlanRead.then(() =>\n tracedRoot.apply(this, args),\n ) as TReturn\n }\n return tracedRoot.apply(this, args)\n }\n const link: NestedTraceLink | undefined =\n getReplayContext() || inSeedScope() ? undefined : { traceFunctionKey }\n const rootName = rootNameFor(this)\n const spanDetails: SpanDetails = { contexts: [] }\n return invokeThroughAutoTraceEntries(\n enclosing,\n (entry, next) =>\n entry.context.invokeNestedRoot(\n rootName,\n name,\n args,\n next,\n entry,\n link,\n spanDetails,\n ),\n () => {\n if (link === undefined) {\n return runRootFunction(this, args)\n }\n const innermost = enclosing[enclosing.length - 1] as AutoTraceEntry\n const innermostNow =\n currentAutoTraceEntries().find(\n (entry) => entry.context === innermost.context,\n ) ?? innermost\n const innermostStack = innermostNow.spanStack as SpanContext[]\n const copy = innermostStack[innermostStack.length - 1]\n const detachedRoot = buildTracedRoot({\n ...rootOptions,\n spanDetails,\n ...(copy !== undefined && {\n enclosingTrace: {\n traceId: copy.traceId,\n spanId: copy.spanId,\n traceFunctionKey: innermost.context.traceFunctionKey,\n link,\n },\n }),\n })\n return runWithSpanStack([], () => detachedRoot.apply(this, args))\n },\n )\n }\n return markTracedFunction(autoTraceRoot, traceFunctionKey, fn)\n }\n\n private applySimulationPlan(\n payload: Record<string, unknown>,\n submit: SimulationPlanSubmit,\n drop: () => void,\n ): void {\n this.simulationPlan.send(\n payload,\n rootTraceFunctionKeyOf(payload),\n submit,\n drop,\n )\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 findApiKey(callsKeyFunction: boolean): string | undefined {\n const replayKey = readEnv(REPLAY_API_KEY_ENV)\n if (replayKey && replayKey.trim() !== \"\") {\n return replayKey\n }\n if (this.resolvedApiKey !== undefined) {\n return this.resolvedApiKey\n }\n if (typeof this.apiKeyConfig === \"function\" && !callsKeyFunction) {\n return undefined\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 }\n return key\n }\n\n private resolveApiKey(): string | undefined {\n const key = this.findApiKey(true)\n if (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.isCaptureConfigured() && !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 isCaptureConfigured(): boolean {\n if (this.captureConfiguredInCode !== undefined) {\n return this.captureConfiguredInCode\n }\n if (this.captureConfiguredFromEnv === undefined) {\n this.captureConfiguredFromEnv =\n readBooleanEnv(CAPTURE_ENABLED_ENV) ?? true\n }\n return this.captureConfiguredFromEnv\n }\n\n private isCaptureEnabled(): boolean {\n if (!this.isCaptureConfigured()) {\n return false\n }\n return this.resolveApiKey() !== undefined\n }\n\n private shouldRecord(): boolean {\n if (!this.isCaptureConfigured() && !getReplayContext() && !inSeedScope()) {\n return false\n }\n return this.resolveApiKey() !== undefined\n }\n\n private canReadSimulationPlan(): boolean {\n const captureConfigured =\n this.captureConfiguredInCode ??\n this.captureConfiguredFromEnv ??\n readBooleanEnv(CAPTURE_ENABLED_ENV) ??\n true\n const recording =\n captureConfigured || getReplayContext() !== null || inSeedScope()\n return recording && this.findApiKey(true) !== undefined\n }\n\n private prepareFrameworkIntegration(): void {\n if (this.isCaptureConfigured() && this.strict) {\n this.resolveApiKey()\n }\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 if (this.shouldRecord()) {\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\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 this.prepareFrameworkIntegration()\n return new BitfabOpenAITracingProcessor({\n serviceUrl: this.serviceUrl,\n shouldRecord: () => this.shouldRecord(),\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 this.prepareFrameworkIntegration()\n return new BitfabLangGraphCallbackHandler({\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n shouldRecord: () => this.shouldRecord(),\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 this.prepareFrameworkIntegration()\n const callbackHandler = new BitfabLangGraphCallbackHandler({\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n shouldRecord: () => this.shouldRecord(),\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 the first-class Rivet actor/workflow-context integration for an\n * existing trace root. The integration binds context and records effect\n * spans; it never creates another root.\n *\n * @param traceFunctionKey - Key used by the enclosing `withTrace()` root\n * @param options - Explicit per-context-path replay mocking policy\n * @experimental This API may change before it is stable.\n */\n getRivetIntegration<TContext extends object = RivetContextLike>(\n traceFunctionKey: string,\n options?: RivetIntegrationOptions,\n ): BitfabRivetIntegration<TContext> {\n return new BitfabRivetIntegration<TContext>(\n traceFunctionKey,\n {\n wrapEffect: <TArgs extends unknown[], TReturn>(\n effect: RivetEffectType,\n mockOnReplay: boolean,\n fn: (...args: TArgs) => TReturn,\n replayOutput?: () => unknown,\n ) => {\n const spanOptions: InternalSpanOptions = {\n name: effect,\n type: \"function\",\n captureWhen: \"nested\",\n mockOnReplay,\n surface: \"inherit\",\n instrumentation: \"rivet\",\n ...(replayOutput !== undefined && { replayOutput }),\n }\n return this.withSpan(traceFunctionKey, spanOptions, fn)\n },\n recordRootFixture: (context, recordedRoots) => {\n const root = getSpanStack()[0]\n if (!root) {\n return\n }\n const rootId = `${root.traceId}:${root.spanId}`\n if (recordedRoots.has(rootId)) {\n return\n }\n root.details.contexts.push(context)\n recordedRoots.add(rootId)\n },\n },\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 this.prepareFrameworkIntegration()\n return new BitfabClaudeAgentHandler({\n traceFunctionKey,\n serviceUrl: this.serviceUrl,\n shouldRecord: () => this.shouldRecord(),\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 this.simulationPlan.refresh()\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 const optionExperimentId = resolveSpanExperimentId(options)\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() || isCaptureSuppressed()) {\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 let startedSpan: { traceId: string; spanId: 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 openAiAgentsParent =\n parentContext !== undefined && options.instrumentation === \"trace\"\n ? openAiAgentsParentSpanId(\n parentContext.traceId,\n parentContext.openAiAgentsSpanIds,\n )\n : undefined\n const parentSpanId = openAiAgentsParent ?? parentContext?.spanId ?? null\n const isRootSpan = parentSpanId === null\n if (options.enclosingTrace !== undefined) {\n options.enclosingTrace.link.traceId = traceId\n options.enclosingTrace.link.rootSpanId = spanId\n }\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 const openAiAgentsSpanIds = openAiAgentsSpanChain()\n const functionNameAtOpen = fn.name !== \"\" ? fn.name : undefined\n const newContext: SpanContext = {\n traceId,\n spanId,\n details: options.spanDetails ?? { contexts: [] },\n spanName:\n options.name ??\n options.nameFor?.(this) ??\n qualifiedSpanName(this, functionNameAtOpen) ??\n traceFunctionKey,\n rootTraceFunctionKey: rootTraceFunctionKeyOfTrace(\n traceId,\n traceFunctionKey,\n ),\n instrumentation: options.instrumentation ?? \"span\",\n declaredNode: options.declaredNode === true,\n isRoot: isRootSpan,\n ...(surface !== undefined && { surface }),\n ...(openAiAgentsSpanIds.length > 0 && { openAiAgentsSpanIds }),\n }\n const nearestCapturedAncestorSpanId =\n self.nearestCapturedAncestorSpanIdOf(currentStack)\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 experimentId =\n replayCtxAtStart?.experimentId ?? optionExperimentId\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 self.simulationPlan.refresh()\n activeTraceStates.set(traceId, {\n traceId,\n traceFunctionKey,\n startedAt,\n contexts: [],\n ...(experimentId !== undefined && { experimentId }),\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 self.httpClient.traceCompletion.start(traceId, spanId)\n startedSpan = { traceId, spanId }\n const functionName = functionNameAtOpen\n const baseSpanParams = {\n traceFunctionKey,\n rootTraceFunctionKey: newContext.rootTraceFunctionKey,\n functionName,\n spanName: newContext.spanName,\n traceId,\n spanId,\n parentSpanId,\n nearestCapturedAncestorSpanId,\n inputs,\n startedAt,\n spanType: options.type ?? \"custom\",\n instrumentation: options.instrumentation ?? \"span\",\n functionId: options.functionId,\n captureContent: options.captureContent ?? true,\n replayReusable: options.replayReusable,\n autoTraceDefinition: options.autoTraceDefinition,\n declaredNode: options.declaredNode === true,\n nestedTrace: options.nestedTrace,\n enclosingTrace: options.enclosingTrace,\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.details.contexts,\n prompt: newContext.details.prompt,\n endedAt,\n ...(experimentId !== undefined && { experimentId }),\n ...(replayCtx?.inputSourceSpanId && {\n inputSourceSpanId: replayCtx.inputSourceSpanId,\n }),\n })\n }\n\n if (isRootSpan) {\n const traceState = activeTraceStates.get(traceId)\n const truncated = truncationMetadata(traceState?.truncation)\n if (truncated !== undefined) {\n recordCallerTraceMetadata(traceId, truncated)\n }\n self.sendTraceCompletion({\n traceFunctionKey,\n traceId,\n startedAt: traceState?.startedAt ?? startedAt,\n endedAt,\n sessionId: traceState?.sessionId,\n name: traceState?.name,\n metadata: callerTraceMetadata(traceId),\n contexts: traceState?.contexts ?? [],\n experimentId: traceState?.experimentId,\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 retireTraceMetadata(traceId)\n }\n } catch {\n // Silently ignore - user's result/exception takes priority\n } finally {\n self.httpClient.traceCompletion.end(traceId, spanId)\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:\n error instanceof StreamFinalizationError\n ? error.output\n : undefined,\n error:\n error instanceof StreamFinalizationError\n ? error.message\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 const resolveMockOrAbort = async <T>(\n resolve: () => T | Promise<T>,\n ): Promise<T> => {\n try {\n return await resolve()\n } catch (error) {\n self.httpClient.traceCompletion.abort(traceId, spanId)\n throw error\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?.selectiveReplay) {\n const decision = replayCtxForMock.selectiveReplay.enter({\n traceFunctionKey,\n spanName: baseSpanParams.spanName ?? traceFunctionKey,\n spanId,\n parentSpanId,\n inputs: args,\n safetyMock: !isRootSpan && options.mockOnReplay === true,\n reuseAllowed: options.replayReusable === true,\n canReuseOutput:\n options.finalize === undefined &&\n options.replayOutput === undefined &&\n !fn.constructor.name.includes(\"Generator\"),\n })\n if (decision.mock) {\n void sendSpan({\n result: decision.output,\n mocked: true,\n mockTarget: \"output\",\n mockSource: \"recorded\",\n })\n return (\n fnReturnsPromise\n ? Promise.resolve(decision.output)\n : decision.output\n ) as TReturn\n }\n }\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 resolveMockOrAbort(() => 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 const resolveBaseOutput = (): unknown | Promise<unknown> =>\n options.replayOutput !== undefined\n ? options.replayOutput()\n : resolveRecordedOutput()\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 resolveMockOrAbort(() => 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 resolveMockOrAbort(() =>\n resolveBaseOutput(),\n )\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 = resolveBaseOutput()\n if (recorded instanceof Promise) {\n return emitMockAsync(recorded, \"recorded\")\n }\n return emitMock(recorded, \"recorded\")\n }\n }\n } catch (setupError) {\n if (startedSpan) {\n self.httpClient.traceCompletion.abort(\n startedSpan.traceId,\n startedSpan.spanId,\n )\n }\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 retireTraceMetadata(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 return markTracedFunction(wrappedFn, traceFunctionKey, fn)\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 (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 (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 (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 (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 * Look up by `id` alone, or by `name` and/or `type` (both must match when\n * both are given). Name and type lookups return the last matching span by\n * default. Pass `occurrence` as `\"first\"` or a zero-based index to select a\n * different match. Returns `null` when no span matches.\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 hasNameOrType = lookup.name !== undefined || lookup.type !== undefined\n if (hasId === hasNameOrType) {\n throw new BitfabError(\"Provide id, or name and/or type\")\n }\n if (hasId) {\n validateSpanId(lookup.id)\n } else {\n if (lookup.name !== undefined && lookup.name.length === 0) {\n throw new BitfabError(\"name must be a non-empty string\")\n }\n if (lookup.type !== undefined && !isSpanType(lookup.type)) {\n throw new BitfabError(`type must be one of ${SPAN_TYPES.join(\", \")}`)\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 async getSpan(spanId: string): Promise<CapturedSpan | null> {\n if (typeof spanId !== \"string\" || spanId.trim().length === 0) {\n throw new BitfabError(\"spanId must be a non-empty string\")\n }\n return this.httpClient.getSpan(spanId)\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 this.simulationPlan.refresh()\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 experimentId?: 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 const commitRef = currentCommitRef()\n if (commitRef) {\n rawTrace.commit_ref = commitRefWire(commitRef)\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.experimentId !== undefined &&\n experimentIdWireFields(params.experimentId)),\n })\n }\n\n private sendsSpanOnCompletion(context: SpanContext): boolean {\n return (\n context.isRoot ||\n context.declaredNode ||\n isFrameworkInstrumentation(context.instrumentation) ||\n !this.simulationPlan.contentOffNow(\n context.rootTraceFunctionKey,\n context.spanName,\n )\n )\n }\n\n private nearestCapturedAncestorSpanIdOf(stack: SpanContext[]): string | null {\n for (let index = stack.length - 1; index >= 0; index -= 1) {\n const candidate = stack[index]\n if (candidate !== undefined && this.sendsSpanOnCompletion(candidate)) {\n return candidate.spanId\n }\n }\n return null\n }\n\n private contentOffBySimulationPlan(params: {\n rootTraceFunctionKey?: string\n spanName: string\n instrumentation: SpanInstrumentation\n parentSpanId: string | null\n }): boolean {\n if (\n params.rootTraceFunctionKey === undefined ||\n isFrameworkInstrumentation(params.instrumentation)\n ) {\n return false\n }\n return (\n this.simulationPlan.contentOffNow(\n params.rootTraceFunctionKey,\n params.spanName,\n ) ||\n (params.parentSpanId !== null && this.simulationPlan.unavailableNow())\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 rootTraceFunctionKey?: 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 instrumentation: SpanInstrumentation\n contexts?: ContextEntry[]\n prompt?: string\n experimentId?: string\n inputSourceSpanId?: string\n mocked?: boolean\n mockTarget?: MockTarget\n mockSource?: MockSource\n functionId?: string\n captureContent: boolean\n nearestCapturedAncestorSpanId?: string | null\n replayReusable?: boolean\n autoTraceDefinition?: AutoTraceFunctionDefinition\n declaredNode?: boolean\n nestedTrace?: NestedTraceLink\n enclosingTrace?: EnclosingTrace\n }): void {\n const contentOff =\n params.declaredNode !== true && this.contentOffBySimulationPlan(params)\n const buildsContent = params.captureContent && !contentOff\n const serializedInputs = buildsContent\n ? serializeValue(params.inputs)\n : undefined\n const serializedResult = buildsContent\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_origin: makeSpanOrigin(params.instrumentation),\n span_data: {\n name: params.spanName,\n ...(params.replayReusable !== undefined && {\n replay_reusable: params.replayReusable,\n }),\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 ...(params.nestedTrace?.traceId !== undefined && {\n nested_trace_id: params.nestedTrace.traceId,\n nested_trace_function_key: params.nestedTrace.traceFunctionKey,\n nested_root_span_id: params.nestedTrace.rootSpanId,\n }),\n ...(params.enclosingTrace !== undefined && {\n enclosing_trace_id: params.enclosingTrace.traceId,\n enclosing_trace_function_key: params.enclosingTrace.traceFunctionKey,\n enclosing_span_id: params.enclosingTrace.spanId,\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 ...(buildsContent &&\n params.prompt !== undefined && { prompt: params.prompt }),\n ...(contentOff && { [CONTENT_OFF_KEY]: true }),\n },\n }\n\n // Add parent_id for nested spans\n if (params.parentSpanId) {\n externalSpan.parent_id = params.parentSpanId\n }\n if (\n params.nearestCapturedAncestorSpanId !== undefined &&\n params.nearestCapturedAncestorSpanId !== null &&\n params.nearestCapturedAncestorSpanId !== params.parentSpanId\n ) {\n externalSpan.nearest_captured_ancestor_id =\n params.nearestCapturedAncestorSpanId\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 ...(params.rootTraceFunctionKey !== undefined && {\n [ROOT_TRACE_FUNCTION_KEY_FIELD]: params.rootTraceFunctionKey,\n }),\n ...(params.declaredNode === true && { [DECLARED_NODE_FIELD]: true }),\n rawSpan: externalSpan,\n ...(params.experimentId !== undefined &&\n experimentIdWireFields(params.experimentId)),\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 an experiment.\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 experiment. 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, experimentId, and experimentUrl\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 if (options.metadata !== undefined) {\n recordCallerTraceMetadata(traceId, options.metadata)\n }\n activeTraceStates.set(traceId, {\n traceId,\n traceFunctionKey,\n startedAt,\n contexts: [],\n ingestionType: \"seeded\",\n ...(options.sessionId !== undefined && { sessionId: options.sessionId }),\n ...(options.name !== undefined && { name: options.name }),\n })\n\n try {\n this.sendWrapperSpan({\n traceFunctionKey,\n rootTraceFunctionKey: 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 instrumentation: \"span\",\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: callerTraceMetadata(traceId),\n contexts: [],\n ingestionType: \"seeded\",\n })\n } finally {\n activeTraceStates.delete(traceId)\n retireTraceMetadata(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 if (options?.metadata !== undefined) {\n recordCallerTraceMetadata(traceId, options.metadata)\n }\n activeTraceStates.set(traceId, {\n traceId,\n traceFunctionKey,\n startedAt: nowIsoTimestamp(),\n contexts: [],\n ingestionType: \"seeded\",\n ...(options?.sessionId !== undefined && { sessionId: options.sessionId }),\n ...(options?.name !== undefined && { name: options.name }),\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 retireTraceMetadata(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 reseedTrace(\n traceFunctionKey: string,\n // biome-ignore lint/suspicious/noExplicitAny: the recorded inputs are deserialized from the trace, typed args would be incorrect\n fn: (...args: any[]) => unknown,\n options: ReseedOptions,\n ): Promise<ReseedResult> {\n const source = await this.httpClient.getReseedSource(options.traceId)\n if (source.traceFunctionKey !== traceFunctionKey) {\n throw new BitfabError(\n `Trace ${options.traceId} belongs to '${source.traceFunctionKey}', not '${traceFunctionKey}'.`,\n )\n }\n const args = deserializeInputs({\n input: source.input,\n input_meta: source.inputMeta,\n })\n const runTraceId = await this.seedTraceByRunning(\n traceFunctionKey,\n fn as (...args: never[]) => unknown,\n {\n args: args as never[],\n metadata: source.metadata,\n ...(source.sessionId === null ? {} : { sessionId: source.sessionId }),\n ...(source.name === null ? {} : { name: source.name }),\n },\n )\n const adopted = await this.httpClient.reseedTrace(\n options.traceId,\n runTraceId,\n )\n return {\n traceId: adopted.traceId,\n previousRunTraceId: adopted.previousRunTraceId,\n }\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 * Wrap a function as an automatically expanded trace root bound to this\n * function's key.\n *\n * Equivalent to `client.withTrace(key, options, fn)` but reuses the key\n * bound on this handle.\n *\n * @param optionsOrFn - Trace options or the workflow entrypoint to wrap\n * @param maybeFn - Workflow entrypoint when options are provided\n * @returns A wrapped function with the same signature\n * @experimental Automatic child-call instrumentation is experimental.\n */\n withTrace<This, TArgs extends unknown[], TReturn>(\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn\n withTrace<This, TArgs extends unknown[], TReturn>(\n options: TraceOptions,\n fn: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn\n withTrace<This, TArgs extends unknown[], TReturn>(\n optionsOrFn: TraceOptions | ((this: This, ...args: TArgs) => TReturn),\n maybeFn?: (this: This, ...args: TArgs) => TReturn,\n ): (this: This, ...args: TArgs) => TReturn {\n if (typeof optionsOrFn === \"function\") {\n return this.client.withTrace(this.traceFunctionKey, optionsOrFn)\n }\n if (!maybeFn) {\n throw new BitfabError(\"BitfabFunction.withTrace requires a function\")\n }\n return this.client.withTrace(this.traceFunctionKey, optionsOrFn, maybeFn)\n }\n\n /**\n * Create a trace method decorator bound to this function's key.\n *\n * Equivalent to `client.trace(key, options)` but reuses the key bound on\n * this handle.\n *\n * @param options - Trace configuration applied to the decorated method\n * @returns A method decorator configured for this key\n * @experimental Automatic child-call instrumentation is experimental.\n */\n trace(options: TraceOptions = {}): TraceMethodDecorator {\n return this.client.trace(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 * Get the first-class Rivet actor-context integration bound to this key.\n * Use its `bind()` or `withContext()` outside this handle's `withTrace()`\n * root, then call `getContext()` inside the root.\n *\n * @param options - Explicit per-context-path replay mocking policy\n * @experimental This API may change before it is stable.\n */\n getRivetIntegration<TContext extends object = RivetContextLike>(\n options?: RivetIntegrationOptions,\n ): BitfabRivetIntegration<TContext> {\n return this.client.getRivetIntegration<TContext>(\n this.traceFunctionKey,\n options,\n )\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","import type { ApprovalState } from \"./approval.js\"\nimport { _resolvedApiKey, _serviceUrl, 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 warnJudgeAssertionsDeprecated,\n} from \"./replay.js\"\nimport {\n describeReplayInterrupt,\n type ReplayInterruptSignal,\n} from \"./replayInterrupt.js\"\nimport { canonicalCliFlag, withCliFlags } from \"./replayInvocation.js\"\nimport { warnOnce } from \"./warnOnce.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\" | \"onExperimentStart\"\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 validateReplayRegistry(registry)\n return registry\n}\n\nconst REGISTRATION_FIELDS = new Set([\n \"client\",\n \"fn\",\n \"traceFunctionKey\",\n \"options\",\n \"optionsFactory\",\n])\n\nexport function validateReplayRegistry(registry: ReplayRegistry): void {\n for (const [pipeline, registration] of Object.entries(registry)) {\n if (typeof registration !== \"object\" || registration === null) {\n throw new BitfabError(\n `Replay registry entry '${pipeline}' must be an object with client and fn.`,\n )\n }\n const unknownFields = Object.keys(registration).filter(\n (field) => !REGISTRATION_FIELDS.has(field),\n )\n if (unknownFields.length > 0) {\n warnOnce(\n `replay-registry-unknown-fields:${pipeline}:${unknownFields.join(\",\")}`,\n `Replay registry entry '${pipeline}' has unknown field(s): ${unknownFields.join(\", \")}. ` +\n \"They are ignored. An entry takes client, fn, traceFunctionKey, options, and optionsFactory. \" +\n \"Put replay options such as adaptInputs, mock, and mockOverride inside options. \" +\n \"A later SDK release will reject unknown fields.\",\n )\n }\n }\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 notes?: string\n metadata?: Record<string, string>\n maxConcurrency?: number\n codeChangePath?: string\n experimentGroupId?: string\n experimentGroupName?: string\n datasetIds?: string[]\n graderIds?: string[]\n onlyWithAssertions?: boolean\n skipAssertionJudging?: boolean\n judgeAssertionsFlag?: boolean\n mock?: \"none\" | \"all\" | \"marked\"\n dbBranch?: boolean\n noCodeChange?: boolean\n dryRun?: boolean\n failOnError?: boolean\n paramsPath?: string\n params: string[]\n resume?: string\n force?: boolean\n flags: Record<string, unknown>\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 \"--notes\",\n \"--metadata\",\n \"--concurrency\",\n \"--max-concurrency\",\n \"--code-change\",\n \"--experiment-group-id\",\n \"--experiment-group-name\",\n \"--dataset-id\",\n \"--dataset-ids\",\n \"--grader-ids\",\n \"--mock\",\n \"--param\",\n \"--params\",\n \"--resume\",\n])\n\nconst BOOLEAN_FLAGS = new Set([\n \"--only-with-assertions\",\n \"--skip-assertion-judging\",\n \"--judge-assertions\",\n \"--db-branch\",\n \"--no-db-branch\",\n \"--no-code-change\",\n \"--dry-run\",\n \"--fail-on-error\",\n \"--force\",\n])\n\nconst HELP_FLAGS = new Set([\"--help\", \"-h\"])\n\nconst REPEATABLE_FLAGS = new Set([\"--metadata\", \"--param\"])\n\nfunction recordFlag(\n flags: Record<string, unknown>,\n flag: string,\n raw?: string,\n): void {\n const name = canonicalCliFlag(flag.slice(2))\n if (raw === undefined) {\n flags[name] = true\n return\n }\n const value = flag === \"--param\" ? raw.split(\"=\")[0] : raw\n if (REPEATABLE_FLAGS.has(flag)) {\n const previous = flags[name]\n flags[name] = [...(Array.isArray(previous) ? previous : []), value]\n return\n }\n flags[name] = value\n}\n\nconst MAX_ATTEMPTS = 100\n\nconst MAX_PINNED_TRACE_IDS = 100\n\nconst INTERRUPT_EXIT_CODES: Record<ReplayInterruptSignal, number> = {\n SIGINT: 130,\n SIGTERM: 143,\n}\n\nconst RESUME_CONFLICTING_FLAGS: ReadonlyArray<[keyof ReplayCliArgs, string]> = [\n [\"traceIds\", \"--trace-ids\"],\n [\"datasetIds\", \"--dataset-ids\"],\n [\"limit\", \"--limit\"],\n [\"attempts\", \"--attempts\"],\n [\"graderIds\", \"--grader-ids\"],\n [\"onlyWithAssertions\", \"--only-with-assertions\"],\n [\"dryRun\", \"--dry-run\"],\n]\n\nconst RESUME_CLEARED_OPTIONS: Partial<ReplayOptions> = {\n traceIds: undefined,\n limit: undefined,\n datasetId: undefined,\n datasetIds: undefined,\n attempts: undefined,\n graderIds: undefined,\n onlyWithAssertions: undefined,\n dryRun: undefined,\n}\n\nfunction hasApprovedAssertion(\n assertions: { approvalState: ApprovalState }[],\n): boolean {\n return assertions.some((assertion) => assertion.approvalState === \"approved\")\n}\n\nasync function boundTraceIds(\n client: Bitfab,\n traceIds: string[],\n limit: number,\n onlyWithAssertions: boolean,\n): Promise<string[]> {\n if (!Number.isInteger(limit) || limit < 1) {\n throw new BitfabError(\"Replay limit must be a positive integer.\")\n }\n if (!onlyWithAssertions || limit >= traceIds.length) {\n return traceIds.slice(0, limit)\n }\n const selected: string[] = []\n for (const traceId of traceIds) {\n const { assertions, inheritedFrom } =\n await client.traces.getAssertions(traceId)\n if (inheritedFrom === null && hasApprovedAssertion(assertions)) {\n selected.push(traceId)\n if (selected.length === limit) {\n break\n }\n }\n }\n if (selected.length === 0) {\n throw new BitfabError(\n \"No traces with approved assertions matched this replay selection.\",\n )\n }\n return selected\n}\n\nasync function pinnedDatasetMembers(\n client: Bitfab,\n datasetIds: string[],\n limit: number,\n onlyWithAssertions = false,\n): Promise<string[] | undefined> {\n const members = new Set<string>()\n for (const datasetId of datasetIds) {\n const { traceIds } = await client.datasets.listTraces(datasetId)\n for (const traceId of traceIds) {\n members.add(traceId)\n }\n }\n const ordered = [...members].sort()\n if (limit >= ordered.length) {\n return undefined\n }\n if (limit > MAX_PINNED_TRACE_IDS) {\n throw new BitfabError(\n `Bounding a dataset replay to ${limit} names one trace ID per replayed item, and a replay accepts at most ${MAX_PINNED_TRACE_IDS}. Drop the limit to replay every selected dataset in full.`,\n )\n }\n return boundTraceIds(client, ordered, limit, onlyWithAssertions)\n}\n\nfunction usage(registry: ReplayRegistry | undefined): string {\n const pipelines =\n registry === undefined ? \"pipeline\" : Object.keys(registry).join(\"|\")\n return `Usage: bitfab-replay --registry <path> <${pipelines}> [options]\\n\\nOptions:\\n --limit N (bounds a trace ID or dataset selection instead of replacing it)\\n --attempts N (replay each trace N times in this run, max ${MAX_ATTEMPTS})\\n --trace-ids id1,id2\\n --name NAME (what this run is testing, such as \"baseline\"; Bitfab already records the commit, branch, and datasets)\\n --notes TEXT (run conditions Bitfab cannot see, such as a forced feature flag)\\n --metadata key=value (repeatable; tags kept on the experiment, such as which schedule launched it, and filterable through client.experiments.list)\\n --concurrency N, --max-concurrency N\\n --code-change PATH, --no-code-change\\n --experiment-group-id UUID (join this experiment group; a new UUID creates the group)\\n --experiment-group-name NAME (name the group when this run creates it or it has no name yet; requires --experiment-group-id)\\n --dataset-ids uuid1,uuid2 (--dataset-id is the same flag)\\n --grader-ids id1,id2\\n --only-with-assertions (replay only traces carrying an approved assertion)\\n --skip-assertion-judging (don't judge approved assertions on each replay; judging is on by default and costs model calls)\\n --judge-assertions (deprecated: judging is on by default)\\n --mock none|all|marked\\n --db-branch, --no-db-branch\\n --dry-run (resolve inputs, run nothing)\\n --fail-on-error (exit 1 after printing the result when any replayed item errored; under --dry-run, items whose inputs failed to resolve count)\\n --resume EXPERIMENT_ID (finish an experiment that stopped partway, running only the items it did not finish, with the traces, attempts, and graders it started with)\\n --force (with --resume, resume even when the experiment may still be running or the code changed since it started)\\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\nexport interface ReseedRegistryResult {\n pipeline: string\n traceFunctionKey: string\n reseeded: { traceId: string; previousRunTraceId: string }[]\n}\n\nexport async function reseedFromRegistry(\n registry: ReplayRegistry,\n pipeline: string,\n traceIds: readonly string[],\n): Promise<ReseedRegistryResult> {\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 const reseeded: ReseedRegistryResult[\"reseeded\"] = []\n for (const traceId of traceIds) {\n reseeded.push(\n await registration.client.reseedTrace(traceFunctionKey, registration.fn, {\n traceId,\n }),\n )\n }\n return { pipeline, traceFunctionKey, reseeded }\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-seed --registry <path> <pipeline> --from-trace <id>[,<id>...]\\n bitfab-seed --registry <path> <pipeline> --cases <cases.jsonl> [--run]\\n\\n--from-trace re-seeds each trace: the registered function runs once on the trace\\'s recorded inputs and the result is recorded under the same trace id, with the previous run kept as history under a new id. Nothing is mocked and no experiment is created. Labels, assertions, and dataset membership stay on the trace.\\n\\n--cases seeds new cases. Each case is a JSON object with an \"input\" array, plus optional \"expected\", \"metadata\", and \"sessionId\"; a JSON array of those objects works too. Without --run, each case is written as a trace directly (\"input\" becomes the root span input and \"expected\" its output) and nothing executes. With --run, each case runs 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\\nbitfab-replay --registry <path> <pipeline> --seed <cases.jsonl> [--run] is the older spelling of --cases.'\n\nexport async function runSeedCli(\n registry: ReplayRegistry,\n argv: readonly string[],\n io: ReplayCliIo = {},\n): Promise<SeedResult | ReseedRegistryResult> {\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 fromTraceIndex = argv.indexOf(\"--from-trace\")\n if (fromTraceIndex !== -1) {\n const raw = argv[fromTraceIndex + 1]\n if (raw === undefined || raw.startsWith(\"--\")) {\n throw new BitfabError(\"--from-trace requires one or more trace ids.\")\n }\n const traceIds = commaSeparated(\"--from-trace\", raw)\n stderr(\n `[seed] Re-seeding ${traceIds.length} trace(s) through \"${pipeline}\"...`,\n )\n const result = await reseedFromRegistry(registry, pipeline, traceIds)\n for (const entry of result.reseeded) {\n stderr(\n `[seed] ${entry.traceId} now holds the fresh run; the previous run is kept as ${entry.previousRunTraceId}`,\n )\n }\n stdout(JSON.stringify(result, null, 2))\n return result\n }\n const casesFlagIndex = argv.indexOf(\"--cases\")\n const seedIndex =\n casesFlagIndex === -1 ? argv.indexOf(\"--seed\") : casesFlagIndex\n if (seedIndex === -1) {\n throw new BitfabError(SEED_USAGE)\n }\n const casesPath = argv[seedIndex + 1]\n if (casesPath === undefined || casesPath.startsWith(\"--\")) {\n throw new BitfabError(`${argv[seedIndex]} 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\nexport function checkReplayCliArgs(argv: readonly string[]): void {\n parseReplayCliArgs(undefined, argv)\n}\n\nfunction parseReplayCliArgs(\n registry: ReplayRegistry | undefined,\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 (\n pipeline === undefined ||\n (registry !== undefined && registry[pipeline] === undefined)\n ) {\n throw new BitfabError(usage(registry))\n }\n\n const parsed: ReplayCliArgs = { pipeline, params: [], flags: {} }\n for (let index = 1; index < argv.length; index += 1) {\n const flag = argv[index]\n if (BOOLEAN_FLAGS.has(flag)) {\n recordFlag(parsed.flags, 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 \"--only-with-assertions\":\n // Left undefined when absent, never set to false: absence means the\n // command line said nothing, so a registry that set the option keeps\n // it. Only a present flag speaks.\n parsed.onlyWithAssertions = true\n break\n case \"--skip-assertion-judging\":\n parsed.skipAssertionJudging = true\n break\n case \"--judge-assertions\":\n parsed.judgeAssertionsFlag = true\n break\n case \"--no-code-change\":\n parsed.noCodeChange = true\n break\n case \"--dry-run\":\n parsed.dryRun = true\n break\n case \"--fail-on-error\":\n parsed.failOnError = true\n break\n case \"--force\":\n parsed.force = 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 recordFlag(parsed.flags, flag, raw)\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 \"--notes\":\n parsed.notes = raw\n break\n case \"--metadata\": {\n const [key, value] = parseMetadataTag(raw)\n parsed.metadata = { ...parsed.metadata, [key]: value }\n break\n }\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 \"--experiment-group-name\":\n parsed.experimentGroupName = raw\n break\n case \"--dataset-id\":\n case \"--dataset-ids\":\n parsed.datasetIds = commaSeparated(flag, 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 case \"--resume\":\n parsed.resume = raw\n break\n }\n }\n if (parsed.force === true && parsed.resume === undefined) {\n throw new BitfabError(\"--force only applies with --resume <experimentId>.\")\n }\n if (parsed.resume !== undefined) {\n const conflicting = RESUME_CONFLICTING_FLAGS.filter(\n ([key]) => parsed[key] !== undefined,\n ).map(([, flag]) => flag)\n if (conflicting.length > 0) {\n throw new BitfabError(\n `--resume reuses the traces, attempts, and graders experiment ${parsed.resume} started with, so it cannot be combined with ${conflicting.join(\", \")}.`,\n )\n }\n }\n if (parsed.traceIds !== undefined && parsed.datasetIds !== undefined) {\n throw new BitfabError(\n \"--trace-ids and --dataset-ids 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 resolveRegistrationDatasetIds(\n options: ReplayRegistryOptions,\n): string[] | undefined {\n if (options.datasetId !== undefined && options.datasetIds !== undefined) {\n throw new BitfabError(\n \"Replay registry options datasetId and datasetIds are the same selector: set one of them.\",\n )\n }\n if (options.datasetId !== undefined) {\n return [options.datasetId]\n }\n return options.datasetIds\n}\n\nfunction describeSelection(options: ReplayOptions): string {\n if (options.traceIds !== undefined) {\n return `${options.traceIds.length} traces`\n }\n if (options.limit !== undefined) {\n return `${options.limit} traces`\n }\n const datasetCount = options.datasetIds?.length ?? 1\n return datasetCount > 1\n ? `${datasetCount} datasets' traces`\n : \"dataset traces\"\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 parseMetadataTag(raw: string): [string, string] {\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 --metadata '${raw}': expected a non-empty key=value pair.`,\n )\n }\n return [key, raw.slice(separator + 1)]\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 let carriedOver = 0\n\n for (const item of result.items) {\n if (item.carriedOver === true) {\n carriedOver += 1\n continue\n }\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 - carriedOver}`)\n if (carriedOver > 0) {\n stderr(` Carried over from the earlier run: ${carriedOver}`)\n }\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.experimentUrl}`)\n}\n\nfunction countErroredItems(result: ReplayResult<unknown>): {\n errored: number\n replayed: number\n} {\n const replayed = result.items.filter((item) => item.carriedOver !== true)\n return {\n errored: replayed.filter((item) => item.error !== null).length,\n replayed: replayed.length,\n }\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 // Current servers record no experiment for a dry run; an older one still does.\n if (result.experimentUrl !== null) {\n stderr(`\\n ${result.experimentUrl}`)\n }\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 shellQuote(value: string): string {\n return /^[\\w@%+=:,./-]+$/.test(value)\n ? value\n : `'${value.replace(/'/g, `'\"'\"'`)}'`\n}\n\nfunction resumeCommand(\n registryPath: string | undefined,\n args: ReplayCliArgs,\n experimentId: string,\n): string {\n const carried = [\n ...(args.mock === undefined ? [] : [\"--mock\", args.mock]),\n ...(args.paramsPath === undefined ? [] : [\"--params\", args.paramsPath]),\n ...args.params.flatMap((param) => [\"--param\", param]),\n ]\n return [\n \"Resume with: bitfab-replay --registry\",\n registryPath === undefined ? \"<path>\" : shellQuote(registryPath),\n ...[args.pipeline, ...carried, \"--resume\", experimentId].map(shellQuote),\n ].join(\" \")\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\nconst API_KEY_LINE_PREFIX = \"@@bitfab:api-key \"\n\nconst PRINT_API_KEY_FLAG = \"--print-api-key\"\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 registryPath?: string,\n): Promise<ReplayResult<unknown> | null> {\n const stdout = io.stdout ?? console.log\n const stderr = io.stderr ?? console.error\n const printApiKey = argv.includes(PRINT_API_KEY_FLAG)\n const args = parseReplayCliArgs(\n registry,\n argv.filter((arg) => arg !== PRINT_API_KEY_FLAG),\n )\n if (printApiKey) {\n const client = registry[args.pipeline].client\n const apiKey = _resolvedApiKey(client)\n const serviceUrl = _serviceUrl(client)\n stdout(`${API_KEY_LINE_PREFIX}${JSON.stringify({ apiKey, serviceUrl })}`)\n return null\n }\n if (args.judgeAssertionsFlag) {\n warnJudgeAssertionsDeprecated(stderr)\n }\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 const registrationDatasetIds =\n resolveRegistrationDatasetIds(registrationOptions)\n if (\n registrationOptions.traceIds !== undefined &&\n registrationDatasetIds !== undefined\n ) {\n throw new BitfabError(\n \"Replay registry options traceIds and datasetIds select different sources and cannot be used together.\",\n )\n }\n const selectedDatasetIds = args.datasetIds ?? registrationDatasetIds\n const codeChange = await loadCodeChange(args.codeChangePath, readFile)\n let startedExperimentId: string | undefined\n\n const options: ReplayOptions = {\n ...registrationOptions,\n ...(args.name === undefined ? {} : { name: args.name }),\n ...(args.notes === undefined ? {} : { notes: args.notes }),\n ...(args.metadata === undefined ? {} : { metadata: args.metadata }),\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.experimentGroupName === undefined\n ? {}\n : { experimentGroupName: args.experimentGroupName }),\n datasetId: undefined,\n datasetIds: selectedDatasetIds,\n ...(args.graderIds === undefined ? {} : { graderIds: args.graderIds }),\n ...(args.onlyWithAssertions === undefined\n ? {}\n : { onlyWithAssertions: args.onlyWithAssertions }),\n ...(args.skipAssertionJudging === undefined\n ? {}\n : { skipAssertionJudging: args.skipAssertionJudging }),\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 onExperimentStart: ({ experimentId, experimentUrl }) => {\n startedExperimentId = experimentId\n stderr(`[replay] Experiment ${experimentId}: ${experimentUrl}`)\n },\n onInterrupt: ({ experimentId, signal, markedInterrupted }) => {\n stderr(\n `${describeReplayInterrupt(experimentId, markedInterrupted)} ${resumeCommand(registryPath, args, experimentId)}`,\n )\n process.exit(INTERRUPT_EXIT_CODES[signal])\n },\n }\n withCliFlags(options, args.flags)\n\n if (args.resume !== undefined) {\n Object.assign(options, RESUME_CLEARED_OPTIONS, {\n resume: args.resume,\n ...(args.force === true ? { force: true } : {}),\n })\n stderr(\n `[replay] Resuming experiment ${args.resume} of \"${traceFunctionKey}\"...`,\n )\n } else {\n if (args.traceIds !== undefined) {\n options.traceIds = args.traceIds\n options.datasetIds = undefined\n } else if (args.datasetIds !== undefined) {\n options.traceIds = undefined\n }\n\n const bound = args.limit ?? registrationOptions.limit\n options.limit = undefined\n\n if (options.traceIds !== undefined) {\n if (bound !== undefined) {\n options.traceIds = await boundTraceIds(\n registration.client,\n options.traceIds,\n bound,\n options.onlyWithAssertions === true,\n )\n }\n } else if (options.datasetIds !== undefined) {\n if (bound !== undefined) {\n const pinned = await pinnedDatasetMembers(\n registration.client,\n options.datasetIds,\n bound,\n options.onlyWithAssertions === true,\n )\n if (pinned !== undefined) {\n options.traceIds = pinned\n }\n }\n } else {\n options.limit = bound ?? 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\"} ${describeSelection(options)} from \"${traceFunctionKey}\"${attemptsSuffix}...`,\n )\n }\n\n let result: ReplayResult<unknown>\n try {\n result = await registration.client.replay(\n traceFunctionKey,\n registration.fn,\n options,\n )\n } catch (error) {\n if (error instanceof ReplayError) {\n reportReplayError(error, stderr)\n }\n const experimentId =\n error instanceof ReplayError ? error.experimentId : startedExperimentId\n if (experimentId !== undefined) {\n stderr(resumeCommand(registryPath, args, experimentId))\n }\n throw error\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 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 if (args.failOnError === true) {\n const { errored, replayed } = countErroredItems(result)\n if (errored > 0) {\n throw new BitfabError(\n `[replay] ${errored} of ${replayed} ${args.dryRun === true ? \"resolved\" : \"replayed\"} items errored; exiting 1 because of --fail-on-error`,\n )\n }\n }\n return result\n}\n","import { register } from \"tsx/esm/api\"\nimport { BitfabError } from \"./errors.js\"\nimport { ReplayError } from \"./replay.js\"\nimport {\n ReplayCliHelp,\n type ReplayCliIo,\n type ReplayRegistry,\n validateReplayRegistry,\n} from \"./replayRegistry.js\"\n\nexport type RegistryImporter = (path: string) => Promise<unknown>\n\nlet isTypeScriptLoaderRegistered = false\n\nexport async function parseRegistryCommandArgs(\n argv: readonly string[],\n usage: string,\n): Promise<{ registryPath: string; commandArgs: string[] }> {\n if (\n argv.some((value) => value === \"--help\" || value === \"-h\") &&\n !argv.includes(\"--registry\")\n ) {\n throw new ReplayCliHelp(usage)\n }\n const registryFlagIndex = argv.indexOf(\"--registry\")\n const registryPath = argv[registryFlagIndex + 1]\n if (\n registryFlagIndex === -1 ||\n registryPath === undefined ||\n registryPath.startsWith(\"--\")\n ) {\n throw new BitfabError(usage)\n }\n\n const commandArgs = argv.filter(\n (_value, index) =>\n index !== registryFlagIndex && index !== registryFlagIndex + 1,\n )\n if (commandArgs.length === 0) {\n throw new BitfabError(usage)\n }\n const { resolve } = await import(\"node:path\")\n return { registryPath: resolve(registryPath), commandArgs }\n}\n\nexport async function importRegistry(path: string): Promise<unknown> {\n const { pathToFileURL } = await import(\"node:url\")\n if (!isTypeScriptLoaderRegistered) {\n register()\n isTypeScriptLoaderRegistered = true\n }\n try {\n return await import(pathToFileURL(path).href)\n } catch (error) {\n if (isModuleNotFoundError(error)) {\n throw new BitfabError(`${error.message}\\n\\n${registryImportHint(path)}`)\n }\n throw error\n }\n}\n\nfunction isModuleNotFoundError(error: unknown): error is Error {\n const code = (error as { code?: unknown } | null)?.code\n return (\n error instanceof Error &&\n (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\")\n )\n}\n\nfunction registryImportHint(path: string): string {\n return [\n `The replay registry '${path}' could not load one of its imports.`,\n \"A registry belongs in the package that builds the traced function's call and already depends on everything it imports (its tools, clients, and config), and bitfab-replay runs from that package's directory.\",\n \"When the traced function lives in a lower-level library that an app package calls, put the registry in the app package and add @bitfab/sdk to it. Copying the app's dependencies into the library is the wrong fix.\",\n `See \"When the traced function needs the app's dependencies\" at https://docs.bitfab.ai/typescript-sdk.`,\n ].join(\"\\n\")\n}\n\nexport function resolveRegistry(\n moduleValue: unknown,\n path: string,\n): ReplayRegistry {\n if (typeof moduleValue !== \"object\" || moduleValue === null) {\n throw new BitfabError(\n `Replay registry '${path}' must export a default registry.`,\n )\n }\n\n const registry = (moduleValue as { default?: unknown }).default\n if (typeof registry !== \"object\" || registry === null) {\n throw new BitfabError(\n `Replay registry '${path}' must export a default registry.`,\n )\n }\n validateReplayRegistry(registry as ReplayRegistry)\n return registry as ReplayRegistry\n}\n\nexport async function runRegistryMain(\n run: () => Promise<unknown>,\n io: ReplayCliIo = {},\n): Promise<number> {\n const stdout = io.stdout ?? console.log\n const stderr = io.stderr ?? console.error\n try {\n await run()\n return 0\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (error instanceof ReplayCliHelp) {\n stdout(message)\n return 0\n }\n if (error instanceof ReplayError) {\n stderr(`Experiment ${error.experimentId}: ${error.experimentUrl}`)\n }\n stderr(message)\n return 1\n }\n}\n\nasync function isEntrypoint(moduleUrl: string): Promise<boolean> {\n const executablePath = process.argv[1]\n if (executablePath === undefined) {\n return false\n }\n const [{ realpath }, { fileURLToPath }] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:url\"),\n ])\n return (\n (await realpath(executablePath)) ===\n (await realpath(fileURLToPath(moduleUrl)))\n )\n}\n\nexport function runIfEntrypoint(\n moduleUrl: string,\n main: () => Promise<number>,\n): void {\n void isEntrypoint(moduleUrl).then((entrypoint) => {\n if (entrypoint) {\n void main().then((exitCode) => {\n process.exitCode = exitCode\n })\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,IAAa,cAAb,cAAiC,MAAM;CACrC,YACE,SACA,KAOA,QAMA,cACA;EACA,MAAM,OAAO;EAfG,KAAA,MAAA;EAOA,KAAA,SAAA;EAMA,KAAA,eAAA;EAGhB,KAAK,OAAO;CACd;AACF;CCSE,OAAO,YAAY,eAAe,QAAQ,UAAU,OAKhD;;CAEE,CAAC,QAAQ,MAAM,CAAC,CAAC,KAAK,GAAG;CAC1B,CACE,MAAM,EAAE,WAAqB,CAW9B,CAAC,CAAC,CACD,YAAY,CAAC,CAAC,IACjB,QAAQ,QAAQ,EAAA,CACpB,WAAW,CAAC,CAAC;;;ACxBf,IAAI,yBACF;AAWF,SAAgB,+BACd,KACM;CACN,IAAI,CAAC,wBACH,yBAAyB;AAG7B;AAoBA,MAAa,qBACX,OAAO,YAAY,eAAe,QAAQ,UAAU;;AAKhD;;CAEE,CAAC,QAAQ,aAAa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