@tangle-network/agent-eval 0.161.1 → 0.163.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/dist/{active-curriculum-CD5TU2yW.js → active-curriculum-OjIWgrUJ.js} +2 -2
- package/dist/{active-curriculum-CD5TU2yW.js.map → active-curriculum-OjIWgrUJ.js.map} +1 -1
- package/dist/analyst/index.d.ts +2 -2
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +3 -3
- package/dist/{baseline-BhPRQBVn.js → baseline-BC-eBZ7U.js} +2 -2
- package/dist/{baseline-BhPRQBVn.js.map → baseline-BC-eBZ7U.js.map} +1 -1
- package/dist/{benchmark-command-BDC3Gocz.js → benchmark-command-CF-4GEWZ.js} +9 -8
- package/dist/benchmark-command-CF-4GEWZ.js.map +1 -0
- package/dist/benchmarks/index.d.ts +1 -1
- package/dist/benchmarks/index.js +3 -3
- package/dist/builder-eval/index.d.ts.map +1 -1
- package/dist/builder-eval/index.js +22 -8
- package/dist/builder-eval/index.js.map +1 -1
- package/dist/campaign/index.js +8 -8
- package/dist/{campaign-BSmOwskD.js → campaign-DQZmc2Dq.js} +12 -12
- package/dist/{campaign-BSmOwskD.js.map → campaign-DQZmc2Dq.js.map} +1 -1
- package/dist/{chat-json-call-6g5sJobJ.js → chat-json-call-5Jxna-aV.js} +2 -2
- package/dist/{chat-json-call-6g5sJobJ.js.map → chat-json-call-5Jxna-aV.js.map} +1 -1
- package/dist/cli.js +3 -3
- package/dist/contract/index.js +7 -7
- package/dist/{counterfactual-D_VWavVm.js → counterfactual-Bjq1mlUu.js} +2 -2
- package/dist/{counterfactual-D_VWavVm.js.map → counterfactual-Bjq1mlUu.js.map} +1 -1
- package/dist/{define-agent-eval-h-s-sI-v.js → define-agent-eval-D08pWIJb.js} +13 -13
- package/dist/{define-agent-eval-h-s-sI-v.js.map → define-agent-eval-D08pWIJb.js.map} +1 -1
- package/dist/{descriptive-jDOuI6mz.js → descriptive-1V17A-qa.js} +2 -2
- package/dist/{descriptive-jDOuI6mz.js.map → descriptive-1V17A-qa.js.map} +1 -1
- package/dist/{dspy-rlm-engine-DptEII26.js → dspy-rlm-engine-DhA9qKIm.js} +2 -2
- package/dist/{dspy-rlm-engine-DptEII26.js.map → dspy-rlm-engine-DhA9qKIm.js.map} +1 -1
- package/dist/emitter-D_jYSGRd.d.ts.map +1 -1
- package/dist/{emitter-BpYFQPj4.js → emitter-DeQHiDMm.js} +13 -6
- package/dist/emitter-DeQHiDMm.js.map +1 -0
- package/dist/{eval-campaign-BsXWL2-2.js → eval-campaign-BfohKmzx.js} +3 -3
- package/dist/{eval-campaign-BsXWL2-2.js.map → eval-campaign-BfohKmzx.js.map} +1 -1
- package/dist/experiment/index.js +8 -8
- package/dist/{experiment-tracker-Ym6rEQT1.js → experiment-tracker-BKEumQug.js} +2 -2
- package/dist/{experiment-tracker-Ym6rEQT1.js.map → experiment-tracker-BKEumQug.js.map} +1 -1
- package/dist/{external-optimizer-process-WosTBChy.js → external-optimizer-process-BFmh36vW.js} +2 -2
- package/dist/{external-optimizer-process-WosTBChy.js.map → external-optimizer-process-BFmh36vW.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BIWbHpgD.js → external-optimizer-subprocess-CqLMW3nh.js} +2 -2
- package/dist/{external-optimizer-subprocess-BIWbHpgD.js.map → external-optimizer-subprocess-CqLMW3nh.js.map} +1 -1
- package/dist/fuzz.d.ts +1 -2
- package/dist/fuzz.d.ts.map +1 -1
- package/dist/fuzz.js +4 -10
- package/dist/fuzz.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +26 -26
- package/dist/index.js.map +1 -1
- package/dist/{internal-BDHPCnjk.js → internal-BMFSR8Ns.js} +3 -19
- package/dist/internal-BMFSR8Ns.js.map +1 -0
- package/dist/{judge-calibration-zZjLz8hr.js → judge-calibration-BnpVKtnb.js} +3 -13
- package/dist/judge-calibration-BnpVKtnb.js.map +1 -0
- package/dist/judge-calibration-C5CbMYce.d.ts.map +1 -1
- package/dist/{llm-client-hgDieDNN.js → llm-client-BFMRpmqb.js} +8 -11
- package/dist/llm-client-BFMRpmqb.js.map +1 -0
- package/dist/{llm-judge-BhasIPFT.js → llm-judge-Du7WQPh7.js} +7 -7
- package/dist/{llm-judge-BhasIPFT.js.map → llm-judge-Du7WQPh7.js.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -1
- package/dist/meta-eval/index.d.ts.map +1 -1
- package/dist/meta-eval/index.js +14 -22
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{paired-arms-D-XRF_fy.js → paired-arms-D4aeIHUy.js} +3 -3
- package/dist/{paired-arms-D-XRF_fy.js.map → paired-arms-D4aeIHUy.js.map} +1 -1
- package/dist/{paired-tests-BHIhYVdu.js → paired-tests-C8iCsioC.js} +3 -3
- package/dist/{paired-tests-BHIhYVdu.js.map → paired-tests-C8iCsioC.js.map} +1 -1
- package/dist/pipelines/index.d.ts +3 -2
- package/dist/pipelines/index.d.ts.map +1 -1
- package/dist/pipelines/index.js +4 -19
- package/dist/pipelines/index.js.map +1 -1
- package/dist/{power-and-mde-CHIrXJll.js → power-and-mde-B8F2RdcD.js} +3 -3
- package/dist/{power-and-mde-CHIrXJll.js.map → power-and-mde-B8F2RdcD.js.map} +1 -1
- package/dist/{power-preflight-DEw-uC7q.js → power-preflight-CFXm0Vjo.js} +3 -3
- package/dist/{power-preflight-DEw-uC7q.js.map → power-preflight-CFXm0Vjo.js.map} +1 -1
- package/dist/{produced-state-DZ89riy5.js → produced-state-Be0BK3RN.js} +3 -3
- package/dist/{produced-state-DZ89riy5.js.map → produced-state-Be0BK3RN.js.map} +1 -1
- package/dist/{promotion-policy-xzA40Evo.js → promotion-policy-LY9mVQ7W.js} +3 -3
- package/dist/{promotion-policy-xzA40Evo.js.map → promotion-policy-LY9mVQ7W.js.map} +1 -1
- package/dist/{query-DxPYqpmT.d.ts → query-CwnHlu5p.d.ts} +19 -2
- package/dist/query-CwnHlu5p.d.ts.map +1 -0
- package/dist/{query-CHmMP42p.js → query-_5g6re3_.js} +44 -2
- package/dist/query-_5g6re3_.js.map +1 -0
- package/dist/random-Dn5fPWkt.js +21 -0
- package/dist/random-Dn5fPWkt.js.map +1 -0
- package/dist/record-id-DUgsK5qp.js +17 -0
- package/dist/record-id-DUgsK5qp.js.map +1 -0
- package/dist/{release-confidence-DKfD2RYU.js → release-confidence-nGDJiiwc.js} +2 -2
- package/dist/{release-confidence-DKfD2RYU.js.map → release-confidence-nGDJiiwc.js.map} +1 -1
- package/dist/reporting.js +6 -6
- package/dist/{reward-hacking-t4lB1yt8.js → reward-hacking-O5zKDANP.js} +2 -2
- package/dist/{reward-hacking-t4lB1yt8.js.map → reward-hacking-O5zKDANP.js.map} +1 -1
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +9 -15
- package/dist/rl.js.map +1 -1
- package/dist/{rubric-predictive-validity-CK8SCOg-.js → rubric-predictive-validity-2D5Gw9z9.js} +3 -3
- package/dist/{rubric-predictive-validity-CK8SCOg-.js.map → rubric-predictive-validity-2D5Gw9z9.js.map} +1 -1
- package/dist/{semantic-concept-judge-BSkKKHeq.js → semantic-concept-judge-BsDMOwJr.js} +2 -2
- package/dist/{semantic-concept-judge-BSkKKHeq.js.map → semantic-concept-judge-BsDMOwJr.js.map} +1 -1
- package/dist/{sequential-rYW-Ophm.js → sequential-BLMbdrD7.js} +3 -3
- package/dist/{sequential-rYW-Ophm.js.map → sequential-BLMbdrD7.js.map} +1 -1
- package/dist/{server-BtFd4uzB.js → server-BjYiJHoJ.js} +2 -2
- package/dist/{server-BtFd4uzB.js.map → server-BjYiJHoJ.js.map} +1 -1
- package/dist/{skillopt-optimization-method-DbaekMcn.js → skillopt-optimization-method-UArRo-nr.js} +6 -6
- package/dist/{skillopt-optimization-method-DbaekMcn.js.map → skillopt-optimization-method-UArRo-nr.js.map} +1 -1
- package/dist/{store-tool-spans-Dlh9vkFK.js → store-tool-spans-BVga3c37.js} +21 -17
- package/dist/store-tool-spans-BVga3c37.js.map +1 -0
- package/dist/store-tool-spans-DPUG7UUY.d.ts.map +1 -1
- package/dist/{student-t-CvBq2mve.js → student-t-BA-Uy51p.js} +2 -2
- package/dist/{student-t-CvBq2mve.js.map → student-t-BA-Uy51p.js.map} +1 -1
- package/dist/{summary-report-BI5hUtvK.js → summary-report-BXeQ5Ues.js} +6 -6
- package/dist/{summary-report-BI5hUtvK.js.map → summary-report-BXeQ5Ues.js.map} +1 -1
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{tool-waste-BqzmVdJk.js → tool-waste-8BQiUc8K.js} +4 -4
- package/dist/{tool-waste-BqzmVdJk.js.map → tool-waste-8BQiUc8K.js.map} +1 -1
- package/dist/{tool-waste-Dro0gJi3.d.ts → tool-waste-CKc7bYIg.d.ts} +2 -2
- package/dist/{tool-waste-Dro0gJi3.d.ts.map → tool-waste-CKc7bYIg.d.ts.map} +1 -1
- package/dist/trace-repair/index.js +1 -1
- package/dist/traces.d.ts +2 -2
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +8 -17
- package/dist/traces.js.map +1 -1
- package/dist/trajectory-replay/index.d.ts.map +1 -1
- package/dist/trajectory-replay/index.js +3 -13
- package/dist/trajectory-replay/index.js.map +1 -1
- package/dist/{types-BPb2Kf_C2.d.ts → types-BPb2Kf_C.d.ts} +1 -1
- package/dist/types-BPb2Kf_C.d.ts.map +1 -0
- package/dist/types-Bfk0uxRj.d.ts.map +1 -1
- package/dist/wire/index.js +1 -1
- package/package.json +1 -1
- package/dist/benchmark-command-BDC3Gocz.js.map +0 -1
- package/dist/emitter-BpYFQPj4.js.map +0 -1
- package/dist/internal-BDHPCnjk.js.map +0 -1
- package/dist/judge-calibration-zZjLz8hr.js.map +0 -1
- package/dist/llm-client-hgDieDNN.js.map +0 -1
- package/dist/query-CHmMP42p.js.map +0 -1
- package/dist/query-DxPYqpmT.d.ts.map +0 -1
- package/dist/store-tool-spans-Dlh9vkFK.js.map +0 -1
- package/dist/types-BPb2Kf_C2.d.ts.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { s as ValidationError } from "./errors-Dngq5h35.js";
|
|
2
|
+
import { t as mulberry32 } from "./random-Dn5fPWkt.js";
|
|
2
3
|
//#region src/math/special-functions.ts
|
|
3
4
|
/** Lanczos approximation to ln Gamma(z). */
|
|
4
5
|
function lnGamma(z) {
|
|
@@ -68,23 +69,6 @@ function betaContinuedFraction(x, a, b) {
|
|
|
68
69
|
return fraction;
|
|
69
70
|
}
|
|
70
71
|
//#endregion
|
|
71
|
-
//#region src/statistics/random.ts
|
|
72
|
-
/** Tiny seedable PRNG (mulberry32) — deterministic resampling/shuffling, not
|
|
73
|
-
* cryptographic. Exported so e-process shuffles and bootstrap resampling
|
|
74
|
-
* share ONE PRNG implementation. Every distinct 32-bit seed gives a distinct
|
|
75
|
-
* stream, including 0. */
|
|
76
|
-
function mulberry32(seed) {
|
|
77
|
-
if (!Number.isFinite(seed)) throw new ValidationError(`mulberry32: seed must be a finite number, got ${seed}`);
|
|
78
|
-
let s = seed | 0;
|
|
79
|
-
return () => {
|
|
80
|
-
s = s + 1831565813 | 0;
|
|
81
|
-
let t = s;
|
|
82
|
-
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
83
|
-
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
84
|
-
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
//#endregion
|
|
88
72
|
//#region src/statistics/internal.ts
|
|
89
73
|
/**
|
|
90
74
|
* Shared internals for the statistics modules. Nothing here is part of the
|
|
@@ -225,6 +209,6 @@ function symmetricTwoSampleSeed(a, b) {
|
|
|
225
209
|
return Math.min(forward, reversed);
|
|
226
210
|
}
|
|
227
211
|
//#endregion
|
|
228
|
-
export { medianInPlace as a,
|
|
212
|
+
export { medianInPlace as a, lnGamma as c, makeRng as i, regularizedIncompleteBeta as l, binomialHalfUpperTail as n, symmetricTwoSampleSeed as o, binomialSignTwoSided as r, zQuantile as s, assertFiniteSample as t };
|
|
229
213
|
|
|
230
|
-
//# sourceMappingURL=internal-
|
|
214
|
+
//# sourceMappingURL=internal-BMFSR8Ns.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-BMFSR8Ns.js","names":[],"sources":["../src/math/special-functions.ts","../src/statistics/internal.ts"],"sourcesContent":["/** Lanczos approximation to ln Gamma(z). */\nexport function lnGamma(z: number): number {\n const g = 7\n const coefficients = [\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,\n -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,\n 1.5056327351493116e-7,\n ]\n if (z < 0.5) {\n return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z)\n }\n z -= 1\n let x = coefficients[0]!\n for (let i = 1; i < g + 2; i++) x += coefficients[i]! / (z + i)\n const t = z + g + 0.5\n return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x)\n}\n\n/**\n * Regularized incomplete beta function I_x(a, b).\n *\n * The Lentz continued fraction converges only for `x < (a+1)/(a+b+2)`; outside\n * that domain it must be reached through the symmetry `I_x(a,b) = 1 −\n * I_{1−x}(b,a)`. `studentTCdf` drives `x → 1` as `|t| → 0`, so the mirrored\n * branch is the one every near-null t-statistic takes.\n */\nexport function regularizedIncompleteBeta(x: number, a: number, b: number): number {\n if (x <= 0) return 0\n if (x >= 1) return 1\n const logBeta = lnGamma(a) + lnGamma(b) - lnGamma(a + b)\n // x^a·(1−x)^b / B(a,b) — symmetric under (x,a,b) → (1−x,b,a), so the\n // mirrored branch reuses it unchanged.\n const front = Math.exp(Math.log(x) * a + Math.log(1 - x) * b - logBeta)\n if (x < (a + 1) / (a + b + 2)) {\n return (front * betaContinuedFraction(x, a, b)) / a\n }\n return 1 - (front * betaContinuedFraction(1 - x, b, a)) / b\n}\n\n/** Modified Lentz evaluation of the beta continued fraction at `x`. */\nfunction betaContinuedFraction(x: number, a: number, b: number): number {\n const maxIterations = 300\n const epsilon = 3e-15\n let c = 1\n let d = 1 - ((a + b) * x) / (a + 1)\n if (Math.abs(d) < 1e-30) d = 1e-30\n d = 1 / d\n let fraction = d\n for (let m = 1; m <= maxIterations; m++) {\n const m2 = 2 * m\n let numerator = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2))\n d = 1 + numerator * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + numerator / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n fraction *= d * c\n numerator = -((a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1))\n d = 1 + numerator * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + numerator / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n const delta = d * c\n fraction *= delta\n if (Math.abs(delta - 1) < epsilon) break\n }\n return fraction\n}\n","/**\n * Shared internals for the statistics modules. Nothing here is part of the\n * public statistics surface — `./index` does not re-export this module.\n */\n\nimport { ValidationError } from '../errors'\nimport { lnGamma } from '../math/special-functions'\nimport { mulberry32 } from './random'\n\n/** Every rank test refuses non-finite input. Beyond the arithmetic being\n * undefined, the tie-grouping scan compares values with `===`, and\n * `NaN === NaN` is false, so a NaN would leave the group boundary unable to\n * advance and spin the loop forever. */\nexport function assertFiniteSample(fn: string, label: string, xs: readonly number[]): void {\n for (let i = 0; i < xs.length; i++) {\n if (!Number.isFinite(xs[i])) {\n throw new ValidationError(`${fn}: ${label}[${i}] must be finite, got ${xs[i]}`)\n }\n }\n}\n\n/**\n * Two-sided exact p-value for b successes out of (b + c) Bernoulli(0.5) trials —\n * the exact-binomial core of {@link mcnemar}. `min(1, 2·P(X ≤ min(b,c)))`. No\n * discordant pairs ⇒ no evidence ⇒ p = 1. Summed in log space (lnGamma) so it\n * stays exact at large discordant counts without overflow.\n */\nexport function binomialSignTwoSided(b: number, c: number): number {\n const nd = b + c\n if (nd === 0) return 1\n return Math.min(1, 2 * binomialHalfLowerTail(Math.min(b, c), nd))\n}\n\n/** P(X >= successes) for X ~ Binomial(n, 0.5). */\nexport function binomialHalfUpperTail(successes: number, n: number): number {\n if (successes <= 0) return 1\n if (successes > n) return 0\n\n // Use the smaller side of the distribution. For lower thresholds the\n // complement sums at most half the mass; for upper thresholds symmetry\n // maps the upper tail to a lower tail without subtraction.\n if (successes <= n / 2) {\n return Math.max(0, 1 - binomialHalfLowerTail(successes - 1, n))\n }\n return binomialHalfLowerTail(n - successes, n)\n}\n\n/** P(X <= maxSuccesses) for X ~ Binomial(n, 0.5), accumulated in log space. */\nfunction binomialHalfLowerTail(maxSuccesses: number, n: number): number {\n if (maxSuccesses < 0) return 0\n if (maxSuccesses >= n) return 1\n if (maxSuccesses === 0) return 2 ** -n\n\n const logHalfN = n * Math.log(0.5)\n let logTail = Number.NEGATIVE_INFINITY\n for (let i = 0; i <= maxSuccesses; i++) {\n const logChoose = lnGamma(n + 1) - lnGamma(i + 1) - lnGamma(n - i + 1)\n logTail = logAddExp(logTail, logChoose + logHalfN)\n }\n return Math.min(1, Math.exp(logTail))\n}\n\nfunction logAddExp(a: number, b: number): number {\n if (a === Number.NEGATIVE_INFINITY) return b\n if (b === Number.NEGATIVE_INFINITY) return a\n const max = Math.max(a, b)\n const min = Math.min(a, b)\n return max + Math.log1p(Math.exp(min - max))\n}\n\n/** Standard-normal inverse CDF (Acklam approximation). */\nexport function zQuantile(p: number): number {\n if (p <= 0 || p >= 1) {\n if (p === 0) return -Infinity\n if (p === 1) return Infinity\n return NaN\n }\n const a = [\n -3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 1.38357751867269e2,\n -3.066479806614716e1, 2.506628277459239,\n ]\n const b = [\n -5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1,\n -1.328068155288572e1,\n ]\n const c = [\n -7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, -2.549732539343734,\n 4.374664141464968, 2.938163982698783,\n ]\n const d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996, 3.754408661907416]\n const pLow = 0.02425\n const pHigh = 1 - pLow\n let q: number\n let r: number\n if (p < pLow) {\n q = Math.sqrt(-2 * Math.log(p))\n return (\n (((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n }\n if (p <= pHigh) {\n q = p - 0.5\n r = q * q\n return (\n ((((((a[0]! * r + a[1]!) * r + a[2]!) * r + a[3]!) * r + a[4]!) * r + a[5]!) * q) /\n (((((b[0]! * r + b[1]!) * r + b[2]!) * r + b[3]!) * r + b[4]!) * r + 1)\n )\n }\n q = Math.sqrt(-2 * Math.log(1 - p))\n return (\n -(((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n}\n\nexport function medianInPlace(xs: number[]): number {\n if (xs.length === 0) return 0\n xs.sort((a, b) => a - b)\n const mid = Math.floor(xs.length / 2)\n return xs.length % 2 === 0 ? (xs[mid - 1]! + xs[mid]!) / 2 : xs[mid]!\n}\n\n/**\n * PRNG for every resampling path in this module.\n *\n * With no caller seed the seed is DERIVED FROM THE DATA rather than taken from\n * `Math.random`, so re-running the same input reproduces the same interval —\n * a gate verdict that cannot be re-derived is not evidence. Distinct data\n * still gets a distinct stream. Same pattern as `promotion-gate.ts`.\n */\nexport function makeRng(\n seed: number | undefined,\n ...series: readonly (readonly number[])[]\n): () => number {\n return mulberry32(seed ?? seedFromData(series))\n}\n\n/** FNV-1a over the IEEE-754 bytes of every observation. */\nfunction seedFromData(series: readonly (readonly number[])[]): number {\n const view = new DataView(new ArrayBuffer(8))\n let hash = 0x811c9dc5\n for (const xs of series) {\n for (const x of xs) {\n view.setFloat64(0, x)\n for (let byte = 0; byte < 8; byte++) {\n hash = Math.imul(hash ^ view.getUint8(byte), 0x01000193)\n }\n }\n // Separator, so ([1],[2]) and ([1,2],[]) do not collide.\n hash = Math.imul(hash ^ 0xff, 0x01000193)\n }\n return hash | 0\n}\n\n/** Order-independent seed for a symmetric two-sample statistic. */\nexport function symmetricTwoSampleSeed(a: readonly number[], b: readonly number[]): number {\n const sortedA = [...a].sort((left, right) => left - right)\n const sortedB = [...b].sort((left, right) => left - right)\n const forward = seedFromData([sortedA, sortedB]) >>> 0\n const reversed = seedFromData([sortedB, sortedA]) >>> 0\n return Math.min(forward, reversed)\n}\n"],"mappings":";;;;AACA,SAAgB,QAAQ,GAAmB;CACzC,MAAM,IAAI;CACV,MAAM,eAAe;EACnB;EAAqB;EAAmB;EAAqB;EAC7D;EAAqB;EAAoB;EAAsB;EAC/D;CACF;CACA,IAAI,IAAI,IACN,OAAO,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,QAAQ,IAAI,CAAC;CAElE,KAAK;CACL,IAAI,IAAI,aAAa;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAO,KAAK,KAAK,aAAa,MAAO,IAAI;CAC7D,MAAM,IAAI,IAAI,IAAI;CAClB,OAAO,KAAM,KAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IAAI,MAAO,KAAK,IAAI,CAAC,IAAI,IAAI,KAAK,IAAI,CAAC;AAC/E;;;;;;;;;AAUA,SAAgB,0BAA0B,GAAW,GAAW,GAAmB;CACjF,IAAI,KAAK,GAAG,OAAO;CACnB,IAAI,KAAK,GAAG,OAAO;CACnB,MAAM,UAAU,QAAQ,CAAC,IAAI,QAAQ,CAAC,IAAI,QAAQ,IAAI,CAAC;CAGvD,MAAM,QAAQ,KAAK,IAAI,KAAK,IAAI,CAAC,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,IAAI,IAAI,OAAO;CACtE,IA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D,IAAI,GAAG,WAAW,GAAG,OAAO;CAC5B,GAAG,MAAM,GAAG,MAAM,IAAI,CAAC;CACvB,MAAM,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;CACpC,OAAO,GAAG,SAAS,MAAM,KAAK,GAAG,MAAM,KAAM,GAAG,QAAS,IAAI,GAAG;AAClE;;;;;;;;;AAUA,SAAgB,QACd,MACA,GAAG,QACW;CACd,OAAO,WAAW,QAAQ,aAAa,MAAM,CAAC;AAChD;;AAGA,SAAS,aAAa,QAAgD;CACpE,MAAM,uBAAO,IAAI,yBAAS,IAAI,YAAY,CAAC,CAAC;CAC5C,IAAI,OAAO;CACX,KAAK,MAAM,MAAM,QAAQ;EACvB,KAAK,MAAM,KAAK,IAAI;GAClB,KAAK,WAAW,GAAG,CAAC;GACpB,KAAK,IAAI,OAAO,GAAG,OAAO,GAAG,QAC3B,OAAO,KAAK,KAAK,OAAO,KAAK,SAAS,IAAI,GAAG,QAAU;EAE3D;EAEA,OAAO,KAAK,KAAK,OAAO,KAAM,QAAU;CAC1C;CACA,OAAO,OAAO;AAChB;;AAGA,SAAgB,uBAAuB,GAAsB,GAA8B;CACzF,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,MAAM,UAAU,OAAO,KAAK;CACzD,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,MAAM,UAAU,OAAO,KAAK;CACzD,MAAM,UAAU,aAAa,CAAC,SAAS,OAAO,CAAC,MAAM;CACrD,MAAM,WAAW,aAAa,CAAC,SAAS,OAAO,CAAC,MAAM;CACtD,OAAO,KAAK,IAAI,SAAS,QAAQ;AACnC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as mulberry32 } from "./random-Dn5fPWkt.js";
|
|
2
|
+
import { a as spearmanR, r as pearsonR } from "./descriptive-1V17A-qa.js";
|
|
2
3
|
//#region src/judge-calibration.ts
|
|
3
4
|
/**
|
|
4
5
|
* Judge calibration — measure judge quality against human gold + bias.
|
|
@@ -285,17 +286,6 @@ function avgPairwise(rows, fn) {
|
|
|
285
286
|
}
|
|
286
287
|
return pairs === 0 ? NaN : sum / pairs;
|
|
287
288
|
}
|
|
288
|
-
/** Seeded PRNG — Mulberry32. Deterministic across platforms. */
|
|
289
|
-
function mulberry32(seed) {
|
|
290
|
-
let a = seed >>> 0;
|
|
291
|
-
return () => {
|
|
292
|
-
a = a + 1831565813 >>> 0;
|
|
293
|
-
let t = a;
|
|
294
|
-
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
295
|
-
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
296
|
-
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
289
|
function percentileBounds(ciLevel) {
|
|
300
290
|
const tail = (1 - ciLevel) / 2;
|
|
301
291
|
return [tail, 1 - tail];
|
|
@@ -314,4 +304,4 @@ function quantile(sorted, q) {
|
|
|
314
304
|
//#endregion
|
|
315
305
|
export { verbosityBias as i, calibrateJudgeContinuous as n, continuousAgreement as r, calibrateJudge as t };
|
|
316
306
|
|
|
317
|
-
//# sourceMappingURL=judge-calibration-
|
|
307
|
+
//# sourceMappingURL=judge-calibration-BnpVKtnb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"judge-calibration-BnpVKtnb.js","names":[],"sources":["../src/judge-calibration.ts"],"sourcesContent":["/**\n * Judge calibration — measure judge quality against human gold + bias.\n *\n * Workflow:\n * 1. Build a golden set: {itemId, humanScore}[].\n * 2. Run candidate judges; each produces {itemId, score}.\n * 3. `calibrateJudge(golden, candidate)` reports κ + Pearson + MAE.\n * 4. `calibrateJudgeContinuous(golden, candidate)` adds quadratic-weighted\n * κ over the un-rounded [0,1] scores plus ICC(2,1), Pearson, Spearman,\n * and bootstrap CIs — use this for fine-grained judges where rounding\n * to int discards information (e.g. 0.78 vs 0.81 both round to 1 and\n * look \"perfectly agreed\" to integer κ).\n * 5. Run bias probes (positional, verbosity, self-preference) to\n * detect systematic score inflation.\n * 6. For N≥2 judges on the same items, `continuousAgreement(scores)`\n * reports ICC(2,1) + κ_w + Pearson + Spearman with bootstrap CIs.\n *\n * Returns actionable diagnostics, not a single number. Consumers then\n * decide whether to trust the judge, retrain it, or add a tie-breaker.\n */\n\nimport { pearsonR, spearmanR } from './statistics/descriptive'\nimport { mulberry32 } from './statistics/random'\n\nexport interface GoldenItem {\n itemId: string\n humanScore: number\n /** Optional group used for per-group bias audits (e.g. model-of-output family). */\n group?: string\n}\n\nexport interface CandidateScore {\n itemId: string\n score: number\n /** Optional — enables positional-bias analysis (did order matter?). */\n positionOfAInput?: 'first' | 'second'\n}\n\nexport interface CalibrationResult {\n n: number\n pearson: number\n /** Cohen's κ with quadratic weights over integer-rounded scores. */\n kappa: number\n /** Mean absolute error vs human. */\n mae: number\n /** Worst-5 miscalibrations (largest |judge - human|). */\n worstItems: Array<{ itemId: string; judge: number; human: number; delta: number }>\n}\n\n/**\n * Measure judge quality against human gold labels: computes Cohen's κ, Pearson correlation, and MAE over matched item ids.\n */\nexport function calibrateJudge(\n golden: GoldenItem[],\n candidate: CandidateScore[],\n): CalibrationResult {\n const map = new Map<string, { h: number; j: number }>()\n for (const g of golden) map.set(g.itemId, { h: g.humanScore, j: NaN })\n for (const c of candidate) {\n const entry = map.get(c.itemId)\n if (entry) entry.j = c.score\n }\n const common = [...map.values()].filter((v) => Number.isFinite(v.j))\n const n = common.length\n if (n < 2) {\n return { n, pearson: NaN, kappa: NaN, mae: NaN, worstItems: [] }\n }\n const humans = common.map((c) => c.h)\n const judges = common.map((c) => c.j)\n const pearson = pearsonR(humans, judges)\n const kappa = weightedKappa(humans.map(Math.round), judges.map(Math.round))\n const absDiffs = common.map((c) => Math.abs(c.j - c.h))\n const mae = absDiffs.reduce((a, b) => a + b, 0) / n\n const worst = [...map.entries()]\n .filter(([, v]) => Number.isFinite(v.j))\n .map(([itemId, v]) => ({ itemId, judge: v.j, human: v.h, delta: Math.abs(v.j - v.h) }))\n .sort((a, b) => b.delta - a.delta)\n .slice(0, 5)\n return { n, pearson, kappa, mae, worstItems: worst }\n}\n\nexport interface PositionalBiasResult {\n /**\n * Score delta (first-position - second-position) averaged across items\n * presented in both positions. Non-zero = positional bias.\n */\n avgDelta: number\n n: number\n}\n\n/**\n * Feed the same items to the judge twice with A/B swapped and pass all\n * results here. Items that don't appear in both positions are ignored.\n */\nexport function positionalBias(scores: CandidateScore[]): PositionalBiasResult {\n const pairs = new Map<string, { first?: number; second?: number }>()\n for (const s of scores) {\n const slot = pairs.get(s.itemId) ?? {}\n if (s.positionOfAInput === 'first') slot.first = s.score\n else if (s.positionOfAInput === 'second') slot.second = s.score\n pairs.set(s.itemId, slot)\n }\n const deltas: number[] = []\n for (const { first, second } of pairs.values()) {\n if (first !== undefined && second !== undefined) deltas.push(first - second)\n }\n if (deltas.length === 0) return { avgDelta: 0, n: 0 }\n return { avgDelta: deltas.reduce((a, b) => a + b, 0) / deltas.length, n: deltas.length }\n}\n\nexport interface VerbosityBiasResult {\n /** Pearson correlation between output length and score. Strong positive = verbosity bias. */\n pearson: number\n n: number\n}\n\nexport function verbosityBias(\n samples: Array<{ outputLen: number; score: number }>,\n): VerbosityBiasResult {\n const n = samples.length\n if (n < 3) return { pearson: NaN, n }\n return {\n pearson: pearsonR(\n samples.map((s) => s.outputLen),\n samples.map((s) => s.score),\n ),\n n,\n }\n}\n\nexport interface SelfPreferenceResult {\n /** Mean judge score when judge's family matches output's family. */\n inFamilyMean: number\n outOfFamilyMean: number\n deltaMean: number\n n: number\n}\n\n/**\n * Pass the same scenarios scored with judge-model X grading outputs from\n * model X (in-family) and model Y (out-of-family). Non-zero delta\n * indicates self-preference.\n */\nexport function selfPreference(\n samples: Array<{ score: number; inFamily: boolean }>,\n): SelfPreferenceResult {\n const inF = samples.filter((s) => s.inFamily).map((s) => s.score)\n const outF = samples.filter((s) => !s.inFamily).map((s) => s.score)\n if (inF.length === 0 || outF.length === 0)\n return { inFamilyMean: 0, outOfFamilyMean: 0, deltaMean: 0, n: 0 }\n const inMean = inF.reduce((a, b) => a + b, 0) / inF.length\n const outMean = outF.reduce((a, b) => a + b, 0) / outF.length\n return {\n inFamilyMean: inMean,\n outOfFamilyMean: outMean,\n deltaMean: inMean - outMean,\n n: samples.length,\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\n/** Quadratic weighted Cohen's κ over bounded integer scores. */\nfunction weightedKappa(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length === 0) return NaN\n const min = Math.min(...a, ...b)\n const max = Math.max(...a, ...b)\n const K = max - min + 1\n if (K < 2) return 1\n const observed: number[][] = Array.from({ length: K }, () => new Array(K).fill(0))\n const rowMarg = new Array(K).fill(0)\n const colMarg = new Array(K).fill(0)\n for (let i = 0; i < a.length; i++) {\n const ai = a[i]! - min\n const bi = b[i]! - min\n const row = observed[ai]!\n row[bi] = (row[bi] ?? 0) + 1\n rowMarg[ai]++\n colMarg[bi]++\n }\n let num = 0\n let den = 0\n for (let i = 0; i < K; i++) {\n for (let j = 0; j < K; j++) {\n const w = (i - j) ** 2 / (K - 1) ** 2\n const expected = (rowMarg[i] * colMarg[j]) / a.length\n num += w * observed[i]![j]!\n den += w * expected\n }\n }\n if (den === 0) return 1\n return 1 - num / den\n}\n\n// ── Continuous-value inter-rater agreement ──────────────────────────\n//\n// `weightedKappa` above quantises to integers. For [0,1] judges that is\n// lossy: 0.78 and 0.81 both round to 1 and look identical to integer κ.\n// `continuousAgreement` keeps the original magnitudes:\n//\n// - κ_w : Cohen's weighted κ generalised to continuous scores. For two\n// raters, weighted κ = 1 − Σ w_ij·o_ij / Σ w_ij·e_ij collapses\n// into the closed form below when each \"category\" is the score\n// itself (Janson & Olsson 2001; Cohen 1968 quadratic weights).\n// - ICC : Intraclass Correlation Coefficient, ICC(2,1) per Shrout &\n// Fleiss (1979) — two-way random effects, absolute agreement,\n// single rater. The right reliability coefficient when judges\n// are a random sample of the judge population.\n// - r, ρ : Pearson + Spearman for sanity-check. Pearson catches linear\n// association regardless of scale; Spearman catches monotone\n// association regardless of distribution.\n// - CIs : Bootstrap percentile CIs over items (rows). Bias is preserved\n// because we resample the full row, i.e. a judge's vector\n// stays internally consistent within each bootstrap replicate.\n//\n// References:\n// - Shrout, P. E. & Fleiss, J. L. (1979). Intraclass correlations: uses\n// in assessing rater reliability. Psychological Bulletin, 86(2), 420.\n// - McGraw, K. O. & Wong, S. P. (1996). Forming inferences about some\n// intraclass correlation coefficients. Psychological Methods, 1, 30.\n// - Janson, H. & Olsson, U. (2001). A measure of agreement for interval\n// or nominal multivariate observations. Educ. Psychol. Meas., 61, 277.\n\nexport interface ContinuousAgreement {\n /** Cohen's κ_w with quadratic weights, computed on raw [0,1] scores. */\n weightedKappa: number\n /** ICC(2,1): two-way random effects, absolute agreement, single rater. */\n icc: number\n /** Pearson product-moment correlation (averaged over rater pairs if N>2). */\n pearson: number\n /** Spearman rank correlation (averaged over rater pairs if N>2). */\n spearman: number\n /** 95% bootstrap percentile CIs over items. */\n ci: {\n icc: [number, number]\n weightedKappa: [number, number]\n }\n /** Number of complete items (no NaN across raters). */\n n: number\n /** Number of raters. */\n raters: number\n}\n\nexport interface ContinuousAgreementOptions {\n /** Bootstrap iterations. Default 1000. Set to 0 to skip CIs (CI = [NaN, NaN]). */\n bootstrap?: number\n /** κ weighting scheme. Default 'quadratic'. */\n weights?: 'linear' | 'quadratic'\n /** PRNG seed for reproducible bootstrap. Default 0xC0FFEE. */\n seed?: number\n /** Confidence level for percentile CI. Default 0.95. */\n ciLevel?: number\n}\n\n/**\n * Inter-rater agreement on continuous (typically [0,1]) scores.\n *\n * `scores` has shape [n_items][n_raters]. Rows with any non-finite entry\n * are dropped. Returns NaN metrics if fewer than 2 raters or 2 complete\n * items remain.\n */\nexport function continuousAgreement(\n scores: number[][],\n opts: ContinuousAgreementOptions = {},\n): ContinuousAgreement {\n const bootstrap = opts.bootstrap ?? 1000\n const weights = opts.weights ?? 'quadratic'\n const seed = opts.seed ?? 0xc0ffee\n const ciLevel = opts.ciLevel ?? 0.95\n\n const matrix = scores.filter((row) => row.length >= 2 && row.every((v) => Number.isFinite(v)))\n const raters = matrix[0]?.length ?? 0\n // All rows must have the same rater count, else drop the offenders.\n const clean = matrix.filter((row) => row.length === raters)\n const nClean = clean.length\n\n if (nClean < 2 || raters < 2) {\n return {\n weightedKappa: NaN,\n icc: NaN,\n pearson: NaN,\n spearman: NaN,\n ci: { icc: [NaN, NaN], weightedKappa: [NaN, NaN] },\n n: nClean,\n raters,\n }\n }\n\n const kappa = continuousWeightedKappa(clean, weights)\n const icc = icc21(clean)\n const pearson = avgPairwise(clean, pearsonR)\n const spearman = avgPairwise(clean, spearmanR)\n\n const ciIcc: [number, number] = [NaN, NaN]\n const ciKappa: [number, number] = [NaN, NaN]\n if (bootstrap > 0) {\n const rng = mulberry32(seed)\n const iccs: number[] = []\n const kappas: number[] = []\n for (let b = 0; b < bootstrap; b++) {\n const sample: number[][] = new Array(nClean)\n for (let i = 0; i < nClean; i++) {\n sample[i] = clean[Math.floor(rng() * nClean)]!\n }\n const iccB = icc21(sample)\n const kB = continuousWeightedKappa(sample, weights)\n if (Number.isFinite(iccB)) iccs.push(iccB)\n if (Number.isFinite(kB)) kappas.push(kB)\n }\n const [lo, hi] = percentileBounds(ciLevel)\n if (iccs.length > 0) {\n iccs.sort((a, b) => a - b)\n ciIcc[0] = quantile(iccs, lo)\n ciIcc[1] = quantile(iccs, hi)\n }\n if (kappas.length > 0) {\n kappas.sort((a, b) => a - b)\n ciKappa[0] = quantile(kappas, lo)\n ciKappa[1] = quantile(kappas, hi)\n }\n }\n\n return {\n weightedKappa: kappa,\n icc,\n pearson,\n spearman,\n ci: { icc: ciIcc, weightedKappa: ciKappa },\n n: nClean,\n raters,\n }\n}\n\nexport interface ContinuousCalibrationResult extends CalibrationResult {\n /** Cohen's κ_w computed on raw (un-rounded) scores. */\n weightedKappaContinuous: number\n /** ICC(2,1) treating golden + candidate as two raters. */\n icc: number\n spearman: number\n ci: {\n icc: [number, number]\n weightedKappa: [number, number]\n }\n}\n\n/**\n * Extends `calibrateJudge` with continuous-value agreement metrics while\n * retaining its base calibration summary.\n */\nexport function calibrateJudgeContinuous(\n golden: GoldenItem[],\n candidate: CandidateScore[],\n opts: ContinuousAgreementOptions = {},\n): ContinuousCalibrationResult {\n const base = calibrateJudge(golden, candidate)\n const map = new Map<string, { h: number; j: number }>()\n for (const g of golden) map.set(g.itemId, { h: g.humanScore, j: NaN })\n for (const c of candidate) {\n const entry = map.get(c.itemId)\n if (entry) entry.j = c.score\n }\n const rows: number[][] = []\n for (const v of map.values()) {\n if (Number.isFinite(v.j)) rows.push([v.h, v.j])\n }\n const agreement = continuousAgreement(rows, opts)\n return {\n ...base,\n weightedKappaContinuous: agreement.weightedKappa,\n icc: agreement.icc,\n spearman: agreement.spearman,\n ci: agreement.ci,\n }\n}\n\n// ── Continuous-agreement internals ──────────────────────────────────\n\n/**\n * Quadratic-weighted κ on continuous scores. With weights w(x,y) = (x-y)^2\n * (or |x-y| for linear) the formula collapses to:\n *\n * κ_w = 1 − E_obs[w] / E_exp[w]\n *\n * where E_obs averages w over paired (a_i, b_i) and E_exp averages w over\n * the independent product distribution (sum_{i,j} w(a_i, b_j) / n^2).\n * The normalisation by (max-min)^2 in the integer version cancels in the\n * ratio, so we don't need it here. Generalises to N raters by averaging κ_w\n * over all rater pairs (mean pairwise weighted agreement).\n */\nfunction continuousWeightedKappa(rows: number[][], scheme: 'linear' | 'quadratic'): number {\n if (rows.length === 0) return NaN\n const raters = rows[0]!.length\n if (raters < 2) return NaN\n const wFn =\n scheme === 'linear'\n ? (x: number, y: number) => Math.abs(x - y)\n : (x: number, y: number) => (x - y) ** 2\n let sum = 0\n let pairs = 0\n for (let r1 = 0; r1 < raters; r1++) {\n for (let r2 = r1 + 1; r2 < raters; r2++) {\n const a = rows.map((row) => row[r1]!)\n const b = rows.map((row) => row[r2]!)\n const n = a.length\n let obs = 0\n for (let i = 0; i < n; i++) obs += wFn(a[i]!, b[i]!)\n obs /= n\n // Expected under independence: average of w over all i,j cross pairs.\n let exp = 0\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) exp += wFn(a[i]!, b[j]!)\n }\n exp /= n * n\n if (exp === 0) {\n // Degenerate: at least one rater is constant. Convention: perfect\n // agreement iff observed disagreement is also zero, else 0.\n sum += obs === 0 ? 1 : 0\n } else {\n sum += 1 - obs / exp\n }\n pairs++\n }\n }\n return pairs === 0 ? NaN : sum / pairs\n}\n\n/**\n * ICC(2,1) — two-way random effects, absolute agreement, single rater.\n *\n * ICC(2,1) = (MSR − MSE) / (MSR + (k−1)·MSE + k·(MSC − MSE)/n)\n *\n * where MSR = between-rows MS, MSC = between-columns MS, MSE = residual MS,\n * n = rows (items), k = columns (raters).\n */\nfunction icc21(rows: number[][]): number {\n const n = rows.length\n if (n < 2) return NaN\n const k = rows[0]!.length\n if (k < 2) return NaN\n\n // Row means.\n const rowMeans = rows.map((row) => row.reduce((s, v) => s + v, 0) / k)\n // Column means.\n const colMeans = new Array(k).fill(0)\n for (let j = 0; j < k; j++) {\n let s = 0\n for (let i = 0; i < n; i++) s += rows[i]![j]!\n colMeans[j] = s / n\n }\n // Grand mean.\n let grand = 0\n for (let i = 0; i < n; i++) grand += rowMeans[i]!\n grand /= n\n\n let ssR = 0\n for (let i = 0; i < n; i++) ssR += (rowMeans[i]! - grand) ** 2\n ssR *= k\n let ssC = 0\n for (let j = 0; j < k; j++) ssC += (colMeans[j]! - grand) ** 2\n ssC *= n\n let ssT = 0\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < k; j++) ssT += (rows[i]![j]! - grand) ** 2\n }\n const ssE = ssT - ssR - ssC\n\n const dfR = n - 1\n const dfC = k - 1\n const dfE = (n - 1) * (k - 1)\n const msR = ssR / dfR\n const msC = ssC / dfC\n const msE = dfE > 0 ? ssE / dfE : 0\n\n const denom = msR + (k - 1) * msE + (k * (msC - msE)) / n\n if (denom === 0) {\n // Degenerate (all values equal): convention = 1 if rows identical,\n // else 0. Identical rows ⇒ msR = 0 too, so msR − msE near 0.\n return msR === 0 && msE === 0 ? 1 : 0\n }\n return (msR - msE) / denom\n}\n\n/** Average pairwise statistic over all rater pairs. */\nfunction avgPairwise(rows: number[][], fn: (a: number[], b: number[]) => number): number {\n const k = rows[0]?.length ?? 0\n if (k < 2) return NaN\n let sum = 0\n let pairs = 0\n for (let i = 0; i < k; i++) {\n for (let j = i + 1; j < k; j++) {\n const a = rows.map((row) => row[i]!)\n const b = rows.map((row) => row[j]!)\n const r = fn(a, b)\n if (Number.isFinite(r)) {\n sum += r\n pairs++\n }\n }\n }\n return pairs === 0 ? NaN : sum / pairs\n}\n\nfunction percentileBounds(ciLevel: number): [number, number] {\n const tail = (1 - ciLevel) / 2\n return [tail, 1 - tail]\n}\n\n/** Linear-interpolated quantile of a pre-sorted ascending array. */\nfunction quantile(sorted: number[], q: number): number {\n if (sorted.length === 0) return NaN\n if (sorted.length === 1) return sorted[0]!\n const pos = q * (sorted.length - 1)\n const lo = Math.floor(pos)\n const hi = Math.ceil(pos)\n if (lo === hi) return sorted[lo]!\n const frac = pos - lo\n return sorted[lo]! * (1 - frac) + sorted[hi]! * frac\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,eACd,QACA,WACmB;CACnB,MAAM,sBAAM,IAAI,IAAsC;CACtD,KAAK,MAAM,KAAK,QAAQ,IAAI,IAAI,EAAE,QAAQ;EAAE,GAAG,EAAE;EAAY,GAAG;CAAI,CAAC;CACrE,KAAK,MAAM,KAAK,WAAW;EACzB,MAAM,QAAQ,IAAI,IAAI,EAAE,MAAM;EAC9B,IAAI,OAAO,MAAM,IAAI,EAAE;CACzB;CACA,MAAM,SAAS,CAAC,GAAG,IAAI,OAAO,CAAC,CAAC,CAAC,QAAQ,MAAM,OAAO,SAAS,EAAE,CAAC,CAAC;CACnE,MAAM,IAAI,OAAO;CACjB,IAAI,IA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B,IAAI,OAAO,IAAI,OAAO,OAAO;CAC7B,MAAM,OAAO,MAAM;CACnB,OAAO,OAAO,OAAQ,IAAI,QAAQ,OAAO,MAAO;AAClD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"judge-calibration-C5CbMYce.d.ts","names":[],"sources":["../src/judge-calibration.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"judge-calibration-C5CbMYce.d.ts","names":[],"sources":["../src/judge-calibration.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;UAwBiB;EACf;EACA;;EAEA;;UAGe;EACf;EACA;;EAEA;;UAGe;EACf;EACA;;EAEA;;EAEA;;EAEA,YAAY;IAAQ;IAAgB;IAAe;IAAe;;;;;;iBAMpD,eACd,QAAQ,cACR,WAAW,mBACV;UAuDc;;EAEf;EACA;;iBAGc,cACd,SAAS;EAAQ;EAAmB;KACnC;UAyGc;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;IACE;IACA;;;EAGF;;EAEA;;UAGe;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;;iBAUc,oBACd,oBACA,OAAM,6BACL;UAqEc,oCAAoC;;EAEnD;;EAEA;EACA;EACA;IACE;IACA;;;;;;;iBAQY,yBACd,QAAQ,cACR,WAAW,kBACX,OAAM,6BACL"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { t as AgentEvalError } from "./errors-Dngq5h35.js";
|
|
2
2
|
import { c as costForTokenPricing } from "./cost-ledger-B1qx30B4.js";
|
|
3
|
+
import { t as newRecordId } from "./record-id-DUgsK5qp.js";
|
|
3
4
|
import { a as providerFromBaseUrl, i as defaultProviderRedactor } from "./raw-provider-sink-BQd7mzyT.js";
|
|
4
5
|
//#region src/judge-families.ts
|
|
5
6
|
/** Explicit `provider/...` prefix → family (models.dev / OpenRouter style). */
|
|
@@ -692,7 +693,7 @@ async function callLlm(req, opts = {}) {
|
|
|
692
693
|
const requestBody = buildBody(effectiveRequest, opts.jsonSchemaTransport === "json-object", opts.thinking);
|
|
693
694
|
let attemptErrorRecorded = false;
|
|
694
695
|
if (sink) await recordRaw(sink, redactor, {
|
|
695
|
-
eventId:
|
|
696
|
+
eventId: newRecordId(),
|
|
696
697
|
runId: traceContext?.runId,
|
|
697
698
|
spanId: traceContext?.spanId,
|
|
698
699
|
provider,
|
|
@@ -719,7 +720,7 @@ async function callLlm(req, opts = {}) {
|
|
|
719
720
|
const body = await res.text();
|
|
720
721
|
if (sink) {
|
|
721
722
|
await recordRaw(sink, redactor, {
|
|
722
|
-
eventId:
|
|
723
|
+
eventId: newRecordId(),
|
|
723
724
|
runId: traceContext?.runId,
|
|
724
725
|
spanId: traceContext?.spanId,
|
|
725
726
|
provider,
|
|
@@ -761,7 +762,7 @@ async function callLlm(req, opts = {}) {
|
|
|
761
762
|
} catch (parseErr) {
|
|
762
763
|
if (sink) {
|
|
763
764
|
await recordRaw(sink, redactor, {
|
|
764
|
-
eventId:
|
|
765
|
+
eventId: newRecordId(),
|
|
765
766
|
runId: traceContext?.runId,
|
|
766
767
|
spanId: traceContext?.spanId,
|
|
767
768
|
provider,
|
|
@@ -783,7 +784,7 @@ async function callLlm(req, opts = {}) {
|
|
|
783
784
|
throw parseErr;
|
|
784
785
|
}
|
|
785
786
|
if (sink) await recordRaw(sink, redactor, {
|
|
786
|
-
eventId:
|
|
787
|
+
eventId: newRecordId(),
|
|
787
788
|
runId: traceContext?.runId,
|
|
788
789
|
spanId: traceContext?.spanId,
|
|
789
790
|
provider,
|
|
@@ -844,7 +845,7 @@ async function callLlm(req, opts = {}) {
|
|
|
844
845
|
lastErr = err;
|
|
845
846
|
if (callerSignal?.aborted) {
|
|
846
847
|
if (sink && !attemptErrorRecorded) await recordRaw(sink, redactor, {
|
|
847
|
-
eventId:
|
|
848
|
+
eventId: newRecordId(),
|
|
848
849
|
runId: traceContext?.runId,
|
|
849
850
|
spanId: traceContext?.spanId,
|
|
850
851
|
provider,
|
|
@@ -861,7 +862,7 @@ async function callLlm(req, opts = {}) {
|
|
|
861
862
|
throw err;
|
|
862
863
|
}
|
|
863
864
|
if (sink && !attemptErrorRecorded) await recordRaw(sink, redactor, {
|
|
864
|
-
eventId:
|
|
865
|
+
eventId: newRecordId(),
|
|
865
866
|
runId: traceContext?.runId,
|
|
866
867
|
spanId: traceContext?.spanId,
|
|
867
868
|
provider,
|
|
@@ -896,10 +897,6 @@ function headersToObject(h) {
|
|
|
896
897
|
});
|
|
897
898
|
return out;
|
|
898
899
|
}
|
|
899
|
-
function cryptoEventId() {
|
|
900
|
-
if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
|
|
901
|
-
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
902
|
-
}
|
|
903
900
|
/**
|
|
904
901
|
* Structured-output call. Returns parsed JSON plus the raw result envelope.
|
|
905
902
|
* Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —
|
|
@@ -976,4 +973,4 @@ var LlmClient = class {
|
|
|
976
973
|
//#endregion
|
|
977
974
|
export { judgeFamily as S, assertServedModels as _, callLlmJson as a, CrossFamilyError as b, extractJsonPayload as c, stripFencedJson as d, ModelSubstitutionError as f, assertServedModelPolicy as g, assertServedModel as h, backoffMs as i, isTransientLlmError as l, assertCrossFamilyServed as m, LlmClient as n, costReceiptFromLlm as o, ServedCrossFamilyError as p, LlmResponseError as r, costReceiptFromLlmError as s, LlmCallError as t, maximumChargeForLlmRequest as u, checkServedModel as v, assertCrossFamily as x, servedModelAcceptable as y };
|
|
978
975
|
|
|
979
|
-
//# sourceMappingURL=llm-client-
|
|
976
|
+
//# sourceMappingURL=llm-client-BFMRpmqb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llm-client-BFMRpmqb.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\n/**\n * Consumer-facing name for the substitution policy a metered surface applies.\n * `'exact'` rejects every substitution. `'allow-within-family'` accepts a\n * different model of the same provider family; it keeps family-level claims\n * valid and forfeits per-model claims. Maps to\n * `AssertServedModelOptions.allowWithinFamily`.\n */\nexport type ServedModelPolicy = 'exact' | 'allow-within-family'\n\nexport function assertServedModelPolicy(\n value: unknown,\n label: string,\n): asserts value is ServedModelPolicy | undefined {\n if (value !== undefined && value !== 'exact' && value !== 'allow-within-family') {\n throw new Error(`${label} must be 'exact' or 'allow-within-family'`)\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 * INTERNAL OpenAI-compatible client. NOT part of the published surface.\n *\n * agent-eval executes no paid model on behalf of a consumer: `createChatClient`\n * binds a caller-supplied transport, and this module is not reachable through\n * any export subpath. Two in-repo callers hold it:\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 {\n type CostReceiptInput,\n type CustomTokenPricing,\n costForTokenPricing,\n type MaximumCharge,\n} from './cost-ledger'\nimport { AgentEvalError } from './errors'\nimport {\n type AssertServedModelOptions,\n assertServedModel as assertServedModelIdentity,\n} 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'\n\n// ─── Types ──────────────────────────────────────────────────────────────\n\nexport interface LlmMessage {\n role: 'system' | 'user' | 'assistant' | 'tool'\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 /** Tool invocations made by an `assistant` message earlier in the turn. */\n toolCalls?: LlmToolCall[]\n /** The invocation a `tool` message answers. Required when role is `tool`. */\n toolCallId?: string\n}\n\nexport type LlmThinkingMode = 'enabled' | 'disabled'\n\n/** Canonical function-tool definition offered to the model. */\nexport interface LlmToolDefinition {\n type: 'function'\n function: {\n name: string\n description?: string\n parameters: Record<string, unknown>\n }\n}\n\n/** Canonical tool-choice policy; meaningful only when `tools` is present. */\nexport type LlmToolChoice =\n | 'auto'\n | 'none'\n | 'required'\n | { type: 'function'; function: { name: string } }\n\n/** One tool invocation on a response or an assistant history message. */\nexport interface LlmToolCall {\n id: string\n name: string\n /** JSON-encoded arguments, exactly as the provider produced them. */\n argumentsJson: string\n}\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 /** Function tools offered to the model for this call. */\n tools?: LlmToolDefinition[]\n /** Tool-choice policy for `tools`. */\n toolChoice?: LlmToolChoice\n temperature?: number\n maxTokens?: number\n /** Ask the provider for the log-probability of each sampled token and its\n * `topLogprobs` most likely alternatives. Sends `logprobs: true` with\n * `top_logprobs`. A provider that ignores the field returns\n * `LlmCallResult.logprobs === null`; nothing is inferred from its absence. */\n logprobs?: { topLogprobs: 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 interface LlmChargeBounds {\n /** Total provider attempts the transport may make for this call. Default 3. */\n maximumAttempts?: number\n /** The transport sends JSON mode instead of a response schema. */\n jsonSchemaTransport?: 'native' | 'json-object'\n /** Default provider reasoning mode the transport applies. */\n thinking?: LlmThinkingMode\n /** Token rates used when the provider omits cost or package pricing does not cover the model. */\n customTokenPricing?: CustomTokenPricing\n}\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 // 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\n/** One sampled token with its own log probability and the alternatives the\n * provider ranked at that position. */\nexport interface LlmTokenLogprob {\n token: string\n logprob: number\n top: ReadonlyArray<{ token: string; logprob: number }>\n}\n\nexport interface LlmCallResult {\n /** The text content of the first choice. Empty string if none. */\n content: string\n /** Tool invocations from the first choice, when the model called tools. */\n toolCalls?: LlmToolCall[]\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 /**\n * Per-token log probabilities for the first choice, in emission order, when\n * the request asked for them and the provider returned\n * `choices[0].logprobs.content`. `null` when the provider returned none, so a\n * caller can tell \"not requested or not supported\" from \"requested and\n * empty\". Absent when the request did not ask for logprobs.\n */\n logprobs?: ReadonlyArray<LlmTokenLogprob> | null\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.\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\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 extends LlmChargeBounds {\n /** Base URL (without trailing slash), ending at the `/v1` prefix. Required: there is no default endpoint. */\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 /**\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 /** 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\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\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.\nconst 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\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.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 */\nfunction parseWireLogprobs(value: unknown, model: string): 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. */\nfunction 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\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 // 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 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: newRecordId(),\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: newRecordId(),\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: newRecordId(),\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: newRecordId(),\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<{\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 =\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 ...(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 } 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: newRecordId(),\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: newRecordId(),\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\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/**\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,SAA8B;CACxD,MAAM,KAAK,QAAQ,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,YAAY;CACrD,MAAM,QAAQ,GAAG,QAAQ,GAAG;CAC5B,IAAI,QAAQ,GAAG;EACb,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onical, r as canonicalString } from "./canonical-IL-Bu-14.js";
|
|
3
|
-
import { s as weightedComposite, t as confidenceInterval } from "./descriptive-
|
|
4
|
-
import { r as pairedBootstrap } from "./paired-tests-
|
|
3
|
+
import { s as weightedComposite, t as confidenceInterval } from "./descriptive-1V17A-qa.js";
|
|
4
|
+
import { r as pairedBootstrap } from "./paired-tests-C8iCsioC.js";
|
|
5
5
|
import { i as modelHasSnapshot } from "./run-record-BC0ebuRP.js";
|
|
6
6
|
import { n as contentHash } from "./verdict-cache-CdVVTVmn.js";
|
|
7
|
-
import { a as campaignCellCostProvenance, o as campaignCellExecutionEvidence, t as detectRewardHacking, u as projectCampaignCellQuality } from "./reward-hacking-
|
|
7
|
+
import { a as campaignCellCostProvenance, o as campaignCellExecutionEvidence, t as detectRewardHacking, u as projectCampaignCellQuality } from "./reward-hacking-O5zKDANP.js";
|
|
8
8
|
import { i as CostLedger, t as CostAccountingIncompleteError } from "./cost-ledger-B1qx30B4.js";
|
|
9
9
|
import { u as mapConcurrent } from "./ledger-core-BOzlRygb.js";
|
|
10
|
-
import { b as createRunCostLedger, h as isRecord, m as isExternalTextCandidate, x as fsCampaignStorage } from "./external-optimizer-subprocess-
|
|
10
|
+
import { b as createRunCostLedger, h as isRecord, m as isExternalTextCandidate, x as fsCampaignStorage } from "./external-optimizer-subprocess-CqLMW3nh.js";
|
|
11
11
|
import { t as DEFAULT_REDACTION_RULES } from "./redact-7Aq1ukl-.js";
|
|
12
|
-
import { a as heldoutSignificance, i as dimensionRegressions, o as pairHoldout } from "./power-preflight-
|
|
12
|
+
import { a as heldoutSignificance, i as dimensionRegressions, o as pairHoldout } from "./power-preflight-CFXm0Vjo.js";
|
|
13
13
|
import { a as combineAbortSignals, n as clamp01, r as assertProposalFindings } from "./run-score-lDzV0X8j.js";
|
|
14
14
|
import { c as deepFreezeCanonicalJson } from "./types-BI4fT3HN.js";
|
|
15
|
-
import { d as stripFencedJson, o as costReceiptFromLlm, s as costReceiptFromLlmError, u as maximumChargeForLlmRequest } from "./llm-client-
|
|
15
|
+
import { d as stripFencedJson, o as costReceiptFromLlm, s as costReceiptFromLlmError, u as maximumChargeForLlmRequest } from "./llm-client-BFMRpmqb.js";
|
|
16
16
|
import { createHash } from "node:crypto";
|
|
17
17
|
import { writeFileSync } from "node:fs";
|
|
18
18
|
import { z } from "zod";
|
|
@@ -6175,4 +6175,4 @@ function firstString(value) {
|
|
|
6175
6175
|
//#endregion
|
|
6176
6176
|
export { scoreRedTeamOutput as $, codeSurfaceIdentityMaterial as A, verifySearchHistoryReceipt as B, openAutoPr as C, costFromLedgerSummary as D, compareOptimizationMethods as E, SearchHistoryRequiredError as F, parseReflectionResponse as G, campaignMeanComposite as H, assertCompleteSearchHistory as I, readGepaCandidatePopulationArtifact as J, recoverTruncatedJson as K, assertSearchHistoryMatchesReplay as L, renderSurfaceDiff as M, surfaceContentHash as N, optimizationTokenUsageFromSummary as O, surfaceHash as P, redTeamReport as Q, createSearchHistoryReceipt as R, paretoFrontierWithCrowding as S, combineComparisonCosts as T, compareRankKeys as U, campaignBreakdown as V, buildReflectionPrompt as W, DEFAULT_RED_TEAM_CORPUS as X, defaultProductionGate as Y, redTeamDataset as Z, labelTrustRank as _, buildLoopProvenanceRecord as a, tangleTracesRoot as at, dominates as b, emitLoopProvenance as c, summarizeBackendIntegrity as ct, provenanceRecordPath as d, campaignScenarioIdentity as dt, runCanaries as et, provenanceSpansPath as f, campaignSplitDigest as ft, isProposedCandidate as g, computeManifestHash as gt, runOptimization as h, cellCachePath as ht, transientDispatchFailure as i, resolveRunDir as it, componentSurfaceIdentityMaterial as j, assertCodeSurfaceIdentity as k, loopProvenanceArgsFromResult as l, assertCampaignDesign as lt, runImprovementLoop as m, readCachedCell as mt, JudgeParseError as n, runCampaign as nt, campaignMeasurementDigest as o, BackendIntegrityError as ot, verifyLoopProvenanceRecord as p, campaignSplitDigestFromIdentities as pt, assertGepaCandidatePopulationSummary as q, isTransientTransportFailure as r, planCampaignRun as rt, canonicalDigest as s, assertRealBackend as st, llmJudge as t, runEval as tt, loopProvenanceSpans as u, assertCampaignSplitIdentity as ut, SearchRecorder as v, assertOptimizationResult as w, paretoFrontier as x, recordCandidatePopulationSearch as y, searchHistoryCoverageRow as z };
|
|
6177
6177
|
|
|
6178
|
-
//# sourceMappingURL=llm-judge-
|
|
6178
|
+
//# sourceMappingURL=llm-judge-Du7WQPh7.js.map
|