bitfab 0.18.0 → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -128,4 +128,4 @@ export {
128
128
  serializeValue,
129
129
  deserializeValue
130
130
  };
131
- //# sourceMappingURL=chunk-QT7HWOKU.js.map
131
+ //# sourceMappingURL=chunk-PY6V4FE3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/asyncStorage.ts","../src/replayContext.ts","../src/serialize.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 super(message)\n this.name = \"BitfabError\"\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 testRunId into the span payload\n * so that new spans created during replay are linked to the test run.\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\"\n\n/** A single span entry in the mock tree with its historical output. */\nexport interface MockSpan {\n sourceSpanId: 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 `ReplayEnvironment`, 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\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 testRunId: string\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 * `ReplayEnvironment.traceId`) should expose, since it's the ID the\n * customer sees in the Bitfab dashboard.\n */\n sourceBitfabTraceId?: string\n mockTree?: MockTree\n callCounters?: Map<string, number>\n mockStrategy?: \"none\" | \"all\" | \"marked\"\n dbBranchLease?: DbBranchLease\n /**\n * Set to true by `ReplayEnvironment` the first time customer code\n * actually obtains `databaseUrl` for this item (via the getter or\n * `snapshot()`). 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 * Any future consumption path that hands the URL to customer code by\n * other means (e.g. a process-isolated runner writing an env overlay)\n * must also set this.\n */\n dbSnapshotAccessed?: boolean\n /**\n * Collector for the replay item's trace-persistence work. When present,\n * the root span's send path pushes a promise that resolves only after\n * every span upload AND the trace completion have been sent (registered\n * synchronously at send time, so the replay runner can await it after\n * the wrapped fn resolves). This is what lets replay guarantee traces\n * are persisted server-side before `completeReplay` builds the\n * trace-ID mapping. Absent outside replay, where sends stay\n * fire-and-forget.\n */\n pendingPersistence?: Promise<unknown>[]\n}\n\nlet replayContextStorage: AsyncLocalStorageLike<ReplayContext | null> | null =\n null\n\nexport const replayContextReady: Promise<void> = asyncStorageReady.then(() => {\n replayContextStorage = createAsyncLocalStorage<ReplayContext | null>()\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","/**\n * Serialization utilities for Bitfab SDK.\n *\n * This module provides serialization with type metadata preservation,\n * using superjson for handling special JavaScript types like Date, Map,\n * Set, BigInt, undefined, etc.\n */\n\nimport superjson from \"superjson\"\n\n/**\n * Serialized value with JSON data and optional superjson meta for type preservation.\n *\n * The json field contains the JSON-serializable data.\n * The meta field (if present) contains superjson type information for deserializing\n * special types like Date, Map, Set, BigInt, etc.\n */\nexport interface SerializedValue {\n json: unknown\n meta?: unknown\n}\n\n// Cap on serialized payload size. superjson can succeed on values like SDK\n// client instances (OpenAI, etc.) and produce hundreds of KB to MB of useless\n// internal state. Anything beyond this is replaced with a stub so the span\n// still ships and the trace isn't dropped server-side.\nconst MAX_SERIALIZED_BYTES = 512_000\n\nfunction describeValue(value: unknown): string {\n try {\n const ctorName = (value as { constructor?: { name?: string } })?.constructor\n ?.name\n if (ctorName && ctorName !== \"Object\") {\n return ctorName\n }\n } catch {\n // Property access on `value` can throw (Proxy, poisoned getter).\n }\n return typeof value\n}\n\nfunction unserializableStub(value: unknown, reason: string): SerializedValue {\n let summary: string\n try {\n summary = `<unserializable: ${describeValue(value)} (${reason})>`\n } catch {\n summary = `<unserializable (${reason})>`\n }\n return { json: summary }\n}\n\n/**\n * Serialize a value using superjson for trace storage.\n *\n * Handles arbitrary JavaScript values including:\n * - Date, RegExp, Error\n * - Map, Set\n * - BigInt\n * - undefined (in objects/arrays)\n * - Circular references\n *\n * Guarantees:\n * - Never throws. Pathological inputs (SDK clients, proxies, poisoned\n * getters, circular graphs that defeat superjson) return a stub string.\n * - Never returns a payload larger than MAX_SERIALIZED_BYTES; oversized\n * inputs are replaced with a stub. Without this the wire-side\n * `JSON.stringify` in http.ts can produce a request that times out or\n * gets rejected, leaving a trace with zero spans.\n *\n * @param value - Any JavaScript value to serialize\n * @returns SerializedValue with 'json' field containing the data.\n * If type metadata is needed for reconstruction, includes 'meta' field.\n *\n * @example\n * ```typescript\n * const result = serializeValue(new Date('2024-01-15T10:30:00Z'))\n * // result.json contains the ISO string\n * // result.meta contains type info for Date reconstruction\n * ```\n */\nexport function serializeValue(value: unknown): SerializedValue {\n try {\n const { json, meta } = superjson.serialize(value)\n\n let size: number\n try {\n size = JSON.stringify(json).length\n } catch {\n return unserializableStub(value, \"stringify_failed_after_superjson\")\n }\n if (size > MAX_SERIALIZED_BYTES) {\n return unserializableStub(value, `too_large_${size}_bytes`)\n }\n\n return meta ? { json, meta } : { json }\n } catch {\n try {\n return { json: JSON.parse(JSON.stringify(value)) }\n } catch {\n return unserializableStub(value, \"json_stringify_failed\")\n }\n }\n}\n\n/**\n * Deserialize a value that was serialized with serializeValue.\n *\n * @param serialized - A SerializedValue object with 'json' and optional 'meta'\n * @returns The reconstructed JavaScript value\n *\n * @example\n * ```typescript\n * const serialized = serializeValue(new Date('2024-01-15'))\n * const date = deserializeValue(serialized)\n * // date is a Date object\n * ```\n */\nexport function deserializeValue(serialized: SerializedValue): unknown {\n if (serialized.meta === undefined) {\n // No metadata, return as-is\n return serialized.json\n }\n\n // Use superjson to deserialize with type reconstruction\n // Cast json to the expected superjson type\n type SuperJSONResult = Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize({\n json: serialized.json as SuperJSONResult[\"json\"],\n meta: serialized.meta as SuperJSONResult[\"meta\"],\n })\n}\n"],"mappings":";AAMO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACE,SACgB,KAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;;;ACqBA,IAAI,yBACF;AACF,IAAI,WAAW;AAUR,SAAS,+BACd,KACM;AACN,MAAI,CAAC,wBAAwB;AAC3B,6BAAyB;AAAA,EAC3B;AACA,aAAW;AACb;AAYO,SAAS,+BAAqC;AACnD,MAAI,CAAC,wBAAwB;AAC3B,YAAQ;AAAA,MACN;AAAA,IACF;AAAA,EACF;AACF;AAEO,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;AAEM,SAAS,yBAAkC;AAChD,SAAO;AACT;AAEO,SAAS,0BAA8D;AAC5E,SAAO,yBACF,IAAI,uBAAuB,IAC5B;AACN;;;ACHA,IAAI,uBACF;AAEK,IAAM,qBAAoC,kBAAkB,KAAK,MAAM;AAC5E,yBAAuB,wBAA8C;AACvE,CAAC;AAGM,SAAS,mBAAyC;AACvD,SAAO,sBAAsB,SAAS,KAAK;AAC7C;AAGO,SAAS,qBAAwB,KAAoB,IAAgB;AAC1E,MAAI,sBAAsB;AACxB,WAAO,qBAAqB,IAAI,KAAK,EAAE;AAAA,EACzC;AACA,SAAO,GAAG;AACZ;;;AChHA,OAAO,eAAe;AAkBtB,IAAM,uBAAuB;AAE7B,SAAS,cAAc,OAAwB;AAC7C,MAAI;AACF,UAAM,WAAY,OAA+C,aAC7D;AACJ,QAAI,YAAY,aAAa,UAAU;AACrC,aAAO;AAAA,IACT;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO,OAAO;AAChB;AAEA,SAAS,mBAAmB,OAAgB,QAAiC;AAC3E,MAAI;AACJ,MAAI;AACF,cAAU,oBAAoB,cAAc,KAAK,CAAC,KAAK,MAAM;AAAA,EAC/D,QAAQ;AACN,cAAU,oBAAoB,MAAM;AAAA,EACtC;AACA,SAAO,EAAE,MAAM,QAAQ;AACzB;AA+BO,SAAS,eAAe,OAAiC;AAC9D,MAAI;AACF,UAAM,EAAE,MAAM,KAAK,IAAI,UAAU,UAAU,KAAK;AAEhD,QAAI;AACJ,QAAI;AACF,aAAO,KAAK,UAAU,IAAI,EAAE;AAAA,IAC9B,QAAQ;AACN,aAAO,mBAAmB,OAAO,kCAAkC;AAAA,IACrE;AACA,QAAI,OAAO,sBAAsB;AAC/B,aAAO,mBAAmB,OAAO,aAAa,IAAI,QAAQ;AAAA,IAC5D;AAEA,WAAO,OAAO,EAAE,MAAM,KAAK,IAAI,EAAE,KAAK;AAAA,EACxC,QAAQ;AACN,QAAI;AACF,aAAO,EAAE,MAAM,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC,EAAE;AAAA,IACnD,QAAQ;AACN,aAAO,mBAAmB,OAAO,uBAAuB;AAAA,IAC1D;AAAA,EACF;AACF;AAeO,SAAS,iBAAiB,YAAsC;AACrE,MAAI,WAAW,SAAS,QAAW;AAEjC,WAAO,WAAW;AAAA,EACpB;AAKA,SAAO,UAAU,YAAY;AAAA,IAC3B,MAAM,WAAW;AAAA,IACjB,MAAM,WAAW;AAAA,EACnB,CAAC;AACH;","names":[]}
@@ -6,10 +6,10 @@ import {
6
6
  getReplayContext,
7
7
  isAsyncStorageInitDone,
8
8
  serializeValue
9
- } from "./chunk-QT7HWOKU.js";
9
+ } from "./chunk-PY6V4FE3.js";
10
10
 
