@tangle-network/agent-eval 1.0.35 → 1.0.37
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 +20 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-BpLyM2kL.d.ts → agent-profile-BKgR30kv.d.ts} +2 -2
- package/dist/{agent-profile-BpLyM2kL.d.ts.map → agent-profile-BKgR30kv.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +11 -11
- package/dist/analyst/index.js +7 -7
- package/dist/{analyze-runs-DfUDLaCk.d.ts → analyze-runs-Ctuz-dd3.d.ts} +12 -7
- package/dist/analyze-runs-Ctuz-dd3.d.ts.map +1 -0
- package/dist/{analyze-runs-AaVEG5r7.js → analyze-runs-DqHx3Q_g.js} +49 -7
- package/dist/analyze-runs-DqHx3Q_g.js.map +1 -0
- package/dist/app-grade/index.d.ts +3 -3
- package/dist/{benchmark-command-ZN7x3hTW.js → benchmark-command-08LitQTo.js} +11 -6
- package/dist/benchmark-command-08LitQTo.js.map +1 -0
- package/dist/benchmarks/index.d.ts +5 -5
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.d.ts +8 -7
- package/dist/campaign/index.js +9 -9
- package/dist/{campaign-BOoc6hc3.js → campaign-DJciOYZ6.js} +15 -19
- package/dist/campaign-DJciOYZ6.js.map +1 -0
- package/dist/{campaign-evidence-DGTNdS_7.js → campaign-evidence-BX8OveG5.js} +28 -4
- package/dist/campaign-evidence-BX8OveG5.js.map +1 -0
- package/dist/{chat-client-PJEzoot9.js → chat-client-DmPB31_2.js} +2 -2
- package/dist/{chat-client-PJEzoot9.js.map → chat-client-DmPB31_2.js.map} +1 -1
- package/dist/{chat-json-call-CaNO3k0A.js → chat-json-call-Rfhu7JbJ.js} +2 -2
- package/dist/{chat-json-call-CaNO3k0A.js.map → chat-json-call-Rfhu7JbJ.js.map} +1 -1
- package/dist/cli.js +10 -10
- package/dist/cluster-CSd0LE_M.d.ts.map +1 -1
- package/dist/{completion-verifier-xkC5kuME.js → completion-verifier-C3q1T96h.js} +4 -3
- package/dist/{completion-verifier-xkC5kuME.js.map → completion-verifier-C3q1T96h.js.map} +1 -1
- package/dist/contract/index.d.ts +13 -12
- package/dist/contract/index.js +10 -10
- package/dist/{default-registry-CfZCJdJT.d.ts → default-registry-BzCIR-YP.d.ts} +7 -7
- package/dist/{default-registry-CfZCJdJT.d.ts.map → default-registry-BzCIR-YP.d.ts.map} +1 -1
- package/dist/{default-registry-DQQ7hTXJ.js → default-registry-CpGvgSYQ.js} +2 -2
- package/dist/{default-registry-DQQ7hTXJ.js.map → default-registry-CpGvgSYQ.js.map} +1 -1
- package/dist/{define-agent-eval-QdTTdbyE.d.ts → define-agent-eval-DOB58LaZ.d.ts} +20 -8
- package/dist/define-agent-eval-DOB58LaZ.d.ts.map +1 -0
- package/dist/{define-agent-eval-Cw0HHdMF.js → define-agent-eval-Db2cZJjC.js} +19 -9
- package/dist/define-agent-eval-Db2cZJjC.js.map +1 -0
- package/dist/diagnosis/index.d.ts +3 -3
- package/dist/diagnosis/index.js +1 -1
- package/dist/{dspy-rlm-engine-Bf6cJHt_.js → dspy-rlm-engine-EC-Pkdf-.js} +2 -2
- package/dist/{dspy-rlm-engine-Bf6cJHt_.js.map → dspy-rlm-engine-EC-Pkdf-.js.map} +1 -1
- package/dist/{engine-yaSDTpEa.d.ts → engine-B2w3ARpj.d.ts} +2 -2
- package/dist/{engine-yaSDTpEa.d.ts.map → engine-B2w3ARpj.d.ts.map} +1 -1
- package/dist/{eval-campaign-CHy1PEhT.js → eval-campaign-CWWh-1p1.js} +2 -2
- package/dist/{eval-campaign-CHy1PEhT.js.map → eval-campaign-CWWh-1p1.js.map} +1 -1
- package/dist/{evaluation-imW3I7tD.d.ts → evaluation-DJqWiVkb.d.ts} +4 -4
- package/dist/{evaluation-imW3I7tD.d.ts.map → evaluation-DJqWiVkb.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/{exact-types-xrjBO9sb.d.ts → exact-types-B0_jA3V7.d.ts} +2 -2
- package/dist/{exact-types-xrjBO9sb.d.ts.map → exact-types-B0_jA3V7.d.ts.map} +1 -1
- package/dist/{execution-insight-B-My58JW.d.ts → execution-insight-9No6Si55.d.ts} +3 -3
- package/dist/{execution-insight-B-My58JW.d.ts.map → execution-insight-9No6Si55.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/experiment/index.js +1 -1
- package/dist/{exporters-CfKvJlti.js → exporters-C9AwGDDK.js} +4 -4
- package/dist/exporters-C9AwGDDK.js.map +1 -0
- package/dist/{external-optimizer-process-CQBDk8TP.js → external-optimizer-process-DFEPdWJY.js} +2 -2
- package/dist/{external-optimizer-process-CQBDk8TP.js.map → external-optimizer-process-DFEPdWJY.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BUCI-uFn.js → external-optimizer-subprocess-BspZ0bZb.js} +2 -2
- package/dist/{external-optimizer-subprocess-BUCI-uFn.js.map → external-optimizer-subprocess-BspZ0bZb.js.map} +1 -1
- package/dist/{feedback-trajectory-BbwTH49m.d.ts → feedback-trajectory-FamLu3Wt.d.ts} +3 -3
- package/dist/{feedback-trajectory-BbwTH49m.d.ts.map → feedback-trajectory-FamLu3Wt.d.ts.map} +1 -1
- package/dist/{findings-store-Dt2l5kHQ.js → findings-store-71J302Ls.js} +4 -4
- package/dist/{findings-store-Dt2l5kHQ.js.map → findings-store-71J302Ls.js.map} +1 -1
- package/dist/{hf-dataset-BA0wmOMB.js → hf-dataset-kthWy7xl.js} +2 -2
- package/dist/{hf-dataset-BA0wmOMB.js.map → hf-dataset-kthWy7xl.js.map} +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/{index-_Gwk9sZl.d.ts → index-BEAzBo4U.d.ts} +4 -4
- package/dist/{index-_Gwk9sZl.d.ts.map → index-BEAzBo4U.d.ts.map} +1 -1
- package/dist/{index-sOdbeWGO.d.ts → index-BOm81bra.d.ts} +9 -9
- package/dist/{index-sOdbeWGO.d.ts.map → index-BOm81bra.d.ts.map} +1 -1
- package/dist/{index-CeTno9aO.d.ts → index-CDEe3TyM.d.ts} +6 -6
- package/dist/{index-CeTno9aO.d.ts.map → index-CDEe3TyM.d.ts.map} +1 -1
- package/dist/{index-CeEW0CHk.d.ts → index-D5_Srjot.d.ts} +19 -19
- package/dist/{index-CeEW0CHk.d.ts.map → index-D5_Srjot.d.ts.map} +1 -1
- package/dist/{index-DshgWP9U.d.ts → index-DX0t5hA_.d.ts} +23 -9
- package/dist/index-DX0t5hA_.d.ts.map +1 -0
- package/dist/{index-Yec_iihg.d.ts → index-DtW7KhyE.d.ts} +2 -2
- package/dist/{index-Yec_iihg.d.ts.map → index-DtW7KhyE.d.ts.map} +1 -1
- package/dist/index.d.ts +24 -24
- package/dist/index.js +19 -18
- package/dist/index.js.map +1 -1
- package/dist/{judge-gate-MP1rHOB4.js → judge-gate-LbmZU-pA.js} +2 -2
- package/dist/{judge-gate-MP1rHOB4.js.map → judge-gate-LbmZU-pA.js.map} +1 -1
- package/dist/{llm-client-Bj-TooRS.js → llm-client-CdHo3SH0.js} +3 -276
- package/dist/llm-client-CdHo3SH0.js.map +1 -0
- package/dist/{llm-judge-DOgWUOml.js → llm-judge-C5pZ7DSS.js} +82 -15
- package/dist/llm-judge-C5pZ7DSS.js.map +1 -0
- package/dist/{matrix-Bk8Iz49C.d.ts → matrix-C5hfz5wA.d.ts} +2 -2
- package/dist/{matrix-Bk8Iz49C.d.ts.map → matrix-C5hfz5wA.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -2
- package/dist/meta-eval/index.js +2 -2
- package/dist/{mint-CVlHND-Q.js → mint-VN-qtJTc.js} +2 -2
- package/dist/{mint-CVlHND-Q.js.map → mint-VN-qtJTc.js.map} +1 -1
- package/dist/model-comparison-BHNL8Qrn.d.ts +25 -0
- package/dist/model-comparison-BHNL8Qrn.d.ts.map +1 -0
- package/dist/model-comparison-BZr_Hu00.js +44 -0
- package/dist/model-comparison-BZr_Hu00.js.map +1 -0
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/multishot/index.js +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{pareto-LXHRfcP7.js → pareto-BNWWbLNl.js} +2 -2
- package/dist/{pareto-LXHRfcP7.js.map → pareto-BNWWbLNl.js.map} +1 -1
- package/dist/{prime-protocol-3aHqoxSH.d.ts → prime-protocol-BR0xy0cF.d.ts} +2 -2
- package/dist/{prime-protocol-3aHqoxSH.d.ts.map → prime-protocol-BR0xy0cF.d.ts.map} +1 -1
- package/dist/{promotion-gate-D-ffRHFQ.d.ts → promotion-gate-XiTqW22r.d.ts} +3 -3
- package/dist/{promotion-gate-D-ffRHFQ.d.ts.map → promotion-gate-XiTqW22r.d.ts.map} +1 -1
- package/dist/{proposal-findings-DHLDbsuH.js → proposal-findings-DFQvA-k5.js} +2 -2
- package/dist/{proposal-findings-DHLDbsuH.js.map → proposal-findings-DFQvA-k5.js.map} +1 -1
- package/dist/{registry-x5n4GeBx.d.ts → registry-D23oO0_f.d.ts} +3 -3
- package/dist/{registry-x5n4GeBx.d.ts.map → registry-D23oO0_f.d.ts.map} +1 -1
- package/dist/{release-confidence-DEMX-Ftk.js → release-confidence-BdidB0mG.js} +2 -2
- package/dist/{release-confidence-DEMX-Ftk.js.map → release-confidence-BdidB0mG.js.map} +1 -1
- package/dist/reporting.d.ts +4 -4
- package/dist/reporting.js +1 -1
- package/dist/{research-report-CUbXuGX-.d.ts → research-report-BGKsOqkF.d.ts} +3 -3
- package/dist/{research-report-CUbXuGX-.d.ts.map → research-report-BGKsOqkF.d.ts.map} +1 -1
- package/dist/{researcher-D6D7q9uQ.d.ts → researcher-k925Q6Jb.d.ts} +3 -3
- package/dist/{researcher-D6D7q9uQ.d.ts.map → researcher-k925Q6Jb.d.ts.map} +1 -1
- package/dist/{reward-hacking-_CAip56v.d.ts → reward-hacking-CLMvxEY_.d.ts} +2 -2
- package/dist/{reward-hacking-_CAip56v.d.ts.map → reward-hacking-CLMvxEY_.d.ts.map} +1 -1
- package/dist/rl.d.ts +7 -7
- package/dist/rl.js +5 -5
- package/dist/rollout/index.d.ts +2 -2
- package/dist/rollout/index.js +4 -4
- package/dist/{rollout-99d3Fbqv.js → rollout-DDMkK_Lw.js} +12 -7
- package/dist/{rollout-99d3Fbqv.js.map → rollout-DDMkK_Lw.js.map} +1 -1
- package/dist/{rubric-predictive-validity-BTN3nNhC.d.ts → rubric-predictive-validity-B7rsN074.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-BTN3nNhC.d.ts.map → rubric-predictive-validity-B7rsN074.d.ts.map} +1 -1
- package/dist/{run-record-hti3ETmO.d.ts → run-record-CCJR7q_j.d.ts} +2 -7
- package/dist/{run-record-hti3ETmO.d.ts.map → run-record-CCJR7q_j.d.ts.map} +1 -1
- package/dist/{run-record-BFrOalUW.js → run-record-Dx64nPcX.js} +36 -22
- package/dist/{run-record-BFrOalUW.js.map → run-record-Dx64nPcX.js.map} +1 -1
- package/dist/{run-record-B7b7fLMj.js → run-record-c860wUR8.js} +2 -2
- package/dist/{run-record-B7b7fLMj.js.map → run-record-c860wUR8.js.map} +1 -1
- package/dist/{runtime-rollouts-DAtRlbBX.js → runtime-rollouts-CALol_Y4.js} +2 -2
- package/dist/{runtime-rollouts-DAtRlbBX.js.map → runtime-rollouts-CALol_Y4.js.map} +1 -1
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-BigyOZX3.d.ts → search-kernel-VeoTiwiJ.d.ts} +3 -3
- package/dist/{search-kernel-BigyOZX3.d.ts.map → search-kernel-VeoTiwiJ.d.ts.map} +1 -1
- package/dist/{search-ledger-D0pWW8kh.js → search-ledger-oyqxZhry.js} +2 -2
- package/dist/{search-ledger-D0pWW8kh.js.map → search-ledger-oyqxZhry.js.map} +1 -1
- package/dist/{search-shipper-CJQaAvvi.js → search-shipper-BwqeQ61l.js} +2 -2
- package/dist/{search-shipper-CJQaAvvi.js.map → search-shipper-BwqeQ61l.js.map} +1 -1
- package/dist/{search-summary-ByUYPfzm.js → search-summary-CNHpHFfw.js} +2 -2
- package/dist/{search-summary-ByUYPfzm.js.map → search-summary-CNHpHFfw.js.map} +1 -1
- package/dist/served-model-qhLmbutL.js +288 -0
- package/dist/served-model-qhLmbutL.js.map +1 -0
- package/dist/{server-C2OqA05E.js → server-DnoEi4Sb.js} +3 -3
- package/dist/{server-C2OqA05E.js.map → server-DnoEi4Sb.js.map} +1 -1
- package/dist/{skillopt-optimization-method-lDHnLno3.js → skillopt-optimization-method-CH9roCBs.js} +8 -7
- package/dist/{skillopt-optimization-method-lDHnLno3.js.map → skillopt-optimization-method-CH9roCBs.js.map} +1 -1
- package/dist/{statistical-heldout-Bd6PVnQD.d.ts → statistical-heldout-Bk9mrEoz.d.ts} +6 -4
- package/dist/statistical-heldout-Bk9mrEoz.d.ts.map +1 -0
- package/dist/{store-tool-spans-Bm0-YhHG.d.ts → store-tool-spans-C1lZKvvl.d.ts} +5 -5
- package/dist/{store-tool-spans-Bm0-YhHG.d.ts.map → store-tool-spans-C1lZKvvl.d.ts.map} +1 -1
- package/dist/{summary-report-figures-BoFCoiOP.d.ts → summary-report-figures-C4JW8fdy.d.ts} +2 -2
- package/dist/{summary-report-figures-BoFCoiOP.d.ts.map → summary-report-figures-C4JW8fdy.d.ts.map} +1 -1
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{systemone-Dpp7I3uV.d.ts → systemone-BCtHGtds.d.ts} +7 -7
- package/dist/{systemone-Dpp7I3uV.d.ts.map → systemone-BCtHGtds.d.ts.map} +1 -1
- package/dist/{systemone-review-CrnsTRav.d.ts → systemone-review-ZAN-5m_2.d.ts} +2 -2
- package/dist/{systemone-review-CrnsTRav.d.ts.map → systemone-review-ZAN-5m_2.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/{tool-groups-5pgmtTmE.d.ts → tool-groups-BOH1E-E4.d.ts} +3 -3
- package/dist/tool-groups-BOH1E-E4.d.ts.map +1 -0
- package/dist/{trace-questions-ETZDn5ax.d.ts → trace-questions-DBsrgY_H.d.ts} +3 -3
- package/dist/{trace-questions-ETZDn5ax.d.ts.map → trace-questions-DBsrgY_H.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +2 -2
- package/dist/traces.d.ts +7 -7
- package/dist/traces.js +5 -6
- package/dist/traces.js.map +1 -1
- package/dist/{tree-C4TtnQYD.js → tree-0r6gPODs.js} +3 -3
- package/dist/{tree-C4TtnQYD.js.map → tree-0r6gPODs.js.map} +1 -1
- package/dist/{types-BeJIREX-.d.ts → types-Bq8xZKCQ.d.ts} +3 -3
- package/dist/{types-BeJIREX-.d.ts.map → types-Bq8xZKCQ.d.ts.map} +1 -1
- package/dist/{types-ff0YYJnj.d.ts → types-D7X941FU.d.ts} +3 -3
- package/dist/{types-ff0YYJnj.d.ts.map → types-D7X941FU.d.ts.map} +1 -1
- package/dist/{types-Dtt11Ppr.d.ts → types-DmYd2Igl.d.ts} +2 -2
- package/dist/{types-Dtt11Ppr.d.ts.map → types-DmYd2Igl.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +3 -3
- package/dist/wire/index.js +1 -1
- package/docs/evaluation-integrity.md +65 -0
- package/docs/insight-report.md +7 -1
- package/docs/rollout.md +8 -1
- package/package.json +1 -1
- package/dist/analyze-runs-AaVEG5r7.js.map +0 -1
- package/dist/analyze-runs-DfUDLaCk.d.ts.map +0 -1
- package/dist/benchmark-command-ZN7x3hTW.js.map +0 -1
- package/dist/campaign-BOoc6hc3.js.map +0 -1
- package/dist/campaign-evidence-DGTNdS_7.js.map +0 -1
- package/dist/define-agent-eval-Cw0HHdMF.js.map +0 -1
- package/dist/define-agent-eval-QdTTdbyE.d.ts.map +0 -1
- package/dist/exporters-CfKvJlti.js.map +0 -1
- package/dist/index-DshgWP9U.d.ts.map +0 -1
- package/dist/llm-client-Bj-TooRS.js.map +0 -1
- package/dist/llm-judge-DOgWUOml.js.map +0 -1
- package/dist/statistical-heldout-Bd6PVnQD.d.ts.map +0 -1
- package/dist/tool-groups-5pgmtTmE.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llm-client-CdHo3SH0.js","names":[],"sources":["../src/abort-signal.ts","../src/llm-client/resilience.ts","../src/llm-client/wire.ts","../src/llm-client/accounting.ts","../src/llm-client/request.ts","../src/llm-client.ts"],"sourcesContent":["/** Combine active cancellation sources without wrapping a single source. */\nexport function combineAbortSignals(\n ...signals: Array<AbortSignal | undefined>\n): AbortSignal | undefined {\n const active = [\n ...new Set(signals.filter((signal): signal is AbortSignal => signal !== undefined)),\n ]\n if (active.length === 0) return undefined\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n","import type { LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\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.\nexport const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\n\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 6\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nexport function 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\nexport function resolveMinIntervalMs(configured: number | undefined): number {\n const interval = configured ?? 0\n if (!Number.isFinite(interval) || interval < 0) {\n throw new RangeError('LLM minIntervalMs must be a finite non-negative number')\n }\n return interval\n}\n\n// Weak keys avoid retaining credentials or completed campaigns. LlmClient binds\n// its per-call option copies to the same state as its constructor options.\nexport const pacingStates = new WeakMap<LlmClientOptions, { lastStartedAt?: number }>()\n\nexport function pacingStateFor(opts: LlmClientOptions): { lastStartedAt?: number } {\n let state = pacingStates.get(opts)\n if (!state) {\n state = {}\n pacingStates.set(opts, state)\n }\n return state\n}\n\n// 522/524: Cloudflare edge timeouts (origin connect/respond) — transient\n// exactly like 504. Router deployments serve through Cloudflare, so a long\n// non-streaming call can draw these from the edge, not the origin.\nexport const RETRYABLE_STATUS = new Set([429, 502, 503, 504, 522, 524])\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\nexport function parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')?.trim()\n if (!h) return null\n const asNumber = Number(h)\n if (!Number.isNaN(asNumber)) {\n const delay = asNumber * 1000\n return Number.isFinite(delay) && delay >= 0 ? delay : null\n }\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\n/** Backoff belongs to the caller's operation and must stop when it is cancelled. */\nexport async function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n // A timer above the signed 32-bit limit becomes a near-immediate timeout.\n // Split long server delays rather than truncating Retry-After or overflowing.\n do {\n signal?.throwIfAborted()\n const chunk = Math.min(Math.ceil(ms), 2_147_483_647)\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n reject(signal?.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, chunk)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n ms -= chunk\n } while (ms > 0)\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nexport function deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n","import type {\n LlmCallRequest,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n} from './contract'\n\nexport function providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nexport function 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\nexport function 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\nexport function 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\nexport function 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.map(encodeWireMessage),\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 if (req.logprobs !== undefined) {\n body.logprobs = true\n body.top_logprobs = req.logprobs.topLogprobs\n }\n if (req.tools !== undefined) body.tools = req.tools\n if (req.toolChoice !== undefined) body.tool_choice = req.toolChoice\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\n/** Encode one canonical message as its OpenAI chat-completions wire shape. */\nfunction encodeWireMessage(message: LlmMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content }\n }\n if (message.toolCalls === undefined) {\n return { role: message.role, content: message.content }\n }\n return {\n role: message.role,\n content: message.content,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: call.argumentsJson },\n })),\n }\n}\n\n/**\n * Parse `choices[0].logprobs.content` into the canonical per-token shape.\n * `null` when the provider returned nothing for a request that asked: a\n * provider that ignores `logprobs` is a fact the caller must be able to read,\n * not an error. A malformed entry is a contract violation and throws.\n */\nexport function parseWireLogprobs(\n value: unknown,\n model: string,\n): ReadonlyArray<LlmTokenLogprob> | null {\n if (value === undefined || value === null) return null\n if (!Array.isArray(value)) {\n throw new Error(`LLM response logprobs.content must be an array (model=${model})`)\n }\n return value.map((entry, index) => {\n const record = entry as { token?: unknown; logprob?: unknown; top_logprobs?: unknown } | null\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.token !== 'string' ||\n typeof record.logprob !== 'number' ||\n !Number.isFinite(record.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}] is not a token with a finite logprob (model=${model})`,\n )\n }\n const top = record.top_logprobs\n if (top !== undefined && top !== null && !Array.isArray(top)) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs must be an array (model=${model})`,\n )\n }\n return {\n token: record.token,\n logprob: record.logprob,\n top: (Array.isArray(top) ? top : []).map((alternative, position) => {\n const candidate = alternative as { token?: unknown; logprob?: unknown } | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.token !== 'string' ||\n typeof candidate.logprob !== 'number' ||\n !Number.isFinite(candidate.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs[${position}] is not a token with a finite logprob (model=${model})`,\n )\n }\n return { token: candidate.token, logprob: candidate.logprob }\n }),\n }\n })\n}\n\n/** Parse provider tool_calls into the canonical shape. A malformed entry is a\n * provider-contract violation and throws rather than degrading silently. */\nexport function parseWireToolCalls(value: unknown, model: string): LlmToolCall[] | undefined {\n if (value === undefined || value === null) return undefined\n if (!Array.isArray(value)) {\n throw new Error(`LLM response tool_calls must be an array (model=${model})`)\n }\n if (value.length === 0) return undefined\n return value.map((entry, index) => {\n const record = entry as {\n id?: unknown\n type?: unknown\n function?: { name?: unknown; arguments?: unknown } | null\n } | null\n const fn = record && typeof record === 'object' ? record.function : undefined\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.id !== 'string' ||\n record.id.length === 0 ||\n (record.type !== undefined && record.type !== 'function') ||\n !fn ||\n typeof fn !== 'object' ||\n typeof fn.name !== 'string' ||\n fn.name.length === 0 ||\n typeof fn.arguments !== 'string'\n ) {\n throw new Error(\n `LLM response tool_calls[${index}] is not a function call with string arguments (model=${model})`,\n )\n }\n return { id: record.id, name: fn.name, argumentsJson: fn.arguments }\n })\n}\n","import type { CostReceiptInput, CustomTokenPricing, MaximumCharge } from '../cost-ledger'\nimport type { LlmCallRequest, LlmCallResult, LlmChargeBounds } from './contract'\nimport { LlmResponseError } from './errors'\nimport { resolveMaximumAttempts } from './resilience'\nimport { buildBody } from './wire'\n\nexport function maximumChargeForLlmRequest(\n request: Pick<\n LlmCallRequest,\n 'model' | 'messages' | 'jsonSchema' | 'tools' | 'toolChoice' | 'maxTokens' | 'thinking'\n >,\n options: LlmChargeBounds = {},\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 // Schema fallback shares the same physical-attempt budget; it cannot buy a second batch.\n const usage = {\n inputTokens: requestBytes * attempts,\n outputTokens: request.maxTokens * attempts,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\n/** Convert a provider result into the canonical paid-call receipt input.\n * The receipt is JSON-clean: absent optional fields are omitted, never carried\n * as explicit-undefined keys. Receipts cross JSON boundaries (the external\n * optimizer's loopback proxy validates them with `assertJsonValue`), where an\n * explicit-undefined value is rejected as non-serializable. */\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 ...(result.usage.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: result.usage.reasoningTokens }),\n ...(cachedTokens > 0 ? { cachedTokens } : {}),\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\nexport function 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","import { combineAbortSignals } from '../abort-signal'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { assertServedModel as assertServedModelIdentity } from '../integrity/served-model'\nimport { newRecordId } from '../record-id'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from '../trace/raw-provider-sink'\nimport { providerReportedCost } from './accounting'\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\nimport {\n backoffMs,\n DEFAULT_TIMEOUT_MS,\n deadlineExceeded,\n isTransientLlmError,\n pacingStateFor,\n parseRetryAfter,\n RETRYABLE_STATUS,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n sleep,\n} from './resilience'\nimport {\n buildBody,\n buildHeaders,\n isSchemaRejection,\n isTemperatureOneRejection,\n parseWireLogprobs,\n parseWireToolCalls,\n providerTokenCount,\n} from './wire'\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 return callLlmAttempts(req, opts, false)\n}\n\n/** One retry owner for raw and structured calls. Fallback changes the next\n * request, not the attempt allowance, deadline origin, or raw-event sequence. */\n/** What one call shares across its attempts: the resolved options, pacing, deadline and the request as it now stands. */\ninterface AttemptRun {\n readonly req: LlmCallRequest\n readonly opts: LlmClientOptions\n readonly allowSchemaFallback: boolean\n readonly baseUrl: string\n readonly url: string\n readonly timeoutMs: number\n readonly maximumAttempts: number\n readonly minIntervalMs: number\n readonly pacing: ReturnType<typeof pacingStateFor>\n readonly headers: ReturnType<typeof buildHeaders>\n readonly provider: string\n readonly deadlineStart: number\n readonly remainingMs: () => number\n readonly retryDelay: (ms: number) => Promise<void>\n effectiveRequest: LlmCallRequest\n lastErr: unknown\n}\n\n/** How one attempt ended without a result or a thrown error. */\ntype AttemptOutcome =\n | { kind: 'result'; result: LlmCallResult }\n | { kind: 'retry' }\n | { kind: 'exhausted' }\n\n/** Which of an attempt's raw events were already written, so the failure path records at most one error. */\ninterface AttemptState {\n dispatched: boolean\n errorRecorded: boolean\n}\n\nconst ENDPOINT = '/chat/completions'\n\nfunction startAttemptRun(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): AttemptRun {\n // No default endpoint. This client is internal to the `agent-eval` binary\n // and the loopback optimizer proxy; both name their endpoint explicitly, and\n // a fallback would let a misconfigured caller bill an unintended provider.\n if (!opts.baseUrl) throw new Error('callLlm: opts.baseUrl is required')\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n const remainingMs = () =>\n deadlineMs === undefined ? Infinity : Math.max(0, deadlineMs - (Date.now() - deadlineStart))\n const run: AttemptRun = {\n req,\n opts,\n allowSchemaFallback,\n baseUrl,\n url: `${baseUrl}${ENDPOINT}`,\n timeoutMs: req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS,\n maximumAttempts: resolveMaximumAttempts(opts.maximumAttempts),\n minIntervalMs: resolveMinIntervalMs(opts.minIntervalMs),\n pacing: pacingStateFor(opts),\n headers: buildHeaders(opts),\n provider: opts.provider ?? providerFromBaseUrl(baseUrl),\n deadlineStart,\n remainingMs,\n retryDelay: (ms) => sleep(Math.min(ms, remainingMs()), opts.signal),\n effectiveRequest: req,\n lastErr: undefined,\n }\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n return run\n}\n\nfunction deadlineError(run: AttemptRun): Error | DOMException {\n return run.lastErr instanceof Error\n ? run.lastErr\n : new DOMException('callLlm deadline exceeded', 'TimeoutError')\n}\n\n/** Write one raw provider event for this attempt. Does nothing without a sink. */\nasync function recordAttemptEvent(\n run: AttemptRun,\n attempt: number,\n fields: Pick<RawProviderEvent, 'direction' | 'timestamp'> & Partial<RawProviderEvent>,\n): Promise<void> {\n const { opts } = run\n if (!opts.rawSink) return\n await recordRaw(opts.rawSink, opts.redactor ?? defaultProviderRedactor, {\n eventId: newRecordId(),\n runId: opts.traceContext?.runId,\n spanId: opts.traceContext?.spanId,\n provider: run.provider,\n model: run.req.model,\n endpoint: ENDPOINT,\n baseUrl: run.baseUrl,\n attemptIndex: attempt,\n ...fields,\n redactedFields: [],\n })\n}\n\n/**\n * Wait for this client's pacing slot, and claim it. Every wake rechecks, so concurrent waiters\n * cannot dispatch a catch-up burst; the claim is made in the same synchronous step that finds the\n * slot free, so no other waiter can slip in between the check and the claim.\n */\nasync function awaitPacingSlot(run: AttemptRun): Promise<number> {\n const { opts, pacing, minIntervalMs } = run\n while (true) {\n opts.signal?.throwIfAborted()\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const waitMs =\n pacing.lastStartedAt === undefined ? 0 : pacing.lastStartedAt + minIntervalMs - Date.now()\n if (waitMs <= 0) {\n // Queue time consumes the operation deadline, not the HTTP timeout.\n const started = Date.now()\n pacing.lastStartedAt = started\n return started\n }\n await run.retryDelay(waitMs)\n }\n}\n\n/** Answer a non-2xx response: retry with an adjusted request or after a wait, give up, or throw its error. */\nasync function handleHttpFailure(\n run: AttemptRun,\n attempt: number,\n res: Response,\n body: string,\n responseHeaders: Record<string, string> | undefined,\n started: number,\n state: AttemptState,\n): Promise<AttemptOutcome> {\n const { req, opts, maximumAttempts, deadlineStart } = run\n await recordAttemptEvent(run, 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 })\n if (opts.rawSink) state.errorRecorded = true\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n const canRetry =\n attempt < maximumAttempts - 1 && !deadlineExceeded(deadlineStart, opts.deadlineMs)\n if (\n isTemperatureOneRejection(res.status, body) &&\n run.effectiveRequest.temperature !== 1 &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, temperature: 1 }\n return { kind: 'retry' }\n }\n if (\n run.allowSchemaFallback &&\n opts.jsonSchemaTransport !== 'json-object' &&\n run.effectiveRequest.jsonSchema &&\n isSchemaRejection(res.status, body) &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, jsonMode: true, jsonSchema: undefined }\n return { kind: 'retry' }\n }\n if (RETRYABLE_STATUS.has(res.status) && canRetry) {\n run.lastErr = err\n const wait = parseRetryAfter(res.headers) ?? backoffMs(attempt)\n // A wait the deadline cannot cover ends the call with this answer. Sleeping to the\n // deadline let a timer that fired a millisecond early start one more attempt with no time\n // left, whose abort replaced the server's status (agent-eval publish run 37238259408).\n if (wait >= run.remainingMs()) {\n // A caller abort that landed while the answer was recorded still wins, as the\n // retry wait would have reported it.\n opts.signal?.throwIfAborted()\n return { kind: 'exhausted' }\n }\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n throw err\n}\n\n/** Turn a parsed completion into the call result: content, tool calls, usage with its completeness, and cost. */\nfunction parseCompletion(\n run: AttemptRun,\n json: Record<string, unknown>,\n started: number,\n): LlmCallResult {\n const { req, opts } = run\n const choice = (\n json.choices as\n | Array<{\n message?: { content?: string | null; tool_calls?: unknown }\n finish_reason?: string | null\n logprobs?: { content?: unknown } | null\n }>\n | undefined\n )?.[0]\n const toolCalls = parseWireToolCalls(choice?.message?.tool_calls, req.model)\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 = 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 = providerReportedCost(json)\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 = 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 ...(toolCalls === undefined ? {} : { toolCalls }),\n ...(req.logprobs === undefined\n ? {}\n : { logprobs: parseWireLogprobs(choice?.logprobs?.content, req.model) }),\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}\n\n/** One attempt: pace, dispatch, read the answer. A failure either becomes a retry outcome or is thrown. */\nasync function runAttempt(run: AttemptRun, attempt: number): Promise<AttemptOutcome> {\n const { opts } = run\n const callerSignal = opts.signal\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 (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const requestBody = buildBody(\n run.effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n const controller = new AbortController()\n const attemptSignal = combineAbortSignals(controller.signal, callerSignal)!\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n let started = Date.now()\n // An attempt cancelled or timed out while queued never reached the\n // provider, so it leaves no request or error event in the raw log.\n const state: AttemptState = { dispatched: false, errorRecorded: false }\n try {\n if (run.minIntervalMs > 0) {\n started = await awaitPacingSlot(run)\n } else {\n // Claim the slot before any await so a concurrent waiter cannot take it.\n run.pacing.lastStartedAt = started\n }\n state.dispatched = true\n timeoutHandle = setTimeout(() => controller.abort(), Math.min(run.timeoutMs, run.remainingMs()))\n await recordAttemptEvent(run, attempt, {\n direction: 'request',\n timestamp: started,\n requestHeaders: run.headers,\n requestBody,\n })\n attemptSignal.throwIfAborted()\n const res = await (opts.fetch ?? globalThis.fetch)(run.url, {\n method: 'POST',\n headers: run.headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n const responseHeaders = opts.rawSink ? headersToObject(res.headers) : undefined\n // Headers are not completion: the same timeout/cancellation covers either response body.\n const text = await res.text()\n attemptSignal.throwIfAborted()\n clearTimeout(timeoutHandle)\n\n if (!res.ok) {\n return await handleHttpFailure(run, attempt, res, text, responseHeaders, started, state)\n }\n\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n await recordAttemptEvent(run, 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 })\n if (opts.rawSink) state.errorRecorded = true\n throw parseErr\n }\n await recordAttemptEvent(run, attempt, {\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n })\n return { kind: 'result', result: parseCompletion(run, json, started) }\n } catch (err) {\n clearTimeout(timeoutHandle)\n run.lastErr = err\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 if (state.dispatched && !state.errorRecorded) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n }\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) throw err\n const wait = backoffMs(attempt)\n if (\n attempt < run.maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(run.deadlineStart, opts.deadlineMs) &&\n wait < run.remainingMs()\n ) {\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n callerSignal?.throwIfAborted()\n throw err\n } finally {\n clearTimeout(timeoutHandle)\n }\n}\n\nasync function callLlmAttempts(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): Promise<LlmCallResult> {\n const run = startAttemptRun(req, opts, allowSchemaFallback)\n for (let attempt = 0; attempt < run.maximumAttempts; attempt++) {\n const outcome = await runAttempt(run, attempt)\n if (outcome.kind === 'result') return outcome.result\n if (outcome.kind === 'exhausted') break\n }\n throw run.lastErr instanceof Error ? run.lastErr : new Error(String(run.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\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nexport async function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts, true)\n}\n","/**\n * OpenAI-compatible client. The CLASS is internal; one transport now drives it\n * for public callers.\n *\n * agent-eval never goes looking for a credential — it reads no environment\n * variable to find one — and this module is still not reachable through any\n * export subpath. What reaches a consumer is `createChatClient({ transport:\n * 'openai-compatible', baseUrl, apiKey })`, the sanctioned public route, which\n * constructs this client from an endpoint and a credential the caller passed as\n * values. Anything richer than that transport's options stays in-repo.\n *\n * Three in-repo callers hold the class directly:\n * - `src/analyst/chat-client.ts`, the public transport above;\n * - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose\n * caller is a JSON-RPC client in another language and which therefore\n * configures its own endpoint from its own environment;\n * - the loopback optimizer proxy path (`src/analyst/benchmark-public-model.ts`,\n * `src/analyst/dspy-rlm-engine.ts`), which targets `http://127.0.0.1:<port>/v1`\n * with an ephemeral token and executes nothing itself.\n *\n * The canonical request/result TYPES it defines ARE public — they are the\n * contract every caller-owned transport speaks.\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: process.env.AGENT_EVAL_LLM_BASE_URL, apiKey: process.env.AGENT_EVAL_LLM_API_KEY },\n * )\n *\n */\n\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './llm-client/contract'\nimport { parseJsonResult } from './llm-client/json'\nimport { callLlm, callLlmStructured } from './llm-client/request'\nimport {\n pacingStateFor,\n pacingStates,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n} from './llm-client/resilience'\n\nexport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client/accounting'\nexport type {\n LlmCallMetadata,\n LlmCallRequest,\n LlmCallResult,\n LlmChargeBounds,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n LlmToolChoice,\n LlmToolDefinition,\n LlmUsage,\n} from './llm-client/contract'\nexport { LlmCallError, LlmResponseError } from './llm-client/errors'\nexport { extractJsonPayload, stripFencedJson } from './llm-client/json'\nexport { callLlm } from './llm-client/request'\nexport { backoffMs, isTransientLlmError } from './llm-client/resilience'\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/**\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 resolveMinIntervalMs(opts.minIntervalMs)\n }\n\n private callOptions(per?: LlmClientOptions): LlmClientOptions {\n const options = { ...this.opts, ...per }\n pacingStates.set(options, pacingStateFor(this.opts))\n return options\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = this.callOptions(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.callOptions(per))\n }\n}\n"],"mappings":";;;;;;;AACA,SAAgB,oBACd,GAAG,SACsB;CACzB,MAAM,SAAS,CACb,GAAG,IAAI,IAAI,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS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,KAAK,kBAAkB,uBAAuB,KAAK,eAAe;EAClE,qBAAqB,KAAK,aAAa;CACzC;CAEA,YAAoB,KAA0C;EAC5D,MAAM,UAAU;GAAE,GAAG,KAAK;GAAM,GAAG;EAAI;EACvC,aAAa,IAAI,SAAS,eAAe,KAAK,IAAI,CAAC;EACnD,OAAO;CACT;CAEA,KAAK,KAAqB,KAAgD;EACxE,MAAM,UAAU,KAAK,YAAY,GAAG;EACpC,OAAO,IAAI,aAAa,kBAAkB,KAAK,OAAO,IAAI,QAAQ,KAAK,OAAO;CAChF;CAEA,SACE,KACA,KAC8C;EAC9C,OAAO,YAAe,KAAK,KAAK,YAAY,GAAG,CAAC;CAClD;AACF"}
|
|
@@ -1,27 +1,28 @@
|
|
|
1
1
|
import { s as ValidationError } from "./errors-DeEEV9Vx.js";
|
|
2
2
|
import { a as hashCanonical, i as compareCodeUnits, r as canonicalString, t as LEDGER_HASH_PATTERN } from "./canonical-BANK6NOj.js";
|
|
3
|
-
import {
|
|
3
|
+
import { c as searchCellRunId, i as modelHasSnapshot } from "./run-record-Dx64nPcX.js";
|
|
4
|
+
import { n as compareModelIdentities, t as captureModelTreatment } from "./model-comparison-BZr_Hu00.js";
|
|
4
5
|
import { dt as weightedComposite, pt as mean$1, rt as confidenceInterval, ut as summarizeNumberSeries } from "./statistics-CHs0jlsY.js";
|
|
5
6
|
import { t as mulberry32 } from "./random-DrzcgC7F.js";
|
|
6
7
|
import { r as minimumPairsForPairedDeltaTest } from "./paired-promotion-decision-BoWHWL1i.js";
|
|
7
8
|
import { a as heldoutSignificance, i as dimensionRegressions, o as pairHoldout } from "./statistical-heldout-BvcAVtof.js";
|
|
8
9
|
import { a as mapConcurrent } from "./journal-DQsbHGjX.js";
|
|
9
10
|
import { n as contentHash } from "./verdict-cache-DfzlHLdf.js";
|
|
10
|
-
import { r as projectCampaignCellQuality, t as campaignCellCostProvenance } from "./run-record-
|
|
11
|
+
import { r as projectCampaignCellQuality, t as campaignCellCostProvenance } from "./run-record-c860wUR8.js";
|
|
11
12
|
import { n as CostAccountingIncompleteError, t as CostLedger } from "./cost-ledger-1CwUnVOd.js";
|
|
12
|
-
import { A as campaignSplitDigest, D as assertCompleteCampaign, E as assertCampaignSplitIdentity, M as formatCoverageFailures, O as campaignCoverage, S as BackendIntegrityError, T as assertCampaignDesign, b as FinalEvidenceError, f as campaignBreakdown, k as campaignScenarioIdentity, m as campaignMeanCompositeOrNull, p as campaignMeanComposite, y as FinalEvidenceConflictError } from "./campaign-evidence-
|
|
13
|
+
import { A as campaignSplitDigest, D as assertCompleteCampaign, E as assertCampaignSplitIdentity, M as formatCoverageFailures, O as campaignCoverage, S as BackendIntegrityError, T as assertCampaignDesign, b as FinalEvidenceError, f as campaignBreakdown, k as campaignScenarioIdentity, m as campaignMeanCompositeOrNull, p as campaignMeanComposite, y as FinalEvidenceConflictError } from "./campaign-evidence-BX8OveG5.js";
|
|
13
14
|
import { t as deepFreezeCanonicalJson } from "./deep-freeze-CK8-2W7p.js";
|
|
14
|
-
import { M as fsCampaignStorage, h as isExternalTextCandidate, j as createRunCostLedger } from "./external-optimizer-subprocess-
|
|
15
|
+
import { M as fsCampaignStorage, h as isExternalTextCandidate, j as createRunCostLedger } from "./external-optimizer-subprocess-BspZ0bZb.js";
|
|
15
16
|
import { c as surfaceDispatchRef, l as surfaceHash, o as renderSurfaceDiff, s as surfaceContentHash, u as surfaceHashMatches } from "./json-recovery-b7O9WVTF.js";
|
|
16
17
|
import { r as summarizeEvaluationUnits, t as defineEvaluationClaim } from "./claim-C6LRiwz1.js";
|
|
17
|
-
import { a as validateSearchLedgerEvent, d as searchNodeId, f as searchTaskSetDigest, i as replaySearchLedgerText, n as openSearchLedger, u as searchCellId } from "./search-ledger-
|
|
18
|
-
import { D as CLAIM_OPERATION, O as SEARCH_KERNEL_SOURCE, b as estimateNode, i as runSearch, k as searchExpansionIndex, n as paretoFrontier, o as searchPolicyView, r as paretoFrontierWithCrowding, s as EXPANSION_OPERATORS } from "./pareto-
|
|
18
|
+
import { a as validateSearchLedgerEvent, d as searchNodeId, f as searchTaskSetDigest, i as replaySearchLedgerText, n as openSearchLedger, u as searchCellId } from "./search-ledger-oyqxZhry.js";
|
|
19
|
+
import { D as CLAIM_OPERATION, O as SEARCH_KERNEL_SOURCE, b as estimateNode, i as runSearch, k as searchExpansionIndex, n as paretoFrontier, o as searchPolicyView, r as paretoFrontierWithCrowding, s as EXPANSION_OPERATORS } from "./pareto-BNWWbLNl.js";
|
|
19
20
|
import { c as redactText, m as detectPersonalData, n as REDACTION_VERSION, p as detectCredential } from "./redact-zp_ILC4l.js";
|
|
20
21
|
import { t as detectRewardHacking } from "./reward-hacking-DNiHskry.js";
|
|
21
|
-
import { t as assertProposalFindings } from "./proposal-findings-
|
|
22
|
-
import { n as searchProposerView, t as renderSearchSummary } from "./search-summary-
|
|
22
|
+
import { t as assertProposalFindings } from "./proposal-findings-DFQvA-k5.js";
|
|
23
|
+
import { n as searchProposerView, t as renderSearchSummary } from "./search-summary-CNHpHFfw.js";
|
|
23
24
|
import { i as stripFencedJson, n as isRecord } from "./json-DtvZNAU9.js";
|
|
24
|
-
import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-
|
|
25
|
+
import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-CdHo3SH0.js";
|
|
25
26
|
import { t as JudgeParseError } from "./judges-BLxg5p8E.js";
|
|
26
27
|
import { createHash } from "node:crypto";
|
|
27
28
|
import { z } from "zod";
|
|
@@ -220,13 +221,19 @@ function assertScheduleCachesReusable(args) {
|
|
|
220
221
|
if (blocked.length > 0) throw invalidCachedCellsError(blocked);
|
|
221
222
|
}
|
|
222
223
|
function modelEvidenceFromReceipts(receipts) {
|
|
223
|
-
const
|
|
224
|
+
const served = receipts.filter((receipt) => receipt.error === void 0);
|
|
225
|
+
const models = [...new Set(served.map(({ model }) => model))];
|
|
224
226
|
if (models.length === 0) return {};
|
|
225
227
|
return {
|
|
226
228
|
resolvedModels: models,
|
|
227
229
|
...models.length === 1 ? { resolvedModel: models[0] } : {}
|
|
228
230
|
};
|
|
229
231
|
}
|
|
232
|
+
/** Every distinct model a cell's paid-call receipts reported, without surrounding space. */
|
|
233
|
+
function cellReceiptModels(cell) {
|
|
234
|
+
const reported = cell.resolvedModels ?? (cell.resolvedModel ? [cell.resolvedModel] : []);
|
|
235
|
+
return [...new Set(reported.map((model) => model.trim()).filter(Boolean))];
|
|
236
|
+
}
|
|
230
237
|
function withCurrentAgentModelEvidence(cached, costLedger, stableCostTags) {
|
|
231
238
|
const cachedCallIds = new Set(cached.costCallIds ?? []);
|
|
232
239
|
const receipts = costLedger.list({
|
|
@@ -1078,9 +1085,21 @@ function captureFinalEvidencePolicy(policy) {
|
|
|
1078
1085
|
return Object.freeze({
|
|
1079
1086
|
ledger: policy.ledger,
|
|
1080
1087
|
requestId: policy.requestId,
|
|
1081
|
-
evaluatorDigest: policy.evaluatorDigest
|
|
1088
|
+
evaluatorDigest: policy.evaluatorDigest,
|
|
1089
|
+
...policy.sourceDigestByScenarioId === void 0 ? {} : { sourceDigestByScenarioId: new Map(policy.sourceDigestByScenarioId) }
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
/** Opt into content-based exposure checks without teaching Eval a product's input schema. */
|
|
1093
|
+
function withFinalEvidenceSources(policy, sourceDigestByScenarioId) {
|
|
1094
|
+
assertSourceIdentities(sourceDigestByScenarioId);
|
|
1095
|
+
return captureFinalEvidencePolicy({
|
|
1096
|
+
...policy,
|
|
1097
|
+
sourceDigestByScenarioId
|
|
1082
1098
|
});
|
|
1083
1099
|
}
|
|
1100
|
+
function assertSourceIdentities(sources) {
|
|
1101
|
+
for (const [id, source] of sources) if (!id.trim() || !LEDGER_HASH_PATTERN.test(source)) throw new ValidationError("final evidence source identities require scenario ids and content digests");
|
|
1102
|
+
}
|
|
1084
1103
|
function evaluationUnitMap(claim, scenarios) {
|
|
1085
1104
|
const map = /* @__PURE__ */ new Map();
|
|
1086
1105
|
for (const scenario of scenarios) {
|
|
@@ -1105,6 +1124,24 @@ function finalEvidenceReservation(policy, claimInput, scenarios, developmentScen
|
|
|
1105
1124
|
const units = evaluationUnitMap(claim, scenarios);
|
|
1106
1125
|
const finalUnitIds = new Set(units.values());
|
|
1107
1126
|
assertIndependentEvaluationSplit(claim, scenarios, developmentScenarios);
|
|
1127
|
+
const sources = policy.sourceDigestByScenarioId;
|
|
1128
|
+
let sourceDigests;
|
|
1129
|
+
let developmentSourceDigests;
|
|
1130
|
+
if (sources !== void 0) {
|
|
1131
|
+
assertSourceIdentities(sources);
|
|
1132
|
+
for (const scenario of [...scenarios, ...developmentScenarios]) if (!sources.has(scenario.id)) throw new ValidationError(`final evidence source identity is missing for '${scenario.id}'`);
|
|
1133
|
+
const finalIds = new Set(scenarios.map((scenario) => scenario.id));
|
|
1134
|
+
sourceDigests = [...new Set(scenarios.map((scenario) => sources.get(scenario.id)))].sort(compareCodeUnits);
|
|
1135
|
+
developmentSourceDigests = [...new Set([...sources].filter(([id]) => !finalIds.has(id)).map(([, source]) => source))].sort(compareCodeUnits);
|
|
1136
|
+
if (sourceDigests.some((source) => developmentSourceDigests.includes(source))) throw new ValidationError("development and final evidence share source content");
|
|
1137
|
+
const sourceUnits = /* @__PURE__ */ new Map();
|
|
1138
|
+
for (const scenario of scenarios) {
|
|
1139
|
+
const source = sources.get(scenario.id);
|
|
1140
|
+
const unit = units.get(scenario.id);
|
|
1141
|
+
if (sourceUnits.has(source) && sourceUnits.get(source) !== unit) throw new ValidationError("identical final source content cannot name different independent units");
|
|
1142
|
+
sourceUnits.set(source, unit);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1108
1145
|
return {
|
|
1109
1146
|
claim,
|
|
1110
1147
|
reservation: {
|
|
@@ -1116,7 +1153,11 @@ function finalEvidenceReservation(policy, claimInput, scenarios, developmentScen
|
|
|
1116
1153
|
}),
|
|
1117
1154
|
populationId: claim.population.id,
|
|
1118
1155
|
inputDigest: hashCanonical([...scenarios].sort((a, b) => compareCodeUnits(a.id, b.id))),
|
|
1119
|
-
unitIds: [...finalUnitIds].sort(compareCodeUnits)
|
|
1156
|
+
unitIds: [...finalUnitIds].sort(compareCodeUnits),
|
|
1157
|
+
...sourceDigests === void 0 ? {} : {
|
|
1158
|
+
sourceDigests,
|
|
1159
|
+
developmentSourceDigests
|
|
1160
|
+
}
|
|
1120
1161
|
}
|
|
1121
1162
|
};
|
|
1122
1163
|
}
|
|
@@ -2527,6 +2568,7 @@ async function runFinalComparison(opts) {
|
|
|
2527
2568
|
opts = {
|
|
2528
2569
|
...opts,
|
|
2529
2570
|
judges: opts.judges?.map(captureJudge),
|
|
2571
|
+
modelTreatment: captureModelTreatment(opts.modelTreatment),
|
|
2530
2572
|
claim: opts.claim && defineEvaluationClaim(opts.claim),
|
|
2531
2573
|
finalEvidence: opts.finalEvidence && captureFinalEvidencePolicy(opts.finalEvidence)
|
|
2532
2574
|
};
|
|
@@ -2630,7 +2672,18 @@ async function runFinalComparison(opts) {
|
|
|
2630
2672
|
neutralizedJudgeScores.set(cell.cellId, cell.judgeScores);
|
|
2631
2673
|
}
|
|
2632
2674
|
}
|
|
2633
|
-
const
|
|
2675
|
+
const models = (cell) => {
|
|
2676
|
+
const reported = cellReceiptModels(cell);
|
|
2677
|
+
return reported.length > 0 || !opts.model ? reported : [opts.model];
|
|
2678
|
+
};
|
|
2679
|
+
const baselineCells = new Map(baselineOnHoldout.cells.map((cell) => [cell.cellId, cell]));
|
|
2680
|
+
const comparisonPairs = (campaign, arm) => campaign.cells.map((cell) => ({
|
|
2681
|
+
id: `${arm}:${cell.cellId}`,
|
|
2682
|
+
baseline: models(baselineCells.get(cell.cellId)),
|
|
2683
|
+
candidate: models(cell)
|
|
2684
|
+
}));
|
|
2685
|
+
const modelComparison = compareModelIdentities([...comparisonPairs(winnerOnHoldout, "winner"), ...neutralizedOnHoldout ? comparisonPairs(neutralizedOnHoldout, "neutralized") : []], opts.modelTreatment, opts.requireReportedModel);
|
|
2686
|
+
const decision = holdoutDeferred ? {
|
|
2634
2687
|
decision: "hold",
|
|
2635
2688
|
reasons: ["holdout deferred — improvement-set search completed without a held-out measurement; nothing to promote from this run"],
|
|
2636
2689
|
contributingGates: [{
|
|
@@ -2647,6 +2700,10 @@ async function runFinalComparison(opts) {
|
|
|
2647
2700
|
detail: { winnerIsBaseline: true }
|
|
2648
2701
|
}],
|
|
2649
2702
|
delta: 0
|
|
2703
|
+
} : !modelComparison.eligible ? {
|
|
2704
|
+
decision: "hold",
|
|
2705
|
+
reasons: ["served model identity does not support the declared comparison"],
|
|
2706
|
+
contributingGates: []
|
|
2650
2707
|
} : await opts.gate.decide({
|
|
2651
2708
|
candidateArtifacts,
|
|
2652
2709
|
baselineArtifacts,
|
|
@@ -2663,6 +2720,14 @@ async function runFinalComparison(opts) {
|
|
|
2663
2720
|
costPhase: costPhase("promotion.gate"),
|
|
2664
2721
|
signal: opts.signal ?? new AbortController().signal
|
|
2665
2722
|
});
|
|
2723
|
+
const gateResult = {
|
|
2724
|
+
...decision,
|
|
2725
|
+
contributingGates: [...decision.contributingGates, {
|
|
2726
|
+
name: "served-model-identity",
|
|
2727
|
+
status: modelComparison.checkedPairs === 0 ? "not_evaluated" : modelComparison.eligible ? "pass" : "fail",
|
|
2728
|
+
detail: modelComparison
|
|
2729
|
+
}]
|
|
2730
|
+
};
|
|
2666
2731
|
const promotedDiff = surfaceHash(winnerSurface) === surfaceHash(baselineSurface) ? "" : renderSurfaceDiff(winnerSurface, baselineSurface);
|
|
2667
2732
|
return {
|
|
2668
2733
|
...opts.claim ? { claim: opts.claim } : {},
|
|
@@ -2675,6 +2740,7 @@ async function runFinalComparison(opts) {
|
|
|
2675
2740
|
} : {},
|
|
2676
2741
|
...holdoutDeferred ? { holdout: "deferred" } : {},
|
|
2677
2742
|
gateResult,
|
|
2743
|
+
modelComparison,
|
|
2678
2744
|
promotedDiff
|
|
2679
2745
|
};
|
|
2680
2746
|
}
|
|
@@ -4995,6 +5061,7 @@ async function runImprovementLoop(opts) {
|
|
|
4995
5061
|
opts = {
|
|
4996
5062
|
...opts,
|
|
4997
5063
|
judges: opts.judges?.map(captureJudge),
|
|
5064
|
+
modelTreatment: captureModelTreatment(opts.modelTreatment),
|
|
4998
5065
|
...opts.claim || opts.finalEvidence ? {
|
|
4999
5066
|
claim: opts.claim && defineEvaluationClaim(opts.claim),
|
|
5000
5067
|
finalEvidence: opts.finalEvidence && captureFinalEvidencePolicy(opts.finalEvidence),
|
|
@@ -5948,6 +6015,6 @@ function parseResponse(name, response, schema, llmCall) {
|
|
|
5948
6015
|
function firstString(value) {
|
|
5949
6016
|
return typeof value === "string" && value.trim() ? value : void 0;
|
|
5950
6017
|
}
|
|
5951
|
-
export {
|
|
6018
|
+
export { runEval as $, campaignCellSearchResult as A, DEFAULT_RED_TEAM_CORPUS as B, surfaceDiff as C, createSearchHistoryReceipt as D, assertSearchHistoryMatchesState as E, uniform as F, runCanaries as G, redTeamReport as H, runFinalComparison as I, evaluationUnitMap as J, assertIndependentEvaluationSplit as K, openAutoPr as L, searchProposalExecution as M, searchReceiptAccounting as N, verifySearchHistoryArtifact as O, asha as P, withFinalEvidenceSources as Q, captureJudge as R, searchEdgeId as S, assertSearchHistoryAdmissionOptions as T, scoreRedTeamOutput as U, redTeamDataset as V, Dataset as W, prepareSearchFinalEvidence as X, exposeFinalEvidence as Y, reserveFinalEvidence as Z, crowdedFrontierParent as _, clamp01 as a, cellCachePath as at, SearchRecorder as b, readGepaCandidatePopulationArtifact as c, optimizationTokenUsageFromSummary as d, runCampaign as et, runImprovementLoop as f, beam as g, aide as h, aggregateRunScore as i, buildCellSchedule as it, searchModelIdentity as j, verifySearchHistoryReceipt as k, combineComparisonCosts as l, isProposedCandidate as m, isTransientTransportFailure as n, resolveRunDir as nt, executeOptimizationMethod as o, computeManifestHash as ot, runOptimization as p, captureFinalEvidencePolicy as q, transientDispatchFailure as r, cellReceiptModels as rt, assertGepaCandidatePopulationSummary as s, llmJudge as t, planCampaignRun as tt, costFromLedgerSummary as u, incumbent as v, surfaceNode as w, developmentClaim as x, incumbentWithOperatorBandit as y, defaultProductionGate as z };
|
|
5952
6019
|
|
|
5953
|
-
//# sourceMappingURL=llm-judge-
|
|
6020
|
+
//# sourceMappingURL=llm-judge-C5pZ7DSS.js.map
|