@tangle-network/agent-eval 0.148.0 → 0.150.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +50 -0
- package/README.md +5 -1
- package/dist/analyst/index.d.ts +14 -14
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +4 -4
- package/dist/{backend-integrity-Bz8nSrRE.d.ts → backend-integrity-DaeroaEs.d.ts} +2 -2
- package/dist/{backend-integrity-Bz8nSrRE.d.ts.map → backend-integrity-DaeroaEs.d.ts.map} +1 -1
- package/dist/{benchmark-Cn7ZMFNW.d.ts → benchmark-A0E-JZ1H.d.ts} +3 -3
- package/dist/{benchmark-Cn7ZMFNW.d.ts.map → benchmark-A0E-JZ1H.d.ts.map} +1 -1
- package/dist/{benchmark-command-Cz4fDmsk.js → benchmark-command-CqGA0SJQ.js} +8 -7
- package/dist/benchmark-command-CqGA0SJQ.js.map +1 -0
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.d.ts +9 -9
- package/dist/campaign/index.js +6 -6
- package/dist/{campaign-BcfXzmPM.js → campaign-CR6Yt5ZS.js} +80 -7
- package/dist/campaign-CR6Yt5ZS.js.map +1 -0
- package/dist/{capture-fetch-BAx3Gntt.d.ts → capture-fetch-Im0UN1i6.d.ts} +2 -2
- package/dist/{capture-fetch-BAx3Gntt.d.ts.map → capture-fetch-Im0UN1i6.d.ts.map} +1 -1
- package/dist/{chat-client-BX8Wh3fn.js → chat-client-sFiClniQ.js} +2 -2
- package/dist/{chat-client-BX8Wh3fn.js.map → chat-client-sFiClniQ.js.map} +1 -1
- package/dist/cli.js +2 -2
- package/dist/{client-BV7icIfy.d.ts → client-w6vVJhSp.d.ts} +2 -2
- package/dist/{client-BV7icIfy.d.ts.map → client-w6vVJhSp.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +5 -5
- package/dist/{default-registry-BUtRMRKk.d.ts → default-registry-BhRNsP-D.d.ts} +6 -6
- package/dist/{default-registry-BUtRMRKk.d.ts.map → default-registry-BhRNsP-D.d.ts.map} +1 -1
- package/dist/{define-agent-eval-CvZQW4u9.js → define-agent-eval-ChrtErmg.js} +3 -3
- package/dist/define-agent-eval-ChrtErmg.js.map +1 -0
- package/dist/{define-agent-eval-hXLUBKtb.d.ts → define-agent-eval-Cw3mkB4-.d.ts} +6 -7
- package/dist/define-agent-eval-Cw3mkB4-.d.ts.map +1 -0
- package/dist/{dspy-rlm-engine-BmtOl_kP.js → dspy-rlm-engine-Csi3CUAT.js} +2 -2
- package/dist/{dspy-rlm-engine-BmtOl_kP.js.map → dspy-rlm-engine-Csi3CUAT.js.map} +1 -1
- package/dist/{engine-CIy18RTX.d.ts → engine-CgQdUh-r.d.ts} +4 -4
- package/dist/{engine-CIy18RTX.d.ts.map → engine-CgQdUh-r.d.ts.map} +1 -1
- package/dist/{eval-campaign-bmZ6NIIP.js → eval-campaign-Czc2TcW5.js} +2 -2
- package/dist/{eval-campaign-bmZ6NIIP.js.map → eval-campaign-Czc2TcW5.js.map} +1 -1
- package/dist/{exact-types-rdKFzEnK.d.ts → exact-types-D9_T83Ol.d.ts} +2 -2
- package/dist/{exact-types-rdKFzEnK.d.ts.map → exact-types-D9_T83Ol.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +73 -4
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +175 -1
- package/dist/experiment/index.js.map +1 -1
- package/dist/{experiment-tracker-D9VHwRm-.d.ts → experiment-tracker-Cp9ougHs.d.ts} +2 -2
- package/dist/{experiment-tracker-D9VHwRm-.d.ts.map → experiment-tracker-Cp9ougHs.d.ts.map} +1 -1
- package/dist/{external-optimizer-contracts-CSjDLLmr.d.ts → external-optimizer-contracts-mbhR9Ldu.d.ts} +13 -6
- package/dist/{external-optimizer-contracts-CSjDLLmr.d.ts.map → external-optimizer-contracts-mbhR9Ldu.d.ts.map} +1 -1
- package/dist/{external-optimizer-process-C4AyCcQd.js → external-optimizer-process-tDe72VRO.js} +4 -4
- package/dist/{external-optimizer-process-C4AyCcQd.js.map → external-optimizer-process-tDe72VRO.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-DU1KM8yV.js → external-optimizer-subprocess-BepyNwtj.js} +341 -25
- package/dist/external-optimizer-subprocess-BepyNwtj.js.map +1 -0
- package/dist/{feedback-trajectory-niGeR6uJ.d.ts → feedback-trajectory-Cc9M2tNF.d.ts} +3 -3
- package/dist/{feedback-trajectory-niGeR6uJ.d.ts.map → feedback-trajectory-Cc9M2tNF.d.ts.map} +1 -1
- package/dist/fuzz.d.ts +1 -1
- package/dist/hosted/index.d.ts +2 -2
- package/dist/{index-gtjtfLEJ.d.ts → index-DL4MJuJL.d.ts} +8 -8
- package/dist/{index-gtjtfLEJ.d.ts.map → index-DL4MJuJL.d.ts.map} +1 -1
- package/dist/index-DjpxROrT.d.ts +1 -0
- package/dist/{index-Dzn8Q3C2.d.ts → index-dh0kp2GM.d.ts} +42 -11
- package/dist/index-dh0kp2GM.d.ts.map +1 -0
- package/dist/index.d.ts +21 -21
- package/dist/index.js +13 -20
- package/dist/index.js.map +1 -1
- package/dist/{integrity-CGfpTE5-.d.ts → integrity-D2MAlC_K.d.ts} +2 -2
- package/dist/{integrity-CGfpTE5-.d.ts.map → integrity-D2MAlC_K.d.ts.map} +1 -1
- package/dist/{llm-client-BMuxYoZy.js → llm-client-CxyJ8Oft.js} +15 -6
- package/dist/llm-client-CxyJ8Oft.js.map +1 -0
- package/dist/{llm-judge-DWq1Ptco.js → llm-judge-D7UuMI2t.js} +4 -3
- package/dist/llm-judge-D7UuMI2t.js.map +1 -0
- package/dist/{matrix-Bc111FKv.d.ts → matrix-D3hL68uV.d.ts} +2 -2
- package/dist/{matrix-Bc111FKv.d.ts.map → matrix-D3hL68uV.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +1 -1
- package/dist/{multi-layer-verifier-DIguZc8Z.d.ts → multi-layer-verifier-BUaQ4C17.d.ts} +3 -3
- package/dist/{multi-layer-verifier-DIguZc8Z.d.ts.map → multi-layer-verifier-BUaQ4C17.d.ts.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{produced-state-C0oJ4vr-.js → produced-state-WJs_enbZ.js} +3 -3
- package/dist/{produced-state-C0oJ4vr-.js.map → produced-state-WJs_enbZ.js.map} +1 -1
- package/dist/{promotion-policy-CewdjfCJ.d.ts → promotion-policy-DYRzXdTV.d.ts} +2 -2
- package/dist/{promotion-policy-CewdjfCJ.d.ts.map → promotion-policy-DYRzXdTV.d.ts.map} +1 -1
- package/dist/{provenance-DA-Pmyfv.d.ts → provenance-Bh9k3sjl.d.ts} +17 -6
- package/dist/{provenance-DA-Pmyfv.d.ts.map → provenance-Bh9k3sjl.d.ts.map} +1 -1
- package/dist/{registry-CaqJIDdN.d.ts → registry-DhpX9Bsg.d.ts} +4 -4
- package/dist/{registry-CaqJIDdN.d.ts.map → registry-DhpX9Bsg.d.ts.map} +1 -1
- package/dist/{researcher-BySlpla_.d.ts → researcher-CbCK-ppF.d.ts} +3 -3
- package/dist/{researcher-BySlpla_.d.ts.map → researcher-CbCK-ppF.d.ts.map} +1 -1
- package/dist/{reward-hacking-Bu8ev6PR.d.ts → reward-hacking-62tojkQd.d.ts} +2 -2
- package/dist/{reward-hacking-Bu8ev6PR.d.ts.map → reward-hacking-62tojkQd.d.ts.map} +1 -1
- package/dist/rl.d.ts +4 -4
- package/dist/rl.js +1 -1
- package/dist/{semantic-concept-judge-BI7Rrl5-.js → semantic-concept-judge-B7KPD57W.js} +2 -2
- package/dist/{semantic-concept-judge-BI7Rrl5-.js.map → semantic-concept-judge-B7KPD57W.js.map} +1 -1
- package/dist/{series-convergence-D2fsoJ2w.d.ts → series-convergence-VhTad5TM.d.ts} +2 -2
- package/dist/{series-convergence-D2fsoJ2w.d.ts.map → series-convergence-VhTad5TM.d.ts.map} +1 -1
- package/dist/{server-D9wQclzG.js → server-DNiUVirV.js} +2 -2
- package/dist/{server-D9wQclzG.js.map → server-DNiUVirV.js.map} +1 -1
- package/dist/{skillopt-optimization-method-CrY0OG17.d.ts → skillopt-optimization-method-BtgL6PMH.d.ts} +20 -14
- package/dist/{skillopt-optimization-method-CrY0OG17.d.ts.map → skillopt-optimization-method-BtgL6PMH.d.ts.map} +1 -1
- package/dist/{skillopt-optimization-method-Donmq4sq.js → skillopt-optimization-method-L8vi4h4m.js} +92 -14
- package/dist/skillopt-optimization-method-L8vi4h4m.js.map +1 -0
- package/dist/{statistical-heldout-uxSpFEjm.d.ts → statistical-heldout-Caxd30ZF.d.ts} +2 -2
- package/dist/{statistical-heldout-uxSpFEjm.d.ts.map → statistical-heldout-Caxd30ZF.d.ts.map} +1 -1
- package/dist/{store-tool-spans-D5FhM0_A.d.ts → store-tool-spans-BGg2QFk1.d.ts} +4 -4
- package/dist/{store-tool-spans-D5FhM0_A.d.ts.map → store-tool-spans-BGg2QFk1.d.ts.map} +1 -1
- package/dist/{tool-groups-zpufabP8.d.ts → tool-groups-BuhFx38z.d.ts} +3 -3
- package/dist/tool-groups-BuhFx38z.d.ts.map +1 -0
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/traces.d.ts +7 -7
- package/dist/{types-ColZlZtc.d.ts → types-B61iI2ZG.d.ts} +2 -2
- package/dist/{types-ColZlZtc.d.ts.map → types-B61iI2ZG.d.ts.map} +1 -1
- package/dist/{types-BohHewKK.d.ts → types-BNbhD_Vj.d.ts} +2 -2
- package/dist/{types-BohHewKK.d.ts.map → types-BNbhD_Vj.d.ts.map} +1 -1
- package/dist/{types-DOhGq4S1.d.ts → types-COAJy8Ku.d.ts} +15 -3
- package/dist/types-COAJy8Ku.d.ts.map +1 -0
- package/dist/{types-C1Bmeb8X.d.ts → types-COEjZMLY.d.ts} +3 -3
- package/dist/{types-C1Bmeb8X.d.ts.map → types-COEjZMLY.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +2 -2
- package/dist/wire/index.js +1 -1
- package/docs/campaign-proposers.md +60 -3
- package/docs/experiment.md +2 -0
- package/docs/feature-guide.md +1 -1
- package/docs/multishot-golden-records.md +3 -0
- package/package.json +4 -2
- package/dist/benchmark-command-Cz4fDmsk.js.map +0 -1
- package/dist/campaign-BcfXzmPM.js.map +0 -1
- package/dist/define-agent-eval-CvZQW4u9.js.map +0 -1
- package/dist/define-agent-eval-hXLUBKtb.d.ts.map +0 -1
- package/dist/external-optimizer-subprocess-DU1KM8yV.js.map +0 -1
- package/dist/index-CKblBxtr.d.ts +0 -1
- package/dist/index-Dzn8Q3C2.d.ts.map +0 -1
- package/dist/llm-client-BMuxYoZy.js.map +0 -1
- package/dist/llm-judge-DWq1Ptco.js.map +0 -1
- package/dist/skillopt-optimization-method-Donmq4sq.js.map +0 -1
- package/dist/tool-groups-zpufabP8.d.ts.map +0 -1
- package/dist/types-DOhGq4S1.d.ts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"external-optimizer-subprocess-DU1KM8yV.js","names":["MAX_TIMER_DELAY_MS","bufferConstants"],"sources":["../src/campaign/search-ledger-errors.ts","../src/campaign/search-ledger-file.ts","../src/campaign/storage.ts","../src/campaign/external-optimizer-contracts.ts","../src/campaign/external-optimizer-http.ts","../src/campaign/external-optimizer-model-proxy.ts","../src/campaign/external-optimizer-resources.ts","../src/campaign/external-optimizer-subprocess.ts"],"sourcesContent":["import { ValidationError } from '../errors'\n\n/** Base error for invalid search-ledger input or operations. */\nexport class SearchLedgerError extends ValidationError {}\n\n/** Error raised when durable search-ledger data fails an integrity check. */\nexport class SearchLedgerIntegrityError extends SearchLedgerError {}\n\n/** Error raised when an event identifier is reused with different content. */\nexport class SearchLedgerConflictError extends SearchLedgerError {}\n","/** Campaign binding of the generic journal file layer to search-ledger errors. */\n\nimport {\n appendLedgerLine,\n type FileLockResult,\n type LedgerFileContext,\n tryWithLedgerFileLock,\n withLedgerFileLock,\n} from '../ledger-core'\nimport { SearchLedgerIntegrityError } from './search-ledger-errors'\n\nexport const SEARCH_LEDGER_FILE_CONTEXT: LedgerFileContext = {\n subject: 'search ledger',\n integrityError: (message, options) => new SearchLedgerIntegrityError(message, options),\n}\n\nexport function appendSearchLedgerLine(path: string, line: string): void {\n appendLedgerLine(path, line, SEARCH_LEDGER_FILE_CONTEXT)\n}\n\nexport function withSearchLedgerFileLock<T>(ledgerPath: string, run: () => T): T {\n return withLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run)\n}\n\nexport type { FileLockResult }\n\nexport function tryWithSearchLedgerFileLock<T>(\n ledgerPath: string,\n run: () => T,\n): FileLockResult<T> {\n return tryWithLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run)\n}\n","import { createRequire } from 'node:module'\nimport { join } from 'node:path'\nimport { CostLedger } from '../cost-ledger'\nimport { appendSearchLedgerLine, tryWithSearchLedgerFileLock } from './search-ledger-file'\n\n/**\n * `CampaignStorage` — the filesystem seam `runCampaign` writes through\n * (run/cell dirs, the resumability cache, per-cell artifacts, trace spans).\n *\n * The default (`fsCampaignStorage`) is the Node filesystem — identical\n * behavior to the inline `node:fs` calls it replaces, so existing CLI\n * consumers are unaffected. `inMemoryCampaignStorage` keeps everything in a\n * `Map`, so the substrate runs in environments WITHOUT a filesystem\n * (Cloudflare Workers, Deno Deploy, other edge runtimes) — the campaign\n * still produces its `CampaignResult` (cells + aggregates) in memory;\n * artifacts/traces simply aren't persisted to disk.\n *\n * Paths are opaque keys to the in-memory adapter — it does not parse them,\n * so the same `join(...)`-built paths work unchanged across both adapters.\n */\nexport interface CampaignStorage {\n /** Ensure a directory exists (recursive). No-op for in-memory. */\n ensureDir(dir: string): void\n /** Does this path exist (as a written file or an ensured dir)? */\n exists(path: string): boolean\n /** Read a UTF-8 file; `undefined` when missing or unreadable. */\n read(path: string): string | undefined\n /** Write a file (string or bytes). Parent dir is assumed ensured. */\n write(path: string, content: string | Uint8Array): void\n /** Append only when the current UTF-8 byte length matches `expectedBytes`.\n * Returns the new length, or undefined when another writer won. */\n append(path: string, content: string, expectedBytes: number): number | undefined\n}\n\n/** Node-filesystem storage — the default. Lazily requires `node:fs` so the\n * module imports cleanly in non-Node runtimes (where the caller passes\n * `inMemoryCampaignStorage` instead and never constructs this).\n *\n * `createRequire(import.meta.url)` is the ESM-native lazy require — a bare\n * `require` is a ReferenceError under `\"type\": \"module\"`, which is exactly\n * the shape this package publishes. */\nexport function fsCampaignStorage(): CampaignStorage {\n const nodeRequire = createRequire(import.meta.url)\n const { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } = nodeRequire(\n 'node:fs',\n ) as typeof import('node:fs')\n return {\n ensureDir(dir) {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n },\n exists(path) {\n return existsSync(path)\n },\n read(path) {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n },\n write(path, content) {\n writeFileSync(path, content as Uint8Array)\n },\n append(path, content, expectedBytes) {\n const result = tryWithSearchLedgerFileLock(path, () => {\n let actualBytes = 0\n try {\n actualBytes = statSync(path).size\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n if (actualBytes !== expectedBytes) return undefined\n appendSearchLedgerLine(path, content)\n return expectedBytes + Buffer.byteLength(content)\n })\n return result.acquired ? result.value : undefined\n },\n }\n}\n\n/** In-memory storage for filesystem-less runtimes. Artifacts + trace spans\n * live in a `Map` for the duration of the run; the `CampaignResult` is\n * fully populated, but nothing is persisted to disk. */\nexport function inMemoryCampaignStorage(): CampaignStorage {\n const files = new Map<string, string | Uint8Array>()\n const dirs = new Set<string>()\n return {\n ensureDir(dir) {\n dirs.add(dir)\n },\n exists(path) {\n return files.has(path) || dirs.has(path)\n },\n read(path) {\n const value = files.get(path)\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : new TextDecoder().decode(value)\n },\n write(path, content) {\n files.set(path, content)\n },\n append(path, content, expectedBytes) {\n const current = files.get(path)\n const currentText =\n current === undefined\n ? ''\n : typeof current === 'string'\n ? current\n : new TextDecoder().decode(current)\n const currentBytes = new TextEncoder().encode(currentText).byteLength\n if (currentBytes !== expectedBytes) return undefined\n files.set(path, `${currentText}${content}`)\n return currentBytes + new TextEncoder().encode(content).byteLength\n },\n }\n}\n\n/** Open the durable spend account stored beside a logical run. */\nexport function createRunCostLedger(input: {\n storage: CampaignStorage\n runDir: string\n costCeilingUsd?: number\n /** Set false for read-only inspection that must not create the run directory. */\n ensureRunDir?: boolean\n}): CostLedger {\n const path = join(input.runDir, 'cost-ledger.jsonl')\n if (input.ensureRunDir ?? true) input.storage.ensureDir(input.runDir)\n return new CostLedger({\n costCeilingUsd: input.costCeilingUsd,\n persistence: {\n read: () => {\n const stored = input.storage.read(path)\n if (stored === undefined && input.storage.exists(path)) {\n throw new Error(`CostLedger: cannot read existing event log '${path}'`)\n }\n const events = stored ?? ''\n return {\n revision: String(new TextEncoder().encode(events).byteLength),\n events,\n }\n },\n append: (expectedRevision, event) => {\n const expectedBytes = Number(expectedRevision)\n if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) {\n throw new Error(`CostLedger: invalid storage revision '${expectedRevision}'`)\n }\n const next = input.storage.append(path, event, expectedBytes)\n return next === undefined ? undefined : String(next)\n },\n },\n })\n}\n","import { constants as bufferConstants } from 'node:buffer'\nimport type { ChatRequest, ChatResponse } from '../analyst/chat-client'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\n\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst MAXIMUM_JSON_BYTES = Math.min(\n bufferConstants.MAX_LENGTH - 1,\n bufferConstants.MAX_STRING_LENGTH,\n)\n\nexport interface ExternalOptimizerProcessLimits {\n /** Maximum serialized input written for the child process. */\n maxInputBytes: number\n /** Maximum JSON result read from the child process. */\n maxResultBytes: number\n /** Maximum stdout or stderr characters retained for diagnostics. */\n maxOutputChars: number\n}\n\nexport const DEFAULT_EXTERNAL_OPTIMIZER_PROCESS_LIMITS: Readonly<ExternalOptimizerProcessLimits> =\n Object.freeze({\n maxInputBytes: 64 * 1024 * 1024,\n maxResultBytes: 4 * 1024 * 1024,\n maxOutputChars: 64_000,\n })\n\nexport interface ExternalOptimizerCallbackLimits {\n /** Maximum serialized request accepted by the loopback callback. */\n maxRequestBytes: number\n /** Maximum serialized response returned by the loopback callback. */\n maxResponseBytes: number\n}\n\nexport const DEFAULT_EXTERNAL_OPTIMIZER_CALLBACK_LIMITS: Readonly<ExternalOptimizerCallbackLimits> =\n Object.freeze({\n maxRequestBytes: 1_000_000,\n maxResponseBytes: 4_000_000,\n })\n\nexport interface ExternalOptimizerRunnerCommand {\n command?: string\n args?: readonly string[]\n env?: NodeJS.ProcessEnv\n /** Child-process resource limits. Omitted fields use finite defaults. */\n limits?: Partial<ExternalOptimizerProcessLimits>\n}\n\nexport type ExternalOptimizerResumeMode = 'never' | 'if-compatible' | 'required'\n\nexport type ExternalTextCandidate = string | Record<string, string>\n\nexport interface ExternalTextEvaluationRequest {\n candidate: ExternalTextCandidate\n exampleId: string\n}\n\nexport interface ExternalOptimizerCallback {\n url: string\n token: string\n evaluations: () => number\n close: () => Promise<void>\n}\n\nexport function resolveExternalOptimizerProcessLimits(\n value: Partial<ExternalOptimizerProcessLimits> | undefined,\n label = 'external optimizer process limits',\n): ExternalOptimizerProcessLimits {\n const resolved = {\n ...DEFAULT_EXTERNAL_OPTIMIZER_PROCESS_LIMITS,\n ...value,\n }\n assertBoundedPositiveInteger(resolved.maxInputBytes, `${label}.maxInputBytes`, MAXIMUM_JSON_BYTES)\n assertBoundedPositiveInteger(\n resolved.maxResultBytes,\n `${label}.maxResultBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n resolved.maxOutputChars,\n `${label}.maxOutputChars`,\n bufferConstants.MAX_STRING_LENGTH,\n )\n return resolved\n}\n\nexport function resolveExternalOptimizerCallbackLimits(\n value: Partial<ExternalOptimizerCallbackLimits> | undefined,\n label = 'external optimizer callback limits',\n): ExternalOptimizerCallbackLimits {\n const resolved = {\n ...DEFAULT_EXTERNAL_OPTIMIZER_CALLBACK_LIMITS,\n ...value,\n }\n assertBoundedPositiveInteger(\n resolved.maxRequestBytes,\n `${label}.maxRequestBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n resolved.maxResponseBytes,\n `${label}.maxResponseBytes`,\n MAXIMUM_JSON_BYTES,\n )\n return resolved\n}\n\ntype DeepReadonly<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends readonly (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T\n\n/** Provider-neutral request parsed once from the optimizer's loopback protocol. */\nexport type ExternalOptimizerChatRequest = DeepReadonly<\n Omit<ChatRequest, 'model'> & { model: string }\n>\n\nexport type ExternalOptimizerEndpointFormat = 'chat-completions' | 'responses'\n\n/** One exact model request admitted by the loopback proxy. */\nexport interface ExternalOptimizerModelCallRequest {\n /** Stable identity allocated by the cost ledger for this paid call. */\n readonly callId: string\n /** Deeply immutable canonical request; HTTP protocol fields never cross this boundary. */\n readonly request: ExternalOptimizerChatRequest\n /** Child response shape, when the execution owner needs to retain it as evidence. */\n readonly endpointFormat?: ExternalOptimizerEndpointFormat\n readonly signal: AbortSignal\n}\n\n/** Runtime-owned result for one admitted optimizer-model call. */\nexport type ExternalOptimizerModelCallResult =\n | {\n readonly succeeded: true\n /** Canonical response encoded back into the child's protocol by Agent Eval. */\n readonly response: ChatResponse\n /**\n * Canonical measured usage/cost input retained by Agent Eval's cost ledger.\n * `inputTokens` is the non-cached portion, `cachedTokens` is the cache-read\n * portion, and response `promptTokens` equals their sum. Cache-write tokens\n * remain a separately billed class and are never silently added to that total.\n */\n readonly receipt: import('../cost-ledger').CostReceiptInput\n /** Opaque, finite JSON proof of the exact execution retained in provenance. */\n readonly execution: unknown\n }\n | {\n readonly succeeded: false\n /** Public failure text safe to retain and return to the child process. */\n readonly error: string\n /** Usage/cost state for the failed Runtime call. Unknown values stay unknown. */\n readonly receipt: import('../cost-ledger').CostReceiptInput\n /** Opaque, finite JSON proof of the failed exact execution. */\n readonly execution: unknown\n }\n\n/**\n * Execution-neutral model-call seam for an external optimizer.\n *\n * The package that owns execution implements this with its exact execution\n * path. For Discovery that owner is Runtime and the identity is an\n * AgentProfile. The loopback proxy owns request validation, limits, response\n * bounds, and cost-ledger recording. Once invoked, the callback must resolve\n * with one success/failure result. Rejecting loses the execution record and\n * therefore fails the optimizer attempt.\n */\nexport type ExternalOptimizerModelCall = (\n request: ExternalOptimizerModelCallRequest,\n) => Promise<ExternalOptimizerModelCallResult>\n\n/** One opaque Runtime execution record retained for one admitted model call. */\nexport type ExternalOptimizerModelExecutionObservation =\n | {\n readonly sequence: number\n readonly callId: string\n readonly callRef: string\n readonly path: '/v1/chat/completions' | '/v1/responses'\n readonly model: string\n readonly succeeded: true\n readonly responseStatus: number\n readonly execution: unknown\n }\n | {\n readonly sequence: number\n readonly callId: string\n readonly callRef: string\n readonly path: '/v1/chat/completions' | '/v1/responses'\n readonly model: string\n readonly succeeded: false\n readonly error: string\n readonly execution: unknown\n }\n\nexport type ExternalOptimizerEvaluationRefusalReason =\n | 'invalid-request'\n | 'evaluation-limit'\n | 'evaluation-failed'\n\n/**\n * Durable callback-side record of every candidate submitted for scoring,\n * scored task, and callback refusal. Optimizer-internal proposals that never\n * reach this callback are outside this record's scope.\n */\nexport type ExternalOptimizerEvaluationObservation =\n | {\n readonly kind: 'proposal'\n readonly sequence: number\n readonly candidate: ExternalTextCandidate\n readonly candidateHash: string\n }\n | {\n readonly kind: 'evaluation'\n readonly sequence: number\n readonly candidate: ExternalTextCandidate\n readonly candidateHash: string\n readonly exampleId: string\n /** One-based accepted evaluation number for this optimizer attempt. */\n readonly evaluationNumber: number\n readonly response: unknown\n }\n | {\n readonly kind: 'refusal'\n readonly sequence: number\n readonly reason: ExternalOptimizerEvaluationRefusalReason\n readonly candidate?: ExternalTextCandidate\n readonly candidateHash?: string\n readonly exampleId?: string\n }\n\nexport interface ExternalOptimizerModelBudget {\n /** Optional optimizer-model spend ceiling, independent of task-evaluation spend. */\n maxCostUsd?: number\n /** Maximum calls into the execution owner; owner-internal retries are reported there. */\n maxRequests: number\n /** Reject a request body above this byte count. */\n maxRequestBytes: number\n /** Reject a provider response above this byte count. */\n maxResponseBytes: number\n /** Reject a request asking the provider for more output tokens. */\n maxOutputTokensPerRequest: number\n /**\n * Reasoning tokens a single response may bill beyond its completion limit.\n *\n * A reasoning model bounds only the completion by `max_tokens` and bills\n * thinking on top, so a reservation sized to the completion alone is always\n * too small and the ledger refuses the real charge. Callers that route a\n * reasoning model declare its thinking budget here; the reservation covers\n * it and a response exceeding it still fails loudly. Default: 0.\n */\n maxReasoningTokensPerRequest?: number\n /**\n * Optional rates used to estimate cost when the provider omits a valid\n * `usage.cost`. Omit when billed USD is unknown; catalog estimates are not\n * enforcement evidence.\n */\n pricing?: CustomTokenPricing\n /** Per-provider-request deadline. Default: 300,000 ms. */\n requestTimeoutMs?: number\n}\n\nexport interface ExternalOptimizerModelProxy {\n /** OpenAI-compatible base URL supplied to the optimizer process. */\n baseUrl: string\n /** Ephemeral credential supplied only to the local proxy. */\n apiKey: string\n /** Execution-owner calls admitted during this proxy process, including failures. */\n requestAttempts: () => number\n /** Successful 2xx responses recorded during this proxy process. */\n successfulCompletions: () => number\n /** Fail if an invoked caller-owned model path omitted its execution record. */\n assertExecutionComplete: () => void\n /** Failures retained by the proxy after converting them to loopback responses. */\n failures: () => readonly Error[]\n close: () => Promise<void>\n}\n\nexport function isCandidateText(value: unknown, maxChars: number): value is string {\n return typeof value === 'string' && value.trim().length > 0 && value.length <= maxChars\n}\n\nexport function isExternalTextCandidate(value: unknown): value is ExternalTextCandidate {\n if (typeof value === 'string') return value.trim().length > 0\n if (!isRecord(value)) return false\n const entries = Object.entries(value)\n return (\n entries.length > 0 &&\n entries.every(\n ([name, content]) =>\n name.trim().length > 0 && name.trim() === name && typeof content === 'string',\n )\n )\n}\n\nexport function assertJsonValue(value: unknown, label: string, seen = new Set<object>()): void {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return\n if (typeof value === 'number' && Number.isFinite(value)) return\n if (Array.isArray(value)) {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n seen.add(value)\n for (const item of value) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n if (typeof value === 'object') {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be JSON-serializable`)\n }\n seen.add(value)\n for (const item of Object.values(value)) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n throw new Error(`${label} must be JSON-serializable`)\n}\n\nexport function assertNoCredentialValues(\n value: unknown,\n path: string,\n credentialLocation = 'runner.env',\n): void {\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n assertNoCredentialValues(item, `${path}[${index}]`, credentialLocation)\n }\n return\n }\n if (!isRecord(value)) return\n for (const [key, item] of Object.entries(value)) {\n if (isCredentialKey(key)) {\n throw new Error(`${path}.${key} must be supplied through ${credentialLocation}`)\n }\n assertNoCredentialValues(item, `${path}.${key}`, credentialLocation)\n }\n}\n\nexport function removeCredentialEnvironment(\n environment: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n const sanitized: Record<string, string> = {}\n for (const [key, value] of Object.entries(environment)) {\n if (value !== undefined && !isCredentialKey(key)) sanitized[key] = value\n }\n return sanitized\n}\n\nexport function assertExternalOptimizerModelBudget(\n value: ExternalOptimizerModelBudget,\n label: string,\n): void {\n if (!value || typeof value !== 'object') {\n throw new Error(`${label} is required`)\n }\n for (const [field, entry] of [\n ['maxRequests', value.maxRequests],\n ['maxOutputTokensPerRequest', value.maxOutputTokensPerRequest],\n ] as const) {\n if (!Number.isSafeInteger(entry) || entry <= 0) {\n throw new Error(`${label}.${field} must be a positive safe integer`)\n }\n }\n assertBoundedPositiveInteger(\n value.maxRequestBytes,\n `${label}.maxRequestBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n value.maxResponseBytes,\n `${label}.maxResponseBytes`,\n MAXIMUM_JSON_BYTES,\n )\n if (\n value.maxReasoningTokensPerRequest !== undefined &&\n (!Number.isSafeInteger(value.maxReasoningTokensPerRequest) ||\n value.maxReasoningTokensPerRequest < 0)\n ) {\n throw new Error(`${label}.maxReasoningTokensPerRequest must be a non-negative safe integer`)\n }\n if (\n value.maxCostUsd !== undefined &&\n (!Number.isFinite(value.maxCostUsd) || value.maxCostUsd <= 0)\n ) {\n throw new Error(`${label}.maxCostUsd must be positive and finite when supplied`)\n }\n if (\n value.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(value.requestTimeoutMs) ||\n value.requestTimeoutMs <= 0 ||\n value.requestTimeoutMs > MAX_TIMER_DELAY_MS)\n ) {\n throw new Error(`${label}.requestTimeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n if (value.pricing !== undefined) {\n costForTokenPricing(value.pricing, { inputTokens: 1, outputTokens: 1 })\n }\n if (value.maxCostUsd !== undefined && value.pricing === undefined) {\n throw new Error(`${label}.pricing is required when maxCostUsd is supplied`)\n }\n}\n\nexport function safePathComponent(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, '_')\n}\n\nfunction assertBoundedPositiveInteger(value: number, label: string, maximum: number): void {\n if (!Number.isSafeInteger(value) || value <= 0 || value > maximum) {\n throw new Error(`${label} must be an integer between 1 and ${maximum}`)\n }\n}\n\nfunction isCredentialKey(key: string): boolean {\n const normalized = key\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/-/g, '_')\n .toLowerCase()\n const segments = normalized.split('_')\n return segments.some((segment) =>\n [\n 'auth',\n 'authorization',\n 'cookie',\n 'credential',\n 'credentials',\n 'key',\n 'password',\n 'secret',\n 'session',\n 'token',\n ].includes(segment),\n )\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","import type { Server, ServerResponse } from 'node:http'\n\nexport function listenLocal(server: Server): Promise<number> {\n return new Promise((resolvePromise, reject) => {\n server.once('error', reject)\n server.listen(0, '127.0.0.1', () => {\n server.off('error', reject)\n const address = server.address()\n if (!address || typeof address === 'string') {\n reject(new Error('external optimizer callback did not bind a TCP port'))\n return\n }\n resolvePromise(address.port)\n })\n })\n}\n\nexport function closeServer(server: Server): Promise<void> {\n return new Promise((resolvePromise, reject) => {\n server.close((error) => (error ? reject(error) : resolvePromise()))\n })\n}\n\nexport function sendJson(response: ServerResponse, status: number, body: unknown): void {\n response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })\n response.end(JSON.stringify(body))\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport type { ChatResponse } from '../analyst/chat-client'\nimport type {\n CostChannel,\n CostLedgerHandle,\n CostReceiptInput,\n CustomTokenPricing,\n} from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { assertServedModel, ModelSubstitutionError } from '../integrity/served-model'\nimport { canonicalJson } from '../verdict-cache'\nimport {\n assertExternalOptimizerModelBudget,\n assertJsonValue,\n type ExternalOptimizerChatRequest,\n type ExternalOptimizerEndpointFormat,\n type ExternalOptimizerModelBudget,\n type ExternalOptimizerModelCall,\n type ExternalOptimizerModelExecutionObservation,\n type ExternalOptimizerModelProxy,\n isRecord,\n} from './external-optimizer-contracts'\nimport { closeServer, listenLocal, sendJson } from './external-optimizer-http'\n\nconst MODEL_PROXY_PATHS = new Set(['/v1/chat/completions', '/v1/responses'])\ntype ModelProxyPath = '/v1/chat/completions' | '/v1/responses'\n\ntype UnsequencedExecutionObservation = ExternalOptimizerModelExecutionObservation extends infer T\n ? T extends ExternalOptimizerModelExecutionObservation\n ? Omit<T, 'sequence'>\n : never\n : never\n\ninterface ProviderProxyResponse {\n status: number\n contentType: string\n body: Uint8Array\n receipt: CostReceiptInput\n usageComplete: boolean\n /** A Runtime-owned call failed after returning complete execution evidence. */\n modelCallFailed?: string\n /** Set when the response violated the output or reasoning limit; forces a 502. */\n usageRejected?: string\n}\n\ntype ExternalOptimizerModelProxyArgs = {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n costLedger: CostLedgerHandle\n phase: string\n actor: string\n /** Cost-ledger channel. Defaults to `optimizer`. */\n channel?: CostChannel\n tags?: Record<string, string>\n /** Deterministic ledger identity for a single-request proxy. */\n callId?: string\n initialUsage?: {\n requests: number\n /** Known billed subtotal. Omit when prior billed USD is unknown. */\n costUsd?: number\n }\n signal?: AbortSignal\n}\n\n/**\n * Put an OpenAI-compatible optimizer behind the shared cost ledger.\n *\n * The child process receives only a loopback URL and an ephemeral token. The\n * package that owns execution receives a validated immutable request through\n * `call`; Eval receives no provider credential. Every request reserves its\n * conservative byte-count input bound plus the declared output cap before the\n * owner is invoked exactly once.\n */\nexport async function startExternalOptimizerModelProxy(\n args: ExternalOptimizerModelProxyArgs,\n): Promise<ExternalOptimizerModelProxy> {\n assertModelProxyConfig(args)\n args.signal?.throwIfAborted()\n const token = randomLocalToken()\n let requestCount = 0\n let successfulCompletionCount = 0\n let modelCallInvocations = 0\n let executionRecordCount = 0\n let executionSequence = 0\n const failures: Error[] = []\n let totalRequestCount = args.initialUsage?.requests ?? 0\n let committedForBudget = args.initialUsage?.costUsd ?? 0\n let reservedForBudget = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'external optimizer model proxy is closing' })\n return\n }\n\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleModelProxyRequest({\n request,\n response,\n controller,\n token,\n args,\n nextReservation: (maximumCostUsd) => {\n if (totalRequestCount >= args.budget.maxRequests) {\n return { accepted: false as const, reason: 'optimizer model request limit reached' }\n }\n if (\n args.budget.maxCostUsd !== undefined &&\n maximumCostUsd !== undefined &&\n committedForBudget + reservedForBudget + maximumCostUsd >\n args.budget.maxCostUsd + Number.EPSILON\n ) {\n return { accepted: false as const, reason: 'optimizer model cost limit reached' }\n }\n requestCount += 1\n totalRequestCount += 1\n reservedForBudget += maximumCostUsd ?? 0\n return { accepted: true as const }\n },\n settleReservation: (maximumCostUsd, chargedCostUsd) => {\n reservedForBudget = Math.max(0, reservedForBudget - (maximumCostUsd ?? 0))\n committedForBudget += chargedCostUsd ?? 0\n },\n recordSuccessfulCompletion: () => {\n successfulCompletionCount += 1\n },\n recordExecutionReceipt: (observation) => {\n try {\n args.recordExecution({ ...observation, sequence: executionSequence + 1 })\n } catch (error) {\n throw new ModelExecutionPersistenceError(\n `optimizer model execution evidence was not persisted: ${toErrorMessage(error)}`,\n )\n }\n executionSequence += 1\n executionRecordCount += 1\n },\n recordModelCallInvocation: () => {\n modelCallInvocations += 1\n },\n recordFailure: (error) => {\n failures.push(error)\n },\n }).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeModelProxy()\n return closePromise\n }\n const onAbort = (): void => {\n for (const controller of activeControllers) controller.abort(args.signal?.reason)\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n const assertExecutionComplete = (): void => {\n if (executionRecordCount !== modelCallInvocations) {\n throw new Error(\n `external optimizer model callback returned ${executionRecordCount} execution records for ${modelCallInvocations} invoked calls`,\n )\n }\n }\n return {\n baseUrl: `http://127.0.0.1:${port}/v1`,\n apiKey: token,\n requestAttempts: () => requestCount,\n successfulCompletions: () => successfulCompletionCount,\n assertExecutionComplete,\n failures: () => [...failures],\n close,\n }\n\n async function closeModelProxy(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('external optimizer model proxy closed with active request work')\n }\n let executionError: unknown\n try {\n assertExecutionComplete()\n } catch (error) {\n executionError = error\n }\n if (serverResult?.status === 'rejected' && executionError !== undefined) {\n throw new AggregateError(\n [serverResult.reason, executionError],\n 'external optimizer model proxy close and execution evidence both failed',\n )\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n if (executionError !== undefined) throw executionError\n }\n}\n\nasync function handleModelProxyRequest(args: {\n request: IncomingMessage\n response: ServerResponse\n controller: AbortController\n token: string\n args: {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n costLedger: CostLedgerHandle\n phase: string\n actor: string\n channel?: CostChannel\n tags?: Record<string, string>\n callId?: string\n }\n nextReservation: (maximumCostUsd: number | undefined) =>\n | { accepted: true }\n | {\n accepted: false\n reason: 'optimizer model request limit reached' | 'optimizer model cost limit reached'\n }\n settleReservation: (\n maximumCostUsd: number | undefined,\n chargedCostUsd: number | undefined,\n ) => void\n recordSuccessfulCompletion: () => void\n recordExecutionReceipt: (observation: UnsequencedExecutionObservation) => void\n recordModelCallInvocation: () => void\n recordFailure: (error: Error) => void\n}): Promise<void> {\n const { controller, request, response } = args\n try {\n const path = request.url ? new URL(request.url, 'http://127.0.0.1').pathname : ''\n if (request.method !== 'POST' || !MODEL_PROXY_PATHS.has(path)) {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n const modelPath = path as ModelProxyPath\n if (request.headers.authorization !== `Bearer ${args.token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n\n const body = await readBody(request, args.args.budget.maxRequestBytes)\n const parsed = parseModelProxyRequest(body, modelPath, args.args.model, args.args.budget)\n const maximumUsage = conservativeMaximumUsage(\n body.byteLength,\n parsed.maxOutputTokens + (args.args.budget.maxReasoningTokensPerRequest ?? 0),\n args.args.budget.pricing,\n )\n const maximumCostUsd = args.args.budget.pricing\n ? costForTokenPricing(args.args.budget.pricing, maximumUsage)\n : undefined\n const reservation = args.nextReservation(maximumCostUsd)\n if (!reservation.accepted) {\n sendJsonIfOpen(response, 429, { error: reservation.reason })\n return\n }\n\n const timeout = setTimeout(\n () => controller.abort(),\n args.args.budget.requestTimeoutMs ?? 300_000,\n )\n let chargedForBudget = maximumCostUsd\n try {\n const paid = await args.args.costLedger.runPaidCall<ProviderProxyResponse>({\n ...(args.args.callId ? { callId: args.args.callId } : {}),\n channel: args.args.channel ?? 'optimizer',\n phase: args.args.phase,\n actor: args.args.actor,\n ...(args.args.tags ? { tags: args.args.tags } : {}),\n model: args.args.model,\n ...(args.args.budget.pricing\n ? {\n maximumCharge: {\n customTokenPricing: args.args.budget.pricing,\n ...maximumUsage,\n },\n }\n : {}),\n signal: controller.signal,\n execute: async (paidCallSignal, paidCallId) =>\n forwardModelProxyRequest({\n call: args.args.call,\n callId: paidCallId,\n callRef: args.args.callRef,\n recordExecutionReceipt: args.recordExecutionReceipt,\n recordModelCallInvocation: args.recordModelCallInvocation,\n path: modelPath,\n request: parsed.request,\n model: args.args.model,\n maxOutputTokens: parsed.maxOutputTokens,\n ...(args.args.budget.maxReasoningTokensPerRequest === undefined\n ? {}\n : { maxReasoningTokens: args.args.budget.maxReasoningTokensPerRequest }),\n maxResponseBytes: args.args.budget.maxResponseBytes,\n signal: paidCallSignal,\n }),\n receipt: (result) => result.receipt,\n receiptFromError: () => ({\n model: args.args.model,\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n usageUnknown: true,\n }),\n })\n if (!paid.succeeded) {\n args.recordFailure(paid.error)\n chargedForBudget = paid.receipt\n ? paid.receipt.usageUnknown || paid.receipt.costUnknown\n ? maximumCostUsd\n : paid.receipt.costUsd\n : undefined\n sendJsonIfOpen(\n response,\n isAbortError(paid.error)\n ? 504\n : paid.error instanceof ProviderResponseTooLargeError ||\n paid.error instanceof MissingModelExecutionError ||\n paid.error instanceof ModelExecutionPersistenceError ||\n paid.error instanceof OwnerModelContractError ||\n paid.error instanceof ModelSubstitutionError\n ? 502\n : 429,\n { error: paid.error.message },\n )\n return\n }\n if (paid.value.modelCallFailed) {\n sendJsonIfOpen(response, 502, { error: paid.value.modelCallFailed })\n return\n }\n chargedForBudget = paid.value.usageComplete ? paid.receipt.costUsd : maximumCostUsd\n // A response that violated the output or reasoning limit is rejected. A\n // response the provider merely under-reported is forwarded with its cost\n // charged at the reservation maximum, so the analysis keeps its usable\n // completion and the ledger holds an honest upper-bound charge.\n if (paid.value.usageRejected) {\n sendJsonIfOpen(response, 502, { error: paid.value.usageRejected })\n return\n }\n if (paid.value.status >= 200 && paid.value.status < 300) {\n args.recordSuccessfulCompletion()\n }\n if (response.destroyed || response.writableEnded) return\n response.writeHead(paid.value.status, {\n 'content-type': paid.value.contentType,\n 'content-length': String(paid.value.body.byteLength),\n })\n response.end(paid.value.body)\n } finally {\n clearTimeout(timeout)\n args.settleReservation(maximumCostUsd, chargedForBudget)\n }\n } catch (error) {\n const status =\n error instanceof RequestBodyTooLargeError\n ? 413\n : error instanceof Error && isAbortError(error)\n ? 503\n : 400\n sendJsonIfOpen(response, status, { error: toErrorMessage(error) })\n }\n}\n\nasync function waitForActiveHandlers(activeHandlers: Set<Promise<void>>): Promise<void> {\n while (activeHandlers.size > 0) {\n await Promise.allSettled([...activeHandlers])\n }\n}\n\nfunction sendJsonIfOpen(response: ServerResponse, status: number, body: unknown): void {\n if (response.destroyed || response.writableEnded) return\n sendJson(response, status, body)\n}\n\nasync function forwardModelProxyRequest(args: {\n call: ExternalOptimizerModelCall\n callId: string\n callRef: string\n recordExecutionReceipt: (observation: UnsequencedExecutionObservation) => void\n recordModelCallInvocation: () => void\n path: ModelProxyPath\n request: ExternalOptimizerChatRequest\n model: string\n maxOutputTokens: number\n /** Enforced only when the caller declared a thinking budget. */\n maxReasoningTokens?: number\n maxResponseBytes: number\n signal: AbortSignal\n}): Promise<ProviderProxyResponse> {\n args.recordModelCallInvocation()\n let called: Awaited<ReturnType<ExternalOptimizerModelCall>>\n try {\n called = await args.call({\n callId: args.callId,\n request: freezeJsonSnapshot(\n args.request,\n 'optimizer model canonical request',\n ) as ExternalOptimizerChatRequest,\n endpointFormat: endpointFormat(args.path),\n signal: args.signal,\n })\n } catch (error) {\n throw new MissingModelExecutionError(\n `optimizer model callback rejected without execution evidence: ${toErrorMessage(error)}`,\n )\n }\n if (!called || typeof called !== 'object' || typeof called.succeeded !== 'boolean') {\n throw new MissingModelExecutionError(\n 'optimizer model callback returned no typed success/failure outcome',\n )\n }\n let execution: unknown\n try {\n execution = freezeJsonSnapshot(called.execution, 'optimizer model callback execution evidence')\n } catch (error) {\n throw new MissingModelExecutionError(\n `optimizer model callback returned invalid execution evidence: ${toErrorMessage(error)}`,\n )\n }\n if (called.succeeded) {\n let authoritativeReceipt: CostReceiptInput\n let canonicalResponse: ChatResponse\n try {\n authoritativeReceipt = snapshotModelReceipt(called.receipt, args.model)\n canonicalResponse = snapshotChatResponse(called.response, args.model)\n assertResponseUsageMatchesReceipt(canonicalResponse, authoritativeReceipt)\n } catch (error) {\n args.recordExecutionReceipt({\n callId: args.callId,\n callRef: args.callRef,\n path: args.path,\n model: args.model,\n succeeded: false,\n error: toErrorMessage(error),\n execution,\n })\n throw error\n }\n args.recordExecutionReceipt({\n callId: args.callId,\n callRef: args.callRef,\n path: args.path,\n model: args.model,\n succeeded: true,\n responseStatus: 200,\n execution,\n })\n // Output tokens include the reasoning subset. The child's requested\n // completion limit governs visible completion tokens, while the separately\n // declared reasoning budget governs thinking tokens.\n const usageKnown = canonicalResponse.usage.captured !== false\n const reasoningTokens = canonicalResponse.usage.reasoningTokens ?? 0\n const completionTokens = canonicalResponse.usage.completionTokens - reasoningTokens\n const usageRejected =\n usageKnown && completionTokens > args.maxOutputTokens\n ? `optimizer model execution reported ${completionTokens} completion tokens, exceeding requested limit ${args.maxOutputTokens}`\n : usageKnown &&\n args.maxReasoningTokens !== undefined &&\n reasoningTokens > args.maxReasoningTokens\n ? `optimizer model execution reported ${reasoningTokens} reasoning tokens, exceeding the declared budget ${args.maxReasoningTokens}`\n : undefined\n const responseBody = encodeCanonicalModelResponse({\n path: args.path,\n callId: args.callId,\n response: canonicalResponse,\n receipt: authoritativeReceipt,\n maxBytes: args.maxResponseBytes,\n })\n return {\n status: 200,\n contentType: 'application/json',\n body: responseBody,\n receipt: authoritativeReceipt,\n usageComplete: authoritativeReceipt.usageUnknown !== true,\n ...(usageRejected ? { usageRejected } : {}),\n }\n } else {\n if (typeof called.error !== 'string' || !called.error.trim()) {\n throw new MissingModelExecutionError(\n 'optimizer model callback failure did not return a public error',\n )\n }\n args.recordExecutionReceipt({\n callId: args.callId,\n callRef: args.callRef,\n path: args.path,\n model: args.model,\n succeeded: false,\n error: called.error,\n execution,\n })\n const failedReceipt = snapshotModelReceipt(called.receipt, args.model)\n return {\n status: 502,\n contentType: 'application/json',\n body: new TextEncoder().encode(JSON.stringify({ error: called.error })),\n receipt: failedReceipt,\n usageComplete: failedReceipt.usageUnknown !== true,\n modelCallFailed: called.error,\n }\n }\n}\n\nfunction snapshotModelReceipt(value: CostReceiptInput, expectedModel: string): CostReceiptInput {\n let snapshot: CostReceiptInput\n try {\n assertJsonValue(value, 'optimizer model callback receipt')\n snapshot = JSON.parse(canonicalJson(value)) as CostReceiptInput\n } catch (error) {\n throw new OwnerModelContractError(\n `optimizer model callback returned an invalid receipt: ${toErrorMessage(error)}`,\n )\n }\n assertServedModel(expectedModel, snapshot.model, {\n context: 'optimizer model callback receipt',\n })\n return snapshot\n}\n\nfunction freezeJsonSnapshot(value: unknown, label: string): unknown {\n assertJsonValue(value, label)\n return deepFreezeJson(JSON.parse(canonicalJson(value)))\n}\n\nfunction deepFreezeJson(value: unknown): unknown {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) deepFreezeJson(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction assertResponseUsageMatchesReceipt(\n response: ChatResponse,\n receipt: CostReceiptInput,\n): void {\n if (response.model !== receipt.model) {\n throw new OwnerModelContractError(\n 'optimizer model response and execution receipt disagree about the served model',\n )\n }\n if (response.usage.captured === false || receipt.usageUnknown === true) {\n if (response.usage.captured !== false || receipt.usageUnknown !== true) {\n throw new OwnerModelContractError(\n 'optimizer model response and execution receipt disagree about whether usage was captured',\n )\n }\n } else {\n const cachedTokens = response.usage.cachedPromptTokens ?? 0\n if (receipt.inputTokens + (receipt.cachedTokens ?? 0) !== response.usage.promptTokens) {\n throw new OwnerModelContractError(\n 'optimizer model response promptTokens must equal receipt inputTokens plus cachedTokens',\n )\n }\n if (cachedTokens !== (receipt.cachedTokens ?? 0)) {\n throw new OwnerModelContractError(\n 'optimizer model response cachedPromptTokens disagrees with the execution receipt',\n )\n }\n if (response.usage.completionTokens !== receipt.outputTokens) {\n throw new OwnerModelContractError(\n 'optimizer model response completionTokens disagrees with the execution receipt',\n )\n }\n if ((response.usage.reasoningTokens ?? 0) !== (receipt.reasoningTokens ?? 0)) {\n throw new OwnerModelContractError(\n 'optimizer model response reasoningTokens disagrees with the execution receipt',\n )\n }\n }\n const receiptCostUsd =\n receipt.actualCostUsd ??\n receipt.estimatedCostUsd ??\n (receipt.customTokenPricing && receipt.usageUnknown !== true\n ? costForTokenPricing(receipt.customTokenPricing, receipt)\n : null)\n if (response.costUsd !== receiptCostUsd) {\n throw new OwnerModelContractError(\n 'optimizer model response billed cost disagrees with the execution receipt',\n )\n }\n}\n\nfunction parseModelProxyRequest(\n body: Uint8Array,\n path: ModelProxyPath,\n expectedModel: string,\n budget: ExternalOptimizerModelBudget,\n): { maxOutputTokens: number; request: ExternalOptimizerChatRequest } {\n let value: unknown\n try {\n value = JSON.parse(Buffer.from(body).toString('utf8'))\n } catch {\n throw new Error('optimizer model request must be valid JSON')\n }\n if (!isRecord(value)) throw new Error('optimizer model request must be a JSON object')\n if (value.model !== expectedModel) {\n throw new Error(`optimizer model request must use configured model '${expectedModel}'`)\n }\n if (value.stream !== undefined && value.stream !== false) {\n throw new Error('streaming optimizer model requests are not supported')\n }\n for (const field of ['n', 'best_of', 'candidate_count', 'num_candidates'] as const) {\n if (value[field] !== undefined && value[field] !== 1) {\n throw new Error(`optimizer model request ${field} must be 1 when supplied`)\n }\n }\n if (value.reasoning !== undefined || value.reasoning_effort !== undefined) {\n throw new Error('optimizer model reasoning settings belong to the execution AgentProfile')\n }\n const maxOutputTokens = parseOutputMaximum(\n value,\n path === '/v1/responses'\n ? ['max_output_tokens']\n : ['max_tokens', 'max_completion_tokens', 'max_output_tokens'],\n )\n if (maxOutputTokens > budget.maxOutputTokensPerRequest) {\n throw new Error('optimizer model request exceeds maxOutputTokensPerRequest')\n }\n const request =\n path === '/v1/chat/completions'\n ? parseChatCompletionsRequest(value, expectedModel, maxOutputTokens)\n : parseResponsesRequest(value, expectedModel, maxOutputTokens)\n return {\n maxOutputTokens,\n request: freezeJsonSnapshot(\n request,\n 'optimizer model canonical request',\n ) as ExternalOptimizerChatRequest,\n }\n}\n\nfunction parseChatCompletionsRequest(\n body: Record<string, unknown>,\n model: string,\n maxTokens: number,\n): Omit<ExternalOptimizerChatRequest, never> {\n assertAllowedKeys(body, [\n 'model',\n 'messages',\n 'max_tokens',\n 'max_completion_tokens',\n 'max_output_tokens',\n 'temperature',\n 'thinking',\n 'response_format',\n 'stream',\n 'n',\n 'best_of',\n 'candidate_count',\n 'num_candidates',\n ])\n return {\n model,\n messages: parseChatMessages(body.messages),\n maxTokens,\n ...parseTemperature(body.temperature),\n ...parseThinking(body.thinking),\n ...parseChatResponseFormat(body.response_format),\n }\n}\n\nfunction parseResponsesRequest(\n body: Record<string, unknown>,\n model: string,\n maxTokens: number,\n): Omit<ExternalOptimizerChatRequest, never> {\n assertAllowedKeys(body, [\n 'model',\n 'input',\n 'instructions',\n 'max_output_tokens',\n 'temperature',\n 'thinking',\n 'text',\n 'stream',\n 'n',\n 'best_of',\n 'candidate_count',\n 'num_candidates',\n ])\n const instructions = body.instructions\n if (instructions !== undefined && typeof instructions !== 'string') {\n throw new Error('optimizer Responses instructions must be a string')\n }\n return {\n model,\n messages: [\n ...(instructions === undefined ? [] : [{ role: 'system' as const, content: instructions }]),\n ...parseResponsesInput(body.input),\n ],\n maxTokens,\n ...parseTemperature(body.temperature),\n ...parseThinking(body.thinking),\n ...parseResponsesTextFormat(body.text),\n }\n}\n\nfunction parseOutputMaximum(body: Record<string, unknown>, fields: readonly string[]): number {\n const supplied = fields.flatMap((field) =>\n body[field] === undefined ? [] : [{ field, value: body[field] }],\n )\n if (\n supplied.length === 0 ||\n supplied.some(({ value }) => !Number.isSafeInteger(value) || (value as number) <= 0)\n ) {\n throw new Error('optimizer model request requires a positive output-token limit')\n }\n const values = new Set(supplied.map(({ value }) => value as number))\n if (values.size !== 1) {\n throw new Error('optimizer model request supplied conflicting output-token limits')\n }\n return supplied[0]!.value as number\n}\n\nfunction parseTemperature(value: unknown): { temperature?: number } {\n if (value === undefined) return {}\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error('optimizer model request temperature must be finite')\n }\n return { temperature: value }\n}\n\nfunction parseThinking(value: unknown): { thinking?: 'enabled' | 'disabled' } {\n if (value === undefined) return {}\n if (!isRecord(value)) {\n throw new Error('optimizer model request thinking must be an object')\n }\n assertAllowedKeys(value, ['type'], 'optimizer model request thinking')\n if (value.type !== 'enabled' && value.type !== 'disabled') {\n throw new Error('optimizer model request thinking.type must be enabled or disabled')\n }\n return { thinking: value.type }\n}\n\nfunction parseChatMessages(value: unknown): ExternalOptimizerChatRequest['messages'] {\n if (!Array.isArray(value)) throw new Error('optimizer chat request messages must be an array')\n return value.map((message, index) => parseMessage(message, `optimizer chat message ${index}`))\n}\n\nfunction parseResponsesInput(value: unknown): ExternalOptimizerChatRequest['messages'] {\n if (typeof value === 'string') return [{ role: 'user', content: value }]\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error('optimizer Responses request requires non-empty input')\n }\n return value.map((message, index) => {\n if (!isRecord(message)) {\n throw new Error(`optimizer Responses input ${index} must be a message object`)\n }\n assertAllowedKeys(message, ['type', 'role', 'content'], `optimizer Responses input ${index}`)\n if (message.type !== undefined && message.type !== 'message') {\n throw new Error(`optimizer Responses input ${index} type must be message`)\n }\n return parseMessage(message, `optimizer Responses input ${index}`, true)\n })\n}\n\nfunction parseMessage(\n value: unknown,\n label: string,\n responsesContent = false,\n): ExternalOptimizerChatRequest['messages'][number] {\n if (!isRecord(value)) throw new Error(`${label} must be an object`)\n assertAllowedKeys(\n value,\n responsesContent ? ['type', 'role', 'content'] : ['role', 'content'],\n label,\n )\n if (value.role !== 'system' && value.role !== 'user' && value.role !== 'assistant') {\n throw new Error(`${label} role must be system, user, or assistant`)\n }\n return {\n role: value.role,\n content: parseMessageContent(value.content, label, responsesContent),\n }\n}\n\nfunction parseMessageContent(\n value: unknown,\n label: string,\n responsesContent: boolean,\n): ExternalOptimizerChatRequest['messages'][number]['content'] {\n if (typeof value === 'string') return value\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error(`${label} content must be text or a non-empty content array`)\n }\n return value.map((part, partIndex) => {\n if (!isRecord(part)) throw new Error(`${label} content ${partIndex} must be an object`)\n const partLabel = `${label} content ${partIndex}`\n if (part.type === 'text' || (responsesContent && part.type === 'input_text')) {\n assertAllowedKeys(part, ['type', 'text'], partLabel)\n if (typeof part.text !== 'string') throw new Error(`${partLabel} text must be a string`)\n return { type: 'text' as const, text: part.text }\n }\n if (responsesContent && part.type === 'output_text') {\n assertAllowedKeys(part, ['type', 'text'], partLabel)\n if (typeof part.text !== 'string') throw new Error(`${partLabel} text must be a string`)\n return { type: 'text' as const, text: part.text }\n }\n if (part.type === 'image_url') {\n assertAllowedKeys(part, ['type', 'image_url'], partLabel)\n if (!isRecord(part.image_url) || typeof part.image_url.url !== 'string') {\n throw new Error(`${partLabel} image_url must contain a URL string`)\n }\n assertAllowedKeys(part.image_url, ['url', 'detail'], `${partLabel} image_url`)\n const detail = parseImageDetail(part.image_url.detail, partLabel)\n return { type: 'image_url' as const, image_url: { url: part.image_url.url, ...detail } }\n }\n if (responsesContent && part.type === 'input_image') {\n assertAllowedKeys(part, ['type', 'image_url', 'detail'], partLabel)\n if (typeof part.image_url !== 'string') {\n throw new Error(`${partLabel} image_url must be a URL string`)\n }\n const detail = parseImageDetail(part.detail, partLabel)\n return { type: 'image_url' as const, image_url: { url: part.image_url, ...detail } }\n }\n throw new Error(`${partLabel} uses an unsupported content type`)\n })\n}\n\nfunction parseImageDetail(value: unknown, label: string): { detail?: 'auto' | 'low' | 'high' } {\n if (value === undefined) return {}\n if (value !== 'auto' && value !== 'low' && value !== 'high') {\n throw new Error(`${label} image detail must be auto, low, or high`)\n }\n return { detail: value }\n}\n\nfunction parseChatResponseFormat(\n value: unknown,\n): Pick<ExternalOptimizerChatRequest, 'jsonMode' | 'jsonSchema'> {\n if (value === undefined) return {}\n if (!isRecord(value) || typeof value.type !== 'string') {\n throw new Error('optimizer chat response_format must be an object with a type')\n }\n if (value.type === 'text') {\n assertAllowedKeys(value, ['type'], 'optimizer chat response_format')\n return {}\n }\n if (value.type === 'json_object') {\n assertAllowedKeys(value, ['type'], 'optimizer chat response_format')\n return { jsonMode: true }\n }\n if (value.type !== 'json_schema') {\n throw new Error('optimizer chat response_format type is unsupported')\n }\n assertAllowedKeys(value, ['type', 'json_schema'], 'optimizer chat response_format')\n return { jsonSchema: parseJsonSchema(value.json_schema, 'optimizer chat response_format') }\n}\n\nfunction parseResponsesTextFormat(\n value: unknown,\n): Pick<ExternalOptimizerChatRequest, 'jsonMode' | 'jsonSchema'> {\n if (value === undefined) return {}\n if (!isRecord(value)) throw new Error('optimizer Responses text must be an object')\n assertAllowedKeys(value, ['format'], 'optimizer Responses text')\n if (value.format === undefined) return {}\n if (!isRecord(value.format) || typeof value.format.type !== 'string') {\n throw new Error('optimizer Responses text.format must be an object with a type')\n }\n const format = value.format\n if (format.type === 'text') {\n assertAllowedKeys(format, ['type'], 'optimizer Responses text.format')\n return {}\n }\n if (format.type === 'json_object') {\n assertAllowedKeys(format, ['type'], 'optimizer Responses text.format')\n return { jsonMode: true }\n }\n if (format.type !== 'json_schema') {\n throw new Error('optimizer Responses text.format type is unsupported')\n }\n return { jsonSchema: parseJsonSchema(format, 'optimizer Responses text.format', true) }\n}\n\nfunction parseJsonSchema(\n value: unknown,\n label: string,\n flat = false,\n): { name: string; schema: Record<string, unknown> } {\n if (!isRecord(value)) throw new Error(`${label} JSON schema must be an object`)\n assertAllowedKeys(value, ['name', 'schema', 'strict', ...(flat ? ['type'] : [])], label)\n if (typeof value.name !== 'string' || !value.name.trim()) {\n throw new Error(`${label} JSON schema name must be non-empty`)\n }\n if (!isRecord(value.schema)) throw new Error(`${label} JSON schema body must be an object`)\n if (value.strict !== undefined && value.strict !== true) {\n throw new Error(`${label} JSON schema strict must be true when supplied`)\n }\n return {\n name: value.name,\n schema: freezeJsonSnapshot(value.schema, `${label} schema`) as Record<string, unknown>,\n }\n}\n\nfunction assertAllowedKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n label = 'optimizer model request',\n): void {\n const allowedSet = new Set(allowed)\n const unknown = Object.keys(value).filter((key) => !allowedSet.has(key))\n if (unknown.length > 0)\n throw new Error(`${label} contains unsupported fields: ${unknown.join(', ')}`)\n}\n\nfunction snapshotChatResponse(value: unknown, expectedModel: string): ChatResponse {\n if (!isRecord(value)) {\n throw new OwnerModelContractError('optimizer model callback response must be an object')\n }\n if (typeof value.content !== 'string') {\n throw new OwnerModelContractError('optimizer model callback response content must be a string')\n }\n assertServedModel(expectedModel, typeof value.model === 'string' ? value.model : null, {\n context: 'optimizer model callback response',\n })\n if (!isNonnegativeFiniteNumber(value.durationMs)) {\n throw new OwnerModelContractError(\n 'optimizer model callback response durationMs must be finite and non-negative',\n )\n }\n if (value.costUsd !== null && !isNonnegativeFiniteNumber(value.costUsd)) {\n throw new OwnerModelContractError(\n 'optimizer model callback response costUsd must be null or finite and non-negative',\n )\n }\n if (\n value.finishReason !== undefined &&\n value.finishReason !== null &&\n typeof value.finishReason !== 'string'\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response finishReason must be a string or null',\n )\n }\n if (\n value.contentEmpty !== undefined &&\n (typeof value.contentEmpty !== 'boolean' ||\n value.contentEmpty !== (value.content.trim().length === 0))\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response contentEmpty must match content',\n )\n }\n if (!isRecord(value.raw)) {\n throw new OwnerModelContractError('optimizer model callback response raw must be an object')\n }\n if (!isRecord(value.usage)) {\n throw new OwnerModelContractError('optimizer model callback response usage must be an object')\n }\n const usage = value.usage\n for (const field of ['promptTokens', 'completionTokens', 'totalTokens'] as const) {\n if (!isNonnegativeSafeInteger(usage[field])) {\n throw new OwnerModelContractError(\n `optimizer model callback response usage.${field} must be a non-negative safe integer`,\n )\n }\n }\n const promptTokens = usage.promptTokens as number\n const completionTokens = usage.completionTokens as number\n const totalTokens = usage.totalTokens as number\n if (totalTokens !== promptTokens + completionTokens) {\n throw new OwnerModelContractError(\n 'optimizer model callback response totalTokens must equal promptTokens plus completionTokens',\n )\n }\n if (usage.captured !== undefined && typeof usage.captured !== 'boolean') {\n throw new OwnerModelContractError(\n 'optimizer model callback response usage.captured must be a boolean',\n )\n }\n if (\n usage.cachedPromptTokens !== undefined &&\n (!isNonnegativeSafeInteger(usage.cachedPromptTokens) || usage.cachedPromptTokens > promptTokens)\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response cachedPromptTokens must be a subset of promptTokens',\n )\n }\n if (\n usage.reasoningTokens !== undefined &&\n (!isNonnegativeSafeInteger(usage.reasoningTokens) || usage.reasoningTokens > completionTokens)\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response reasoningTokens must be a subset of completionTokens',\n )\n }\n let raw: Record<string, unknown>\n try {\n raw = freezeJsonSnapshot(\n value.raw,\n 'optimizer model callback canonical response.raw',\n ) as Record<string, unknown>\n } catch (error) {\n throw new OwnerModelContractError(\n `optimizer model callback returned invalid raw response evidence: ${toErrorMessage(error)}`,\n )\n }\n return deepFreezeJson({\n content: value.content,\n usage: {\n promptTokens,\n completionTokens,\n totalTokens,\n ...(usage.captured === undefined ? {} : { captured: usage.captured }),\n ...(usage.reasoningTokens === undefined ? {} : { reasoningTokens: usage.reasoningTokens }),\n ...(usage.cachedPromptTokens === undefined\n ? {}\n : { cachedPromptTokens: usage.cachedPromptTokens }),\n },\n costUsd: value.costUsd,\n model: value.model,\n durationMs: value.durationMs,\n ...(value.finishReason === undefined ? {} : { finishReason: value.finishReason }),\n ...(value.contentEmpty === undefined ? {} : { contentEmpty: value.contentEmpty }),\n raw,\n }) as ChatResponse\n}\n\nfunction encodeCanonicalModelResponse(args: {\n path: ModelProxyPath\n callId: string\n response: ChatResponse\n receipt: CostReceiptInput\n maxBytes: number\n}): Uint8Array {\n const usage = encodeProtocolUsage(args.path, args.response, args.receipt)\n const finishReason =\n args.response.finishReason === undefined ? 'stop' : args.response.finishReason\n const body =\n args.path === '/v1/chat/completions'\n ? {\n id: `chatcmpl-${args.callId}`,\n object: 'chat.completion',\n created: 0,\n model: args.response.model,\n choices: [\n {\n index: 0,\n message: { role: 'assistant', content: args.response.content },\n finish_reason: finishReason,\n },\n ],\n ...(usage ? { usage } : {}),\n }\n : {\n id: `resp-${args.callId}`,\n object: 'response',\n created_at: 0,\n model: args.response.model,\n status: finishReason === 'length' ? 'incomplete' : 'completed',\n error: null,\n incomplete_details: finishReason === 'length' ? { reason: 'max_output_tokens' } : null,\n output: [\n {\n id: `msg-${args.callId}`,\n type: 'message',\n status: finishReason === 'length' ? 'incomplete' : 'completed',\n role: 'assistant',\n content: [\n {\n type: 'output_text',\n text: args.response.content,\n annotations: [],\n },\n ],\n },\n ],\n output_text: args.response.content,\n ...(usage ? { usage } : {}),\n }\n const encoded = new TextEncoder().encode(JSON.stringify(body))\n if (encoded.byteLength > args.maxBytes) throw new ProviderResponseTooLargeError()\n return encoded\n}\n\nfunction endpointFormat(path: ModelProxyPath): ExternalOptimizerEndpointFormat {\n return path === '/v1/responses' ? 'responses' : 'chat-completions'\n}\n\nfunction encodeProtocolUsage(\n path: ModelProxyPath,\n response: ChatResponse,\n receipt: CostReceiptInput,\n): Record<string, unknown> | undefined {\n if (response.usage.captured === false) return undefined\n const inputDetails = {\n ...(receipt.cachedTokens === undefined ? {} : { cached_tokens: receipt.cachedTokens }),\n ...(receipt.cacheWriteTokens === undefined\n ? {}\n : path === '/v1/chat/completions'\n ? { cache_creation_tokens: receipt.cacheWriteTokens }\n : { cache_write_tokens: receipt.cacheWriteTokens }),\n }\n const outputDetails = {\n ...(receipt.reasoningTokens === undefined ? {} : { reasoning_tokens: receipt.reasoningTokens }),\n }\n return path === '/v1/chat/completions'\n ? {\n prompt_tokens: response.usage.promptTokens,\n completion_tokens: response.usage.completionTokens,\n total_tokens: response.usage.totalTokens,\n ...(Object.keys(inputDetails).length > 0 ? { prompt_tokens_details: inputDetails } : {}),\n ...(Object.keys(outputDetails).length > 0\n ? { completion_tokens_details: outputDetails }\n : {}),\n ...(receipt.actualCostUsd === undefined ? {} : { cost: receipt.actualCostUsd }),\n }\n : {\n input_tokens: response.usage.promptTokens,\n output_tokens: response.usage.completionTokens,\n total_tokens: response.usage.totalTokens,\n ...(Object.keys(inputDetails).length > 0 ? { input_tokens_details: inputDetails } : {}),\n ...(Object.keys(outputDetails).length > 0 ? { output_tokens_details: outputDetails } : {}),\n ...(receipt.actualCostUsd === undefined ? {} : { cost: receipt.actualCostUsd }),\n }\n}\n\nfunction isNonnegativeFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\nfunction isNonnegativeSafeInteger(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0\n}\n\nfunction conservativeMaximumUsage(\n inputTokenUpperBound: number,\n outputTokenUpperBound: number,\n pricing?: CustomTokenPricing,\n): Pick<CostReceiptInput, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'> {\n if (pricing === undefined) {\n return { inputTokens: inputTokenUpperBound, outputTokens: outputTokenUpperBound }\n }\n const inputRates = [\n pricing.inputUsdPerMillion,\n pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion,\n ]\n const mostExpensiveInputClass = inputRates.indexOf(Math.max(...inputRates))\n return {\n inputTokens: mostExpensiveInputClass === 0 ? inputTokenUpperBound : 0,\n ...(mostExpensiveInputClass === 1 ? { cachedTokens: inputTokenUpperBound } : {}),\n // Cache creation is a separately billed class in CostReceipt. Reserve a\n // full request-sized write in addition to the most expensive prompt class;\n // selecting only one class would understate a call that both reads and writes.\n cacheWriteTokens: inputTokenUpperBound,\n outputTokens: outputTokenUpperBound,\n }\n}\n\nfunction assertModelProxyConfig(args: {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n phase: string\n actor: string\n tags?: Record<string, string>\n callId?: string\n initialUsage?: {\n requests: number\n costUsd?: number\n }\n}): void {\n for (const [label, value] of [\n ['model', args.model],\n ['phase', args.phase],\n ['actor', args.actor],\n ] as const) {\n if (typeof value !== 'string' || !value.trim() || value.trim() !== value) {\n throw new Error(`external optimizer model proxy: ${label} must be trimmed and non-empty`)\n }\n }\n if (typeof args.call !== 'function') {\n throw new Error('external optimizer model proxy: call must be a function')\n }\n if (\n typeof args.callRef !== 'string' ||\n !args.callRef.trim() ||\n args.callRef.trim() !== args.callRef\n ) {\n throw new Error('external optimizer model proxy: callRef must be trimmed and non-empty')\n }\n if (typeof args.recordExecution !== 'function') {\n throw new Error('external optimizer model proxy: recordExecution must be a function')\n }\n if (args.callId !== undefined) {\n if (\n typeof args.callId !== 'string' ||\n !args.callId.trim() ||\n args.callId !== args.callId.trim()\n ) {\n throw new Error('external optimizer model proxy: callId must be trimmed and non-empty')\n }\n if (args.budget.maxRequests !== 1) {\n throw new Error('external optimizer model proxy: callId requires budget.maxRequests to be 1')\n }\n }\n assertExternalOptimizerModelBudget(args.budget, 'external optimizer model proxy: budget')\n if (args.tags !== undefined) {\n for (const [key, value] of Object.entries(args.tags)) {\n if (!key.trim() || key.trim() !== key || !value.trim() || value.trim() !== value) {\n throw new Error('external optimizer model proxy: tags must be trimmed and non-empty')\n }\n }\n }\n if (args.initialUsage !== undefined) {\n if (\n !Number.isSafeInteger(args.initialUsage.requests) ||\n args.initialUsage.requests < 0 ||\n (args.initialUsage.costUsd !== undefined &&\n (!Number.isFinite(args.initialUsage.costUsd) || args.initialUsage.costUsd < 0))\n ) {\n throw new Error(\n 'external optimizer model proxy: initialUsage must contain non-negative requests and cost',\n )\n }\n if (\n args.initialUsage.requests > args.budget.maxRequests ||\n (args.budget.maxCostUsd !== undefined &&\n args.initialUsage.costUsd !== undefined &&\n args.initialUsage.costUsd > args.budget.maxCostUsd + Number.EPSILON)\n ) {\n throw new Error('external optimizer model proxy: initialUsage exceeds the configured budget')\n }\n }\n}\n\nclass RequestBodyTooLargeError extends Error {}\n\nclass ProviderResponseTooLargeError extends Error {\n constructor() {\n super('optimizer model response exceeds maxResponseBytes')\n }\n}\n\nclass MissingModelExecutionError extends Error {}\nclass ModelExecutionPersistenceError extends Error {}\nclass OwnerModelContractError extends Error {}\n\nfunction readBody(request: IncomingMessage, maximumBytes: number): Promise<Uint8Array> {\n return new Promise((resolvePromise, reject) => {\n let size = 0\n let tooLarge = false\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n if (tooLarge) return\n size += chunk.byteLength\n if (size > maximumBytes) {\n tooLarge = true\n chunks.length = 0\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n if (tooLarge) {\n reject(new RequestBodyTooLargeError('optimizer model request body too large'))\n return\n }\n resolvePromise(new Uint8Array(Buffer.concat(chunks)))\n })\n })\n}\n\nfunction randomLocalToken(): string {\n return randomBytes(32).toString('hex')\n}\n\nfunction isAbortError(error: Error): boolean {\n return error.name === 'AbortError' || error.message.toLowerCase().includes('abort')\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import type {\n ExternalOptimizerCallback,\n ExternalOptimizerModelProxy,\n} from './external-optimizer-contracts'\n\nexport async function runWithCleanup<T>(args: {\n label: string\n run: () => Promise<T>\n cleanup: () => Promise<void>\n}): Promise<T> {\n let value: T | undefined\n let operationError: Error | undefined\n try {\n value = await args.run()\n } catch (cause) {\n operationError = toError(cause)\n }\n\n let cleanupError: Error | undefined\n try {\n await args.cleanup()\n } catch (cause) {\n cleanupError = toError(cause)\n }\n\n if (operationError && cleanupError) {\n throw new AggregateError(\n [operationError, cleanupError],\n `${operationError.message}; ${args.label} cleanup failed: ${cleanupError.message}`,\n )\n }\n if (operationError) throw operationError\n if (cleanupError) {\n throw new Error(`${args.label} cleanup failed: ${cleanupError.message}`, {\n cause: cleanupError,\n })\n }\n return value as T\n}\n\nexport async function closeExternalOptimizerResources(args: {\n label: string\n callback: ExternalOptimizerCallback\n modelProxy?: ExternalOptimizerModelProxy\n}): Promise<void> {\n const results = await Promise.allSettled([\n ...(args.modelProxy ? [args.modelProxy.close()] : []),\n args.callback.close(),\n ])\n const errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []))\n if (errors.length > 0) {\n throw new AggregateError(errors, `${args.label}: failed to close optimizer resources`)\n }\n}\n\nfunction toError(cause: unknown): Error {\n return cause instanceof Error ? cause : new Error(String(cause))\n}\n","import { type ChildProcess, spawn } from 'node:child_process'\nimport { lstat, mkdtemp, open, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport {\n type ExternalOptimizerRunnerCommand,\n isRecord,\n resolveExternalOptimizerProcessLimits,\n} from './external-optimizer-contracts'\nimport { runWithCleanup } from './external-optimizer-resources'\n\nconst PROCESS_TERMINATION_GRACE_MS = 5_000\nconst PROCESS_TERMINATION_POLL_MS = 25\nconst PROCESS_KILL_WAIT_MS = 1_000\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\ninterface ProcessOutputCapture {\n full: string | undefined\n head: string\n tail: string\n totalChars: number\n}\n\nexport async function runExternalOptimizerProcess<TOutput>(args: {\n label: string\n tempPrefix: string\n module: string\n input: unknown\n runner?: ExternalOptimizerRunnerCommand\n /** Additional bridge arguments inserted before --input/--output. */\n additionalArgs?: readonly string[]\n timeoutMs: number\n signal?: AbortSignal\n}): Promise<TOutput> {\n if (\n !Number.isSafeInteger(args.timeoutMs) ||\n args.timeoutMs <= 0 ||\n args.timeoutMs > MAX_TIMER_DELAY_MS\n ) {\n throw new Error(`${args.label} timeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n const limits = resolveExternalOptimizerProcessLimits(args.runner?.limits)\n if (process.platform === 'win32') {\n throw new Error(\n `${args.label} requires POSIX process-group cleanup; run the optimizer through WSL or Linux`,\n )\n }\n throwIfAborted(args.signal, args.label)\n const dir = await mkdtemp(join(tmpdir(), args.tempPrefix))\n const inputPath = join(dir, 'input.json')\n const outputPath = join(dir, 'output.json')\n return runWithCleanup({\n label: `${args.label} temporary directory`,\n run: async () => {\n const serializedInput = JSON.stringify(args.input)\n if (serializedInput === undefined) {\n throw new Error(`${args.label} input must be JSON-serializable`)\n }\n const inputJson = `${serializedInput}\\n`\n const inputBytes = Buffer.byteLength(inputJson)\n if (inputBytes > limits.maxInputBytes) {\n throw new Error(`${args.label} input exceeds ${limits.maxInputBytes} bytes (${inputBytes})`)\n }\n await writeFile(inputPath, inputJson)\n const command = resolveRunnerCommand(args.runner?.command ?? 'python')\n const commandArgs = [\n ...(args.runner?.args ?? ['-m', args.module]),\n ...(args.additionalArgs ?? []),\n '--input',\n inputPath,\n '--output',\n outputPath,\n ]\n await runProcess({\n label: args.label,\n command,\n args: commandArgs,\n cwd: dir,\n env: args.runner?.env,\n timeoutMs: args.timeoutMs,\n maxOutputChars: limits.maxOutputChars,\n signal: args.signal,\n })\n throwIfAborted(args.signal, args.label)\n const raw = JSON.parse(\n await readBoundedTextFile(outputPath, limits.maxResultBytes, `${args.label} output`),\n ) as unknown\n throwIfAborted(args.signal, args.label)\n if (!isRecord(raw)) throw new Error(`${args.label} output must be a JSON object`)\n return raw as TOutput\n },\n cleanup: () => rm(dir, { recursive: true, force: true }),\n })\n}\n\nfunction resolveRunnerCommand(command: string): string {\n if (isAbsolute(command) || (!command.includes('/') && !command.includes('\\\\'))) return command\n return resolve(command)\n}\n\nasync function readBoundedTextFile(path: string, maxBytes: number, label: string): Promise<string> {\n const entry = await lstat(path)\n if (!entry.isFile()) throw new Error(`${label} must be a regular file`)\n const file = await open(path, 'r')\n try {\n const buffer = Buffer.allocUnsafe(maxBytes + 1)\n let bytesRead = 0\n while (bytesRead < buffer.byteLength) {\n const chunk = await file.read(buffer, bytesRead, buffer.byteLength - bytesRead, bytesRead)\n if (chunk.bytesRead === 0) break\n bytesRead += chunk.bytesRead\n }\n if (bytesRead > maxBytes) {\n throw new Error(`${label} exceeds ${maxBytes} bytes`)\n }\n return buffer.subarray(0, bytesRead).toString('utf8')\n } finally {\n await file.close()\n }\n}\n\nfunction runProcess(args: {\n label: string\n command: string\n args: string[]\n cwd: string | undefined\n env: NodeJS.ProcessEnv | undefined\n timeoutMs: number\n maxOutputChars: number\n signal: AbortSignal | undefined\n}): Promise<void> {\n throwIfAborted(args.signal, args.label)\n return new Promise((resolvePromise, reject) => {\n const child = spawn(args.command, args.args, {\n cwd: args.cwd,\n env: { ...safeProcessEnvironment(), ...args.env },\n stdio: ['ignore', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n const stdout = createProcessOutputCapture()\n const stderr = createProcessOutputCapture()\n let settled = false\n let timeout: NodeJS.Timeout | undefined\n const onAbort = () => finish(abortReason(args.signal!, args.label))\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n if (timeout) clearTimeout(timeout)\n args.signal?.removeEventListener('abort', onAbort)\n void terminateProcessTree(child).then(\n () => {\n if (error) reject(error)\n else resolvePromise()\n },\n (cleanupError: unknown) => {\n if (error) {\n const cleanup =\n cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError))\n reject(\n new AggregateError(\n [error, cleanup],\n `${error.message}; ${args.label} process cleanup failed: ${cleanup.message}`,\n ),\n )\n return\n }\n reject(\n new Error(\n `${args.label} process cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,\n ),\n )\n },\n )\n }\n timeout = setTimeout(() => {\n finish(new Error(`${args.label} exceeded ${args.timeoutMs}ms`))\n }, args.timeoutMs)\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n child.stdout.on('data', (chunk: Buffer) => {\n appendProcessOutput(stdout, chunk, args.maxOutputChars)\n })\n child.stderr.on('data', (chunk: Buffer) => {\n appendProcessOutput(stderr, chunk, args.maxOutputChars)\n })\n child.on('error', (error) => {\n finish(new Error(`${args.label} could not start: ${error.message}`))\n })\n child.on('close', (code) => {\n if (code === 0) {\n finish()\n return\n }\n finish(\n new Error(\n `${args.label} exited ${String(code)}. stderr=${summarizeProcessOutput(stderr)} stdout=${summarizeProcessOutput(stdout)}`,\n ),\n )\n })\n })\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined, label: string): void {\n if (signal?.aborted) throw abortReason(signal, label)\n}\n\nfunction abortReason(signal: AbortSignal, label: string): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new Error(`${label} aborted`, { cause: signal.reason })\n}\n\nfunction safeProcessEnvironment(): NodeJS.ProcessEnv {\n const allowed = [\n 'PATH',\n 'HOME',\n 'USER',\n 'LOGNAME',\n 'SHELL',\n 'TMPDIR',\n 'TMP',\n 'TEMP',\n 'LANG',\n 'LANGUAGE',\n 'LC_ALL',\n 'VIRTUAL_ENV',\n 'PYTHONPATH',\n 'SYSTEMROOT',\n 'COMSPEC',\n 'PATHEXT',\n 'WINDIR',\n ] as const\n return Object.fromEntries(\n allowed.flatMap((name) => {\n const value = process.env[name]\n return value === undefined ? [] : [[name, value]]\n }),\n )\n}\n\nasync function terminateProcessTree(child: ChildProcess): Promise<void> {\n const pid = child.pid\n if (!pid) return\n if (process.platform === 'win32') {\n throw new Error('native Windows process-tree cleanup is unsupported')\n }\n\n if (!signalProcessGroup(pid, 'SIGTERM')) return\n if (await waitForProcessGroupExit(pid, PROCESS_TERMINATION_GRACE_MS)) return\n if (!signalProcessGroup(pid, 'SIGKILL')) return\n if (await waitForProcessGroupExit(pid, PROCESS_KILL_WAIT_MS)) return\n throw new Error(`process group ${pid} remained alive after SIGKILL`)\n}\n\nfunction signalProcessGroup(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(-pid, signal)\n return true\n } catch (error) {\n if (isMissingProcessError(error)) return false\n throw error\n }\n}\n\nasync function waitForProcessGroupExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n while (processGroupExists(pid)) {\n const remainingMs = deadline - Date.now()\n if (remainingMs <= 0) return false\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(PROCESS_TERMINATION_POLL_MS, remainingMs)),\n )\n }\n return true\n}\n\nfunction processGroupExists(pid: number): boolean {\n try {\n process.kill(-pid, 0)\n return true\n } catch (error) {\n if (isMissingProcessError(error)) return false\n throw error\n }\n}\n\nfunction isMissingProcessError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ESRCH'\n )\n}\n\nfunction createProcessOutputCapture(): ProcessOutputCapture {\n return { full: '', head: '', tail: '', totalChars: 0 }\n}\n\nfunction appendProcessOutput(\n capture: ProcessOutputCapture,\n chunk: Buffer,\n maxOutputChars: number,\n): void {\n const text = chunk.toString()\n capture.totalChars += text.length\n const headChars = Math.floor(maxOutputChars / 2)\n const tailChars = maxOutputChars - headChars\n if (capture.full !== undefined) {\n const combined = `${capture.full}${text}`\n if (combined.length <= maxOutputChars) {\n capture.full = combined\n return\n }\n capture.head = combined.slice(0, headChars)\n capture.tail = combined.slice(-tailChars)\n capture.full = undefined\n return\n }\n capture.tail = `${capture.tail}${text}`.slice(-tailChars)\n}\n\nfunction summarizeProcessOutput(capture: ProcessOutputCapture, max = 4_000): string {\n const raw =\n capture.full ??\n `${capture.head}\\n...[${capture.totalChars - capture.head.length - capture.tail.length} chars omitted]...\\n${capture.tail}`\n const compact = raw.trim().replace(/\\s+/g, ' ')\n if (compact.length <= max) return compact\n const headChars = Math.floor(max / 3)\n const tailChars = max - headChars\n return `${compact.slice(0, headChars)}...[${compact.length - max} chars omitted]...${compact.slice(-tailChars)}`\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGA,IAAa,oBAAb,cAAuC,gBAAgB,CAAC;;AAGxD,IAAa,6BAAb,cAAgD,kBAAkB,CAAC;;AAGnE,IAAa,4BAAb,cAA+C,kBAAkB,CAAC;;;;ACElE,MAAa,6BAAgD;CAC3D,SAAS;CACT,iBAAiB,SAAS,YAAY,IAAI,2BAA2B,SAAS,OAAO;AACvF;AAEA,SAAgB,uBAAuB,MAAc,MAAoB;CACvE,iBAAiB,MAAM,MAAM,0BAA0B;AACzD;AAQA,SAAgB,4BACd,YACA,KACmB;CACnB,OAAO,sBAAsB,YAAY,4BAA4B,GAAG;AAC1E;;;;;;;;;;ACUA,SAAgB,oBAAqC;CAEnD,MAAM,EAAE,YAAY,WAAW,cAAc,UAAU,kBADnC,cAAc,OAAO,KAAK,GACqC,CAAC,CAClF,SACF;CACA,OAAO;EACL,UAAU,KAAK;GACb,IAAI,CAAC,WAAW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
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import "./capture-fetch-BAx3Gntt.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-Dzn8Q3C2.d.ts","names":[],"sources":["../src/campaign/analyst-surface.ts","../src/campaign/cross-surface-types.ts","../src/campaign/cross-surface-interaction.ts","../src/campaign/search-ledger-errors.ts","../src/campaign/fixtures.ts","../src/campaign/gates/neutralization-gate.ts","../src/campaign/grounded-reflection.ts","../src/campaign/labeled-store/fs-adapter.ts","../src/campaign/neutralize.ts","../src/campaign/presets/run-profile-matrix.ts","../src/campaign/presets/playback.ts","../src/campaign/presets/segmented-profile-matrix.ts","../src/campaign/run-dir.ts","../src/campaign/scenario-selection.ts","../src/campaign/score-utils.ts","../src/campaign/single-run-lock.ts","../src/campaign/surface-identity.ts","../src/campaign/transient-failure.ts","../src/campaign/upstream-evaluators.ts","../src/campaign/worktree/index.ts"],"mappings":";;;;;;;;;;;;;;;;UAWiB,6BAA6B;EAC5C;EACA,YAAY;EACZ,YAAY;EACZ,yBAAyB;EACzB,kBAAkB;;UAGH;EACf,mBAAmB;EACnB,QAAQ;EACR,MAAM;;UAGS;EACf,QAAQ;IACN;IACA,YAAY;IACZ;IACA,QAAQ;MACN,QAAQ;;iBAGE,iCACd,SAAS,2CAET,SAAS,gBACT,UAAU,sBACV,SAAS,oBACN,QAAQ;iBAgBG,4BAA4B,YAC1C,sBACA;;;;KCtDU;;UAGK;EACf;EACA;;EAEA;;;UAIe;EACf;EACA;EACA;EACA;;;UAIe;EACf;;EAEA;;EAEA;;;;;;;UAQe;EACf;EACA;;EAEA;EACA,cAAc;EACd;EACA;;;;;;EAMA,MAAM;EACN,mBAAmB;;EAEnB;;UAGe;EACf;EACA;EACA;;;UAIe;EACf;EACA;EACA;EACA;;EAEA,kCAAkC;;EAElC;;UAGe,qCACf,aAAa,sBAAsB;EAEnC,qBAAqB;EACrB,qBAAqB;EACrB,eAAe;EACf;;EAEA;;EAEA;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ACR;;KAGN,sBAAsB,WAAW,KACpC,iBAAiB;EAGjB;;UAGQ,qBAAqB,kBAAkB;EAC/C;EACA;EACA;EACA,aAAa,UAAU;;EAEvB,eAAe;;iBAGD,sBACd,gBAAgB,yBAChB,WACA,kBAAkB,WAAW,UAE7B,WAAW,qBAAqB,UAChC,SAAS,qBAAqB;EAC5B,SAAS;IAAS,UAAU;IAAW,UAAU;MAAc;EAC/D,WAAW,sBAAsB;IAElC,YAAY,WAAW;iBA8CV,qBACd,eAAe,yBACf,WACA,kBAAkB,WAAW,UAE7B,QAAQ,oBAAoB,SAC5B,SAAS,qBAAqB;EAC5B;EACA,SAAS;IAAS,UAAU;IAAW,UAAU;MAAc;;EAEzD;EAAc;;EACd;EAAa,UAAU,sBAAsB;KAEpD,YAAY,WAAW;;;KCxFrB,qBAAqB;KACrB,iBAAiB,SAAS;KAC1B,aAAa,gBAAgB,aAAa,MAAM,mBAAmB;UAcvD;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;UAGM;;EAEf,OAAO;IAAQ;IAAiB;MAAkB,QAAQ;;;EAG1D,SAAS,UAAU,UAAU,kBAAkB,QAAQ;;EAEvD,QAAQ,UAAU,WAAW;;;cAIlB,6BAA6B;WAG7B;EAFX,YACE,iBACS;;UAOI;;EAEf;;EAEA;;EAEA;;;;EAIA,MAAM;;UAobS;;EAEf;;EAEA;;EAEA;;;EAGA,YAAY;;;;;iBAoJE,mBAAmB,MAAM,4BAA4B;;;;iBA0FrD,kBACd,SAAS,aACT,uBACC;;;iBAOa,oBAAoB,SAAS,aAAa"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"llm-client-BMuxYoZy.js","names":[],"sources":["../src/judge-families.ts","../src/integrity/served-model.ts","../src/llm-client.ts"],"sourcesContent":["/**\n * Judge model-family classification + cross-family enforcement.\n *\n * A judge ensemble built entirely from one provider family shares that\n * family's blind spots and self-preference — its \"agreement\" is correlated\n * bias, not independent signal. `assertCrossFamily` makes the consumer prove\n * the ensemble spans ≥2 families; `judgeFamily` is the single regex map that\n * replaces the per-consumer copies (tax/legal/creative/gtm each ship one).\n */\n\n/** Provider family a model belongs to. `unknown` when no rule matches. */\nexport type JudgeFamily =\n | 'anthropic'\n | 'openai'\n | 'google'\n | 'meta'\n | 'mistral'\n | 'deepseek'\n | 'xai'\n | 'qwen'\n | 'cohere'\n | 'amazon'\n | 'moonshot'\n | 'zhipu'\n | 'unknown'\n\n/** Explicit `provider/...` prefix → family (models.dev / OpenRouter style). */\nconst PROVIDER_PREFIX: Record<string, JudgeFamily> = {\n anthropic: 'anthropic',\n openai: 'openai',\n 'azure-openai': 'openai',\n google: 'google',\n 'google-vertex': 'google',\n meta: 'meta',\n 'meta-llama': 'meta',\n mistral: 'mistral',\n mistralai: 'mistral',\n deepseek: 'deepseek',\n xai: 'xai',\n qwen: 'qwen',\n alibaba: 'qwen',\n cohere: 'cohere',\n amazon: 'amazon',\n bedrock: 'amazon',\n moonshot: 'moonshot',\n moonshotai: 'moonshot',\n kimi: 'moonshot',\n 'kimi-code': 'moonshot',\n zhipu: 'zhipu',\n zhipuai: 'zhipu',\n zai: 'zhipu',\n 'z-ai': 'zhipu',\n glm: 'zhipu',\n}\n\n/** Fallback model-name patterns when there's no recognised provider prefix. */\nconst NAME_PATTERNS: Array<[RegExp, JudgeFamily]> = [\n [/claude/i, 'anthropic'],\n [/\\b(gpt|davinci|babbage)\\b|^o[134]\\b|[-/]o[134]\\b|gpt-/i, 'openai'],\n [/gemini|palm|gemma|bison/i, 'google'],\n [/llama/i, 'meta'],\n [/mi(s|x)tral|codestral|magistral/i, 'mistral'],\n [/deepseek/i, 'deepseek'],\n [/grok/i, 'xai'],\n [/qwen/i, 'qwen'],\n [/command-?(r|a)?/i, 'cohere'],\n [/\\b(nova|titan)\\b/i, 'amazon'],\n [/\\bkimi\\b|moonshot/i, 'moonshot'],\n [/\\bglm\\b|zhipu|\\bz-?ai\\b/i, 'zhipu'],\n]\n\n/**\n * Classify a model id into its provider family. Strips a `@snapshot` suffix\n * and prefers an explicit `provider/...` prefix; otherwise matches the model\n * name. Returns `unknown` when nothing matches (callers decide whether that's\n * acceptable — `assertCrossFamily` counts it as its own family).\n */\nexport function judgeFamily(modelId: string): JudgeFamily {\n const id = modelId.trim().split('@')[0]!.toLowerCase()\n const slash = id.indexOf('/')\n if (slash > 0) {\n const prefix = id.slice(0, slash)\n const mapped = PROVIDER_PREFIX[prefix]\n if (mapped) return mapped\n }\n for (const [pattern, family] of NAME_PATTERNS) {\n if (pattern.test(id)) return family\n }\n return 'unknown'\n}\n\nexport interface AssertCrossFamilyOptions {\n /** Minimum number of distinct families the ensemble must span. Default 2. */\n minFamilies?: number\n /** When false (default), `unknown`-family models do NOT count toward the\n * family total — an ensemble of all-unclassifiable models is not provably\n * cross-family. Set true to count `unknown` as one shared family. */\n allowUnknown?: boolean\n}\n\nexport class CrossFamilyError extends Error {\n constructor(\n message: string,\n public readonly families: JudgeFamily[],\n public readonly models: string[],\n ) {\n super(message)\n this.name = 'CrossFamilyError'\n }\n}\n\n/**\n * Throw unless the judge models span at least `minFamilies` distinct provider\n * families. Pass the model ids backing your judge ensemble. Fail-loud by\n * design — a correlated single-family ensemble silently inflates agreement.\n *\n * Scope: this reads the ids you REQUEST. It proves the panel was configured\n * across families; it cannot prove the panel RAN across families, because a\n * routing gateway may answer several different ids from one provider. Where\n * the diversity claim is load-bearing (a published leaderboard, a\n * certification, a non-self-judging exclusion), assert on the ids the\n * provider echoed instead: `assertCrossFamilyServed` in\n * ./integrity/served-model.\n */\nexport function assertCrossFamily(\n models: string[],\n opts: AssertCrossFamilyOptions = {},\n): JudgeFamily[] {\n const minFamilies = opts.minFamilies ?? 2\n const families = new Set<JudgeFamily>()\n for (const m of models) {\n const f = judgeFamily(m)\n if (f === 'unknown' && !opts.allowUnknown) continue\n families.add(f)\n }\n const list = [...families].sort()\n if (list.length < minFamilies) {\n throw new CrossFamilyError(\n `judge ensemble spans ${list.length} provider famil${list.length === 1 ? 'y' : 'ies'} ` +\n `(${list.join(', ') || 'none'}) but ${minFamilies} required — a single-family ensemble ` +\n 'is correlated bias, not independent signal',\n list,\n models,\n )\n }\n return list\n}\n","/**\n * Served-model identity: prove the model that ANSWERED is the model that was\n * REQUESTED.\n *\n * A routing gateway can accept `model: \"gpt-4.1-mini\"` and answer from a\n * different model entirely. Every guard that reasons about the requested id —\n * cross-family judge diversity, per-model leaderboard rows, non-self-judging\n * exclusions, cost attribution — then passes while measuring something else.\n * The requested id is an intent; only the id echoed on the response is\n * evidence.\n *\n * `checkServedModel` classifies one requested/served pair; `assertServedModel`\n * and `assertServedModels` are the fail-loud gates; `assertCrossFamilyServed`\n * is the family-diversity rule computed over SERVED ids (the requested-id\n * version lives in ../judge-families and cannot see substitution).\n *\n * Aliasing is tolerated, substitution is not: `openai/gpt-4.1-mini` and\n * `gpt-4.1-mini` are the same request expressed two ways, so a response\n * echoing either satisfies the other. A response echoing `gemini-2.5-flash-lite`\n * does not.\n */\n\nimport { AgentEvalError } from '../errors'\nimport { type JudgeFamily, judgeFamily } from '../judge-families'\n\n/**\n * Output-token budget a liveness probe must grant a model.\n *\n * Identity is only readable off a response the provider actually produced. A\n * reasoning model spends budget on hidden reasoning tokens before it emits a\n * single visible one, so a cap of a few tokens makes a HEALTHY deepseek/glm\n * model fail with `reasoning_budget_exhausted` — it names no model, its\n * identity reads as `unreported`, and a preflight scores it DEAD. 64 clears\n * that floor. Every probe in this package reads this constant, so two probes\n * cannot reach two different answers about the same router.\n *\n * Cost: a probe spends at most `PROBE_MAX_TOKENS` output tokens per model,\n * plus whatever reasoning tokens a reasoning model bills — roughly 400 output\n * tokens for a six-model preflight. That is fractions of a cent, and far\n * cheaper than a campaign that runs on a model nobody proved was alive.\n */\nexport const PROBE_MAX_TOKENS = 64\n\n/** How a served id relates to the id that was requested. */\nexport type ServedModelVerdict =\n /** Byte-identical after normalisation — the requested model answered. */\n | 'exact'\n /** Same model, different spelling (provider prefix, snapshot, tier suffix). */\n | 'alias'\n /** A different model of the SAME provider family answered. */\n | 'substituted-within-family'\n /** A different provider's model answered. */\n | 'substituted-cross-family'\n /** The response carried no model id — identity is unproven either way. */\n | 'unreported'\n\nexport interface ServedModelCheck {\n /** The id the caller asked for. */\n requested: string\n /** The id echoed on the response; `null` when the response omitted it. */\n served: string | null\n requestedFamily: JudgeFamily\n /** `null` when `served` is null. */\n servedFamily: JudgeFamily | null\n verdict: ServedModelVerdict\n /** True for every verdict except `exact` and `alias`. */\n substituted: boolean\n}\n\n/**\n * Reduce a model id to its comparable core: lowercase, no surrounding space,\n * no `provider/` prefix, no `@snapshot` / `:batch` / `:free` tier suffix, no\n * trailing build date, and `.`/`_` folded to `-` so one version is spelled one\n * way.\n *\n * Dropping the build date is what makes snapshot resolution legible as the\n * non-event it is: a router answering `gpt-4o-mini` with\n * `gpt-4o-mini-2024-07-18` pinned a floating alias to a reproducible build —\n * the same model, which is the behaviour we want. Only routing decoration is\n * stripped; version digits are load-bearing, so `deepseek-v3.2` and\n * `deepseek-v4-flash` stay distinct, and comparison is EXACT equality rather\n * than a prefix test (a prefix rule would accept `gpt-5` → `gpt-5-mini`, a\n * silent downgrade wearing the right vendor name).\n */\nexport function normalizeModelId(modelId: string): string {\n let id = modelId.trim().toLowerCase()\n const at = id.indexOf('@')\n if (at > 0) id = id.slice(0, at)\n const colon = id.indexOf(':')\n if (colon > 0) id = id.slice(0, colon)\n const slash = id.lastIndexOf('/')\n if (slash >= 0) id = id.slice(slash + 1)\n return id\n .replace(/-\\d{4}-\\d{2}-\\d{2}$/, '')\n .replace(/-\\d{8}$/, '')\n .replace(/[._]/g, '-')\n .replace(/-+$/, '')\n .trim()\n}\n\n/**\n * Classify one requested/served pair. Pure — no I/O — so it is safe inside\n * response handlers, reducers, and CI gates.\n *\n * `served` is the id echoed by the provider (OpenAI-compatible bodies put it\n * at `model`). `null`/`undefined` means the body omitted it; that is\n * `unreported`, NOT a pass — a provider that does not name what answered has\n * not proven identity, and a transport that drops the field must not read as\n * agreement.\n */\nexport function checkServedModel(\n requested: string,\n served: string | null | undefined,\n): ServedModelCheck {\n const requestedFamily = judgeFamily(requested)\n if (served === null || served === undefined || served.trim() === '') {\n return {\n requested,\n served: null,\n requestedFamily,\n servedFamily: null,\n verdict: 'unreported',\n substituted: true,\n }\n }\n const servedFamily = judgeFamily(served)\n if (requested.trim().toLowerCase() === served.trim().toLowerCase()) {\n return {\n requested,\n served,\n requestedFamily,\n servedFamily,\n verdict: 'exact',\n substituted: false,\n }\n }\n if (normalizeModelId(requested) === normalizeModelId(served)) {\n return {\n requested,\n served,\n requestedFamily,\n servedFamily,\n verdict: 'alias',\n substituted: false,\n }\n }\n return {\n requested,\n served,\n requestedFamily,\n servedFamily,\n verdict:\n requestedFamily === servedFamily ? 'substituted-within-family' : 'substituted-cross-family',\n substituted: true,\n }\n}\n\nexport class ModelSubstitutionError extends AgentEvalError {\n constructor(\n message: string,\n public readonly checks: ReadonlyArray<ServedModelCheck>,\n ) {\n super('model_substitution', message)\n this.name = 'ModelSubstitutionError'\n }\n}\n\nexport interface AssertServedModelOptions {\n /**\n * Accept a different model of the same provider family (e.g. requested\n * `deepseek-v3.2`, served `deepseek-v4-flash`). Default false. Setting this\n * keeps family-level claims valid and forfeits per-model claims.\n */\n allowWithinFamily?: boolean\n /**\n * Accept a response that carried no model id. Default false — an\n * unidentified response cannot support a per-model or per-family claim.\n */\n allowUnreported?: boolean\n /** Prefixed to the thrown message, e.g. the judge or campaign cell name. */\n context?: string\n}\n\n/**\n * The one place the accept/reject policy lives, so a caller that reports\n * substitution (a preflight table, a run record) and a caller that throws on it\n * can never drift apart. A cross-family substitution is never acceptable.\n */\nexport function servedModelAcceptable(\n check: ServedModelCheck,\n opts: AssertServedModelOptions = {},\n): boolean {\n switch (check.verdict) {\n case 'exact':\n case 'alias':\n return true\n case 'unreported':\n return opts.allowUnreported === true\n case 'substituted-within-family':\n return opts.allowWithinFamily === true\n default:\n return false\n }\n}\n\nfunction describe(check: ServedModelCheck): string {\n if (check.verdict === 'unreported')\n return `${check.requested}: response carried no model id (identity unproven)`\n return (\n `${check.requested} (${check.requestedFamily}) → served ${check.served} ` +\n `(${check.servedFamily}) [${check.verdict}]`\n )\n}\n\n/**\n * Throw `ModelSubstitutionError` unless the served id is the requested model.\n * Returns the check on success so callers can record the served id alongside\n * the result.\n */\nexport function assertServedModel(\n requested: string,\n served: string | null | undefined,\n opts: AssertServedModelOptions = {},\n): ServedModelCheck {\n const check = checkServedModel(requested, served)\n if (servedModelAcceptable(check, opts)) return check\n const prefix = opts.context ? `${opts.context}: ` : ''\n throw new ModelSubstitutionError(\n `${prefix}model substitution — ${describe(check)}. The measurement is of the SERVED model, ` +\n 'not the requested one; any per-model or per-family claim from this call is invalid.',\n [check],\n )\n}\n\n/**\n * Batch form: check every pair and throw naming EVERY substitution, so one\n * failure does not hide the rest. Returns all checks on success.\n */\nexport function assertServedModels(\n pairs: ReadonlyArray<{ requested: string; served: string | null | undefined }>,\n opts: AssertServedModelOptions = {},\n): ServedModelCheck[] {\n const checks = pairs.map((p) => checkServedModel(p.requested, p.served))\n const bad = checks.filter((c) => !servedModelAcceptable(c, opts))\n if (bad.length > 0) {\n const prefix = opts.context ? `${opts.context}: ` : ''\n throw new ModelSubstitutionError(\n `${prefix}${bad.length}/${checks.length} call(s) were answered by a different model than ` +\n `requested — ${bad.map(describe).join('; ')}. Per-model and per-family claims from this ` +\n 'run are invalid until the ids are re-measured.',\n checks,\n )\n }\n return checks\n}\n\nexport interface AssertCrossFamilyServedOptions extends AssertServedModelOptions {\n /** Minimum distinct SERVED families required. Default 2. */\n minFamilies?: number\n /** Count `unknown`-family served ids toward the total. Default false. */\n allowUnknown?: boolean\n}\n\nexport class ServedCrossFamilyError extends AgentEvalError {\n constructor(\n message: string,\n public readonly families: JudgeFamily[],\n public readonly checks: ReadonlyArray<ServedModelCheck>,\n ) {\n super('model_substitution', message)\n this.name = 'ServedCrossFamilyError'\n }\n}\n\n/**\n * Family-diversity rule over the models that actually ANSWERED.\n *\n * `assertCrossFamily` (../judge-families) reads the requested ids and so\n * cannot see a gateway that answers three \"different\" requests from one\n * provider. This one asserts no substitution first, then counts families from\n * the served ids — a panel that collapsed to one family under the hood fails\n * here even though its request list looked diverse.\n */\nexport function assertCrossFamilyServed(\n pairs: ReadonlyArray<{ requested: string; served: string | null | undefined }>,\n opts: AssertCrossFamilyServedOptions = {},\n): JudgeFamily[] {\n const checks = assertServedModels(pairs, opts)\n const families = new Set<JudgeFamily>()\n for (const check of checks) {\n const family = check.servedFamily\n if (family === null) continue\n if (family === 'unknown' && !opts.allowUnknown) continue\n families.add(family)\n }\n const list = [...families].sort()\n const minFamilies = opts.minFamilies ?? 2\n if (list.length < minFamilies) {\n const prefix = opts.context ? `${opts.context}: ` : ''\n throw new ServedCrossFamilyError(\n `${prefix}the models that ANSWERED span ${list.length} provider famil` +\n `${list.length === 1 ? 'y' : 'ies'} (${list.join(', ') || 'none'}) but ${minFamilies} ` +\n `required — served ids: ${checks.map((c) => c.served ?? 'unreported').join(', ')}`,\n list,\n checks,\n )\n }\n return list\n}\n","/**\n * LLM client with graceful degrade.\n *\n * OpenAI-compatible `/v1/chat/completions` client with:\n * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).\n * - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).\n * - One retry at temperature 1 when a model explicitly requires it.\n * - Graceful json_schema → json_object degrade on 400 with schema-reject body.\n * - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.\n * - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI\n * directly, cli-bridge subscriptions, and any router that speaks the spec.\n *\n * Usage:\n * const { value, result } = await callLlmJson<MyType>(\n * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },\n * { baseUrl: 'https://router.tangle.tools/v1', apiKey: process.env.KEY },\n * )\n *\n * `createChatClient` wraps this implementation for provider-neutral package\n * entry points. Direct callers can use `callLlm` or `callLlmJson`.\n */\n\nimport {\n type CostReceiptInput,\n type CustomTokenPricing,\n costForTokenPricing,\n type MaximumCharge,\n} from './cost-ledger'\nimport { AgentEvalError, CaptureIntegrityError } from './errors'\nimport {\n type AssertServedModelOptions,\n assertServedModel as assertServedModelIdentity,\n checkServedModel,\n PROBE_MAX_TOKENS,\n} from './integrity/served-model'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from './trace/raw-provider-sink'\n\n// ─── Types ──────────────────────────────────────────────────────────────\n\nexport interface LlmMessage {\n role: 'system' | 'user' | 'assistant'\n /**\n * Either a plain text content string OR a multimodal content array\n * (text + image_url parts) for vision-capable models.\n */\n content:\n | string\n | Array<\n | { type: 'text'; text: string }\n | { type: 'image_url'; image_url: { url: string; detail?: 'auto' | 'low' | 'high' } }\n >\n}\n\nexport type LlmThinkingMode = 'enabled' | 'disabled'\n\nexport interface LlmCallRequest {\n model: string\n messages: LlmMessage[]\n /** Optional JSON-mode response format (response_format: json_object). */\n jsonMode?: boolean\n /** Optional structured output via JSON Schema. Falls back to json_object on 400. */\n jsonSchema?: { name: string; schema: Record<string, unknown> }\n temperature?: number\n maxTokens?: number\n /** OpenAI-compatible reasoning mode. Omitted when the provider default should apply. */\n thinking?: LlmThinkingMode\n /** Per-call timeout, default 300s. */\n timeoutMs?: number\n}\n\n/** Conservative priced bound for the exact text request sent to a provider.\n * Returns undefined when output or multimodal input is not bounded, causing a\n * capped CostLedger to reject the call before execution. Pass\n * `customTokenPricing` when package pricing does not cover the model or endpoint. */\nexport function maximumChargeForLlmRequest(\n request: Pick<LlmCallRequest, 'model' | 'messages' | 'jsonSchema' | 'maxTokens' | 'thinking'>,\n options: LlmClientOptions = {},\n): MaximumCharge | undefined {\n if (request.maxTokens === undefined) return undefined\n if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) {\n throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`)\n }\n if (\n request.messages.some(\n (message) =>\n Array.isArray(message.content) && message.content.some((part) => part.type === 'image_url'),\n )\n ) {\n return undefined\n }\n\n const attempts = resolveMaximumAttempts(options.maximumAttempts)\n const forceJsonObject = options.jsonSchemaTransport === 'json-object'\n // A byte-level tokenizer cannot emit more input tokens than request bytes.\n // Pricing the complete body also covers role/schema framing omitted from content-only estimates.\n const requestBytes = new TextEncoder().encode(\n JSON.stringify(buildBody(request, forceJsonObject, options.thinking)),\n ).byteLength\n // A rejected response schema can trigger one JSON-mode batch with the same output limit.\n const batches = request.jsonSchema && !forceJsonObject ? 2 : 1\n const usage = {\n inputTokens: requestBytes * attempts * batches,\n outputTokens: request.maxTokens * attempts * batches,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\nexport interface LlmUsage {\n promptTokens: number\n completionTokens: number\n totalTokens: number\n /** False when the provider omitted or malformed prompt/completion usage. */\n captured?: boolean\n /** Reasoning-token subset of completionTokens, when reported. */\n reasoningTokens?: number\n /** Proxies populate this when prompt caching is on. */\n cachedPromptTokens?: number\n}\n\nexport interface LlmCallResult {\n /** The text content of the first choice. Empty string if none. */\n content: string\n usage: LlmUsage\n /**\n * Cost in USD. Uses the provider's reported cost when present, otherwise\n * caller-supplied token pricing. `null` when neither is available.\n */\n costUsd: number | null\n /**\n * Model id used for attribution (cost, pricing, log lines). The response's\n * echoed id when the provider sent one, else the requested id.\n *\n * NOT evidence of which model answered — read `servedModel` for that. A\n * provider that omits `model` makes this equal to the request, which is\n * exactly the case an identity check must be able to distinguish.\n */\n model: string\n /**\n * The model id the provider echoed on the response, verbatim; `null` when\n * the body carried none. This is the only field that can witness a gateway\n * substituting a different model for the one requested — compare it with\n * `assertServedModel` / `checkServedModel` (src/integrity/served-model.ts).\n *\n * Optional so hand-built results (mock/custom transports) still typecheck,\n * but omitting it is not a pass: the identity checks read `undefined` as\n * `unreported` and reject it by default. A transport that knows which model\n * answered should say so.\n */\n servedModel?: string | null\n /** Wall-clock duration of the HTTP call (last attempt, if retried). */\n durationMs: number\n /**\n * `finish_reason` echoed from the first choice (`stop`, `length`,\n * `content_filter`, `tool_calls`, ...). `null` when the provider omits it.\n * Exposed so a free-form `callLlm` caller CAN detect a truncated answer\n * (`length`) instead of treating a cut-off completion as complete. Note:\n * `callLlm` does not itself reject on it — acting on this signal is the\n * caller's responsibility (in-repo free-form drivers do not yet enforce it).\n */\n finishReason?: string | null\n /**\n * True when `content.trim()` is empty. An empty completion is a silent zero\n * for free-form `callLlm` callers; this flag is the signal a caller can\n * inspect to fail loud rather than proceed on an empty string. `callLlm`\n * surfaces it but does not throw on it.\n */\n contentEmpty?: boolean\n /** Raw response body. */\n raw: Record<string, unknown>\n}\n\nexport type LlmCallMetadata = Pick<LlmCallResult, 'usage' | 'costUsd' | 'model' | 'durationMs'>\n\n/** Convert a provider result into the canonical paid-call receipt input. */\nexport function costReceiptFromLlm(\n result: LlmCallResult,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput {\n const cachedTokens = result.usage.cachedPromptTokens ?? 0\n const inputTokens = Math.max(0, result.usage.promptTokens - cachedTokens)\n const providerCostUsd = providerReportedCost(result.raw)\n return {\n model: result.model,\n inputTokens,\n outputTokens: result.usage.completionTokens,\n reasoningTokens: result.usage.reasoningTokens,\n cachedTokens: cachedTokens > 0 ? cachedTokens : undefined,\n ...(providerCostUsd === undefined\n ? customTokenPricing && result.usage.captured !== false\n ? { customTokenPricing }\n : result.costUsd === null\n ? {}\n : { estimatedCostUsd: result.costUsd }\n : { actualCostUsd: providerCostUsd }),\n usageUnknown: result.usage.captured === false,\n }\n}\n\nfunction providerReportedCost(raw: Record<string, unknown>): number | undefined {\n const value = raw._response_cost ?? raw.cost_usd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/** Structured-response failures retain their completed provider receipt. */\nexport function costReceiptFromLlmError(\n error: Error,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput | undefined {\n return error instanceof LlmResponseError\n ? costReceiptFromLlm(error.result, customTokenPricing)\n : undefined\n}\n\nexport class LlmCallError extends AgentEvalError {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: string,\n public readonly model: string,\n ) {\n super('judge', message)\n }\n}\n\n/** A provider response completed and incurred measurable usage, but its content\n * could not satisfy the caller's response contract. The response envelope is\n * retained so accounting can commit the receipt before the error propagates. */\nexport class LlmResponseError extends AgentEvalError {\n constructor(\n message: string,\n public readonly result: LlmCallResult,\n options?: { cause?: unknown },\n ) {\n super('judge', message, options)\n }\n}\n\nexport interface LlmClientOptions {\n /** Base URL (without trailing slash). Must end at the `/v1` prefix. */\n baseUrl?: string\n /** Bearer token — either `apiKey` or `bearer` populates `Authorization: Bearer ...`. */\n apiKey?: string\n bearer?: string\n /** Override for the `Authorization` header (e.g. `X-Auth: ...`). Takes precedence over apiKey/bearer. */\n authHeader?: { name: string; value: string }\n /** Stable provider idempotency key, reused across retries of this logical call. */\n idempotencyKey?: string\n /** Default timeout in ms. Per-call can override. */\n defaultTimeoutMs?: number\n /**\n * Caller-supplied abort signal — e.g. a campaign-wide cancel. Linked to\n * each attempt's per-attempt timeout controller, so aborting it cancels\n * the in-flight fetch. A caller abort is FATAL: it is not retried even\n * though an AbortError otherwise matches the transient patterns.\n */\n signal?: AbortSignal\n /**\n * Cross-attempt wall-clock budget in ms, measured from the first attempt.\n * Before launching each attempt the loop checks the remaining budget and\n * stops retrying once it is exhausted, rather than waiting the full\n * per-attempt timeout on every retry. Bounds total time independent of\n * total attempts × `timeoutMs`.\n */\n deadlineMs?: number\n /** Total provider attempts. Default 3. */\n maximumAttempts?: number\n /** Token rates used when the provider omits cost or package pricing does not cover the model. */\n customTokenPricing?: CustomTokenPricing\n /**\n * Transport for requests that declare `jsonSchema`. `native` sends\n * `response_format: json_schema`; `json-object` sends the broadly supported\n * JSON mode and relies on the caller to include the schema in model-visible\n * instructions. Default: `native`.\n */\n jsonSchemaTransport?: 'native' | 'json-object'\n /**\n * JSON payload parsing policy. `extract` accepts fenced or prose-prefixed JSON.\n * `exact` requires the complete response content to be one JSON value.\n * Default: `extract`.\n */\n jsonPayloadMode?: 'extract' | 'exact'\n /** Default provider reasoning mode. A per-call request value takes precedence. */\n thinking?: LlmThinkingMode\n /** Fetch implementation — defaults to global `fetch`. Override for custom transport (e.g. tests). */\n fetch?: typeof fetch\n /**\n * Optional raw HTTP capture sink. When provided, every request, response,\n * and error (across all retry attempts) is recorded to the sink, with auth\n * headers and credential-shaped body fields redacted by default. This is\n * the layer-1 forensics primitive: structured `LlmSpan`s record intent,\n * raw events record what actually crossed the wire.\n */\n rawSink?: RawProviderSink\n /**\n * Logical provider id attached to raw events. When omitted, derived from\n * `baseUrl` via `providerFromBaseUrl`.\n */\n provider?: string\n /** Trace context attached to raw events; populated by emitter-aware callers. */\n traceContext?: { runId?: string; spanId?: string }\n /** Override the redaction strategy for this call. Defaults to `defaultProviderRedactor`. */\n redactor?: ProviderRedactor\n /**\n * Reject a response whose echoed model is not the model that was requested.\n * A routing gateway can accept one id and answer from another, which\n * silently invalidates every per-model and per-family claim downstream.\n * `true` uses the strict default (aliases pass, substitutions and\n * unidentified responses throw `ModelSubstitutionError`); pass an options\n * object to relax a specific case. Off by default — turning it on for a\n * measurement run is the point.\n */\n assertServedModel?: boolean | AssertServedModelOptions\n}\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\nconst DEFAULT_BASE_URL = 'https://router.tangle.tools/v1'\n// Flagship / reasoning models routinely take several minutes on large prompts (a\n// reflection over many failures, a long tool transcript). A tight cap aborts a\n// legitimately-slow but healthy call — and because every retry attempt re-uses\n// the same window, such a model aborts on ALL attempts and the loop throws. The\n// default is generous enough to let those complete, bounded enough that a truly\n// hung call still fails over after retries, and tunable per deployment via\n// TANGLE_LLM_TIMEOUT_MS. Per-call `req.timeoutMs` / `opts.defaultTimeoutMs`\n// still win for callers that know their model's latency.\nconst DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 3\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nfunction resolveMaximumAttempts(configured: number | undefined): number {\n const attempts = configured ?? DEFAULT_MAXIMUM_ATTEMPTS\n if (!Number.isInteger(attempts) || attempts <= 0) {\n throw new RangeError('LLM maximum attempts must be a positive integer')\n }\n return attempts\n}\n\nfunction providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nconst RETRYABLE_STATUS = new Set([429, 502, 503, 504])\n\n/**\n * Transient transport/network error signatures, matched against an error's\n * name, message, and `code`. Covers fetch/undici network failures, aborts\n * and timeouts, and — critically — HTTP/2 transport faults a keep-alive\n * connection raises mid-response: `terminated`, `NGHTTP2_INTERNAL_ERROR`,\n * `UND_ERR_*`, `other side closed`. Those last ones carry no clean HTTP\n * status; unrecognised, they escape the retry loop and surface as an\n * uncaught rejection.\n */\nconst TRANSIENT_ERROR_PATTERNS: readonly RegExp[] = [\n /AbortError/i,\n /TimeoutError/i,\n /this operation was aborted/i,\n /fetch failed/i,\n /ECONNRESET/i,\n /ETIMEDOUT/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /stream.*ended.*unexpectedly/i,\n /terminated/i,\n /other side closed/i,\n /NGHTTP2/i,\n /UND_ERR/i,\n]\n\n/**\n * True when an error is a transient transport/network fault worth retrying,\n * as opposed to a deterministic failure (4xx schema reject, JSON parse) that\n * a retry cannot fix. Inspects `LlmCallError.status`, then the error's\n * name/message/code, then recurses into `error.cause` — undici nests the\n * real socket fault one or more levels under `.cause`.\n *\n * This is the retry classifier for the package: `callLlm` and\n * `withJudgeRetry` both route through it, so connection failures are treated\n * consistently across transports.\n */\nexport function isTransientLlmError(err: unknown): boolean {\n return classifyTransient(err, 0)\n}\n\nfunction classifyTransient(err: unknown, depth: number): boolean {\n if (err instanceof LlmCallError) return RETRYABLE_STATUS.has(err.status)\n if (!(err instanceof Error)) return false\n // Foreign transport errors can carry a numeric HTTP status without being an\n // LlmCallError. A retryable status is decisive.\n const status = (err as { status?: unknown }).status\n if (typeof status === 'number' && RETRYABLE_STATUS.has(status)) return true\n const code = (err as { code?: unknown }).code\n const haystack = `${err.name}\\n${err.message}\\n${typeof code === 'string' ? code : ''}`\n if (TRANSIENT_ERROR_PATTERNS.some((p) => p.test(haystack))) return true\n const cause = (err as { cause?: unknown }).cause\n if (depth < 4 && cause instanceof Error && cause !== err) {\n return classifyTransient(cause, depth + 1)\n }\n return false\n}\n\nfunction parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')\n if (!h) return null\n const asNumber = Number(h)\n if (Number.isFinite(asNumber) && asNumber > 0) return asNumber * 1000\n const asDate = Date.parse(h)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return null\n}\n\n/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */\nexport function backoffMs(attempt: number): number {\n return Math.min(500 * 2 ** attempt, 16_000)\n}\n\nfunction buildHeaders(opts: LlmClientOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (opts.authHeader) {\n headers[opts.authHeader.name] = opts.authHeader.value\n } else if (opts.bearer || opts.apiKey) {\n headers.Authorization = `Bearer ${opts.bearer ?? opts.apiKey}`\n }\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n return headers\n}\n\nfunction isSchemaRejection(status: number, body: string): boolean {\n if (status !== 400) return false\n const lower = body.toLowerCase()\n return (\n lower.includes('response_format') ||\n lower.includes('json_schema') ||\n lower.includes('is unavailable') ||\n lower.includes('not supported')\n )\n}\n\nfunction isTemperatureOneRejection(status: number, body: string): boolean {\n if (status !== 400 || !/temperature/i.test(body)) return false\n return (\n /temperature[^.\\n]{0,120}\\b(?:only|must|should|required|requires?)\\b[^.\\n]{0,40}\\b1(?:\\.0+)?\\b/i.test(\n body,\n ) || /\\bonly\\s+1(?:\\.0+)?\\s+is\\s+allowed\\b[^.\\n]{0,120}\\btemperature\\b/i.test(body)\n )\n}\n\nfunction buildBody(\n req: LlmCallRequest,\n forceJsonObject: boolean,\n defaultThinking?: LlmThinkingMode,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model: req.model,\n messages: req.messages,\n temperature: req.temperature ?? 0,\n }\n if (req.maxTokens != null) {\n if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens\n else body.max_tokens = req.maxTokens\n }\n const thinking = req.thinking ?? defaultThinking\n if (thinking !== undefined) {\n body.thinking = { type: thinking }\n }\n\n if (req.jsonSchema && !forceJsonObject) {\n body.response_format = {\n type: 'json_schema',\n json_schema: { name: req.jsonSchema.name, schema: req.jsonSchema.schema, strict: true },\n }\n } else if (req.jsonMode || req.jsonSchema) {\n body.response_format = { type: 'json_object' }\n }\n\n return body\n}\n\nfunction usesMaxCompletionTokens(model: string): boolean {\n return /^gpt-5(?:[.-]|$)/i.test(model)\n}\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Combine the per-attempt timeout signal with an optional caller signal into\n * one signal the fetch listens on. Prefers the native `AbortSignal.any`; falls\n * back to manual wiring on runtimes that predate it. The caller signal is also\n * propagated to the timeout controller so aborting it cancels the in-flight\n * fetch immediately.\n */\nfunction linkSignals(timeoutController: AbortController, caller?: AbortSignal): AbortSignal {\n if (!caller) return timeoutController.signal\n if (typeof (AbortSignal as { any?: unknown }).any === 'function') {\n return AbortSignal.any([timeoutController.signal, caller])\n }\n if (caller.aborted) {\n timeoutController.abort()\n } else {\n caller.addEventListener('abort', () => timeoutController.abort(), { once: true })\n }\n return timeoutController.signal\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nfunction deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n\n// ─── Public API ─────────────────────────────────────────────────────────\n\n/**\n * Strip a ```json / ``` code fence if the model emitted one.\n * Idempotent for naked JSON. Some models (claude-code via router, certain\n * deepseek models) wrap output even under json_object.\n */\nexport function stripFencedJson(raw: string): string {\n const trimmed = raw.trim()\n const m = trimmed.match(/^```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```\\s*$/)\n return m ? m[1]!.trim() : trimmed\n}\n\nexport function extractJsonPayload(raw: string): string {\n const stripped = stripFencedJson(raw)\n try {\n JSON.parse(stripped)\n return stripped\n } catch {\n // A response that declares a JSON root must parse as that complete root.\n // Scanning onward could turn a truncated object into one of its valid nested\n // arrays or objects and silently change the response schema.\n if (stripped.startsWith('{') || stripped.startsWith('[')) return stripped\n }\n\n // Only prose-leading responses may contain a recoverable JSON payload.\n const starts = [...stripped.matchAll(/[[{]/g)]\n .map((match) => match.index)\n .filter((index) => index != null)\n for (const start of starts) {\n const candidate = extractBalancedJson(stripped, start)\n if (!candidate) continue\n try {\n JSON.parse(candidate)\n return candidate\n } catch {\n // Keep scanning; earlier braces may belong to prose.\n }\n }\n\n return stripped\n}\n\nfunction extractBalancedJson(input: string, start: number): string | null {\n const opener = input[start]\n const closer = opener === '{' ? '}' : opener === '[' ? ']' : null\n if (!closer) return null\n\n const stack: string[] = [closer]\n let isInString = false\n let isEscaped = false\n\n for (let i = start + 1; i < input.length; i++) {\n const char = input[i]!\n if (isEscaped) {\n isEscaped = false\n continue\n }\n if (char === '\\\\') {\n isEscaped = isInString\n continue\n }\n if (char === '\"') {\n isInString = !isInString\n continue\n }\n if (isInString) continue\n\n if (char === '{') stack.push('}')\n else if (char === '[') stack.push(']')\n else if (char === stack[stack.length - 1]) {\n stack.pop()\n if (stack.length === 0) return input.slice(start, i + 1)\n }\n }\n\n return null\n}\n\n/**\n * Low-level call. Returns raw content + usage + cost. Retries on transient\n * failures; does NOT degrade schema here — callers that want graceful\n * degrade use `callLlmJson`.\n */\nexport async function callLlm(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n const url = `${baseUrl}/chat/completions`\n const endpoint = '/chat/completions'\n const timeoutMs = req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS\n const maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n const fetchFn = opts.fetch ?? globalThis.fetch\n const headers = buildHeaders(opts)\n const provider = opts.provider ?? providerFromBaseUrl(baseUrl)\n const sink = opts.rawSink\n const redactor = opts.redactor ?? defaultProviderRedactor\n const traceContext = opts.traceContext\n const callerSignal = opts.signal\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n\n let lastErr: unknown\n let effectiveRequest = req\n for (let attempt = 0; attempt < maximumAttempts; attempt++) {\n // A caller cancel is fatal — never retried. Checking before each attempt\n // means an already-aborted signal short-circuits without firing fetch.\n if (callerSignal?.aborted) {\n throw new DOMException('callLlm aborted by caller signal', 'AbortError')\n }\n // Stop retrying once the cross-attempt budget is spent rather than burning\n // a full per-attempt timeout on each remaining retry.\n if (attempt > 0 && deadlineExceeded(deadlineStart, deadlineMs)) {\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))\n }\n const controller = new AbortController()\n const attemptSignal = linkSignals(controller, callerSignal)\n const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs)\n const started = Date.now()\n const requestBody = buildBody(\n effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n let attemptErrorRecorded = false\n if (sink) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'request',\n timestamp: started,\n requestHeaders: headers,\n requestBody,\n redactedFields: [],\n })\n }\n\n try {\n const res = await fetchFn(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n clearTimeout(timeoutHandle)\n const responseHeaders = sink ? headersToObject(res.headers) : undefined\n\n if (!res.ok) {\n const body = await res.text()\n if (sink) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: body,\n errorMessage: `HTTP ${res.status}`,\n redactedFields: [],\n })\n attemptErrorRecorded = true\n }\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n if (\n isTemperatureOneRejection(res.status, body) &&\n effectiveRequest.temperature !== 1 &&\n attempt < maximumAttempts - 1 &&\n !deadlineExceeded(deadlineStart, deadlineMs)\n ) {\n lastErr = err\n effectiveRequest = { ...effectiveRequest, temperature: 1 }\n continue\n }\n if (\n RETRYABLE_STATUS.has(res.status) &&\n attempt < maximumAttempts - 1 &&\n !deadlineExceeded(deadlineStart, deadlineMs)\n ) {\n lastErr = err\n const retryAfter = parseRetryAfter(res.headers)\n await sleep(retryAfter ?? backoffMs(attempt))\n continue\n }\n throw err\n }\n\n const text = await res.text()\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n if (sink) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: text,\n errorMessage: `non-JSON response: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,\n redactedFields: [],\n })\n attemptErrorRecorded = true\n }\n throw parseErr\n }\n if (sink) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n redactedFields: [],\n })\n }\n const choice = (\n json.choices as\n | Array<{ message?: { content?: string }; finish_reason?: string | null }>\n | undefined\n )?.[0]\n const usageRaw =\n json.usage && typeof json.usage === 'object' && !Array.isArray(json.usage)\n ? (json.usage as Record<string, unknown>)\n : undefined\n const promptTokens = providerTokenCount(usageRaw?.prompt_tokens)\n const completionTokens = providerTokenCount(usageRaw?.completion_tokens)\n const totalTokens = providerTokenCount(usageRaw?.total_tokens)\n const completionDetails =\n usageRaw?.completion_tokens_details &&\n typeof usageRaw.completion_tokens_details === 'object' &&\n !Array.isArray(usageRaw.completion_tokens_details)\n ? (usageRaw.completion_tokens_details as Record<string, unknown>)\n : undefined\n const reasoningRaw = completionDetails?.reasoning_tokens\n const reasoningTokens =\n reasoningRaw === undefined ? undefined : providerTokenCount(reasoningRaw)\n const cachedRaw =\n usageRaw?.prompt_tokens_details &&\n typeof usageRaw.prompt_tokens_details === 'object' &&\n !Array.isArray(usageRaw.prompt_tokens_details)\n ? (usageRaw.prompt_tokens_details as Record<string, unknown>).cached_tokens\n : undefined\n const cachedPromptTokens = cachedRaw === undefined ? undefined : providerTokenCount(cachedRaw)\n const usageCaptured =\n promptTokens !== undefined &&\n completionTokens !== undefined &&\n (reasoningRaw === undefined ||\n (reasoningTokens !== undefined && reasoningTokens <= completionTokens)) &&\n (cachedRaw === undefined ||\n (cachedPromptTokens !== undefined && cachedPromptTokens <= promptTokens)) &&\n (totalTokens === undefined || totalTokens === promptTokens + completionTokens)\n const costFromProxy = (json._response_cost ?? json.cost_usd) as number | undefined\n const content = choice?.message?.content ?? ''\n\n const configuredCost =\n typeof costFromProxy !== 'number' && usageCaptured && opts.customTokenPricing\n ? costForTokenPricing(opts.customTokenPricing, {\n inputTokens: promptTokens! - (cachedPromptTokens ?? 0),\n ...(cachedPromptTokens ? { cachedTokens: cachedPromptTokens } : {}),\n outputTokens: completionTokens!,\n })\n : undefined\n\n // The echoed id, kept separate from the attribution id: a provider that\n // omits it must read as \"unproven\", never as \"the model I asked for\".\n const servedModel =\n typeof json.model === 'string' && json.model.trim() !== '' ? json.model : null\n if (opts.assertServedModel) {\n assertServedModelIdentity(\n req.model,\n servedModel,\n opts.assertServedModel === true ? {} : opts.assertServedModel,\n )\n }\n\n return {\n content,\n finishReason: choice?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n usage: {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: totalTokens ?? (promptTokens ?? 0) + (completionTokens ?? 0),\n captured: usageCaptured,\n reasoningTokens,\n cachedPromptTokens,\n },\n costUsd: typeof costFromProxy === 'number' ? costFromProxy : (configuredCost ?? null),\n model: servedModel ?? req.model,\n servedModel,\n durationMs: Date.now() - started,\n raw: json,\n }\n } catch (err) {\n clearTimeout(timeoutHandle)\n lastErr = err\n // A caller cancel is fatal even though an AbortError matches the\n // transient patterns — a cancelled call must surface immediately, not\n // be retried against the same dead intent.\n if (callerSignal?.aborted) {\n if (sink && !attemptErrorRecorded) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n redactedFields: [],\n })\n }\n throw err\n }\n if (sink && !attemptErrorRecorded) {\n // Record only if neither the !res.ok branch nor the JSON.parse catch\n // already produced an error event for this attempt. Covers network\n // failures, timeouts, and aborts.\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n redactedFields: [],\n })\n }\n if (\n attempt < maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(deadlineStart, deadlineMs)\n ) {\n await sleep(backoffMs(attempt))\n continue\n }\n throw err\n }\n }\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))\n}\n\nasync function recordRaw(\n sink: RawProviderSink,\n redactor: ProviderRedactor,\n event: RawProviderEvent,\n): Promise<void> {\n // Errors from sinks must not crash the LLM call. Forensic capture is\n // best-effort; the structured trace is the system of record.\n try {\n await sink.record(redactor(event))\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction headersToObject(h: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n h.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\nfunction cryptoEventId(): string {\n if (typeof globalThis.crypto?.randomUUID === 'function') return globalThis.crypto.randomUUID()\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\n/**\n * Structured-output call. Returns parsed JSON plus the raw result envelope.\n * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —\n * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept\n * the `response_format.json_schema` shape but DO accept `json_object`.\n */\nexport async function callLlmJson<T = unknown>(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<{ value: T; result: LlmCallResult }> {\n const result = await callLlmStructured(req, opts)\n const value = parseJsonResult<T>(result, opts.jsonPayloadMode ?? 'extract')\n return { value, result }\n}\n\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nasync function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n try {\n return await callLlm({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts)\n } catch (err) {\n if (\n opts.jsonSchemaTransport !== 'json-object' &&\n err instanceof LlmCallError &&\n isSchemaRejection(err.status, err.body) &&\n req.jsonSchema\n ) {\n const degradedReq: LlmCallRequest = { ...req, jsonMode: true, jsonSchema: undefined }\n return await callLlm(degradedReq, opts)\n }\n throw err\n }\n}\n\nfunction parseJsonResult<T>(\n result: LlmCallResult,\n jsonPayloadMode: NonNullable<LlmClientOptions['jsonPayloadMode']>,\n): T {\n try {\n if (result.finishReason === 'length') {\n throw new Error(\n `LLM returned truncated JSON content (model=${result.model}, finishReason=length)`,\n )\n }\n return parseJsonSafely<T>(result.content, result.model, jsonPayloadMode)\n } catch (error) {\n if (error instanceof LlmResponseError) throw error\n const cause = error instanceof Error ? error : new Error(String(error))\n throw new LlmResponseError(cause.message, result, { cause })\n }\n}\n\nfunction parseJsonSafely<T>(\n content: string,\n model: string,\n jsonPayloadMode: NonNullable<LlmClientOptions['jsonPayloadMode']>,\n): T {\n const payload = jsonPayloadMode === 'exact' ? content : extractJsonPayload(content)\n try {\n return JSON.parse(payload) as T\n } catch {\n throw new Error(`LLM returned non-JSON content (model=${model})`)\n }\n}\n\n// ─── Route assertion ────────────────────────────────────────────────────\n\nexport type LlmRouteAssertionReason =\n | 'no_explicit_base_url'\n | 'base_url_blocked'\n | 'base_url_not_allowed'\n | 'no_auth'\n | 'wrong_provider'\n\nexport class LlmRouteAssertionError extends CaptureIntegrityError {\n constructor(\n message: string,\n public readonly reason: LlmRouteAssertionReason,\n public readonly baseUrl: string,\n ) {\n super(message)\n }\n}\n\nexport interface LlmRouteRequirements {\n /**\n * Throw if `opts.baseUrl` is undefined, i.e. the call would fall back to\n * `DEFAULT_BASE_URL`. Set this for evaluation runs where silently using\n * the public/free-tier router is a defect — the launch reviewer needs to\n * know exactly which provider answered.\n */\n requireExplicitBaseUrl?: boolean\n /**\n * Allowlist of acceptable base URLs. Strings match by prefix\n * (case-insensitive); RegExps test against the full base URL.\n */\n allowedBaseUrls?: Array<string | RegExp>\n /** Blocklist that takes precedence over `allowedBaseUrls`. */\n blockedBaseUrls?: Array<string | RegExp>\n /** Throw if no auth header / api key is configured. */\n requireAuth?: boolean\n /**\n * Logical provider id the configured `baseUrl` is expected to match (via\n * `providerFromBaseUrl`). Mainly useful when paired with `requireExplicitBaseUrl`.\n */\n expectedProvider?: string\n}\n\n/**\n * Fail-loud assertion that the configured LLM client points at the route\n * the caller intends. Designed for the matrix-runner preflight: invoke\n * once before any LLM call to catch misconfiguration before a sweep burns\n * dollars on the wrong provider.\n *\n * Throws `LlmRouteAssertionError`. Pure — no I/O — so it's safe to call\n * from constructors and CI gates.\n */\nexport function assertLlmRoute(opts: LlmClientOptions, req: LlmRouteRequirements = {}): void {\n const baseUrlExplicit = opts.baseUrl !== undefined\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n\n if (req.requireExplicitBaseUrl && !baseUrlExplicit) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: requireExplicitBaseUrl set but opts.baseUrl is undefined; would fall back to ${DEFAULT_BASE_URL}.`,\n 'no_explicit_base_url',\n baseUrl,\n )\n }\n\n if (req.blockedBaseUrls?.some((p) => matchUrl(baseUrl, p))) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: baseUrl ${baseUrl} matches a blocked pattern.`,\n 'base_url_blocked',\n baseUrl,\n )\n }\n\n if (req.allowedBaseUrls && req.allowedBaseUrls.length > 0) {\n const ok = req.allowedBaseUrls.some((p) => matchUrl(baseUrl, p))\n if (!ok) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: baseUrl ${baseUrl} is not in the allowed list (${req.allowedBaseUrls.map(describePattern).join(', ')}).`,\n 'base_url_not_allowed',\n baseUrl,\n )\n }\n }\n\n if (req.requireAuth && !opts.apiKey && !opts.bearer && !opts.authHeader) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: requireAuth set but no apiKey, bearer, or authHeader was supplied.`,\n 'no_auth',\n baseUrl,\n )\n }\n\n if (req.expectedProvider) {\n const actual = opts.provider ?? providerFromBaseUrl(baseUrl)\n if (actual !== req.expectedProvider) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: expected provider ${req.expectedProvider} but baseUrl ${baseUrl} resolves to ${actual}.`,\n 'wrong_provider',\n baseUrl,\n )\n }\n }\n}\n\nfunction matchUrl(url: string, pattern: string | RegExp): boolean {\n if (pattern instanceof RegExp) return pattern.test(url)\n return url.toLowerCase().startsWith(pattern.toLowerCase())\n}\n\nfunction describePattern(p: string | RegExp): string {\n return p instanceof RegExp ? p.source : p\n}\n\n/**\n * Probe whether a model is reachable. Returns latency + null error on\n * success; `ok=false` + error message on any failure (HTTP, timeout,\n * network, parse). Designed for sweep preflights — fail loud at the\n * boundary before burning a 30-leaf run on a misconfigured router.\n *\n * Sends a tiny `ping` message with `maxTokens = PROBE_MAX_TOKENS`. Reasoning\n * models (glm-5.1, deepseek-v4) can burn the entire budget on internal\n * reasoning for short prompts, so don't tighten this further — the shared\n * constant keeps this probe and `preflightModels` on one answer. We don't\n * validate content.\n *\n * Reachability and identity are separate answers: `ok` means the route\n * answered, `servedModel` / `substituted` say WHICH model answered. A gateway\n * that serves another provider's model returns `ok: true` with\n * `substituted: true` — inspect both before treating the id as measured.\n */\nexport async function probeLlm(\n model: string,\n opts: LlmClientOptions & { timeoutMs?: number } = {},\n): Promise<{\n ok: boolean\n latencyMs: number\n error: string | null\n /** Id echoed by the provider; `null` when it sent none or the probe failed. */\n servedModel: string | null\n /** True when the echoed id is a different model than `model` (or absent). */\n substituted: boolean\n}> {\n const start = Date.now()\n try {\n const result = await callLlm(\n {\n model,\n messages: [{ role: 'user', content: 'ping' }],\n maxTokens: PROBE_MAX_TOKENS,\n timeoutMs: opts.timeoutMs ?? 30_000,\n },\n opts,\n )\n return {\n ok: true,\n latencyMs: Date.now() - start,\n error: null,\n servedModel: result.servedModel ?? null,\n substituted: checkServedModel(model, result.servedModel).substituted,\n }\n } catch (err) {\n return {\n ok: false,\n latencyMs: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n servedModel: null,\n substituted: false,\n }\n }\n}\n\n/**\n * Stateful client — construct once with defaults, call many times.\n * Thin wrapper around the free functions; exists for callers that want\n * to inject a single configured instance into multiple primitives.\n */\nexport class LlmClient {\n readonly maximumAttempts: number\n private readonly opts: LlmClientOptions\n\n constructor(opts: LlmClientOptions = {}) {\n this.opts = opts\n this.maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = { ...this.opts, ...per }\n return req.jsonSchema ? callLlmStructured(req, options) : callLlm(req, options)\n }\n\n callJson<T = unknown>(\n req: LlmCallRequest,\n per?: LlmClientOptions,\n ): Promise<{ value: T; result: LlmCallResult }> {\n return callLlmJson<T>(req, { ...this.opts, ...per })\n }\n}\n"],"mappings":";;;;;AA2BA,MAAM,kBAA+C;CACnD,WAAW;CACX,QAAQ;CACR,gBAAgB;CAChB,QAAQ;CACR,iBAAiB;CACjB,MAAM;CACN,cAAc;CACd,SAAS;CACT,WAAW;CACX,UAAU;CACV,KAAK;CACL,MAAM;CACN,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,UAAU;CACV,YAAY;CACZ,MAAM;CACN,aAAa;CACb,OAAO;CACP,SAAS;CACT,KAAK;CACL,QAAQ;CACR,KAAK;AACP;;AAGA,MAAM,gBAA8C;CAClD,CAAC,WAAW,WAAW;CACvB,CAAC,0DAA0D,QAAQ;CACnE,CAAC,4BAA4B,QAAQ;CACrC,CAAC,UAAU,MAAM;CACjB,CAAC,oCAAoC,SAAS;CAC9C,CAAC,aAAa,UAAU;CACxB,CAAC,SAAS,KAAK;CACf,CAAC,SAAS,MAAM;CAChB,CAAC,oBAAoB,QAAQ;CAC7B,CAAC,qBAAqB,QAAQ;CAC9B,CAAC,sBAAsB,UAAU;CACjC,CAAC,4BAA4B,OAAO;AACtC;;;;;;;AAQA,SAAgB,YAAY,SA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