@bitfab/sdk 0.61.2 → 0.61.3

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.
Files changed (41) hide show
  1. package/dist/autoTrace.cjs.map +1 -1
  2. package/dist/autoTrace.d.cts +1 -0
  3. package/dist/autoTrace.d.ts +1 -0
  4. package/dist/autoTrace.js +1 -1
  5. package/dist/{chunk-X5DRPZJJ.js → chunk-34UFYAE6.js} +306 -7
  6. package/dist/chunk-34UFYAE6.js.map +1 -0
  7. package/dist/{chunk-SJPMWVJ3.js → chunk-65QKCHI2.js} +7 -3
  8. package/dist/chunk-65QKCHI2.js.map +1 -0
  9. package/dist/{chunk-IR5KCKHF.js → chunk-7BU5LUMR.js} +6 -3
  10. package/dist/chunk-7BU5LUMR.js.map +1 -0
  11. package/dist/{chunk-BMJNDIVA.js → chunk-K4XCWQBC.js} +1 -1
  12. package/dist/chunk-K4XCWQBC.js.map +1 -0
  13. package/dist/{chunk-DSVQPSAL.js → chunk-OWXP3YXA.js} +3 -3
  14. package/dist/chunk-OWXP3YXA.js.map +1 -0
  15. package/dist/{chunk-HNEKBDI7.js → chunk-TZSTKVZF.js} +38 -7
  16. package/dist/chunk-TZSTKVZF.js.map +1 -0
  17. package/dist/{http-OEABHRHY.js → http-VTIALK4P.js} +2 -2
  18. package/dist/{http-RNI6PKQ3.js → http-ZWENQXQA.js} +2 -2
  19. package/dist/index.cjs +355 -7
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +120 -3
  22. package/dist/index.d.ts +120 -3
  23. package/dist/index.js +4 -4
  24. package/dist/node.cjs +355 -7
  25. package/dist/node.cjs.map +1 -1
  26. package/dist/node.d.cts +1 -1
  27. package/dist/node.d.ts +1 -1
  28. package/dist/node.js +4 -4
  29. package/dist/{replay-3ERB6W6N.js → replay-YQG3OGDN.js} +3 -3
  30. package/dist/replayCli.js +2 -2
  31. package/dist/seedCli.js +2 -2
  32. package/package.json +1 -1
  33. package/dist/chunk-BMJNDIVA.js.map +0 -1
  34. package/dist/chunk-DSVQPSAL.js.map +0 -1
  35. package/dist/chunk-HNEKBDI7.js.map +0 -1
  36. package/dist/chunk-IR5KCKHF.js.map +0 -1
  37. package/dist/chunk-SJPMWVJ3.js.map +0 -1
  38. package/dist/chunk-X5DRPZJJ.js.map +0 -1
  39. /package/dist/{http-OEABHRHY.js.map → http-VTIALK4P.js.map} +0 -0
  40. /package/dist/{http-RNI6PKQ3.js.map → http-ZWENQXQA.js.map} +0 -0
  41. /package/dist/{replay-3ERB6W6N.js.map → replay-YQG3OGDN.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/autoTrace.ts","../src/asyncStorage.ts","../src/captureSuppression.ts","../src/warnOnce.ts"],"sourcesContent":["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 // 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 AutoTraceScope {\n entries: readonly AutoTraceEntry[]\n nodeConfiguration?: AutoTraceNodeConfiguration\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\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 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","/**\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","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 * 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\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmCA,IAAI,yBACF;AACF,IAAI,WAAW;AAUR,SAAS,+BACd,KACM;AACN,MAAI,CAAC,wBAAwB;AAC3B,6BAAyB;AAAA,EAC3B;AACA,aAAW;AACb;AAoBO,IAAM,qBACX,OAAO,YAAY,eAAe,QAAQ,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA,EAKhD;AAAA;AAAA,IAEE,CAAC,QAAQ,aAAa,EAAE,KAAK,GAAG;AAAA,IAE/B;AAAA,IACC,CAAC,QAEK;AACJ,qCAA+B,IAAI,iBAAiB;AAAA,IACtD;AAAA,EACF,EACC,MAAM,MAAM;AAAA,EAAC,CAAC;AAAA,IACjB,QAAQ,QAAQ,GACpB,KAAK,MAAM;AACX,aAAW;AACb,CAAC;AAMM,SAAS,0BAA8D;AAC5E,SAAO,yBACF,IAAI,uBAAuB,IAC5B;AACN;;;ACjGA,IAAM,oBAAoB;AAC1B,IAAM,mBACJ,kBAAkB,gCAAgC,EAAE,OAAO,EAAE;AAC/D,kBAAkB,+BAA+B;AAE1C,SAAS,sBAA+B;AAC7C,SAAO,iBAAiB,QAAQ;AAClC;;;ACDA,IAAM,SAAS,oBAAI,IAAY;AAExB,SAAS,KAAK,SAAuB;AAC1C,MAAI;AACF,YAAQ,KAAK,YAAY,OAAO,EAAE;AAAA,EACpC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BAAiB,QAAW;AAC9B,aAAO,eAAe,IAAI,QAAQ;AAAA,QAChC,cAAc;AAAA,QACd,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,SAAS;AACf,SAAO,IAAI,MAAM,QAAQ;AAAA,IACvB,MAAM,YAAY,SAAS,MAAM;AAC/B,UAAI,CAAC,wBAAwB,GAAG;AAC9B,eAAO,QAAQ,MAAM,YAAY,SAAS,IAAI;AAAA,MAChD;AACA,aAAO;AAAA,QAAiB;AAAA,QAAY;AAAA,QAAM,MACxC,QAAQ,MAAM,YAAY,SAAS,IAAI;AAAA,MACzC;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAWO,SAAS,0BAAmC;AACjD,MAAI,eAAe,gBAAgB,KAAK,oBAAoB,GAAG;AAC7D,WAAO;AAAA,EACT;AACA,SAAO,wBAAwB,EAAE,SAAS;AAC5C;AAEA,SAAS,wBAAoD;AAC3D,6BAA2B;AAC3B,SAAO,eAAe,SAAS,SAAS,KAAK,eAAe;AAC9D;AAEO,SAAS,oCAA0C;AACxD,kBAAgB,uCAAuC;AACzD;","names":[]}
1
+ {"version":3,"sources":["../src/autoTrace.ts","../src/asyncStorage.ts","../src/captureSuppression.ts","../src/warnOnce.ts"],"sourcesContent":["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 AutoTraceScope {\n entries: readonly AutoTraceEntry[]\n nodeConfiguration?: AutoTraceNodeConfiguration\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\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 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","/**\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","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 * 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\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmCA,IAAI,yBACF;AACF,IAAI,WAAW;AAUR,SAAS,+BACd,KACM;AACN,MAAI,CAAC,wBAAwB;AAC3B,6BAAyB;AAAA,EAC3B;AACA,aAAW;AACb;AAoBO,IAAM,qBACX,OAAO,YAAY,eAAe,QAAQ,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA,EAKhD;AAAA;AAAA,IAEE,CAAC,QAAQ,aAAa,EAAE,KAAK,GAAG;AAAA,IAE/B;AAAA,IACC,CAAC,QAEK;AACJ,qCAA+B,IAAI,iBAAiB;AAAA,IACtD;AAAA,EACF,EACC,MAAM,MAAM;AAAA,EAAC,CAAC;AAAA,IACjB,QAAQ,QAAQ,GACpB,KAAK,MAAM;AACX,aAAW;AACb,CAAC;AAMM,SAAS,0BAA8D;AAC5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iBAAiB,IACrC;AACN,SAAO;AAAA,IACL,MAAM;AAAA,IACN,CAAC,OAAO,SACN,MAAM,QAAQ,OAAO,YAAY,QAAQ,MAAM,OAAO,iBAAiB;AAAA,IACzE;AAAA,EACF;AACF;AAYO,SAAS,iBACd,YACA,IACG;AACH,wBAAsB;AACtB,MAAI,GAAG,SAAS,IAAI;AAClB,UAAM,YAAY,WAAW,KAAK,MAAM,GAAG;AAC3C,UAAM,eAAe,UAAU,UAAU,SAAS,CAAC;AACnD,QAAI,iBAAiB,QAAW;AAC9B,aAAO,eAAe,IAAI,QAAQ;AAAA,QAChC,cAAc;AAAA,QACd,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,SAAS;AACf,SAAO,IAAI,MAAM,QAAQ;AAAA,IACvB,MAAM,YAAY,SAAS,MAAM;AAC/B,UAAI,CAAC,wBAAwB,GAAG;AAC9B,eAAO,QAAQ,MAAM,YAAY,SAAS,IAAI;AAAA,MAChD;AACA,aAAO;AAAA,QAAiB;AAAA,QAAY;AAAA,QAAM,MACxC,QAAQ,MAAM,YAAY,SAAS,IAAI;AAAA,MACzC;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAWO,SAAS,0BAAmC;AACjD,MAAI,eAAe,gBAAgB,KAAK,oBAAoB,GAAG;AAC7D,WAAO;AAAA,EACT;AACA,SAAO,wBAAwB,EAAE,SAAS;AAC5C;AAEA,SAAS,wBAAoD;AAC3D,6BAA2B;AAC3B,SAAO,eAAe,SAAS,SAAS,KAAK,eAAe;AAC9D;AAEO,SAAS,oCAA0C;AACxD,kBAAgB,uCAAuC;AACzD;","names":[]}
@@ -16,6 +16,7 @@ interface AutoTraceNodeConfiguration {
16
16
  /** @deprecated Use experimentId. */
17
17
  testRunId?: string;
18
18
  mockOnReplay?: boolean;
19
+ replayReusable?: boolean;
19
20
  finalize?: (result: any) => unknown | Promise<unknown>;
20
21
  }
21
22
  interface NestedTraceLink {
@@ -16,6 +16,7 @@ interface AutoTraceNodeConfiguration {
16
16
  /** @deprecated Use experimentId. */
17
17
  testRunId?: string;
18
18
  mockOnReplay?: boolean;
19
+ replayReusable?: boolean;
19
20
  finalize?: (result: any) => unknown | Promise<unknown>;
20
21
  }
21
22
  interface NestedTraceLink {
package/dist/autoTrace.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  runWithAutoTraceEntry,
10
10
  runWithAutoTraceNodeConfiguration,
11
11
  runWithAutoTraceRootContext
12
- } from "./chunk-BMJNDIVA.js";
12
+ } from "./chunk-K4XCWQBC.js";
13
13
  import "./chunk-BAOIRE5T.js";
14
14
  export {
15
15
  __bitfabAutoSpan,
@@ -5,7 +5,7 @@ import {
5
5
  gitRunner,
6
6
  replayContextReady,
7
7
  runWithReplayContext
8
- } from "./chunk-SJPMWVJ3.js";
8
+ } from "./chunk-65QKCHI2.js";
9
9
  import {
10
10
  runWithCaptureSuppressed,
11
11
  warnOnce
@@ -437,6 +437,278 @@ function fallbackUuidV4() {
437
437
  });
438
438
  }
439
439
 
440
+ // src/selectiveReplay.ts
441
+ function replayNodeKey(node) {
442
+ return JSON.stringify([node.traceFunctionKey, node.spanName]);
443
+ }
444
+ function jsonFingerprint(value) {
445
+ const seen = /* @__PURE__ */ new Set();
446
+ function encode(input) {
447
+ if (input === null || typeof input === "boolean") {
448
+ return JSON.stringify(input);
449
+ }
450
+ if (typeof input === "string" && !input.startsWith("<unserializable")) {
451
+ return JSON.stringify(input);
452
+ }
453
+ if (typeof input === "number" && Number.isFinite(input) && !Object.is(input, -0)) {
454
+ return JSON.stringify(input);
455
+ }
456
+ if (typeof input !== "object" || input === null || seen.has(input)) {
457
+ throw new Error("Not a lossless JSON value");
458
+ }
459
+ seen.add(input);
460
+ const prototype = Object.getPrototypeOf(input);
461
+ if (prototype !== (Array.isArray(input) ? Array.prototype : Object.prototype)) {
462
+ throw new Error("Not a plain JSON object");
463
+ }
464
+ if (Object.getOwnPropertySymbols(input).length > 0) {
465
+ throw new Error("Symbol properties are not recorded");
466
+ }
467
+ const keys = Object.keys(input);
468
+ if (Object.getOwnPropertyNames(input).length !== keys.length + (Array.isArray(input) ? 1 : 0)) {
469
+ throw new Error("Non-enumerable properties are not recorded");
470
+ }
471
+ if (Array.isArray(input) && (keys.length !== input.length || keys.some((key, index) => key !== String(index)))) {
472
+ throw new Error("Not a dense JSON array");
473
+ }
474
+ const properties = keys.map((key) => {
475
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
476
+ if (!descriptor || !("value" in descriptor)) {
477
+ throw new Error("Accessor properties are not replay inputs");
478
+ }
479
+ return `${Array.isArray(input) ? "" : `${JSON.stringify(key)}:`}${encode(descriptor.value)}`;
480
+ });
481
+ return Array.isArray(input) ? `[${properties.join(",")}]` : `{${properties.join(",")}}`;
482
+ }
483
+ try {
484
+ return encode(value);
485
+ } catch {
486
+ return void 0;
487
+ }
488
+ }
489
+
490
+ // src/selectiveReplayRuntime.ts
491
+ function validateSelectiveReplayOptions(options) {
492
+ const validNodes = (nodes) => Array.isArray(nodes) && nodes.length <= 100 && nodes.every(
493
+ (node) => typeof node?.traceFunctionKey === "string" && node.traceFunctionKey.length > 0 && node.traceFunctionKey.length <= 500 && typeof node.spanName === "string" && node.spanName.length > 0 && node.spanName.length <= 500
494
+ );
495
+ if (!options || !validNodes(options.mustRun) || options.mustRun.length === 0 || Object.keys(options).some((key) => key !== "mustRun")) {
496
+ throw new BitfabError(
497
+ "experimentalSelectiveReplay accepts only 1\u2013100 mustRun with traceFunctionKey and spanName. Declare replayReusable on eligible spans, not reusableNodes in the replay request."
498
+ );
499
+ }
500
+ }
501
+ function policyKey(options) {
502
+ return JSON.stringify(options.mustRun.map(replayNodeKey).sort());
503
+ }
504
+ var SelectiveReplayRuntime = class {
505
+ constructor(plan, options) {
506
+ this.plan = plan;
507
+ this.options = options;
508
+ this.nodes = /* @__PURE__ */ new Map();
509
+ this.children = /* @__PURE__ */ new Map();
510
+ this.runtimeParents = /* @__PURE__ */ new Map();
511
+ this.consumed = /* @__PURE__ */ new Map();
512
+ this.requiredScopes = /* @__PURE__ */ new Set();
513
+ this.recordings = /* @__PURE__ */ new Map();
514
+ this.reached = /* @__PURE__ */ new Set();
515
+ this.decisions = [];
516
+ this.assertionNames = /* @__PURE__ */ new Set();
517
+ this.assertionScopes = /* @__PURE__ */ new Set();
518
+ this.observedNames = /* @__PURE__ */ new Map();
519
+ this.unresolvedAssertions = [];
520
+ validateSelectiveReplayOptions(options);
521
+ if (plan?.version !== 4 || !Array.isArray(plan.nodes) || plan.nodes.length === 0 || plan.nodes.length > 500 || !Array.isArray(plan.unresolvedMustRun) || !Array.isArray(plan.assertions) || !plan.options) {
522
+ throw new BitfabError(
523
+ "Server did not return a compatible selective replay plan. Update the server or disable experimentalSelectiveReplay."
524
+ );
525
+ }
526
+ validateSelectiveReplayOptions(plan.options);
527
+ if (policyKey(plan.options) !== policyKey(options)) {
528
+ throw new BitfabError(
529
+ "Selective replay plan does not match the requested mustRun nodes."
530
+ );
531
+ }
532
+ this.required = new Set(options.mustRun.map(replayNodeKey));
533
+ for (const node of plan.nodes) {
534
+ if (typeof node.id !== "string" || this.nodes.has(node.id) || typeof node.traceFunctionKey !== "string" || typeof node.spanName !== "string" || typeof node.mustRun !== "boolean" || typeof node.reusable !== "boolean") {
535
+ throw new BitfabError("Invalid selective replay node.");
536
+ }
537
+ this.nodes.set(node.id, node);
538
+ if (node.recording !== void 0) {
539
+ this.recordings.set(node.id, {
540
+ input: node.recording.kwargs === void 0 ? jsonFingerprint(node.recording.input) : void 0,
541
+ output: jsonFingerprint(node.recording.output)
542
+ });
543
+ }
544
+ if (node.parentId !== null) {
545
+ const siblings = this.children.get(node.parentId) ?? [];
546
+ siblings.push(node);
547
+ this.children.set(node.parentId, siblings);
548
+ }
549
+ }
550
+ const root = this.nodes.get(plan.rootId);
551
+ if (!root || root.parentId !== null || !root.mustRun) {
552
+ throw new BitfabError("Selective replay requires a live recorded root.");
553
+ }
554
+ const assertionIds = /* @__PURE__ */ new Set();
555
+ let wholeTrace = false;
556
+ for (const assertion of plan.assertions) {
557
+ const target = assertion?.target;
558
+ if (typeof assertion?.id !== "string" || assertion.id.length === 0 || assertionIds.has(assertion.id) || target !== null && (typeof target !== "object" || target.kind !== "output" && target.kind !== "span")) {
559
+ throw new BitfabError(
560
+ "Invalid selective replay assertion requirements."
561
+ );
562
+ }
563
+ assertionIds.add(assertion.id);
564
+ if (target === null) {
565
+ wholeTrace = true;
566
+ } else if (target.kind === "span") {
567
+ if (typeof target.name !== "string" || target.name.length === 0 || target.occurrence !== void 0 && target.occurrence !== "first" && target.occurrence !== "last" && !(Number.isInteger(target.occurrence) && typeof target.occurrence === "number" && target.occurrence >= 0)) {
568
+ throw new BitfabError("Invalid selective replay assertion target.");
569
+ }
570
+ this.assertionNames.add(target.name);
571
+ const count = plan.nodes.filter(
572
+ (node) => node.spanName === target.name
573
+ ).length;
574
+ if (count <= (typeof target.occurrence === "number" ? target.occurrence : 0)) {
575
+ this.unresolvedAssertions.push(assertion.id);
576
+ }
577
+ }
578
+ }
579
+ this.fullTraceForAssertions = wholeTrace || this.unresolvedAssertions.length > 0;
580
+ const recordedKeys = new Set(plan.nodes.map(replayNodeKey));
581
+ const unresolved = options.mustRun.filter(
582
+ (node) => !recordedKeys.has(replayNodeKey(node))
583
+ );
584
+ if (JSON.stringify(unresolved.map(replayNodeKey).sort()) !== JSON.stringify(plan.unresolvedMustRun.map(replayNodeKey).sort())) {
585
+ throw new BitfabError(
586
+ "Selective replay plan has incomplete mustRun coverage."
587
+ );
588
+ }
589
+ for (const node of plan.nodes) {
590
+ const ancestors = /* @__PURE__ */ new Set([node.id]);
591
+ let requiredByManifest = this.required.has(replayNodeKey(node));
592
+ let requiredForAssertion = this.fullTraceForAssertions || this.assertionNames.has(node.spanName);
593
+ let parentId = node.parentId;
594
+ while (parentId !== null) {
595
+ const parent = this.nodes.get(parentId);
596
+ if (!parent || ancestors.has(parentId) || node.mustRun && !parent.mustRun) {
597
+ throw new BitfabError("Invalid selective replay ancestry.");
598
+ }
599
+ ancestors.add(parentId);
600
+ requiredByManifest || (requiredByManifest = this.required.has(replayNodeKey(parent)));
601
+ requiredForAssertion || (requiredForAssertion = this.assertionNames.has(parent.spanName));
602
+ parentId = parent.parentId;
603
+ }
604
+ if (!ancestors.has(plan.rootId) || (requiredByManifest || unresolved.length > 0) && !node.mustRun) {
605
+ throw new BitfabError("Selective replay plan could hide required code.");
606
+ }
607
+ if (requiredForAssertion && !node.mustRun) {
608
+ throw new BitfabError(
609
+ "Selective replay plan could hide assertion evidence."
610
+ );
611
+ }
612
+ }
613
+ }
614
+ enter(params) {
615
+ const identity = {
616
+ traceFunctionKey: params.traceFunctionKey,
617
+ spanName: params.spanName
618
+ };
619
+ const key = replayNodeKey(identity);
620
+ const fingerprint = jsonFingerprint(params.inputs);
621
+ let node;
622
+ let matchReason = "unmatched-call";
623
+ if (params.parentSpanId === null) {
624
+ node = this.nodes.get(this.plan.rootId);
625
+ } else {
626
+ const recordedParent = this.runtimeParents.get(params.parentSpanId);
627
+ const consumed = this.consumed.get(params.parentSpanId) ?? /* @__PURE__ */ new Set();
628
+ this.consumed.set(params.parentSpanId, consumed);
629
+ const candidates = recordedParent ? (this.children.get(recordedParent) ?? []).filter(
630
+ (candidate) => replayNodeKey(candidate) === key && !consumed.has(candidate.id)
631
+ ) : [];
632
+ const exact = fingerprint === void 0 ? [] : candidates.filter(
633
+ (candidate) => this.recordings.get(candidate.id)?.input === fingerprint
634
+ );
635
+ node = exact.length === 1 ? exact[0] : exact.length === 0 && candidates.length === 1 ? candidates[0] : void 0;
636
+ if (node) {
637
+ consumed.add(node.id);
638
+ } else if (candidates.length > 0) {
639
+ matchReason = "ambiguous-call";
640
+ for (const candidate of candidates) {
641
+ consumed.add(candidate.id);
642
+ }
643
+ }
644
+ }
645
+ this.runtimeParents.set(params.spanId, node?.id ?? null);
646
+ const requiredByManifest = this.required.has(key) || params.parentSpanId !== null && this.requiredScopes.has(params.parentSpanId);
647
+ if (requiredByManifest) {
648
+ this.requiredScopes.add(params.spanId);
649
+ }
650
+ const requiredForAssertion = this.fullTraceForAssertions || this.assertionNames.has(params.spanName) || params.parentSpanId !== null && this.assertionScopes.has(params.parentSpanId);
651
+ if (requiredForAssertion) {
652
+ this.assertionScopes.add(params.spanId);
653
+ }
654
+ const mustRun = params.parentSpanId === null || requiredByManifest || node?.mustRun === true || requiredForAssertion || this.plan.unresolvedMustRun.length > 0;
655
+ const recording = node === void 0 ? void 0 : this.recordings.get(node.id);
656
+ const equalInputs = fingerprint !== void 0 && recording?.input === fingerprint;
657
+ const reusable = recording?.output !== void 0 && equalInputs && params.canReuseOutput;
658
+ const reason = mustRun ? requiredByManifest ? "must-run" : requiredForAssertion ? "assertion" : node?.reason ?? "unresolved-must-run" : !node ? matchReason : !equalInputs ? "input-drift-or-missing-recording" : !params.canReuseOutput ? "unsupported-output-boundary" : !params.safetyMock && !params.reuseAllowed ? "reuse-not-declared" : node.reason;
659
+ const decision = (action, why) => {
660
+ this.decisions.push({
661
+ ...identity,
662
+ originalSpanId: node?.id ?? null,
663
+ action,
664
+ reason: why
665
+ });
666
+ };
667
+ if (params.safetyMock && (mustRun || !reusable)) {
668
+ decision("blocked", `safety-conflict:${reason}`);
669
+ this.failure = new BitfabError(
670
+ `Selective replay cannot execute or safely reuse safety-mocked node ${params.spanName} (${reason}).`
671
+ );
672
+ throw this.failure;
673
+ }
674
+ if (!mustRun && reusable && (params.safetyMock || node?.reusable === true && params.reuseAllowed)) {
675
+ decision("mock", params.safetyMock ? "safety-mock" : "unchanged-inputs");
676
+ return {
677
+ mock: true,
678
+ output: JSON.parse(recording.output)
679
+ };
680
+ }
681
+ decision("run", reason);
682
+ this.observedNames.set(
683
+ params.spanName,
684
+ (this.observedNames.get(params.spanName) ?? 0) + 1
685
+ );
686
+ if (this.required.has(key)) {
687
+ this.reached.add(key);
688
+ }
689
+ return { mock: false };
690
+ }
691
+ assertNoSafetyConflict() {
692
+ if (this.failure) {
693
+ throw this.failure;
694
+ }
695
+ }
696
+ report() {
697
+ return {
698
+ decisions: this.decisions,
699
+ mustRunNotReached: this.options.mustRun.filter(
700
+ (node) => !this.reached.has(replayNodeKey(node))
701
+ ),
702
+ unresolvedMustRun: this.plan.unresolvedMustRun,
703
+ assertionIds: this.plan.assertions.map((assertion) => assertion.id),
704
+ unresolvedAssertions: this.unresolvedAssertions,
705
+ assertionTargetsNotReached: this.plan.assertions.flatMap(
706
+ ({ id, target }) => target?.kind === "span" && (this.observedNames.get(target.name) ?? 0) <= (typeof target.occurrence === "number" ? target.occurrence : 0) ? [id] : []
707
+ )
708
+ };
709
+ }
710
+ };
711
+
440
712
  // src/replay.ts
441
713
  var REPLAY_PERSISTENCE_TIMEOUT_MS = 3e4;
442
714
  var MAX_REPLAY_ATTEMPTS = 100;
@@ -454,7 +726,8 @@ var RESUME_CONFLICTING_OPTIONS = [
454
726
  "attempts",
455
727
  "graderIds",
456
728
  "onlyWithAssertions",
457
- "dryRun"
729
+ "dryRun",
730
+ "experimentalSelectiveReplay"
458
731
  ];
459
732
  var CARRIED_OVER_ERROR = "This item errored in an earlier run of this experiment, before it was resumed.";
460
733
  function validateResume(resume, options) {
@@ -715,7 +988,7 @@ function buildMockTree(rootNode) {
715
988
  }
716
989
  return { spans };
717
990
  }
718
- async function processItem(httpClient, serverItem, fn, experimentId, mockStrategy, resolvedOverrides, replayedTraceId, attempt, includeDbBranchLease, dbBranchSettings, adaptInputs, dryRun) {
991
+ async function processItem(httpClient, serverItem, fn, experimentId, mockStrategy, resolvedOverrides, replayedTraceId, attempt, includeDbBranchLease, dbBranchSettings, adaptInputs, dryRun, selectiveOptions) {
719
992
  let lease = includeDbBranchLease ? serverItem.dbBranchLease : void 0;
720
993
  let leaseError = includeDbBranchLease ? serverItem.dbBranchLeaseError : void 0;
721
994
  let dbSnapshotRef = serverItem.dbSnapshotRef;
@@ -728,6 +1001,7 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
728
1001
  let replayError = null;
729
1002
  let replayDurationMs = null;
730
1003
  let replayStarted = null;
1004
+ let selectiveReplay;
731
1005
  const originalTraceId = serverItem.originalTraceId ?? serverItem.sourceTraceId;
732
1006
  const originalSpanId = serverItem.originalSpanId ?? serverItem.sourceSpanId;
733
1007
  try {
@@ -760,6 +1034,17 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
760
1034
  originalTraceId
761
1035
  );
762
1036
  }
1037
+ if (selectiveOptions !== void 0) {
1038
+ if (serverItem.selectiveReplayPlan === void 0) {
1039
+ throw new BitfabError(
1040
+ "Server did not return a selective replay plan. Update the server or disable experimentalSelectiveReplay."
1041
+ );
1042
+ }
1043
+ selectiveReplay = new SelectiveReplayRuntime(
1044
+ serverItem.selectiveReplayPlan,
1045
+ selectiveOptions
1046
+ );
1047
+ }
763
1048
  const span = await httpClient.getExternalSpan(originalSpanId, {
764
1049
  view: "replay"
765
1050
  });
@@ -779,7 +1064,7 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
779
1064
  });