11
11
  // src/version.generated.ts
12
- var __version__ = "0.18.0";
12
+ var __version__ = "0.18.2";
13
13
 
14
14
  // src/constants.ts
15
15
  var DEFAULT_SERVICE_URL = "https://bitfab.ai";
@@ -1234,21 +1234,131 @@ function extractModelName(serialized, metadata) {
1234
1234
  }
1235
1235
  return void 0;
1236
1236
  }
1237
+ function asTokenCount(value) {
1238
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
1239
+ }
1240
+ function normalizeTokenUsage(raw) {
1241
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
1242
+ return null;
1243
+ }
1244
+ const u = raw;
1245
+ if ("cache_read_input_tokens" in u || "cache_creation_input_tokens" in u) {
1246
+ const cacheRead = asTokenCount(u.cache_read_input_tokens);
1247
+ const cacheCreation = asTokenCount(u.cache_creation_input_tokens);
1248
+ const baseInput = asTokenCount(u.input_tokens);
1249
+ const outputTokens = asTokenCount(u.output_tokens);
1250
+ if (cacheRead === null && cacheCreation === null && baseInput === null && outputTokens === null) {
1251
+ return null;
1252
+ }
1253
+ const inputTokens = (baseInput ?? 0) + (cacheRead ?? 0) + (cacheCreation ?? 0);
1254
+ return {
1255
+ inputTokens,
1256
+ outputTokens,
1257
+ totalTokens: inputTokens + (outputTokens ?? 0),
1258
+ cachedInputTokens: cacheRead
1259
+ };
1260
+ }
1261
+ if ("prompt_tokens" in u || "completion_tokens" in u || "promptTokens" in u || "completionTokens" in u) {
1262
+ const promptDetails = u.prompt_tokens_details ?? {};
1263
+ return withAnyTokenCount({
1264
+ inputTokens: asTokenCount(u.prompt_tokens) ?? asTokenCount(u.promptTokens),
1265
+ outputTokens: asTokenCount(u.completion_tokens) ?? asTokenCount(u.completionTokens),
1266
+ totalTokens: asTokenCount(u.total_tokens) ?? asTokenCount(u.totalTokens),
1267
+ cachedInputTokens: asTokenCount(promptDetails.cached_tokens)
1268
+ });
1269
+ }
1270
+ if ("prompt_token_count" in u || "candidates_token_count" in u) {
1271
+ return withAnyTokenCount({
1272
+ inputTokens: asTokenCount(u.prompt_token_count),
1273
+ outputTokens: asTokenCount(u.candidates_token_count),
1274
+ totalTokens: asTokenCount(u.total_token_count),
1275
+ cachedInputTokens: asTokenCount(u.cached_content_token_count)
1276
+ });
1277
+ }
1278
+ if ("input_tokens" in u || "output_tokens" in u) {
1279
+ const inputDetails = u.input_token_details ?? {};
1280
+ const inputTokens = asTokenCount(u.input_tokens);
1281
+ const outputTokens = asTokenCount(u.output_tokens);
1282
+ let totalTokens = asTokenCount(u.total_tokens);
1283
+ if (totalTokens === null && inputTokens !== null && outputTokens !== null) {
1284
+ totalTokens = inputTokens + outputTokens;
1285
+ }
1286
+ return withAnyTokenCount({
1287
+ inputTokens,
1288
+ outputTokens,
1289
+ totalTokens,
1290
+ cachedInputTokens: asTokenCount(inputDetails.cache_read)
1291
+ });
1292
+ }
1293
+ return null;
1294
+ }
1295
+ function withAnyTokenCount(usage) {
1296
+ const hasCount = usage.inputTokens !== null || usage.outputTokens !== null || usage.totalTokens !== null || usage.cachedInputTokens !== null;
1297
+ return hasCount ? usage : null;
1298
+ }
1299
+ function addUsage(totals, usage) {
1300
+ for (const key of [
1301
+ "inputTokens",
1302
+ "outputTokens",
1303
+ "totalTokens",
1304
+ "cachedInputTokens"
1305
+ ]) {
1306
+ const value = usage[key];
1307
+ if (value !== null) {
1308
+ totals[key] = (totals[key] ?? 0) + value;
1309
+ }
1310
+ }
1311
+ }
1312
+ function usageFromGenerations(generations) {
1313
+ if (!generations?.length) {
1314
+ return null;
1315
+ }
1316
+ const totals = {
1317
+ inputTokens: null,
1318
+ outputTokens: null,
1319
+ totalTokens: null,
1320
+ cachedInputTokens: null
1321
+ };
1322
+ let found = false;
1323
+ for (const batch of generations) {
1324
+ if (!Array.isArray(batch)) {
1325
+ continue;
1326
+ }
1327
+ for (const gen of batch) {
1328
+ const msg = gen?.message;
1329
+ if (!msg || typeof msg !== "object") {
1330
+ continue;
1331
+ }
1332
+ const responseMetadata = msg.response_metadata;
1333
+ const usage = normalizeTokenUsage(msg.usage_metadata) ?? normalizeTokenUsage(responseMetadata?.token_usage) ?? normalizeTokenUsage(responseMetadata?.usage) ?? normalizeTokenUsage(responseMetadata?.tokenUsage);
1334
+ if (!usage) {
1335
+ continue;
1336
+ }
1337
+ found = true;
1338
+ addUsage(totals, usage);
1339
+ }
1340
+ }
1341
+ return found ? totals : null;
1342
+ }
1237
1343
  function extractUsage2(output) {
1344
+ const generations = output.generations;
1345
+ const llmOutput = output.llmOutput ?? output.llm_output;
1346
+ const normalized = usageFromGenerations(generations) ?? normalizeTokenUsage(llmOutput?.tokenUsage) ?? normalizeTokenUsage(llmOutput?.token_usage) ?? normalizeTokenUsage(llmOutput?.usage);
1238
1347
  const usage = {};
1239
- const llmOutput = output.llmOutput;
1240
- const tokenUsage = llmOutput?.tokenUsage ?? llmOutput?.token_usage ?? llmOutput?.usage ?? {};
1241
- const inputTokens = tokenUsage.promptTokens ?? tokenUsage.prompt_tokens ?? tokenUsage.input_tokens;
1242
- const outputTokens = tokenUsage.completionTokens ?? tokenUsage.completion_tokens ?? tokenUsage.output_tokens;
1243
- const totalTokens = tokenUsage.totalTokens ?? tokenUsage.total_tokens;
1244
- if (inputTokens !== void 0 && inputTokens !== null) {
1245
- usage.inputTokens = inputTokens;
1348
+ if (!normalized) {
1349
+ return usage;
1350
+ }
1351
+ if (normalized.inputTokens !== null) {
1352
+ usage.inputTokens = normalized.inputTokens;
1246
1353
  }
1247
- if (outputTokens !== void 0 && outputTokens !== null) {
1248
- usage.outputTokens = outputTokens;
1354
+ if (normalized.outputTokens !== null) {
1355
+ usage.outputTokens = normalized.outputTokens;
1249
1356
  }
1250
- if (totalTokens !== void 0 && totalTokens !== null) {
1251
- usage.totalTokens = totalTokens;
1357
+ if (normalized.totalTokens !== null) {
1358
+ usage.totalTokens = normalized.totalTokens;
1359
+ }
1360
+ if (normalized.cachedInputTokens !== null) {
1361
+ usage.cachedInputTokens = normalized.cachedInputTokens;
1252
1362
  }
1253
1363
  return usage;
1254
1364
  }
@@ -1605,7 +1715,9 @@ var ReplayEnvironment = class {
1605
1715
  * Throws if read outside a replay item.
1606
1716
  */
1607
1717
  get databaseUrl() {
1608
- return this.require().databaseUrl;
1718
+ const snapshot = this.require();
1719
+ this.markAccessed();
1720
+ return snapshot.databaseUrl;
1609
1721
  }
1610
1722
  /** When the per-trace branch URL stops being valid. ISO-8601. */
1611
1723
  get expiresAt() {
@@ -1633,7 +1745,24 @@ var ReplayEnvironment = class {
1633
1745
  }
1634
1746
  /** Non-throwing variant for callers that handle the inactive case. */
1635
1747
  snapshot() {
1636
- return this.read();
1748
+ const snapshot = this.read();
1749
+ if (snapshot) {
1750
+ this.markAccessed();
1751
+ }
1752
+ return snapshot;
1753
+ }
1754
+ /**
1755
+ * Record on the replay context that customer code obtained the branch
1756
+ * URL. Only `databaseUrl` and `snapshot()` count — `active`, `readOnly`
1757
+ * and friends inspect the lease without exposing the connection string,
1758
+ * so they don't prove the replayed code could have connected to the
1759
+ * branch.
1760
+ */
1761
+ markAccessed() {
1762
+ const ctx = getReplayContext();
1763
+ if (ctx?.dbBranchLease) {
1764
+ ctx.dbSnapshotAccessed = true;
1765
+ }
1637
1766
  }
1638
1767
  read() {
1639
1768
  const ctx = getReplayContext();
@@ -2562,7 +2691,19 @@ var Bitfab = class {
2562
2691
  contexts: traceState?.contexts ?? [],
2563
2692
  testRunId: traceState?.testRunId,
2564
2693
  inputSourceTraceId: traceState?.inputSourceTraceId,
2565
- dbSnapshotRef: traceState?.dbSnapshotRef
2694
+ dbSnapshotRef: traceState?.dbSnapshotRef,
2695
+ // Built AFTER the wrapped fn finished, so `accessed` reflects
2696
+ // whether customer code obtained the branch URL during this
2697
+ // item. Omitted entirely when no lease was attached, so the
2698
+ // server can distinguish "no branch" from "branch ignored".
2699
+ ...replayCtx?.dbBranchLease && {
2700
+ dbSnapshotUsage: {
2701
+ neonBranchId: replayCtx.dbBranchLease.neonBranchId,
2702
+ snapshotTimestamp: replayCtx.dbBranchLease.snapshotTimestamp,
2703
+ sourceTraceId: replayCtx.sourceBitfabTraceId,
2704
+ accessed: replayCtx.dbSnapshotAccessed === true
2705
+ }
2706
+ }
2566
2707
  });
2567
2708
  activeTraceStates.delete(traceId);
2568
2709
  if (persistenceCollector) {
@@ -2734,6 +2875,18 @@ var Bitfab = class {
2734
2875
  if (params.dbSnapshotRef) {
2735
2876
  rawTrace.db_snapshot_ref = params.dbSnapshotRef;
2736
2877
  }
2878
+ if (params.dbSnapshotUsage) {
2879
+ rawTrace.db_snapshot_usage = {
2880
+ neon_branch_id: params.dbSnapshotUsage.neonBranchId,
2881
+ ...params.dbSnapshotUsage.snapshotTimestamp && {
2882
+ snapshot_timestamp: params.dbSnapshotUsage.snapshotTimestamp
2883
+ },
2884
+ ...params.dbSnapshotUsage.sourceTraceId && {
2885
+ source_trace_id: params.dbSnapshotUsage.sourceTraceId
2886
+ },
2887
+ accessed: params.dbSnapshotUsage.accessed
2888
+ };
2889
+ }
2737
2890
  return this.httpClient.sendExternalTrace({
2738
2891
  type: "sdk-function",
2739
2892
  source: "typescript-sdk-function",
@@ -2831,7 +2984,7 @@ var Bitfab = class {
2831
2984
  `Function is wrapped with trace function key '${wrappedKey}' but replay was called with '${traceFunctionKey}'. Pass matching keys, or pass the unwrapped function to replay it under the explicit key.`
2832
2985
  );
2833
2986
  }
2834
- const { replay: doReplay } = await import("./replay-BIPIDXX6.js");
2987
+ const { replay: doReplay } = await import("./replay-P3QXRLOC.js");
2835
2988
  return doReplay(
2836
2989
  this.httpClient,
2837
2990
  this.serviceUrl,
@@ -2910,4 +3063,4 @@ export {
2910
3063
  Bitfab,
2911
3064
  BitfabFunction
2912
3065
  };
2913
- //# sourceMappingURL=chunk-S3YLZ47O.js.map
3066
+ //# sourceMappingURL=chunk-UTVFKV2Z.js.map