780
1065
  }
781
1066
  const hasOverrides = resolvedOverrides.length > 0;
782
- const needTree = mockStrategy === "all" || mockStrategy === "marked" || hasOverrides;
1067
+ const needTree = selectiveReplay === void 0 && (mockStrategy === "all" || mockStrategy === "marked" || hasOverrides);
783
1068
  const includeOutputs = mockStrategy === "all";
784
1069
  let mockTree;
785
1070
  if (needTree) {
@@ -854,6 +1139,7 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
854
1139
  sourceBitfabTraceId: originalTraceId,
855
1140
  replayAttempt: attempt,
856
1141
  mockTree,
1142
+ selectiveReplay,
857
1143
  callCounters: mockTree ? /* @__PURE__ */ new Map() : void 0,
858
1144
  mockStrategy,
859
1145
  mockOverrides: hasOverrides ? resolvedOverrides : void 0,
@@ -865,6 +1151,7 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
865
1151
  () => fn(...inputs)
866
1152
  );
867
1153
  result = maybePromise instanceof Promise ? await maybePromise : maybePromise;
1154
+ selectiveReplay?.assertNoSafetyConflict();
868
1155
  replayDurationMs = Math.round(performance.now() - replayStarted);
869
1156
  } catch (e) {
870
1157
  if (replayStarted !== null) {
@@ -916,6 +1203,7 @@ async function processItem(httpClient, serverItem, fn, experimentId, mockStrateg
916
1203
  traceError,
917
1204
  replayError,
918
1205
  durationMs: replayDurationMs,
1206
+ ...selectiveReplay === void 0 ? {} : { selectiveReplay: selectiveReplay.report() },
919
1207
  originalDurationMs,
920
1208
  originalTokens: serverItem.originalTokens ?? serverItem.tokens ?? null,
921
1209
  originalModel,
@@ -1020,6 +1308,14 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options, reg
1020
1308
  "force only applies when resuming an experiment. Pass it together with resume."
1021
1309
  );
1022
1310
  }
1311
+ if (options?.experimentalSelectiveReplay !== void 0) {
1312
+ validateSelectiveReplayOptions(options.experimentalSelectiveReplay);
1313
+ if ((options.mock ?? "marked") !== "marked" || normalizeMockOverrides(options.mockOverride).length > 0 || registeredOverrides.length > 0) {
1314
+ throw new BitfabError(
1315
+ "experimentalSelectiveReplay requires mock: 'marked' and cannot be combined with mock overrides."
1316
+ );
1317
+ }
1318
+ }
1023
1319
  if (options?.traceIds !== void 0) {
1024
1320
  if (options.traceIds.length === 0) {
1025
1321
  throw new BitfabError("traceIds must contain at least one trace ID.");
@@ -1081,7 +1377,8 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options, reg
1081
1377
  requestedAttempts,
1082
1378
  options?.adaptInputs !== void 0,
1083
1379
  options?.onlyWithAssertions,
1084
- options?.judgeAssertions
1380
+ options?.judgeAssertions,
1381
+ options?.experimentalSelectiveReplay
1085
1382
  );
1086
1383
  if (started2.items.length === 0) {
1087
1384
  try {
@@ -1143,7 +1440,8 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options, reg
1143
1440
  session.includeDbBranchLease,
1144
1441
  session.dbBranchSettings,
1145
1442
  options?.adaptInputs,
1146
- options?.dryRun === true
1443
+ options?.dryRun === true,
1444
+ options?.experimentalSelectiveReplay
1147
1445
  )
1148
1446
  );
1149
1447
  const total = tasks.length + carriedOverItems.length;
@@ -1216,6 +1514,7 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options, reg
1216
1514
  traceError: item.traceError,
1217
1515
  replayError: item.replayError,
1218
1516
  durationMs: item.durationMs,
1517
+ ...item.selectiveReplay === void 0 ? {} : { selectiveReplay: item.selectiveReplay },
1219
1518
  originalDurationMs: item.originalDurationMs,
1220
1519
  originalTokens: item.originalTokens,
1221
1520
  originalModel: item.originalModel,
@@ -1403,4 +1702,4 @@ export {
1403
1702
  sleepForReplayPersistence,
1404
1703
  replay
1405
1704
  };
1406
- //# sourceMappingURL=chunk-X5DRPZJJ.js.map
1705
+ //# sourceMappingURL=chunk-34UFYAE6.js.map