@tangle-network/agent-eval 0.221.5 → 0.221.6
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 +56 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-Bc7ADJY4.d.ts → agent-profile-CNmwfaqq.d.ts} +3 -3
- package/dist/{agent-profile-Bc7ADJY4.d.ts.map → agent-profile-CNmwfaqq.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +12 -12
- package/dist/analyst/index.js +7 -7
- package/dist/{analyze-runs-D7In4c3z.d.ts → analyze-runs-DfX6dHP0.d.ts} +2 -2
- package/dist/{analyze-runs-D7In4c3z.d.ts.map → analyze-runs-DfX6dHP0.d.ts.map} +1 -1
- package/dist/{benchmark-command-BDq0VgoP.js → benchmark-command-Cnjfo0Zh.js} +6 -6
- package/dist/{benchmark-command-BDq0VgoP.js.map → benchmark-command-Cnjfo0Zh.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.d.ts +6 -6
- package/dist/campaign/index.js +4 -4
- package/dist/{campaign-Bt6rbWIU.js → campaign-uddTlFg5.js} +6 -6
- package/dist/{campaign-Bt6rbWIU.js.map → campaign-uddTlFg5.js.map} +1 -1
- package/dist/{chat-client-CMQ8_h4J.js → chat-client-BNATB3rJ.js} +2 -2
- package/dist/{chat-client-CMQ8_h4J.js.map → chat-client-BNATB3rJ.js.map} +1 -1
- package/dist/{chat-json-call-BrZKn0L3.js → chat-json-call-BzWYp18J.js} +2 -2
- package/dist/{chat-json-call-BrZKn0L3.js.map → chat-json-call-BzWYp18J.js.map} +1 -1
- package/dist/cli.js +3 -3
- package/dist/{completion-verifier-YwoeujPl.js → completion-verifier-asaV1nSj.js} +3 -3
- package/dist/{completion-verifier-YwoeujPl.js.map → completion-verifier-asaV1nSj.js.map} +1 -1
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +6 -6
- package/dist/{default-registry-BZ5FyYl9.js → default-registry-BBTDgkDM.js} +2 -2
- package/dist/{default-registry-BZ5FyYl9.js.map → default-registry-BBTDgkDM.js.map} +1 -1
- package/dist/{default-registry-BMHqNR6_.d.ts → default-registry-CLG5YqGS.d.ts} +7 -7
- package/dist/{default-registry-BMHqNR6_.d.ts.map → default-registry-CLG5YqGS.d.ts.map} +1 -1
- package/dist/{define-agent-eval-CJhECJNL.js → define-agent-eval-CCbT7Kfr.js} +3 -3
- package/dist/{define-agent-eval-CJhECJNL.js.map → define-agent-eval-CCbT7Kfr.js.map} +1 -1
- package/dist/{define-agent-eval-Bsoi2GUV.d.ts → define-agent-eval-JKt3gMQr.d.ts} +7 -7
- package/dist/{define-agent-eval-Bsoi2GUV.d.ts.map → define-agent-eval-JKt3gMQr.d.ts.map} +1 -1
- package/dist/diagnosis/index.d.ts +2 -2
- package/dist/{dspy-rlm-engine-BTy7u0jQ.js → dspy-rlm-engine-DN1p_5jx.js} +2 -2
- package/dist/{dspy-rlm-engine-BTy7u0jQ.js.map → dspy-rlm-engine-DN1p_5jx.js.map} +1 -1
- package/dist/{engine-BF95CWzH.d.ts → engine-dtRVeuQs.d.ts} +2 -2
- package/dist/{engine-BF95CWzH.d.ts.map → engine-dtRVeuQs.d.ts.map} +1 -1
- package/dist/{evaluation-D1PGzkPR.d.ts → evaluation-DblGquCB.d.ts} +3 -3
- package/dist/{evaluation-D1PGzkPR.d.ts.map → evaluation-DblGquCB.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/{exact-types-CVn1QxFO.d.ts → exact-types-Do63KoKn.d.ts} +2 -2
- package/dist/{exact-types-CVn1QxFO.d.ts.map → exact-types-Do63KoKn.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/{external-optimizer-process-E5yY2SYS.js → external-optimizer-process-DEzJ2CGX.js} +2 -2
- package/dist/{external-optimizer-process-E5yY2SYS.js.map → external-optimizer-process-DEzJ2CGX.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-DA02c_L6.js → external-optimizer-subprocess-B_ukPtRD.js} +2 -2
- package/dist/{external-optimizer-subprocess-DA02c_L6.js.map → external-optimizer-subprocess-B_ukPtRD.js.map} +1 -1
- package/dist/{feedback-trajectory-BZhVCWuz.d.ts → feedback-trajectory-CYVJXolG.d.ts} +3 -3
- package/dist/{feedback-trajectory-BZhVCWuz.d.ts.map → feedback-trajectory-CYVJXolG.d.ts.map} +1 -1
- package/dist/{findings-store-DRiFdoid.js → findings-store-Bg4sdS-e.js} +4 -4
- package/dist/{findings-store-DRiFdoid.js.map → findings-store-Bg4sdS-e.js.map} +1 -1
- package/dist/{index-BJZ7s-sv.d.ts → index-CTIRz-AB.d.ts} +7 -7
- package/dist/{index-BJZ7s-sv.d.ts.map → index-CTIRz-AB.d.ts.map} +1 -1
- package/dist/{index-BvX3CFNS.d.ts → index-CdEVr8-O.d.ts} +7 -7
- package/dist/{index-BvX3CFNS.d.ts.map → index-CdEVr8-O.d.ts.map} +1 -1
- package/dist/{index-DWd1gUwR.d.ts → index-CfJULcW5.d.ts} +116 -3
- package/dist/index-CfJULcW5.d.ts.map +1 -0
- package/dist/{index-y7i8l6Y_.d.ts → index-jnuFLxOs.d.ts} +8 -8
- package/dist/{index-y7i8l6Y_.d.ts.map → index-jnuFLxOs.d.ts.map} +1 -1
- package/dist/index.d.ts +21 -21
- package/dist/index.js +11 -90
- package/dist/index.js.map +1 -1
- package/dist/{integrity-CCwvezWS.d.ts → integrity-D9lBnv_K.d.ts} +2 -2
- package/dist/{integrity-CCwvezWS.d.ts.map → integrity-D9lBnv_K.d.ts.map} +1 -1
- package/dist/{judge-gate-Co5tuh57.js → judge-gate-BVvmP00P.js} +82 -2
- package/dist/judge-gate-BVvmP00P.js.map +1 -0
- package/dist/{llm-client-DXuOTseU.js → llm-client-b1ysZVIU.js} +7 -6
- package/dist/llm-client-b1ysZVIU.js.map +1 -0
- package/dist/{llm-judge-3uAeRawE.js → llm-judge-Cybq29bL.js} +4 -4
- package/dist/{llm-judge-3uAeRawE.js.map → llm-judge-Cybq29bL.js.map} +1 -1
- package/dist/{matrix-BXo3PSqM.d.ts → matrix-DtkZLD_3.d.ts} +2 -2
- package/dist/{matrix-BXo3PSqM.d.ts.map → matrix-DtkZLD_3.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -2
- package/dist/meta-eval/index.js +217 -2
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +47 -3
- package/dist/multishot/index.d.ts.map +1 -1
- package/dist/multishot/index.js +257 -216
- package/dist/multishot/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{prime-protocol-BEaqBoQE.d.ts → prime-protocol-BGxjfhM4.d.ts} +2 -2
- package/dist/{prime-protocol-BEaqBoQE.d.ts.map → prime-protocol-BGxjfhM4.d.ts.map} +1 -1
- package/dist/{proposal-findings-D0_zkQ2l.js → proposal-findings-DqLUWsAG.js} +2 -2
- package/dist/{proposal-findings-D0_zkQ2l.js.map → proposal-findings-DqLUWsAG.js.map} +1 -1
- package/dist/{registry-DDKaUrmM.d.ts → registry-BcdJmyoU.d.ts} +4 -4
- package/dist/{registry-DDKaUrmM.d.ts.map → registry-BcdJmyoU.d.ts.map} +1 -1
- package/dist/{researcher-H0p44OYC.d.ts → researcher-DKWtoMWk.d.ts} +3 -3
- package/dist/{researcher-H0p44OYC.d.ts.map → researcher-DKWtoMWk.d.ts.map} +1 -1
- package/dist/rl.d.ts +4 -4
- package/dist/search/index.d.ts +2 -2
- package/dist/{search-kernel-C6__V0IS.d.ts → search-kernel-CctpiDd2.d.ts} +2 -2
- package/dist/{search-kernel-C6__V0IS.d.ts.map → search-kernel-CctpiDd2.d.ts.map} +1 -1
- package/dist/{server-8TS8XCvg.js → server-ChhXPCgX.js} +2 -2
- package/dist/{server-8TS8XCvg.js.map → server-ChhXPCgX.js.map} +1 -1
- package/dist/{skillopt-optimization-method-D21dH_Bh.js → skillopt-optimization-method-sB_-yi1G.js} +5 -5
- package/dist/{skillopt-optimization-method-D21dH_Bh.js.map → skillopt-optimization-method-sB_-yi1G.js.map} +1 -1
- package/dist/{statistical-heldout-pD1Yah-0.d.ts → statistical-heldout-BjzSOmLH.d.ts} +3 -3
- package/dist/{statistical-heldout-pD1Yah-0.d.ts.map → statistical-heldout-BjzSOmLH.d.ts.map} +1 -1
- package/dist/{store-tool-spans-Bf9OVKs6.d.ts → store-tool-spans-DxsFwtdr.d.ts} +5 -5
- package/dist/{store-tool-spans-Bf9OVKs6.d.ts.map → store-tool-spans-DxsFwtdr.d.ts.map} +1 -1
- package/dist/{systemone-D3MrW63C.d.ts → systemone-CHnqwmYg.d.ts} +6 -6
- package/dist/{systemone-D3MrW63C.d.ts.map → systemone-CHnqwmYg.d.ts.map} +1 -1
- package/dist/{systemone-review-C8DRiT_-.d.ts → systemone-review-cQ9acAsb.d.ts} +2 -2
- package/dist/{systemone-review-C8DRiT_-.d.ts.map → systemone-review-cQ9acAsb.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/{tool-groups-DK1bu5TD.d.ts → tool-groups-b3oU_D88.d.ts} +3 -3
- package/dist/tool-groups-b3oU_D88.d.ts.map +1 -0
- package/dist/{trace-questions-D_OKYZ6u.d.ts → trace-questions-BmT8M6UQ.d.ts} +3 -3
- package/dist/{trace-questions-D_OKYZ6u.d.ts.map → trace-questions-BmT8M6UQ.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/traces.d.ts +5 -5
- package/dist/{types-DGImvHIr.d.ts → types-6Lfdlshp.d.ts} +2 -2
- package/dist/{types-DGImvHIr.d.ts.map → types-6Lfdlshp.d.ts.map} +1 -1
- package/dist/{types-eMhdacVp.d.ts → types-B_IFcKp5.d.ts} +12 -2
- package/dist/types-B_IFcKp5.d.ts.map +1 -0
- package/dist/{types-IERw_HxR.d.ts → types-DZ0mYVw9.d.ts} +2 -2
- package/dist/{types-IERw_HxR.d.ts.map → types-DZ0mYVw9.d.ts.map} +1 -1
- package/dist/{types-DDKfH-N6.d.ts → types-M6eF9m-r.d.ts} +3 -3
- package/dist/{types-DDKfH-N6.d.ts.map → types-M6eF9m-r.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +2 -2
- package/dist/wire/index.js +1 -1
- package/docs/multishot-golden-records.md +1 -0
- package/package.json +1 -1
- package/dist/index-DWd1gUwR.d.ts.map +0 -1
- package/dist/judge-gate-Co5tuh57.js.map +0 -1
- package/dist/llm-client-DXuOTseU.js.map +0 -1
- package/dist/tool-groups-DK1bu5TD.d.ts.map +0 -1
- package/dist/types-eMhdacVp.d.ts.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as CaptureIntegrityError } from "./errors-DEE6u6ot.js";
|
|
2
|
-
import {
|
|
2
|
+
import { Z as RawProviderSink } from "./types-B_IFcKp5.js";
|
|
3
3
|
import { s as TraceStore } from "./store-B3nWRy3B.js";
|
|
4
4
|
//#region src/trace/integrity.d.ts
|
|
5
5
|
interface RunIntegrityExpectations {
|
|
@@ -56,4 +56,4 @@ declare class RunIntegrityError extends CaptureIntegrityError {
|
|
|
56
56
|
declare function assertRunCaptured(store: TraceStore, runId: string, expectations?: RunIntegrityExpectations): Promise<RunIntegrityReport>;
|
|
57
57
|
//#endregion
|
|
58
58
|
export { RunIntegrityReport as a, RunIntegrityIssueCode as i, RunIntegrityExpectations as n, assertRunCaptured as o, RunIntegrityIssue as r, RunIntegrityError as t };
|
|
59
|
-
//# sourceMappingURL=integrity-
|
|
59
|
+
//# sourceMappingURL=integrity-D9lBnv_K.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integrity-
|
|
1
|
+
{"version":3,"file":"integrity-D9lBnv_K.d.ts","names":[],"sources":["../src/trace/integrity.ts"],"mappings":";;;;UAyBiB;;EAEf;;EAEA;;EAEA;;;;;EAKA,UAAU;;EAEV;;;;;;EAMA;;EAEA;;KAGU;UAWK;EACf,MAAM;EACN;EACA,SAAS;;UAGM;EACf;EACA;EACA;EACA;EACA;EACA;;;;;;EAMA;IAAmB;IAAiB;;EACpC,QAAQ;;cAGG,0BAA0B;WACT,QAAQ;EAApC,YAA4B,QAAQ;;iBAOhB,kBACpB,OAAO,YACP,eACA,eAAc,2BACb,QAAQ"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { i as JudgeError, s as ValidationError } from "./errors-BcOs5MKW.js";
|
|
2
|
+
import { o as backoffMs, s as isTransientLlmError } from "./llm-client-b1ysZVIU.js";
|
|
2
3
|
import { t as computeInterval } from "./interval-Dq9gt7jx.js";
|
|
3
4
|
//#region src/series-convergence.ts
|
|
4
5
|
function analyzeSeries(values, options = {}) {
|
|
@@ -40,6 +41,85 @@ function analyzeSeries(values, options = {}) {
|
|
|
40
41
|
};
|
|
41
42
|
}
|
|
42
43
|
//#endregion
|
|
44
|
+
//#region src/judge-retry.ts
|
|
45
|
+
/**
|
|
46
|
+
* Wrap a single judge LLM call with retry, optional fallback-model
|
|
47
|
+
* rotation, exponential backoff, and a typed `JudgeRetryOutcome`. Callers
|
|
48
|
+
* MUST inspect `succeeded` before using `value`; on failure the library
|
|
49
|
+
* returns `value: null` rather than substituting a default, so a judge
|
|
50
|
+
* abort cannot silently corrupt a downstream composite.
|
|
51
|
+
*
|
|
52
|
+
* Reporting contract: callers ship `TrialResult.judgeSucceeded = succeeded`
|
|
53
|
+
* and `TrialResult.judgeAttempts = attempts` so `aggregateTrialsByMode`
|
|
54
|
+
* with `mode: 'exclude-failed'` drops the trial.
|
|
55
|
+
*/
|
|
56
|
+
const DEFAULT_MAX_ATTEMPTS = 3;
|
|
57
|
+
const DEFAULT_TIMEOUT_MS = 3e5;
|
|
58
|
+
function sleep(ms) {
|
|
59
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Wrap a judge call with retry + fallback-model + typed outcome semantics.
|
|
63
|
+
*
|
|
64
|
+
* The `judgeFn` signature is `(model: string, signal: AbortSignal) => Promise<T>`.
|
|
65
|
+
* The signal will be aborted at `timeoutMs`. Callers should pass the signal
|
|
66
|
+
* to their underlying fetch/SDK call so the abort actually fires.
|
|
67
|
+
*
|
|
68
|
+
* Returns a typed outcome — callers MUST inspect `succeeded` before using
|
|
69
|
+
* `value`. The library refuses to default to a silent zero score because a
|
|
70
|
+
* synthetic zero is indistinguishable from a real low score downstream.
|
|
71
|
+
*/
|
|
72
|
+
async function withJudgeRetry(judgeFn, policy = {}) {
|
|
73
|
+
const maxAttempts = policy.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
74
|
+
const timeoutMs = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
75
|
+
const backoff = policy.backoffMs ?? backoffMs;
|
|
76
|
+
const isRetryable = policy.isRetryable ?? isTransientLlmError;
|
|
77
|
+
const models = policy.models && policy.models.length > 0 ? policy.models : [void 0];
|
|
78
|
+
let totalAttempts = 0;
|
|
79
|
+
const attemptErrors = [];
|
|
80
|
+
let lastError;
|
|
81
|
+
for (const model of models) for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
82
|
+
totalAttempts += 1;
|
|
83
|
+
const controller = new AbortController();
|
|
84
|
+
const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("TimeoutError")), timeoutMs);
|
|
85
|
+
try {
|
|
86
|
+
const value = await judgeFn(model, controller.signal);
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
return {
|
|
89
|
+
value,
|
|
90
|
+
succeeded: true,
|
|
91
|
+
attempts: totalAttempts,
|
|
92
|
+
modelUsed: model,
|
|
93
|
+
attemptErrors
|
|
94
|
+
};
|
|
95
|
+
} catch (err) {
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
const errObj = err instanceof Error ? err : new Error(String(err));
|
|
98
|
+
lastError = errObj;
|
|
99
|
+
attemptErrors.push({
|
|
100
|
+
attempt: totalAttempts,
|
|
101
|
+
model: model ?? "(default)",
|
|
102
|
+
error: errObj.message
|
|
103
|
+
});
|
|
104
|
+
if (!isRetryable(errObj)) return {
|
|
105
|
+
value: null,
|
|
106
|
+
succeeded: false,
|
|
107
|
+
attempts: totalAttempts,
|
|
108
|
+
error: errObj,
|
|
109
|
+
attemptErrors
|
|
110
|
+
};
|
|
111
|
+
if (attempt < maxAttempts - 1) await sleep(backoff(attempt));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
value: null,
|
|
116
|
+
succeeded: false,
|
|
117
|
+
attempts: totalAttempts,
|
|
118
|
+
error: lastError,
|
|
119
|
+
attemptErrors
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
//#endregion
|
|
43
123
|
//#region src/meta-eval/sentinel.ts
|
|
44
124
|
/**
|
|
45
125
|
* Judge sentinel — eval trustworthiness as a continuously measured,
|
|
@@ -630,6 +710,6 @@ function snapshotFromJudgeAgreement(agreement, options = {}) {
|
|
|
630
710
|
return snapshot;
|
|
631
711
|
}
|
|
632
712
|
//#endregion
|
|
633
|
-
export { judgeGateDecision as a, snapshotFromJudgeAgreement as c, judgeSentinelReport as d, snapshotFromAgreement as f,
|
|
713
|
+
export { analyzeSeries as _, judgeGateDecision as a, snapshotFromJudgeAgreement as c, judgeSentinelReport as d, snapshotFromAgreement as f, withJudgeRetry as g, validateSentinelSnapshot as h, assertJudgeMayGate as i, evalHealthStamp as l, snapshotFromSentinelSet as m, JudgeGateRefusedError as n, measureJudgeAgreement as o, snapshotFromCalibration as p, addCalibrationVerdicts as r, registerCalibrationSet as s, DEFAULT_JUDGE_GATE_POLICY as t, fileSentinelStore as u };
|
|
634
714
|
|
|
635
|
-
//# sourceMappingURL=judge-gate-
|
|
715
|
+
//# sourceMappingURL=judge-gate-BVvmP00P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"judge-gate-BVvmP00P.js","names":["parseIso"],"sources":["../src/series-convergence.ts","../src/judge-retry.ts","../src/meta-eval/sentinel.ts","../src/meta-eval/judge-gate.ts"],"sourcesContent":["/**\n * Series convergence — detects whether a sequence of scalar measurements\n * is stabilizing, drifting, or noisy. It reads drift *across* runs, e.g.\n * \"are my nightly eval scores stabilizing?\".\n *\n * Three signals:\n * - stabilized: last K values have low variance (< epsilon) — done\n * - drifting: recent trend is monotonic and beyond noise — regressing or improving\n * - noisy: neither — keep iterating, but flag as untrustworthy for gating\n */\n\nexport interface SeriesConvergenceOptions {\n /** Window size for \"recent\" analysis (default 5). */\n window?: number\n /** Coefficient-of-variation threshold below which the window is stabilized (default 0.05 = 5%). */\n stableCv?: number\n /** Minimum monotone run length to call drift (default 3). */\n driftRun?: number\n}\n\nexport interface SeriesConvergenceResult {\n state: 'stabilized' | 'drifting-up' | 'drifting-down' | 'noisy' | 'insufficient-data'\n windowMean: number\n windowCv: number\n /** Longest monotonic run at the tail of the series (positive for up, negative for down). */\n tailRun: number\n /** True when n ≥ window AND windowCv ≤ stableCv. */\n stable: boolean\n}\n\nexport function analyzeSeries(\n values: number[],\n options: SeriesConvergenceOptions = {},\n): SeriesConvergenceResult {\n const window = options.window ?? 5\n const stableCv = options.stableCv ?? 0.05\n const driftRun = options.driftRun ?? 3\n\n if (values.length < Math.max(2, Math.min(window, 3))) {\n return { state: 'insufficient-data', windowMean: 0, windowCv: 0, tailRun: 0, stable: false }\n }\n\n const tail = values.slice(-window)\n const mean = tail.reduce((a, b) => a + b, 0) / tail.length\n const variance = tail.reduce((acc, v) => acc + (v - mean) ** 2, 0) / tail.length\n const stdDev = Math.sqrt(variance)\n const refMean = Math.abs(mean) > 1e-9 ? Math.abs(mean) : 1\n const cv = stdDev / refMean\n const stable = tail.length >= window && cv <= stableCv\n\n // Tail monotonic run: count how many consecutive strictly-increasing (or decreasing)\n // steps end at the final value.\n let tailRun = 0\n let direction: 1 | -1 | 0 = 0\n for (let i = values.length - 1; i > 0; i--) {\n const delta = values[i]! - values[i - 1]!\n if (delta === 0) break\n const dir = delta > 0 ? 1 : -1\n if (direction === 0) direction = dir\n if (dir !== direction) break\n tailRun += dir\n }\n\n let state: SeriesConvergenceResult['state']\n if (stable) {\n state = 'stabilized'\n } else if (Math.abs(tailRun) >= driftRun) {\n state = tailRun > 0 ? 'drifting-up' : 'drifting-down'\n } else {\n state = 'noisy'\n }\n\n return { state, windowMean: mean, windowCv: cv, tailRun, stable }\n}\n","/**\n * Wrap a single judge LLM call with retry, optional fallback-model\n * rotation, exponential backoff, and a typed `JudgeRetryOutcome`. Callers\n * MUST inspect `succeeded` before using `value`; on failure the library\n * returns `value: null` rather than substituting a default, so a judge\n * abort cannot silently corrupt a downstream composite.\n *\n * Reporting contract: callers ship `TrialResult.judgeSucceeded = succeeded`\n * and `TrialResult.judgeAttempts = attempts` so `aggregateTrialsByMode`\n * with `mode: 'exclude-failed'` drops the trial.\n */\n\nimport { backoffMs, isTransientLlmError } from './llm-client'\n\n/** Retry policy for judge LLM calls. */\nexport interface JudgeRetryPolicy {\n /** Max attempts per model. Default 3 (one initial + two retries). */\n maxAttempts?: number\n /** Per-attempt timeout in ms. Default 300_000. */\n timeoutMs?: number\n /**\n * Models to try, in order. The first model is the primary; subsequent\n * models are fallbacks invoked only when ALL retries on the previous\n * model have been exhausted. Example: `['claude-code/sonnet', 'kimi-code/k2p6']`\n * runs claude-code up to maxAttempts times, then falls back to kimi.\n * If omitted, the caller's judge function controls model selection and\n * the retries apply to that single model.\n */\n models?: readonly string[]\n /** Exponential backoff function, default `attempt → min(500 * 2^attempt, 16_000)`. */\n backoffMs?: (attempt: number) => number\n /**\n * Predicate deciding whether an error should trigger a retry. Defaults to\n * `isTransientLlmError` — the package-wide classifier shared with\n * `callLlm` — which retries aborts/timeouts, network faults, HTTP/2\n * transport faults, and any `LlmCallError` with status in {429,502,503,504}.\n * JSON-parse and schema-rejection errors are NOT retriable (the model\n * needs prompt adjustment, not another shot).\n */\n isRetryable?: (err: unknown) => boolean\n}\n\n/** Outcome of a wrapped judge invocation. */\nexport interface JudgeRetryOutcome<T> {\n /** The judge's returned value when `succeeded === true`. */\n value: T | null\n /** True iff one of the attempts completed without throwing. */\n succeeded: boolean\n /** Total attempts made across all models. */\n attempts: number\n /** Which model the successful attempt used (when succeeded). */\n modelUsed?: string\n /** Last error captured when `succeeded === false`. */\n error?: Error\n /** Per-attempt error log for forensics. */\n attemptErrors: Array<{ attempt: number; model: string; error: string }>\n}\n\nconst DEFAULT_MAX_ATTEMPTS = 3\nconst DEFAULT_TIMEOUT_MS = 300_000\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Wrap a judge call with retry + fallback-model + typed outcome semantics.\n *\n * The `judgeFn` signature is `(model: string, signal: AbortSignal) => Promise<T>`.\n * The signal will be aborted at `timeoutMs`. Callers should pass the signal\n * to their underlying fetch/SDK call so the abort actually fires.\n *\n * Returns a typed outcome — callers MUST inspect `succeeded` before using\n * `value`. The library refuses to default to a silent zero score because a\n * synthetic zero is indistinguishable from a real low score downstream.\n */\nexport async function withJudgeRetry<T>(\n judgeFn: (model: string, signal: AbortSignal) => Promise<T>,\n policy: JudgeRetryPolicy = {},\n): Promise<JudgeRetryOutcome<T>> {\n const maxAttempts = policy.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n const timeoutMs = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const backoff = policy.backoffMs ?? backoffMs\n const isRetryable = policy.isRetryable ?? isTransientLlmError\n const models =\n policy.models && policy.models.length > 0 ? policy.models : [undefined as unknown as string]\n\n let totalAttempts = 0\n const attemptErrors: JudgeRetryOutcome<T>['attemptErrors'] = []\n let lastError: Error | undefined\n\n for (const model of models) {\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n totalAttempts += 1\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(new Error('TimeoutError')), timeoutMs)\n try {\n const value = await judgeFn(model as string, controller.signal)\n clearTimeout(timer)\n return {\n value,\n succeeded: true,\n attempts: totalAttempts,\n modelUsed: model,\n attemptErrors,\n }\n } catch (err) {\n clearTimeout(timer)\n const errObj = err instanceof Error ? err : new Error(String(err))\n lastError = errObj\n attemptErrors.push({\n attempt: totalAttempts,\n model: model ?? '(default)',\n error: errObj.message,\n })\n if (!isRetryable(errObj)) {\n // Non-retriable (e.g., JSON parse, schema rejection): break out of\n // attempts on this model AND skip the fallback rotation — a\n // permanent error here will be permanent on the fallback too.\n return {\n value: null,\n succeeded: false,\n attempts: totalAttempts,\n error: errObj,\n attemptErrors,\n }\n }\n if (attempt < maxAttempts - 1) {\n await sleep(backoff(attempt))\n }\n }\n }\n // Exhausted attempts on this model — fall through to next model in the\n // rotation (if any). The backoff between MODEL rotations is the same\n // as the last per-attempt backoff (already slept above).\n }\n\n return {\n value: null,\n succeeded: false,\n attempts: totalAttempts,\n error: lastError,\n attemptErrors,\n }\n}\n","/**\n * Judge sentinel — eval trustworthiness as a continuously measured,\n * alarmed trend.\n *\n * Judges are models; models change underneath us; calibration decays.\n * This module composes three existing instruments into one loop:\n *\n * snapshot — adapters turn real instrument outputs (`calibrateJudge` /\n * `calibrateJudgeContinuous`, `corpusInterRaterAgreement` /\n * `continuousAgreement`, a rerun sentinel golden set) into\n * `SentinelSnapshot`s\n * series — `analyzeSeries` (src/series-convergence) classifies each\n * judge×metric history as stabilized / drifting / noisy\n * alarm — `judgeSentinelReport` turns trends + thresholds into named\n * alarms; `evalHealthStamp` is the tiny object a campaign\n * attaches to its verdicts\n *\n * Alarm conditions:\n * - convergence state `drifting-down` on any tracked metric\n * - irr below `minIrr`\n * - calibrationKappa / sentinelPassRate dropped vs the series baseline\n * beyond `maxKappaDrop` / `maxSentinelDrop`\n * - judge model changed with no post-change golden-grounded snapshot\n * (the silent-upgrade trap: judges agreeing with each other after a\n * model swap proves nothing — only re-measuring against gold does)\n * - newest snapshot older than `staleAfterDays` relative to `asOf`\n *\n * Wire-in: run the snapshot adapters from a post-campaign hook or a\n * nightly job, append to a `SentinelStore`, then compute\n * `judgeSentinelReport(await store.history(), { asOf })` with `asOf` =\n * the campaign timestamp. Attach `evalHealthStamp(report)` to campaign\n * verdicts: an alarmed sentinel means every downstream verdict carries\n * an integrity warning until the judge is recalibrated.\n *\n * The module is clock-free — every timestamp (`at`, `asOf`) is\n * caller-supplied ISO-8601, so reports are reproducible.\n */\n\nimport { ValidationError } from '../errors'\nimport type {\n CalibrationResult,\n CandidateScore,\n ContinuousAgreement,\n ContinuousCalibrationResult,\n GoldenItem,\n} from '../judge-calibration'\nimport {\n analyzeSeries,\n type SeriesConvergenceOptions,\n type SeriesConvergenceResult,\n} from '../series-convergence'\nimport type { CorpusAgreementReport } from '../statistics'\n\nconst SENTINEL_METRIC_NAMES = ['irr', 'calibrationKappa', 'sentinelPassRate'] as const\n\nexport type SentinelMetricName = (typeof SENTINEL_METRIC_NAMES)[number]\n\nexport interface SentinelMetrics {\n /** Inter-rater reliability — ICC(2,1) from agreement instruments. */\n irr?: number\n /** Weighted κ vs the human golden set (`calibrateJudge*`). */\n calibrationKappa?: number\n /** Fraction of a fixed sentinel golden set the judge still scores within tolerance. */\n sentinelPassRate?: number\n}\n\nexport interface SentinelSnapshot {\n /** Caller-supplied ISO-8601 timestamp — the module never reads a clock. */\n at: string\n judgeId: string\n /** Exact model identity behind the judge (pin the full version string). */\n judgeModel: string\n /**\n * Metrics measured at `at`. May be empty: an empty-metrics snapshot is a\n * model-change marker — it records the new `judgeModel` immediately and\n * the silent-upgrade alarm stays raised until a golden-grounded snapshot\n * (calibrationKappa or sentinelPassRate) follows.\n */\n metrics: SentinelMetrics\n}\n\n/** Identity + timestamp the caller supplies alongside an instrument output. */\nexport interface SnapshotMeta {\n at: string\n judgeId: string\n judgeModel: string\n}\n\nfunction parseIso(value: string, label: string): number {\n const ms = typeof value === 'string' ? Date.parse(value) : NaN\n if (!Number.isFinite(ms)) {\n throw new ValidationError(\n `judge-sentinel: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`,\n )\n }\n return ms\n}\n\n/** Shape guard for snapshots crossing a boundary (store append, JSONL load, report input). */\nexport function validateSentinelSnapshot(snapshot: SentinelSnapshot, source = 'snapshot'): void {\n parseIso(snapshot.at, `${source}.at`)\n if (typeof snapshot.judgeId !== 'string' || snapshot.judgeId.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeId must be a non-empty string`)\n }\n if (typeof snapshot.judgeModel !== 'string' || snapshot.judgeModel.length === 0) {\n throw new ValidationError(`judge-sentinel: ${source}.judgeModel must be a non-empty string`)\n }\n if (snapshot.metrics === null || typeof snapshot.metrics !== 'object') {\n throw new ValidationError(`judge-sentinel: ${source}.metrics must be an object (may be empty)`)\n }\n for (const [key, value] of Object.entries(snapshot.metrics)) {\n if (!(SENTINEL_METRIC_NAMES as readonly string[]).includes(key)) {\n // A typo'd key would silently never trend — reject instead.\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics carries unknown key \"${key}\" — known: ${SENTINEL_METRIC_NAMES.join(', ')}`,\n )\n }\n if (value !== undefined && !Number.isFinite(value)) {\n throw new ValidationError(\n `judge-sentinel: ${source}.metrics.${key} is not a finite number: ${String(value)}`,\n )\n }\n }\n}\n\n// ── Snapshot adapters — real instrument output → SentinelSnapshot ───\n\n/**\n * From `calibrateJudge` / `calibrateJudgeContinuous` output. Prefers the\n * un-rounded continuous κ_w when the report carries one (integer κ\n * discards information for [0,1] judges).\n */\nexport function snapshotFromCalibration(\n report: CalibrationResult | ContinuousCalibrationResult,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const kappa = 'weightedKappaContinuous' in report ? report.weightedKappaContinuous : report.kappa\n if (!Number.isFinite(kappa)) {\n throw new ValidationError(\n `snapshotFromCalibration: κ is not finite (n=${report.n}) — calibrate against ≥2 joined golden items before snapshotting`,\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { calibrationKappa: kappa } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n/**\n * From `corpusInterRaterAgreement` (statistics.ts) or `continuousAgreement`\n * (judge-calibration.ts) output. IRR = ICC(2,1) — the reliability\n * coefficient both instruments compute. For ensemble-level agreement,\n * `meta.judgeId` names the ensemble and `meta.judgeModel` pins its\n * composition (e.g. a joined list of member model strings).\n */\nexport function snapshotFromAgreement(\n report: CorpusAgreementReport | ContinuousAgreement,\n meta: SnapshotMeta,\n): SentinelSnapshot {\n const irr = 'overallIcc' in report ? report.overallIcc : report.icc\n if (!Number.isFinite(irr)) {\n throw new ValidationError(\n 'snapshotFromAgreement: ICC is not finite — agreement needs ≥2 raters and ≥2 complete items',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { irr } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\nexport interface SentinelSetOptions {\n /** Max |judge − human| for an item to count as passed. Default 0.1 (tuned for [0,1] scores). */\n tolerance?: number\n}\n\n/**\n * From a rerun of a fixed sentinel golden set: the same `GoldenItem`s the\n * judge was originally calibrated on, re-scored periodically. Pass rate =\n * fraction of joined items where the judge stays within `tolerance` of the\n * human score. Items the judge didn't score are excluded from the\n * denominator; zero joined items is an error, not a 0% pass rate.\n */\nexport function snapshotFromSentinelSet(\n scores: CandidateScore[],\n golden: GoldenItem[],\n meta: SnapshotMeta,\n options: SentinelSetOptions = {},\n): SentinelSnapshot {\n const tolerance = options.tolerance ?? 0.1\n if (!Number.isFinite(tolerance) || tolerance < 0) {\n throw new ValidationError(\n `snapshotFromSentinelSet: tolerance must be a finite number ≥ 0, got ${tolerance}`,\n )\n }\n const goldenById = new Map<string, number>()\n for (const item of golden) {\n if (!Number.isFinite(item.humanScore)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: golden item \"${item.itemId}\" has a non-finite humanScore`,\n )\n }\n if (goldenById.has(item.itemId)) {\n throw new ValidationError(`snapshotFromSentinelSet: duplicate golden itemId \"${item.itemId}\"`)\n }\n goldenById.set(item.itemId, item.humanScore)\n }\n let joined = 0\n let passed = 0\n for (const s of scores) {\n const human = goldenById.get(s.itemId)\n if (human === undefined) continue\n if (!Number.isFinite(s.score)) {\n throw new ValidationError(\n `snapshotFromSentinelSet: judge score for item \"${s.itemId}\" is not finite`,\n )\n }\n joined++\n if (Math.abs(s.score - human) <= tolerance) passed++\n }\n if (joined === 0) {\n throw new ValidationError(\n 'snapshotFromSentinelSet: no judge scores joined the golden set — itemIds mismatch or empty sentinel run',\n )\n }\n const snapshot: SentinelSnapshot = { ...meta, metrics: { sentinelPassRate: passed / joined } }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n\n// ── Persistence ──────────────────────────────────────────────────────\n\nexport interface SentinelStore {\n append(snapshot: SentinelSnapshot): Promise<void>\n /** All snapshots (optionally for one judge), in append order. */\n history(judgeId?: string): Promise<SentinelSnapshot[]>\n}\n\n/**\n * JSONL store — one snapshot per line, appended atomically per call.\n * A corrupt or shape-invalid line is a loud error naming the file and\n * line number: a sentinel history that silently drops records would\n * defeat the drift detection it exists to provide.\n */\nexport function fileSentinelStore(path: string): SentinelStore {\n return {\n async append(snapshot) {\n validateSentinelSnapshot(snapshot)\n const fs = await import('node:fs/promises')\n const pathMod = await import('node:path')\n await fs.mkdir(pathMod.dirname(path), { recursive: true })\n await fs.appendFile(path, `${JSON.stringify(snapshot)}\\n`, 'utf8')\n },\n async history(judgeId) {\n const fs = await import('node:fs/promises')\n let raw: string\n try {\n raw = await fs.readFile(path, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw err\n }\n const lines = raw.split('\\n')\n const snapshots: SentinelSnapshot[] = []\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n if (line.trim().length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `judge-sentinel: store at ${path} has a corrupt JSONL line ${i + 1}: ${(err as Error).message}`,\n )\n }\n const snapshot = parsed as SentinelSnapshot\n validateSentinelSnapshot(snapshot, `${path}:${i + 1}`)\n snapshots.push(snapshot)\n }\n return judgeId === undefined ? snapshots : snapshots.filter((s) => s.judgeId === judgeId)\n },\n }\n}\n\n// ── Trend report ─────────────────────────────────────────────────────\n\nexport interface SentinelThresholds {\n /** Floor for irr — below it the judge ensemble is unreliable regardless of trend. Default 0.6. */\n minIrr?: number\n /** Max tolerated calibrationKappa drop vs the series baseline. Default 0.15. */\n maxKappaDrop?: number\n /** Max tolerated sentinelPassRate drop vs the series baseline. Default 0.1. */\n maxSentinelDrop?: number\n /** Newest snapshot older than this (days, vs asOf) = the sentinel itself went blind. Default 30. */\n staleAfterDays?: number\n}\n\nexport interface JudgeSentinelOptions {\n /** Caller-supplied ISO timestamp staleness is measured against. */\n asOf: string\n thresholds?: SentinelThresholds\n /** Forwarded to `analyzeSeries` (window, stableCv, driftRun). */\n convergence?: SeriesConvergenceOptions\n}\n\nexport interface SentinelTrend {\n judgeId: string\n metric: SentinelMetricName\n /** Verbatim `analyzeSeries` state for this judge×metric history. */\n state: SeriesConvergenceResult['state']\n /** Newest value in the series. */\n current: number\n /** Oldest value in the series — the reference the drop thresholds compare against. */\n baseline: number\n /** current − baseline (signed; negative = decayed). */\n drift: number\n alarmed: boolean\n reason?: string\n}\n\nexport interface SentinelReport {\n perJudge: SentinelTrend[]\n alarms: string[]\n healthy: boolean\n /**\n * `judgeId:metric` pairs with too few snapshots for the convergence\n * machine. Named, not counted — a blind spot you can't see is a blind\n * spot you won't fix. Floor/drop checks still apply to thin series, so\n * insufficient history alone never masks an alarm.\n */\n insufficientHistory: string[]\n}\n\nconst MS_PER_DAY = 86_400_000\n\nexport function judgeSentinelReport(\n history: SentinelSnapshot[],\n opts: JudgeSentinelOptions,\n): SentinelReport {\n const asOfMs = parseIso(opts.asOf, 'asOf')\n const minIrr = opts.thresholds?.minIrr ?? 0.6\n const maxKappaDrop = opts.thresholds?.maxKappaDrop ?? 0.15\n const maxSentinelDrop = opts.thresholds?.maxSentinelDrop ?? 0.1\n const staleAfterDays = opts.thresholds?.staleAfterDays ?? 30\n\n const byJudge = new Map<string, Array<SentinelSnapshot & { atMs: number }>>()\n for (const snapshot of history) {\n validateSentinelSnapshot(snapshot)\n const atMs = parseIso(snapshot.at, `snapshot.at (judge \"${snapshot.judgeId}\")`)\n const arr = byJudge.get(snapshot.judgeId) ?? []\n arr.push({ ...snapshot, atMs })\n byJudge.set(snapshot.judgeId, arr)\n }\n\n const perJudge: SentinelTrend[] = []\n const alarms: string[] = []\n const insufficientHistory: string[] = []\n\n for (const judgeId of [...byJudge.keys()].sort()) {\n const snaps = byJudge.get(judgeId)!.sort((a, b) => a.atMs - b.atMs)\n const newest = snaps[snaps.length - 1]!\n\n const ageDays = (asOfMs - newest.atMs) / MS_PER_DAY\n if (ageDays > staleAfterDays) {\n alarms.push(\n `judge \"${judgeId}\": stale — newest snapshot ${newest.at} is ${ageDays.toFixed(1)}d old vs asOf (limit ${staleAfterDays}d)`,\n )\n }\n\n // Silent-upgrade trap: only the latest model change matters for current\n // trust, and only golden-grounded metrics clear it — irr alone proves\n // judges still agree with each other, not that they're still right.\n let changeIdx = -1\n for (let i = 1; i < snaps.length; i++) {\n if (snaps[i]!.judgeModel !== snaps[i - 1]!.judgeModel) changeIdx = i\n }\n if (changeIdx >= 0) {\n const recalibrated = snaps\n .slice(changeIdx)\n .some(\n (s) =>\n Number.isFinite(s.metrics.calibrationKappa) ||\n Number.isFinite(s.metrics.sentinelPassRate),\n )\n if (!recalibrated) {\n alarms.push(\n `judge \"${judgeId}\": model changed \"${snaps[changeIdx - 1]!.judgeModel}\" → \"${snaps[changeIdx]!.judgeModel}\" at ${snaps[changeIdx]!.at} with no post-change calibration snapshot — silent-upgrade trap; rerun calibrateJudge or the sentinel set against the new model`,\n )\n }\n }\n\n for (const metric of SENTINEL_METRIC_NAMES) {\n const values = snaps\n .filter((s) => typeof s.metrics[metric] === 'number')\n .map((s) => s.metrics[metric]!)\n if (values.length === 0) continue\n\n const convergence = analyzeSeries(values, opts.convergence)\n if (convergence.state === 'insufficient-data')\n insufficientHistory.push(`${judgeId}:${metric}`)\n\n const current = values[values.length - 1]!\n const baseline = values[0]!\n const drift = current - baseline\n const reasons: string[] = []\n if (convergence.state === 'drifting-down') {\n reasons.push(\n `convergence state drifting-down (tail run ${convergence.tailRun}, window mean ${convergence.windowMean.toFixed(3)})`,\n )\n }\n if (metric === 'irr' && current < minIrr) {\n reasons.push(`irr ${current.toFixed(3)} below floor ${minIrr}`)\n }\n if (metric === 'calibrationKappa' && baseline - current > maxKappaDrop) {\n reasons.push(\n `calibrationKappa dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxKappaDrop})`,\n )\n }\n if (metric === 'sentinelPassRate' && baseline - current > maxSentinelDrop) {\n reasons.push(\n `sentinelPassRate dropped ${(baseline - current).toFixed(3)} from baseline ${baseline.toFixed(3)} (limit ${maxSentinelDrop})`,\n )\n }\n\n const alarmed = reasons.length > 0\n const trend: SentinelTrend = {\n judgeId,\n metric,\n state: convergence.state,\n current,\n baseline,\n drift,\n alarmed,\n }\n if (alarmed) {\n trend.reason = reasons.join('; ')\n alarms.push(`judge \"${judgeId}\" ${metric}: ${trend.reason}`)\n }\n perJudge.push(trend)\n }\n }\n\n return { perJudge, alarms, healthy: alarms.length === 0, insufficientHistory }\n}\n\n// ── Verdict stamp ────────────────────────────────────────────────────\n\nexport interface EvalHealthStamp {\n healthy: boolean\n alarms: string[]\n}\n\n/**\n * The object a campaign attaches to its verdicts. Compute it from the\n * sentinel report in a post-campaign hook (or a nightly job feeding the\n * next day's campaigns) and store it alongside the verdict payload.\n * `healthy: false` means the judges that produced those verdicts have an\n * unresolved drift / decay / silent-upgrade / staleness alarm — treat the\n * verdicts as carrying an integrity warning until recalibration clears it.\n */\nexport function evalHealthStamp(report: SentinelReport): EvalHealthStamp {\n return { healthy: report.healthy, alarms: [...report.alarms] }\n}\n","/**\n * Judge calibration gate: a judge may gate only while its measured agreement\n * with its owner's verdicts holds.\n *\n * A judge (a model judge or a deterministic grader) registers a calibration\n * set: items its owner has decided, each verdict with its provenance. A\n * calibration run replays the judge on those items, once or several times, and\n * `measureJudgeAgreement` reports how often it reached the owner's verdict\n * (accuracy, and Cohen's κ for the pass/fail pair), how much its own verdict\n * moves between runs and between samples, and where it disagreed.\n *\n * `judgeGateDecision` turns that report into the one decision a consumer acts\n * on. A judge either decides (`decides: 'verdict'`, the default: it passes and\n * blocks, so it must reach the owner's verdict) or only vetoes\n * (`decides: 'veto'`: a necessary-condition check such as a copy or policy\n * check, which blocks but never passes work on its own; owners also reject\n * for reasons it does not cover, so its error is blocking what they approved).\n * It refuses when the judge has no measured agreement, too few decided\n * items of either verdict, a report measured on a different model or rubric\n * than the one the judge now runs, a report older than the policy allows,\n * agreement below the policy floors, or an alarmed drift history. A refused\n * judge's verdict is advisory: the consumer reports it but does not let it\n * pass or block anything.\n *\n * Drift is the judge sentinel (`./sentinel`): `snapshotFromJudgeAgreement`\n * records accuracy as `sentinelPassRate` and κ as `calibrationKappa`, so each\n * calibration run appends one snapshot to a `SentinelStore` and the gate reads\n * the alarms `judgeSentinelReport` raises over that history.\n *\n * Every timestamp is caller-supplied ISO-8601, so decisions are reproducible.\n */\n\nimport { JudgeError, ValidationError } from '../errors'\nimport { type ComputedInterval, computeInterval } from '../experiment/ast/interval'\nimport {\n judgeSentinelReport,\n type SentinelSnapshot,\n type SentinelThresholds,\n validateSentinelSnapshot,\n} from './sentinel'\n\nexport type OwnerVerdict = 'pass' | 'fail'\n\n/** One item the owner decided, with where that decision is recorded. */\nexport interface CalibrationExample {\n /** Stable id of the decided item; a judge run names it in `exampleId`. */\n id: string\n verdict: OwnerVerdict\n /** The person whose verdict this is. Never a model. */\n labeledBy: string\n /** ISO-8601 time the verdict was given. */\n labeledAt: string\n /** Where the verdict is recorded, e.g. `gtm:asset_decision:<id>`. */\n source: string\n /** What the owner judged (an image digest, a run id), so a replay judges the same thing. */\n evidenceRef?: string\n note?: string\n}\n\nexport interface JudgeCalibrationSet {\n judgeId: string\n /** Whose verdicts the judge stands in for. */\n owner: string\n examples: readonly CalibrationExample[]\n}\n\nfunction parseIso(value: unknown, label: string): number {\n const ms = typeof value === 'string' ? Date.parse(value) : Number.NaN\n if (!Number.isFinite(ms)) {\n throw new ValidationError(\n `judge-gate: ${label} is not a parseable ISO timestamp: ${JSON.stringify(value)}`,\n )\n }\n return ms\n}\n\nfunction requireText(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`judge-gate: ${label} must be a non-empty string`)\n }\n return value\n}\n\nfunction requireVerdict(value: unknown, label: string): OwnerVerdict {\n if (value !== 'pass' && value !== 'fail') {\n throw new ValidationError(\n `judge-gate: ${label} must be 'pass' or 'fail', got ${JSON.stringify(value)}`,\n )\n }\n return value\n}\n\nfunction checkExample(example: CalibrationExample, label: string): CalibrationExample {\n if (example === null || typeof example !== 'object') {\n throw new ValidationError(`judge-gate: ${label} must be an object`)\n }\n requireText(example.id, `${label}.id`)\n requireVerdict(example.verdict, `${label}.verdict`)\n requireText(example.labeledBy, `${label}.labeledBy`)\n parseIso(example.labeledAt, `${label}.labeledAt`)\n requireText(example.source, `${label}.source`)\n if (example.evidenceRef !== undefined) requireText(example.evidenceRef, `${label}.evidenceRef`)\n const copy: CalibrationExample = {\n id: example.id,\n verdict: example.verdict,\n labeledBy: example.labeledBy,\n labeledAt: example.labeledAt,\n source: example.source,\n }\n if (example.evidenceRef !== undefined) copy.evidenceRef = example.evidenceRef\n if (example.note !== undefined) copy.note = example.note\n return copy\n}\n\n/**\n * Validate a calibration set and return a normalized copy ordered by example\n * id. Every verdict needs its person, time and source; ids are unique.\n */\nexport function registerCalibrationSet(set: JudgeCalibrationSet): JudgeCalibrationSet {\n if (set === null || typeof set !== 'object') {\n throw new ValidationError('judge-gate: calibration set must be an object')\n }\n const judgeId = requireText(set.judgeId, 'calibration set judgeId')\n const owner = requireText(set.owner, `calibration set \"${judgeId}\" owner`)\n if (!Array.isArray(set.examples)) {\n throw new ValidationError(`judge-gate: calibration set \"${judgeId}\" examples must be an array`)\n }\n const seen = new Set<string>()\n const examples = set.examples.map((example, index) => {\n const checked = checkExample(example, `calibration set \"${judgeId}\" example ${index}`)\n if (seen.has(checked.id)) {\n throw new ValidationError(\n `judge-gate: calibration set \"${judgeId}\" has duplicate example id \"${checked.id}\"`,\n )\n }\n seen.add(checked.id)\n return checked\n })\n examples.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n return { judgeId, owner, examples }\n}\n\nexport interface CalibrationMerge {\n set: JudgeCalibrationSet\n /** Ids that joined the set. */\n added: string[]\n /** Ids whose verdict a later decision replaced. */\n superseded: string[]\n /** Ids whose incoming verdict was already recorded, or older than the recorded one. */\n unchanged: string[]\n}\n\n/**\n * Join new owner verdicts to a set. A verdict already recorded from the same\n * source is unchanged, so ingestion can rerun. A later verdict on an item\n * replaces an earlier one: the owner changed their mind, and the set keeps\n * what they decided last.\n */\nexport function addCalibrationVerdicts(\n set: JudgeCalibrationSet,\n verdicts: readonly CalibrationExample[],\n): CalibrationMerge {\n const base = registerCalibrationSet(set)\n const byId = new Map(base.examples.map((example) => [example.id, example]))\n const added: string[] = []\n const superseded: string[] = []\n const unchanged: string[] = []\n for (const [index, verdict] of verdicts.entries()) {\n const incoming = checkExample(verdict, `incoming verdict ${index} for \"${base.judgeId}\"`)\n const current = byId.get(incoming.id)\n if (!current) {\n byId.set(incoming.id, incoming)\n added.push(incoming.id)\n continue\n }\n const sameDecision = current.source === incoming.source && current.verdict === incoming.verdict\n if (\n sameDecision ||\n parseIso(incoming.labeledAt, 'labeledAt') <= parseIso(current.labeledAt, 'labeledAt')\n ) {\n unchanged.push(incoming.id)\n continue\n }\n byId.set(incoming.id, incoming)\n superseded.push(incoming.id)\n }\n return {\n set: registerCalibrationSet({ ...base, examples: [...byId.values()] }),\n added,\n superseded,\n unchanged,\n }\n}\n\n/** One gate decision the judge made on a calibration example. */\nexport interface JudgeRun {\n exampleId: string\n /** The judge's decision after its own sample aggregation (median, majority). */\n verdict: OwnerVerdict\n /** The per-sample verdicts behind that decision, when the judge samples. */\n samples?: readonly OwnerVerdict[]\n}\n\nexport interface JudgeRunMeta {\n judgeId: string\n /** Exact model identity, or `deterministic` for a grader without one. */\n judgeModel: string\n rubricVersion: string\n measuredAt: string\n}\n\nexport interface JudgeConfusion {\n /** Judge pass, owner pass. */\n truePass: number\n /** Judge fail, owner fail. */\n trueFail: number\n /** Judge pass, owner fail: the judge let through what the owner rejected. */\n falsePass: number\n /** Judge fail, owner pass: the judge blocked what the owner accepted. */\n falseFail: number\n}\n\nexport interface JudgeExampleAgreement {\n id: string\n verdict: OwnerVerdict\n runs: number\n /** Share of runs that passed. */\n passRate: number\n /** Share of runs that reached the owner's verdict. */\n agreement: number\n}\n\nexport interface JudgeAgreement extends JudgeRunMeta {\n owner: string\n /** Examples in the calibration set. */\n examples: number\n /** Examples the judge ran on at least once. */\n judged: number\n /** Judged examples per owner verdict. */\n judgedByVerdict: Record<OwnerVerdict, number>\n runs: number\n /** Runs that reached the owner's verdict, over all runs; null with no runs. */\n accuracy: number | null\n /**\n * Exact (Clopper-Pearson) 95% interval for the share of judged examples on\n * which every run reached the owner's verdict. Examples, not runs, are the\n * independent units.\n */\n exampleAccuracy: { agreed: number; judged: number; interval: ComputedInterval } | null\n /**\n * Cohen's κ between the judge and the owner over runs. Null when undefined:\n * no runs, or both sides used a single verdict.\n */\n kappa: number | null\n /** Runs that failed what the owner passed, over runs on owner passes; null with none. A veto judge is held to this. */\n falseFailRate: number | null\n /** Runs that failed what the owner failed, over runs on owner fails; null with none. */\n catchRate: number | null\n confusion: JudgeConfusion\n variance: {\n /** Mean over judged examples of p(1 − p), p the example's run pass rate. 0 = no run changed its mind. */\n betweenRuns: number | null\n /** Mean over runs that reported samples of p(1 − p) across those samples; null when none did. */\n withinRun: number | null\n /** Examples whose runs disagree with each other. */\n unstable: string[]\n }\n /** Examples with at least one run against the owner, least agreement first. */\n disagreements: JudgeExampleAgreement[]\n /** Examples without any run. */\n unjudged: string[]\n}\n\nfunction bernoulliVariance(passes: number, n: number): number {\n const p = passes / n\n return p * (1 - p)\n}\n\n/** Cohen's κ for two raters over a binary pass/fail table. */\nfunction binaryKappa(confusion: JudgeConfusion): number | null {\n const n = confusion.truePass + confusion.trueFail + confusion.falsePass + confusion.falseFail\n if (n === 0) return null\n const observed = (confusion.truePass + confusion.trueFail) / n\n const judgePass = (confusion.truePass + confusion.falsePass) / n\n const ownerPass = (confusion.truePass + confusion.falseFail) / n\n const expected = judgePass * ownerPass + (1 - judgePass) * (1 - ownerPass)\n if (expected === 1) return null\n return (observed - expected) / (1 - expected)\n}\n\n/**\n * Agreement between a judge's runs and the owner's verdicts on one\n * calibration set. A run that names an example outside the set is an error:\n * a silently dropped run would overstate agreement.\n */\nexport function measureJudgeAgreement(\n set: JudgeCalibrationSet,\n runs: readonly JudgeRun[],\n meta: JudgeRunMeta,\n): JudgeAgreement {\n const registered = registerCalibrationSet(set)\n if (meta.judgeId !== registered.judgeId) {\n throw new ValidationError(\n `judge-gate: runs are for judge \"${meta.judgeId}\" but the set belongs to \"${registered.judgeId}\"`,\n )\n }\n requireText(meta.judgeModel, 'judgeModel')\n requireText(meta.rubricVersion, 'rubricVersion')\n parseIso(meta.measuredAt, 'measuredAt')\n const byId = new Map(registered.examples.map((example) => [example.id, example]))\n const runsById = new Map<string, JudgeRun[]>()\n const confusion: JudgeConfusion = { truePass: 0, trueFail: 0, falsePass: 0, falseFail: 0 }\n const withinRun: number[] = []\n for (const [index, run] of runs.entries()) {\n const example = byId.get(run?.exampleId)\n if (!example) {\n throw new ValidationError(\n `judge-gate: run ${index} names example ${JSON.stringify(run?.exampleId)}, which is not in \"${registered.judgeId}\"'s calibration set`,\n )\n }\n const verdict = requireVerdict(run.verdict, `run ${index} verdict`)\n if (run.samples !== undefined) {\n if (!Array.isArray(run.samples) || run.samples.length === 0) {\n throw new ValidationError(`judge-gate: run ${index} samples must be a non-empty array`)\n }\n const samples = run.samples.map((sample, s) =>\n requireVerdict(sample, `run ${index} sample ${s}`),\n )\n withinRun.push(\n bernoulliVariance(samples.filter((sample) => sample === 'pass').length, samples.length),\n )\n }\n const list = runsById.get(example.id) ?? []\n list.push({ ...run, verdict })\n runsById.set(example.id, list)\n if (verdict === 'pass') {\n if (example.verdict === 'pass') confusion.truePass++\n else confusion.falsePass++\n } else if (example.verdict === 'fail') confusion.trueFail++\n else confusion.falseFail++\n }\n\n const perExample: JudgeExampleAgreement[] = []\n const unjudged: string[] = []\n const judgedByVerdict: Record<OwnerVerdict, number> = { pass: 0, fail: 0 }\n for (const example of registered.examples) {\n const list = runsById.get(example.id)\n if (!list) {\n unjudged.push(example.id)\n continue\n }\n judgedByVerdict[example.verdict]++\n const passes = list.filter((run) => run.verdict === 'pass').length\n perExample.push({\n id: example.id,\n verdict: example.verdict,\n runs: list.length,\n passRate: passes / list.length,\n agreement: list.filter((run) => run.verdict === example.verdict).length / list.length,\n })\n }\n\n const total = runs.length\n const agreedRuns = confusion.truePass + confusion.trueFail\n const agreedExamples = perExample.filter((example) => example.agreement === 1).length\n const mean = (values: readonly number[]) =>\n values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0) / values.length\n return {\n ...meta,\n owner: registered.owner,\n examples: registered.examples.length,\n judged: perExample.length,\n judgedByVerdict,\n runs: total,\n accuracy: total === 0 ? null : agreedRuns / total,\n exampleAccuracy:\n perExample.length === 0\n ? null\n : {\n agreed: agreedExamples,\n judged: perExample.length,\n interval: computeInterval(\n { kind: 'clopper-pearson', level: 0.95 },\n { kind: 'binomial', successes: agreedExamples, trials: perExample.length },\n ),\n },\n kappa: binaryKappa(confusion),\n falseFailRate:\n confusion.truePass + confusion.falseFail === 0\n ? null\n : confusion.falseFail / (confusion.truePass + confusion.falseFail),\n catchRate:\n confusion.trueFail + confusion.falsePass === 0\n ? null\n : confusion.trueFail / (confusion.trueFail + confusion.falsePass),\n confusion,\n variance: {\n betweenRuns: mean(perExample.map((example) => example.passRate * (1 - example.passRate))),\n withinRun: mean(withinRun),\n unstable: perExample\n .filter((example) => example.passRate > 0 && example.passRate < 1)\n .map((example) => example.id),\n },\n disagreements: perExample\n .filter((example) => example.agreement < 1)\n .sort((a, b) => a.agreement - b.agreement || (a.id < b.id ? -1 : 1)),\n unjudged,\n }\n}\n\nexport interface JudgeGatePolicy {\n /**\n * `verdict`: the judge passes and blocks, so accuracy and κ must hold.\n * `veto`: it only blocks, so its false-fail rate on owner passes must hold.\n */\n decides: 'verdict' | 'veto'\n /** Judged examples required before the judge may gate; for a veto judge, owner passes. */\n minExamples: number\n /** Judged examples required of each owner verdict, so κ is defined. */\n minPerVerdict: number\n /** Floor on run accuracy. */\n minAccuracy: number\n /** Floor on Cohen's κ. */\n minKappa: number\n /** Ceiling on a veto judge's false-fail rate. */\n maxFalseFailRate: number\n /** A report older than this (days, vs `asOf`) no longer calibrates the judge. */\n maxAgeDays: number\n /** Drift thresholds forwarded to `judgeSentinelReport` over the history. */\n drift?: SentinelThresholds\n}\n\nexport const DEFAULT_JUDGE_GATE_POLICY: Readonly<JudgeGatePolicy> = Object.freeze({\n decides: 'verdict',\n minExamples: 10,\n minPerVerdict: 1,\n minAccuracy: 0.9,\n minKappa: 0.6,\n maxFalseFailRate: 0.1,\n maxAgeDays: 30,\n})\n\nexport type JudgeGateStatus = 'calibrated' | 'uncalibrated' | 'below-threshold' | 'drifted'\n\nexport interface JudgeGateDecision {\n judgeId: string\n judgeModel: string\n rubricVersion: string\n /** True only for `calibrated`. */\n mayGate: boolean\n status: JudgeGateStatus\n /** Why the judge may not gate; empty when it may. */\n reasons: string[]\n agreement: JudgeAgreement | null\n policy: JudgeGatePolicy\n}\n\nexport interface JudgeGateInput {\n judgeId: string\n /** The model the judge runs now. */\n judgeModel: string\n /** The rubric the judge runs now. */\n rubricVersion: string\n /** The latest calibration report; null when the judge was never measured. */\n agreement: JudgeAgreement | null\n asOf: string\n /** Sentinel snapshots for this judge, oldest first or in any order. */\n history?: readonly SentinelSnapshot[]\n policy?: Partial<JudgeGatePolicy>\n}\n\nconst DAY_MS = 86_400_000\n\nfunction percent(value: number): string {\n return `${(value * 100).toFixed(1)}%`\n}\n\n/** Whether a judge may gate now, and every reason it may not. */\nexport function judgeGateDecision(input: JudgeGateInput): JudgeGateDecision {\n const judgeId = requireText(input.judgeId, 'judgeId')\n const judgeModel = requireText(input.judgeModel, 'judgeModel')\n const rubricVersion = requireText(input.rubricVersion, 'rubricVersion')\n const asOf = parseIso(input.asOf, 'asOf')\n const policy: JudgeGatePolicy = {\n ...DEFAULT_JUDGE_GATE_POLICY,\n ...Object.fromEntries(\n Object.entries(input.policy ?? {}).filter(([, value]) => value !== undefined),\n ),\n }\n if (policy.decides !== 'verdict' && policy.decides !== 'veto') {\n throw new ValidationError(\n `judge-gate: policy.decides must be 'verdict' or 'veto', got ${JSON.stringify(policy.decides)}`,\n )\n }\n const agreement = input.agreement\n const decide = (status: JudgeGateStatus, reasons: string[]): JudgeGateDecision => ({\n judgeId,\n judgeModel,\n rubricVersion,\n mayGate: status === 'calibrated',\n status,\n reasons,\n agreement,\n policy,\n })\n\n if (!agreement) return decide('uncalibrated', ['no measured agreement with owner verdicts'])\n if (agreement.judgeId !== judgeId) {\n throw new ValidationError(\n `judge-gate: agreement belongs to \"${agreement.judgeId}\", not \"${judgeId}\"`,\n )\n }\n\n const uncalibrated: string[] = []\n if (agreement.judgeModel !== judgeModel) {\n uncalibrated.push(\n `agreement was measured on model ${agreement.judgeModel}; the judge now runs ${judgeModel}`,\n )\n }\n if (agreement.rubricVersion !== rubricVersion) {\n uncalibrated.push(\n `agreement was measured on rubric ${agreement.rubricVersion}; the judge now runs ${rubricVersion}`,\n )\n }\n const ageDays = (asOf - parseIso(agreement.measuredAt, 'agreement.measuredAt')) / DAY_MS\n if (ageDays > policy.maxAgeDays) {\n uncalibrated.push(`agreement is ${ageDays.toFixed(1)} days old (limit ${policy.maxAgeDays})`)\n }\n if (policy.decides === 'veto') {\n // Only owner passes can show a veto judge blocking what it should not.\n if (agreement.judgedByVerdict.pass < policy.minExamples) {\n uncalibrated.push(\n `${agreement.judgedByVerdict.pass} judged examples the owner marked pass; a veto judge needs at least ${policy.minExamples}`,\n )\n }\n } else {\n if (agreement.judged < policy.minExamples) {\n uncalibrated.push(\n `${agreement.judged} judged ${agreement.judged === 1 ? 'example' : 'examples'}; at least ${policy.minExamples} required`,\n )\n }\n for (const verdict of ['pass', 'fail'] as const) {\n if (agreement.judgedByVerdict[verdict] < policy.minPerVerdict) {\n uncalibrated.push(\n `${agreement.judgedByVerdict[verdict]} judged examples the owner marked ${verdict}; at least ${policy.minPerVerdict} required`,\n )\n }\n }\n }\n if (uncalibrated.length > 0) return decide('uncalibrated', uncalibrated)\n\n const below: string[] = []\n if (policy.decides === 'veto') {\n if (agreement.falseFailRate === null || agreement.falseFailRate > policy.maxFalseFailRate) {\n below.push(\n `it fails ${agreement.falseFailRate === null ? 'an unmeasured share' : percent(agreement.falseFailRate)} of what the owner passed (limit ${percent(policy.maxFalseFailRate)})`,\n )\n }\n } else if (agreement.accuracy === null || agreement.accuracy < policy.minAccuracy) {\n below.push(\n `accuracy ${agreement.accuracy === null ? 'unmeasured' : percent(agreement.accuracy)} is below ${percent(policy.minAccuracy)}`,\n )\n }\n if (\n policy.decides === 'verdict' &&\n (agreement.kappa === null || agreement.kappa < policy.minKappa)\n ) {\n below.push(\n `kappa ${agreement.kappa === null ? 'undefined' : agreement.kappa.toFixed(2)} is below ${policy.minKappa}`,\n )\n }\n if (below.length > 0) return decide('below-threshold', below)\n\n const history = (input.history ?? []).filter((snapshot) => snapshot.judgeId === judgeId)\n if (history.length > 0) {\n const report = judgeSentinelReport([...history], {\n asOf: input.asOf,\n ...(policy.drift ? { thresholds: policy.drift } : {}),\n })\n if (!report.healthy) return decide('drifted', report.alarms)\n }\n return decide('calibrated', [])\n}\n\n/** Thrown by `assertJudgeMayGate`; carries the refused decision. */\nexport class JudgeGateRefusedError extends JudgeError {\n readonly decision: JudgeGateDecision\n\n constructor(decision: JudgeGateDecision) {\n super(\n `judge \"${decision.judgeId}\" may not gate (${decision.status}): ${decision.reasons.join('; ')}`,\n )\n this.decision = decision\n }\n}\n\n/** Throw unless the decision lets the judge gate. */\nexport function assertJudgeMayGate(decision: JudgeGateDecision): void {\n if (!decision.mayGate) throw new JudgeGateRefusedError(decision)\n}\n\n/**\n * The sentinel snapshot for one calibration run. A deciding judge records\n * accuracy as `sentinelPassRate` and κ as `calibrationKappa` when it is\n * defined; a veto judge records the share of owner passes it let through as\n * `sentinelPassRate`. Append it to the judge's `SentinelStore`; the gate reads\n * drift from that history.\n */\nexport function snapshotFromJudgeAgreement(\n agreement: JudgeAgreement,\n options: { decides?: JudgeGatePolicy['decides'] } = {},\n): SentinelSnapshot {\n const veto = options.decides === 'veto'\n const rate = veto\n ? agreement.falseFailRate === null\n ? null\n : 1 - agreement.falseFailRate\n : agreement.accuracy\n if (rate === null) {\n throw new ValidationError(\n `snapshotFromJudgeAgreement: judge \"${agreement.judgeId}\" has no ${veto ? 'runs on owner passes' : 'runs'} to snapshot`,\n )\n }\n const snapshot: SentinelSnapshot = {\n at: agreement.measuredAt,\n judgeId: agreement.judgeId,\n judgeModel: agreement.judgeModel,\n metrics: {\n sentinelPassRate: rate,\n ...(veto || agreement.kappa === null ? {} : { calibrationKappa: agreement.kappa }),\n },\n }\n validateSentinelSnapshot(snapshot)\n return snapshot\n}\n"],"mappings":";;;;AA8BA,SAAgB,cACd,QACA,UAAoC,CAAC,GACZ;CACzB,MAAM,SAAS,QAAQ,UAAU;CACjC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAW,QAAQ,YAAY;CAErC,IAAI,OAAO,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,CAAC,CAAC,GACjD,OAAO;EAAE,OAAO;EAAqB,YAAY;EAAG,UAAU;EAAG,SAAS;EAAG,QAAQ;CAAM;CAG7F,MAAM,OAAO,OAAO,MAAM,CAAC,MAAM;CACjC,MAAM,OAAO,KAAK,QAAQ,GAAG,MAAM,IAAI,GAAG,CAAC,IAAI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,MAAM,SAAS,oBAAoB,CAAC,GAAG,OAAO,GAAG;GAC/C,MAAM,MAAM;GACZ,GAAI,OAAO,QAAQ,EAAE,YAAY,OAAO,MAAM,IAAI,CAAC;EACrD,CAAC;EACD,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO,WAAW,OAAO,MAAM;CAC7D;CACA,OAAO,OAAO,cAAc,CAAC,CAAC;AAChC;;AAGA,IAAa,wBAAb,cAA2C,WAAW;CACpD;CAEA,YAAY,UAA6B;EACvC,MACE,UAAU,SAAS,QAAQ,kBAAkB,SAAS,OAAO,KAAK,SAAS,QAAQ,KAAK,IAAI,GAC9F;EACA,KAAK,WAAW;CAClB;AACF;;AAGA,SAAgB,mBAAmB,UAAmC;CACpE,IAAI,CAAC,SAAS,SAAS,MAAM,IAAI,sBAAsB,QAAQ;AACjE;;;;;;;;AASA,SAAgB,2BACd,WACA,UAAoD,CAAC,GACnC;CAClB,MAAM,OAAO,QAAQ,YAAY;CACjC,MAAM,OAAO,OACT,UAAU,kBAAkB,OAC1B,OACA,IAAI,UAAU,gBAChB,UAAU;CACd,IAAI,SAAS,MACX,MAAM,IAAI,gBACR,sCAAsC,UAAU,QAAQ,WAAW,OAAO,yBAAyB,OAAO,aAC5G;CAEF,MAAM,WAA6B;EACjC,IAAI,UAAU;EACd,SAAS,UAAU;EACnB,YAAY,UAAU;EACtB,SAAS;GACP,kBAAkB;GAClB,GAAI,QAAQ,UAAU,UAAU,OAAO,CAAC,IAAI,EAAE,kBAAkB,UAAU,MAAM;EAClF;CACF;CACA,yBAAyB,QAAQ;CACjC,OAAO;AACT"}
|
|
@@ -228,7 +228,8 @@ function servedModelAcceptable(check, opts = {}) {
|
|
|
228
228
|
default: return false;
|
|
229
229
|
}
|
|
230
230
|
}
|
|
231
|
-
|
|
231
|
+
/** One line naming the requested and served ids, families and verdict. */
|
|
232
|
+
function describeServedModelCheck(check) {
|
|
232
233
|
if (check.verdict === "unreported") return `${check.requested}: response carried no model id (identity unproven)`;
|
|
233
234
|
return `${check.requested} (${check.requestedFamily}) → served ${check.served} (${check.servedFamily}) [${check.verdict}]`;
|
|
234
235
|
}
|
|
@@ -240,7 +241,7 @@ function describe(check) {
|
|
|
240
241
|
function assertServedModel(requested, served, opts = {}) {
|
|
241
242
|
const check = checkServedModel(requested, served);
|
|
242
243
|
if (servedModelAcceptable(check, opts)) return check;
|
|
243
|
-
throw new ModelSubstitutionError(`${opts.context ? `${opts.context}: ` : ""}model substitution — ${
|
|
244
|
+
throw new ModelSubstitutionError(`${opts.context ? `${opts.context}: ` : ""}model substitution — ${describeServedModelCheck(check)}. The measurement is of the SERVED model, not the requested one; any per-model or per-family claim from this call is invalid.`, [check]);
|
|
244
245
|
}
|
|
245
246
|
/**
|
|
246
247
|
* Batch form: check every pair and throw naming EVERY substitution, so one
|
|
@@ -249,7 +250,7 @@ function assertServedModel(requested, served, opts = {}) {
|
|
|
249
250
|
function assertServedModels(pairs, opts = {}) {
|
|
250
251
|
const checks = pairs.map((p) => checkServedModel(p.requested, p.served));
|
|
251
252
|
const bad = checks.filter((c) => !servedModelAcceptable(c, opts));
|
|
252
|
-
if (bad.length > 0) throw new ModelSubstitutionError(`${opts.context ? `${opts.context}: ` : ""}${bad.length}/${checks.length} call(s) were answered by a different model than requested — ${bad.map(
|
|
253
|
+
if (bad.length > 0) throw new ModelSubstitutionError(`${opts.context ? `${opts.context}: ` : ""}${bad.length}/${checks.length} call(s) were answered by a different model than requested — ${bad.map(describeServedModelCheck).join("; ")}. Per-model and per-family claims from this run are invalid until the ids are re-measured.`, checks);
|
|
253
254
|
return checks;
|
|
254
255
|
}
|
|
255
256
|
var ServedCrossFamilyError = class extends AgentEvalError {
|
|
@@ -281,7 +282,7 @@ function assertCrossFamilyServed(pairs, opts = {}) {
|
|
|
281
282
|
families.add(family);
|
|
282
283
|
}
|
|
283
284
|
const list = [...families].sort();
|
|
284
|
-
const minFamilies = opts.minFamilies ?? 2;
|
|
285
|
+
const minFamilies = opts.requestedPanel ? new Set(opts.requestedPanel.map((id) => judgeFamily(id)).filter((family) => family !== "unknown" || opts.allowUnknown)).size : opts.minFamilies ?? 2;
|
|
285
286
|
if (list.length < minFamilies) throw new ServedCrossFamilyError(`${opts.context ? `${opts.context}: ` : ""}the models that ANSWERED span ${list.length} provider famil${list.length === 1 ? "y" : "ies"} (${list.join(", ") || "none"}) but ${minFamilies} required — served ids: ${checks.map((c) => c.served ?? "unreported").join(", ")}`, list, checks);
|
|
286
287
|
return list;
|
|
287
288
|
}
|
|
@@ -906,6 +907,6 @@ var LlmClient = class {
|
|
|
906
907
|
}
|
|
907
908
|
};
|
|
908
909
|
//#endregion
|
|
909
|
-
export {
|
|
910
|
+
export { judgeFamily as _, maximumChargeForLlmRequest as a, ModelSubstitutionError as c, assertServedModelPolicy as d, assertServedModels as f, assertCrossFamily as g, CrossFamilyError as h, costReceiptFromLlmError as i, assertCrossFamilyServed as l, describeServedModelCheck as m, callLlmJson as n, backoffMs as o, checkServedModel as p, costReceiptFromLlm as r, isTransientLlmError as s, LlmClient as t, assertServedModel as u, combineAbortSignals as v };
|
|
910
911
|
|
|
911
|
-
//# sourceMappingURL=llm-client-
|
|
912
|
+
//# sourceMappingURL=llm-client-b1ysZVIU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llm-client-b1ysZVIU.js","names":[],"sources":["../src/abort-signal.ts","../src/judge-families.ts","../src/integrity/served-model.ts","../src/llm-client/resilience.ts","../src/llm-client/wire.ts","../src/llm-client/accounting.ts","../src/llm-client/request.ts","../src/llm-client.ts"],"sourcesContent":["/** Combine active cancellation sources without wrapping a single source. */\nexport function combineAbortSignals(\n ...signals: Array<AbortSignal | undefined>\n): AbortSignal | undefined {\n const active = [\n ...new Set(signals.filter((signal): signal is AbortSignal => signal !== undefined)),\n ]\n if (active.length === 0) return undefined\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n","/**\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 // Anthropic's own bare aliases (`claude --model sonnet|opus|haiku`). A run that requested `sonnet`\n // and was served claude-sonnet-5 is an alias resolution, not a cross-family substitution: without\n // this row the alias classified as `unknown` and assertServedModel refused the pair.\n [/^(?:sonnet|opus|haiku)(?:[-@\\s]|$)/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\n/** One line naming the requested and served ids, families and verdict. */\nexport function describeServedModelCheck(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 — ${describeServedModelCheck(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(describeServedModelCheck).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 /**\n * The panel as requested. When set, the minimum is the number of distinct\n * families this list claims (instead of `minFamilies`), so a panel whose\n * failed or dropped judges leave the survivors spanning fewer families than\n * the request list is refused: their mean would be correlated bias reported\n * as independent agreement.\n */\n requestedPanel?: readonly string[]\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.requestedPanel\n ? new Set(\n opts.requestedPanel\n .map((id) => judgeFamily(id))\n .filter((family) => family !== 'unknown' || opts.allowUnknown),\n ).size\n : (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","import type { LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\n// Flagship / reasoning models routinely take several minutes on large prompts (a\n// reflection over many failures, a long tool transcript). A tight cap aborts a\n// legitimately-slow but healthy call — and because every retry attempt re-uses\n// the same window, such a model aborts on ALL attempts and the loop throws. The\n// default is generous enough to let those complete, bounded enough that a truly\n// hung call still fails over after retries, and tunable per deployment via\n// TANGLE_LLM_TIMEOUT_MS. Per-call `req.timeoutMs` / `opts.defaultTimeoutMs`\n// still win for callers that know their model's latency.\nexport const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\n\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 6\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nexport function resolveMaximumAttempts(configured: number | undefined): number {\n const attempts = configured ?? DEFAULT_MAXIMUM_ATTEMPTS\n if (!Number.isInteger(attempts) || attempts <= 0) {\n throw new RangeError('LLM maximum attempts must be a positive integer')\n }\n return attempts\n}\n\nexport function resolveMinIntervalMs(configured: number | undefined): number {\n const interval = configured ?? 0\n if (!Number.isFinite(interval) || interval < 0) {\n throw new RangeError('LLM minIntervalMs must be a finite non-negative number')\n }\n return interval\n}\n\n// Weak keys avoid retaining credentials or completed campaigns. LlmClient binds\n// its per-call option copies to the same state as its constructor options.\nexport const pacingStates = new WeakMap<LlmClientOptions, { lastStartedAt?: number }>()\n\nexport function pacingStateFor(opts: LlmClientOptions): { lastStartedAt?: number } {\n let state = pacingStates.get(opts)\n if (!state) {\n state = {}\n pacingStates.set(opts, state)\n }\n return state\n}\n\n// 522/524: Cloudflare edge timeouts (origin connect/respond) — transient\n// exactly like 504. Router deployments serve through Cloudflare, so a long\n// non-streaming call can draw these from the edge, not the origin.\nexport const RETRYABLE_STATUS = new Set([429, 502, 503, 504, 522, 524])\n\n/**\n * Transient transport/network error signatures, matched against an error's\n * name, message, and `code`. Covers fetch/undici network failures, aborts\n * and timeouts, and — critically — HTTP/2 transport faults a keep-alive\n * connection raises mid-response: `terminated`, `NGHTTP2_INTERNAL_ERROR`,\n * `UND_ERR_*`, `other side closed`. Those last ones carry no clean HTTP\n * status; unrecognised, they escape the retry loop and surface as an\n * uncaught rejection.\n */\nconst TRANSIENT_ERROR_PATTERNS: readonly RegExp[] = [\n /AbortError/i,\n /TimeoutError/i,\n /this operation was aborted/i,\n /fetch failed/i,\n /ECONNRESET/i,\n /ETIMEDOUT/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /stream.*ended.*unexpectedly/i,\n /terminated/i,\n /other side closed/i,\n /NGHTTP2/i,\n /UND_ERR/i,\n]\n\n/**\n * True when an error is a transient transport/network fault worth retrying,\n * as opposed to a deterministic failure (4xx schema reject, JSON parse) that\n * a retry cannot fix. Inspects `LlmCallError.status`, then the error's\n * name/message/code, then recurses into `error.cause` — undici nests the\n * real socket fault one or more levels under `.cause`.\n *\n * This is the retry classifier for the package: `callLlm` and\n * `withJudgeRetry` both route through it, so connection failures are treated\n * consistently across transports.\n */\nexport function isTransientLlmError(err: unknown): boolean {\n return classifyTransient(err, 0)\n}\n\nfunction classifyTransient(err: unknown, depth: number): boolean {\n if (err instanceof LlmCallError) return RETRYABLE_STATUS.has(err.status)\n if (!(err instanceof Error)) return false\n // Foreign transport errors can carry a numeric HTTP status without being an\n // LlmCallError. A retryable status is decisive.\n const status = (err as { status?: unknown }).status\n if (typeof status === 'number' && RETRYABLE_STATUS.has(status)) return true\n const code = (err as { code?: unknown }).code\n const haystack = `${err.name}\\n${err.message}\\n${typeof code === 'string' ? code : ''}`\n if (TRANSIENT_ERROR_PATTERNS.some((p) => p.test(haystack))) return true\n const cause = (err as { cause?: unknown }).cause\n if (depth < 4 && cause instanceof Error && cause !== err) {\n return classifyTransient(cause, depth + 1)\n }\n return false\n}\n\nexport function parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')?.trim()\n if (!h) return null\n const asNumber = Number(h)\n if (!Number.isNaN(asNumber)) {\n const delay = asNumber * 1000\n return Number.isFinite(delay) && delay >= 0 ? delay : null\n }\n const asDate = Date.parse(h)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return null\n}\n\n/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */\nexport function backoffMs(attempt: number): number {\n return Math.min(500 * 2 ** attempt, 16_000)\n}\n\n/** Backoff belongs to the caller's operation and must stop when it is cancelled. */\nexport async function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n // A timer above the signed 32-bit limit becomes a near-immediate timeout.\n // Split long server delays rather than truncating Retry-After or overflowing.\n do {\n signal?.throwIfAborted()\n const chunk = Math.min(Math.ceil(ms), 2_147_483_647)\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n reject(signal?.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, chunk)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n ms -= chunk\n } while (ms > 0)\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nexport function deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n","import type {\n LlmCallRequest,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n} from './contract'\n\nexport function providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nexport function buildHeaders(opts: LlmClientOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (opts.authHeader) {\n headers[opts.authHeader.name] = opts.authHeader.value\n } else if (opts.bearer || opts.apiKey) {\n headers.Authorization = `Bearer ${opts.bearer ?? opts.apiKey}`\n }\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n return headers\n}\n\nexport function isSchemaRejection(status: number, body: string): boolean {\n if (status !== 400) return false\n const lower = body.toLowerCase()\n return (\n lower.includes('response_format') ||\n lower.includes('json_schema') ||\n lower.includes('is unavailable') ||\n lower.includes('not supported')\n )\n}\n\nexport function isTemperatureOneRejection(status: number, body: string): boolean {\n if (status !== 400 || !/temperature/i.test(body)) return false\n return (\n /temperature[^.\\n]{0,120}\\b(?:only|must|should|required|requires?)\\b[^.\\n]{0,40}\\b1(?:\\.0+)?\\b/i.test(\n body,\n ) || /\\bonly\\s+1(?:\\.0+)?\\s+is\\s+allowed\\b[^.\\n]{0,120}\\btemperature\\b/i.test(body)\n )\n}\n\nexport function buildBody(\n req: LlmCallRequest,\n forceJsonObject: boolean,\n defaultThinking?: LlmThinkingMode,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model: req.model,\n messages: req.messages.map(encodeWireMessage),\n temperature: req.temperature ?? 0,\n }\n if (req.maxTokens != null) {\n if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens\n else body.max_tokens = req.maxTokens\n }\n if (req.logprobs !== undefined) {\n body.logprobs = true\n body.top_logprobs = req.logprobs.topLogprobs\n }\n if (req.tools !== undefined) body.tools = req.tools\n if (req.toolChoice !== undefined) body.tool_choice = req.toolChoice\n const thinking = req.thinking ?? defaultThinking\n if (thinking !== undefined) {\n body.thinking = { type: thinking }\n }\n\n if (req.jsonSchema && !forceJsonObject) {\n body.response_format = {\n type: 'json_schema',\n json_schema: { name: req.jsonSchema.name, schema: req.jsonSchema.schema, strict: true },\n }\n } else if (req.jsonMode || req.jsonSchema) {\n body.response_format = { type: 'json_object' }\n }\n\n return body\n}\n\nfunction usesMaxCompletionTokens(model: string): boolean {\n return /^gpt-5(?:[.-]|$)/i.test(model)\n}\n\n/** Encode one canonical message as its OpenAI chat-completions wire shape. */\nfunction encodeWireMessage(message: LlmMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content }\n }\n if (message.toolCalls === undefined) {\n return { role: message.role, content: message.content }\n }\n return {\n role: message.role,\n content: message.content,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: call.argumentsJson },\n })),\n }\n}\n\n/**\n * Parse `choices[0].logprobs.content` into the canonical per-token shape.\n * `null` when the provider returned nothing for a request that asked: a\n * provider that ignores `logprobs` is a fact the caller must be able to read,\n * not an error. A malformed entry is a contract violation and throws.\n */\nexport function parseWireLogprobs(\n value: unknown,\n model: string,\n): ReadonlyArray<LlmTokenLogprob> | null {\n if (value === undefined || value === null) return null\n if (!Array.isArray(value)) {\n throw new Error(`LLM response logprobs.content must be an array (model=${model})`)\n }\n return value.map((entry, index) => {\n const record = entry as { token?: unknown; logprob?: unknown; top_logprobs?: unknown } | null\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.token !== 'string' ||\n typeof record.logprob !== 'number' ||\n !Number.isFinite(record.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}] is not a token with a finite logprob (model=${model})`,\n )\n }\n const top = record.top_logprobs\n if (top !== undefined && top !== null && !Array.isArray(top)) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs must be an array (model=${model})`,\n )\n }\n return {\n token: record.token,\n logprob: record.logprob,\n top: (Array.isArray(top) ? top : []).map((alternative, position) => {\n const candidate = alternative as { token?: unknown; logprob?: unknown } | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.token !== 'string' ||\n typeof candidate.logprob !== 'number' ||\n !Number.isFinite(candidate.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs[${position}] is not a token with a finite logprob (model=${model})`,\n )\n }\n return { token: candidate.token, logprob: candidate.logprob }\n }),\n }\n })\n}\n\n/** Parse provider tool_calls into the canonical shape. A malformed entry is a\n * provider-contract violation and throws rather than degrading silently. */\nexport function parseWireToolCalls(value: unknown, model: string): LlmToolCall[] | undefined {\n if (value === undefined || value === null) return undefined\n if (!Array.isArray(value)) {\n throw new Error(`LLM response tool_calls must be an array (model=${model})`)\n }\n if (value.length === 0) return undefined\n return value.map((entry, index) => {\n const record = entry as {\n id?: unknown\n type?: unknown\n function?: { name?: unknown; arguments?: unknown } | null\n } | null\n const fn = record && typeof record === 'object' ? record.function : undefined\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.id !== 'string' ||\n record.id.length === 0 ||\n (record.type !== undefined && record.type !== 'function') ||\n !fn ||\n typeof fn !== 'object' ||\n typeof fn.name !== 'string' ||\n fn.name.length === 0 ||\n typeof fn.arguments !== 'string'\n ) {\n throw new Error(\n `LLM response tool_calls[${index}] is not a function call with string arguments (model=${model})`,\n )\n }\n return { id: record.id, name: fn.name, argumentsJson: fn.arguments }\n })\n}\n","import type { CostReceiptInput, CustomTokenPricing, MaximumCharge } from '../cost-ledger'\nimport type { LlmCallRequest, LlmCallResult, LlmChargeBounds } from './contract'\nimport { LlmResponseError } from './errors'\nimport { resolveMaximumAttempts } from './resilience'\nimport { buildBody } from './wire'\n\nexport function maximumChargeForLlmRequest(\n request: Pick<\n LlmCallRequest,\n 'model' | 'messages' | 'jsonSchema' | 'tools' | 'toolChoice' | 'maxTokens' | 'thinking'\n >,\n options: LlmChargeBounds = {},\n): MaximumCharge | undefined {\n if (request.maxTokens === undefined) return undefined\n if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) {\n throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`)\n }\n if (\n request.messages.some(\n (message) =>\n Array.isArray(message.content) && message.content.some((part) => part.type === 'image_url'),\n )\n ) {\n return undefined\n }\n\n const attempts = resolveMaximumAttempts(options.maximumAttempts)\n const forceJsonObject = options.jsonSchemaTransport === 'json-object'\n // A byte-level tokenizer cannot emit more input tokens than request bytes.\n // Pricing the complete body also covers role/schema framing omitted from content-only estimates.\n const requestBytes = new TextEncoder().encode(\n JSON.stringify(buildBody(request, forceJsonObject, options.thinking)),\n ).byteLength\n // Schema fallback shares the same physical-attempt budget; it cannot buy a second batch.\n const usage = {\n inputTokens: requestBytes * attempts,\n outputTokens: request.maxTokens * attempts,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\n/** Convert a provider result into the canonical paid-call receipt input.\n * The receipt is JSON-clean: absent optional fields are omitted, never carried\n * as explicit-undefined keys. Receipts cross JSON boundaries (the external\n * optimizer's loopback proxy validates them with `assertJsonValue`), where an\n * explicit-undefined value is rejected as non-serializable. */\nexport function costReceiptFromLlm(\n result: LlmCallResult,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput {\n const cachedTokens = result.usage.cachedPromptTokens ?? 0\n const inputTokens = Math.max(0, result.usage.promptTokens - cachedTokens)\n const providerCostUsd = providerReportedCost(result.raw)\n return {\n model: result.model,\n inputTokens,\n outputTokens: result.usage.completionTokens,\n ...(result.usage.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: result.usage.reasoningTokens }),\n ...(cachedTokens > 0 ? { cachedTokens } : {}),\n ...(providerCostUsd === undefined\n ? customTokenPricing && result.usage.captured !== false\n ? { customTokenPricing }\n : result.costUsd === null\n ? {}\n : { estimatedCostUsd: result.costUsd }\n : { actualCostUsd: providerCostUsd }),\n usageUnknown: result.usage.captured === false,\n }\n}\n\nexport function providerReportedCost(raw: Record<string, unknown>): number | undefined {\n const value = raw._response_cost ?? raw.cost_usd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/** Structured-response failures retain their completed provider receipt. */\nexport function costReceiptFromLlmError(\n error: Error,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput | undefined {\n return error instanceof LlmResponseError\n ? costReceiptFromLlm(error.result, customTokenPricing)\n : undefined\n}\n","import { combineAbortSignals } from '../abort-signal'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { assertServedModel as assertServedModelIdentity } from '../integrity/served-model'\nimport { newRecordId } from '../record-id'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from '../trace/raw-provider-sink'\nimport { providerReportedCost } from './accounting'\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\nimport {\n backoffMs,\n DEFAULT_TIMEOUT_MS,\n deadlineExceeded,\n isTransientLlmError,\n pacingStateFor,\n parseRetryAfter,\n RETRYABLE_STATUS,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n sleep,\n} from './resilience'\nimport {\n buildBody,\n buildHeaders,\n isSchemaRejection,\n isTemperatureOneRejection,\n parseWireLogprobs,\n parseWireToolCalls,\n providerTokenCount,\n} from './wire'\n\n/**\n * Low-level call. Returns raw content + usage + cost. Retries on transient\n * failures; does NOT degrade schema here — callers that want graceful\n * degrade use `callLlmJson`.\n */\nexport async function callLlm(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts(req, opts, false)\n}\n\n/** One retry owner for raw and structured calls. Fallback changes the next\n * request, not the attempt allowance, deadline origin, or raw-event sequence. */\n/** What one call shares across its attempts: the resolved options, pacing, deadline and the request as it now stands. */\ninterface AttemptRun {\n readonly req: LlmCallRequest\n readonly opts: LlmClientOptions\n readonly allowSchemaFallback: boolean\n readonly baseUrl: string\n readonly url: string\n readonly timeoutMs: number\n readonly maximumAttempts: number\n readonly minIntervalMs: number\n readonly pacing: ReturnType<typeof pacingStateFor>\n readonly headers: ReturnType<typeof buildHeaders>\n readonly provider: string\n readonly deadlineStart: number\n readonly remainingMs: () => number\n readonly retryDelay: (ms: number) => Promise<void>\n effectiveRequest: LlmCallRequest\n lastErr: unknown\n}\n\n/** How one attempt ended without a result or a thrown error. */\ntype AttemptOutcome =\n | { kind: 'result'; result: LlmCallResult }\n | { kind: 'retry' }\n | { kind: 'exhausted' }\n\n/** Which of an attempt's raw events were already written, so the failure path records at most one error. */\ninterface AttemptState {\n dispatched: boolean\n errorRecorded: boolean\n}\n\nconst ENDPOINT = '/chat/completions'\n\nfunction startAttemptRun(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): AttemptRun {\n // No default endpoint. This client is internal to the `agent-eval` binary\n // and the loopback optimizer proxy; both name their endpoint explicitly, and\n // a fallback would let a misconfigured caller bill an unintended provider.\n if (!opts.baseUrl) throw new Error('callLlm: opts.baseUrl is required')\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n const remainingMs = () =>\n deadlineMs === undefined ? Infinity : Math.max(0, deadlineMs - (Date.now() - deadlineStart))\n const run: AttemptRun = {\n req,\n opts,\n allowSchemaFallback,\n baseUrl,\n url: `${baseUrl}${ENDPOINT}`,\n timeoutMs: req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS,\n maximumAttempts: resolveMaximumAttempts(opts.maximumAttempts),\n minIntervalMs: resolveMinIntervalMs(opts.minIntervalMs),\n pacing: pacingStateFor(opts),\n headers: buildHeaders(opts),\n provider: opts.provider ?? providerFromBaseUrl(baseUrl),\n deadlineStart,\n remainingMs,\n retryDelay: (ms) => sleep(Math.min(ms, remainingMs()), opts.signal),\n effectiveRequest: req,\n lastErr: undefined,\n }\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n return run\n}\n\nfunction deadlineError(run: AttemptRun): Error | DOMException {\n return run.lastErr instanceof Error\n ? run.lastErr\n : new DOMException('callLlm deadline exceeded', 'TimeoutError')\n}\n\n/** Write one raw provider event for this attempt. Does nothing without a sink. */\nasync function recordAttemptEvent(\n run: AttemptRun,\n attempt: number,\n fields: Pick<RawProviderEvent, 'direction' | 'timestamp'> & Partial<RawProviderEvent>,\n): Promise<void> {\n const { opts } = run\n if (!opts.rawSink) return\n await recordRaw(opts.rawSink, opts.redactor ?? defaultProviderRedactor, {\n eventId: newRecordId(),\n runId: opts.traceContext?.runId,\n spanId: opts.traceContext?.spanId,\n provider: run.provider,\n model: run.req.model,\n endpoint: ENDPOINT,\n baseUrl: run.baseUrl,\n attemptIndex: attempt,\n ...fields,\n redactedFields: [],\n })\n}\n\n/**\n * Wait for this client's pacing slot, and claim it. Every wake rechecks, so concurrent waiters\n * cannot dispatch a catch-up burst; the claim is made in the same synchronous step that finds the\n * slot free, so no other waiter can slip in between the check and the claim.\n */\nasync function awaitPacingSlot(run: AttemptRun): Promise<number> {\n const { opts, pacing, minIntervalMs } = run\n while (true) {\n opts.signal?.throwIfAborted()\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const waitMs =\n pacing.lastStartedAt === undefined ? 0 : pacing.lastStartedAt + minIntervalMs - Date.now()\n if (waitMs <= 0) {\n // Queue time consumes the operation deadline, not the HTTP timeout.\n const started = Date.now()\n pacing.lastStartedAt = started\n return started\n }\n await run.retryDelay(waitMs)\n }\n}\n\n/** Answer a non-2xx response: retry with an adjusted request or after a wait, give up, or throw its error. */\nasync function handleHttpFailure(\n run: AttemptRun,\n attempt: number,\n res: Response,\n body: string,\n responseHeaders: Record<string, string> | undefined,\n started: number,\n state: AttemptState,\n): Promise<AttemptOutcome> {\n const { req, opts, maximumAttempts, deadlineStart } = run\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: body,\n errorMessage: `HTTP ${res.status}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n const canRetry =\n attempt < maximumAttempts - 1 && !deadlineExceeded(deadlineStart, opts.deadlineMs)\n if (\n isTemperatureOneRejection(res.status, body) &&\n run.effectiveRequest.temperature !== 1 &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, temperature: 1 }\n return { kind: 'retry' }\n }\n if (\n run.allowSchemaFallback &&\n opts.jsonSchemaTransport !== 'json-object' &&\n run.effectiveRequest.jsonSchema &&\n isSchemaRejection(res.status, body) &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, jsonMode: true, jsonSchema: undefined }\n return { kind: 'retry' }\n }\n if (RETRYABLE_STATUS.has(res.status) && canRetry) {\n run.lastErr = err\n const wait = parseRetryAfter(res.headers) ?? backoffMs(attempt)\n // A wait the deadline cannot cover ends the call with this answer. Sleeping to the\n // deadline let a timer that fired a millisecond early start one more attempt with no time\n // left, whose abort replaced the server's status (agent-eval publish run 37238259408).\n if (wait >= run.remainingMs()) {\n // A caller abort that landed while the answer was recorded still wins, as the\n // retry wait would have reported it.\n opts.signal?.throwIfAborted()\n return { kind: 'exhausted' }\n }\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n throw err\n}\n\n/** Turn a parsed completion into the call result: content, tool calls, usage with its completeness, and cost. */\nfunction parseCompletion(\n run: AttemptRun,\n json: Record<string, unknown>,\n started: number,\n): LlmCallResult {\n const { req, opts } = run\n const choice = (\n json.choices as\n | Array<{\n message?: { content?: string | null; tool_calls?: unknown }\n finish_reason?: string | null\n logprobs?: { content?: unknown } | null\n }>\n | undefined\n )?.[0]\n const toolCalls = parseWireToolCalls(choice?.message?.tool_calls, req.model)\n const usageRaw =\n json.usage && typeof json.usage === 'object' && !Array.isArray(json.usage)\n ? (json.usage as Record<string, unknown>)\n : undefined\n const promptTokens = providerTokenCount(usageRaw?.prompt_tokens)\n const completionTokens = providerTokenCount(usageRaw?.completion_tokens)\n const totalTokens = providerTokenCount(usageRaw?.total_tokens)\n const completionDetails =\n usageRaw?.completion_tokens_details &&\n typeof usageRaw.completion_tokens_details === 'object' &&\n !Array.isArray(usageRaw.completion_tokens_details)\n ? (usageRaw.completion_tokens_details as Record<string, unknown>)\n : undefined\n const reasoningRaw = completionDetails?.reasoning_tokens\n const reasoningTokens = reasoningRaw === undefined ? undefined : providerTokenCount(reasoningRaw)\n const cachedRaw =\n usageRaw?.prompt_tokens_details &&\n typeof usageRaw.prompt_tokens_details === 'object' &&\n !Array.isArray(usageRaw.prompt_tokens_details)\n ? (usageRaw.prompt_tokens_details as Record<string, unknown>).cached_tokens\n : undefined\n const cachedPromptTokens = cachedRaw === undefined ? undefined : providerTokenCount(cachedRaw)\n const usageCaptured =\n promptTokens !== undefined &&\n completionTokens !== undefined &&\n (reasoningRaw === undefined ||\n (reasoningTokens !== undefined && reasoningTokens <= completionTokens)) &&\n (cachedRaw === undefined ||\n (cachedPromptTokens !== undefined && cachedPromptTokens <= promptTokens)) &&\n (totalTokens === undefined || totalTokens === promptTokens + completionTokens)\n const costFromProxy = providerReportedCost(json)\n const content = choice?.message?.content ?? ''\n\n const configuredCost =\n typeof costFromProxy !== 'number' && usageCaptured && opts.customTokenPricing\n ? costForTokenPricing(opts.customTokenPricing, {\n inputTokens: promptTokens! - (cachedPromptTokens ?? 0),\n ...(cachedPromptTokens ? { cachedTokens: cachedPromptTokens } : {}),\n outputTokens: completionTokens!,\n })\n : undefined\n\n // The echoed id, kept separate from the attribution id: a provider that\n // omits it must read as \"unproven\", never as \"the model I asked for\".\n const servedModel = typeof json.model === 'string' && json.model.trim() !== '' ? json.model : null\n if (opts.assertServedModel) {\n assertServedModelIdentity(\n req.model,\n servedModel,\n opts.assertServedModel === true ? {} : opts.assertServedModel,\n )\n }\n\n return {\n content,\n ...(toolCalls === undefined ? {} : { toolCalls }),\n ...(req.logprobs === undefined\n ? {}\n : { logprobs: parseWireLogprobs(choice?.logprobs?.content, req.model) }),\n finishReason: choice?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n usage: {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: totalTokens ?? (promptTokens ?? 0) + (completionTokens ?? 0),\n captured: usageCaptured,\n reasoningTokens,\n cachedPromptTokens,\n },\n costUsd: typeof costFromProxy === 'number' ? costFromProxy : (configuredCost ?? null),\n model: servedModel ?? req.model,\n servedModel,\n durationMs: Date.now() - started,\n raw: json,\n }\n}\n\n/** One attempt: pace, dispatch, read the answer. A failure either becomes a retry outcome or is thrown. */\nasync function runAttempt(run: AttemptRun, attempt: number): Promise<AttemptOutcome> {\n const { opts } = run\n const callerSignal = opts.signal\n // A caller cancel is fatal — never retried. Checking before each attempt\n // means an already-aborted signal short-circuits without firing fetch.\n if (callerSignal?.aborted) {\n throw new DOMException('callLlm aborted by caller signal', 'AbortError')\n }\n // Stop retrying once the cross-attempt budget is spent rather than burning\n // a full per-attempt timeout on each remaining retry.\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const requestBody = buildBody(\n run.effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n const controller = new AbortController()\n const attemptSignal = combineAbortSignals(controller.signal, callerSignal)!\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n let started = Date.now()\n // An attempt cancelled or timed out while queued never reached the\n // provider, so it leaves no request or error event in the raw log.\n const state: AttemptState = { dispatched: false, errorRecorded: false }\n try {\n if (run.minIntervalMs > 0) {\n started = await awaitPacingSlot(run)\n } else {\n // Claim the slot before any await so a concurrent waiter cannot take it.\n run.pacing.lastStartedAt = started\n }\n state.dispatched = true\n timeoutHandle = setTimeout(() => controller.abort(), Math.min(run.timeoutMs, run.remainingMs()))\n await recordAttemptEvent(run, attempt, {\n direction: 'request',\n timestamp: started,\n requestHeaders: run.headers,\n requestBody,\n })\n attemptSignal.throwIfAborted()\n const res = await (opts.fetch ?? globalThis.fetch)(run.url, {\n method: 'POST',\n headers: run.headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n const responseHeaders = opts.rawSink ? headersToObject(res.headers) : undefined\n // Headers are not completion: the same timeout/cancellation covers either response body.\n const text = await res.text()\n attemptSignal.throwIfAborted()\n clearTimeout(timeoutHandle)\n\n if (!res.ok) {\n return await handleHttpFailure(run, attempt, res, text, responseHeaders, started, state)\n }\n\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: text,\n errorMessage: `non-JSON response: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n throw parseErr\n }\n await recordAttemptEvent(run, attempt, {\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n })\n return { kind: 'result', result: parseCompletion(run, json, started) }\n } catch (err) {\n clearTimeout(timeoutHandle)\n run.lastErr = err\n // Record only if neither the !res.ok branch nor the JSON.parse catch\n // already produced an error event for this attempt. Covers network\n // failures, timeouts, and aborts.\n if (state.dispatched && !state.errorRecorded) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n }\n // A caller cancel is fatal even though an AbortError matches the\n // transient patterns — a cancelled call must surface immediately, not\n // be retried against the same dead intent.\n if (callerSignal?.aborted) throw err\n const wait = backoffMs(attempt)\n if (\n attempt < run.maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(run.deadlineStart, opts.deadlineMs) &&\n wait < run.remainingMs()\n ) {\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n callerSignal?.throwIfAborted()\n throw err\n } finally {\n clearTimeout(timeoutHandle)\n }\n}\n\nasync function callLlmAttempts(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): Promise<LlmCallResult> {\n const run = startAttemptRun(req, opts, allowSchemaFallback)\n for (let attempt = 0; attempt < run.maximumAttempts; attempt++) {\n const outcome = await runAttempt(run, attempt)\n if (outcome.kind === 'result') return outcome.result\n if (outcome.kind === 'exhausted') break\n }\n throw run.lastErr instanceof Error ? run.lastErr : new Error(String(run.lastErr))\n}\n\nasync function recordRaw(\n sink: RawProviderSink,\n redactor: ProviderRedactor,\n event: RawProviderEvent,\n): Promise<void> {\n // Errors from sinks must not crash the LLM call. Forensic capture is\n // best-effort; the structured trace is the system of record.\n try {\n await sink.record(redactor(event))\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction headersToObject(h: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n h.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nexport async function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts, true)\n}\n","/**\n * OpenAI-compatible client. The CLASS is internal; one transport now drives it\n * for public callers.\n *\n * agent-eval never goes looking for a credential — it reads no environment\n * variable to find one — and this module is still not reachable through any\n * export subpath. What reaches a consumer is `createChatClient({ transport:\n * 'openai-compatible', baseUrl, apiKey })`, the sanctioned public route, which\n * constructs this client from an endpoint and a credential the caller passed as\n * values. Anything richer than that transport's options stays in-repo.\n *\n * Three in-repo callers hold the class directly:\n * - `src/analyst/chat-client.ts`, the public transport above;\n * - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose\n * caller is a JSON-RPC client in another language and which therefore\n * configures its own endpoint from its own environment;\n * - the loopback optimizer proxy path (`src/analyst/benchmark-public-model.ts`,\n * `src/analyst/dspy-rlm-engine.ts`), which targets `http://127.0.0.1:<port>/v1`\n * with an ephemeral token and executes nothing itself.\n *\n * The canonical request/result TYPES it defines ARE public — they are the\n * contract every caller-owned transport speaks.\n *\n * OpenAI-compatible `/v1/chat/completions` client with:\n * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).\n * - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).\n * - One retry at temperature 1 when a model explicitly requires it.\n * - Graceful json_schema → json_object degrade on 400 with schema-reject body.\n * - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.\n * - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI\n * directly, cli-bridge subscriptions, and any router that speaks the spec.\n *\n * Usage:\n * const { value, result } = await callLlmJson<MyType>(\n * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },\n * { baseUrl: process.env.AGENT_EVAL_LLM_BASE_URL, apiKey: process.env.AGENT_EVAL_LLM_API_KEY },\n * )\n *\n */\n\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './llm-client/contract'\nimport { parseJsonResult } from './llm-client/json'\nimport { callLlm, callLlmStructured } from './llm-client/request'\nimport {\n pacingStateFor,\n pacingStates,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n} from './llm-client/resilience'\n\nexport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client/accounting'\nexport type {\n LlmCallMetadata,\n LlmCallRequest,\n LlmCallResult,\n LlmChargeBounds,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n LlmToolChoice,\n LlmToolDefinition,\n LlmUsage,\n} from './llm-client/contract'\nexport { LlmCallError, LlmResponseError } from './llm-client/errors'\nexport { extractJsonPayload, stripFencedJson } from './llm-client/json'\nexport { callLlm } from './llm-client/request'\nexport { backoffMs, isTransientLlmError } from './llm-client/resilience'\n\n/**\n * Structured-output call. Returns parsed JSON plus the raw result envelope.\n * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —\n * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept\n * the `response_format.json_schema` shape but DO accept `json_object`.\n */\nexport async function callLlmJson<T = unknown>(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<{ value: T; result: LlmCallResult }> {\n const result = await callLlmStructured(req, opts)\n const value = parseJsonResult<T>(result, opts.jsonPayloadMode ?? 'extract')\n return { value, result }\n}\n\n/**\n * Stateful client — construct once with defaults, call many times.\n * Thin wrapper around the free functions; exists for callers that want\n * to inject a single configured instance into multiple primitives.\n */\nexport class LlmClient {\n readonly maximumAttempts: number\n private readonly opts: LlmClientOptions\n\n constructor(opts: LlmClientOptions = {}) {\n this.opts = opts\n this.maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n resolveMinIntervalMs(opts.minIntervalMs)\n }\n\n private callOptions(per?: LlmClientOptions): LlmClientOptions {\n const options = { ...this.opts, ...per }\n pacingStates.set(options, pacingStateFor(this.opts))\n return options\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = this.callOptions(per)\n return req.jsonSchema ? callLlmStructured(req, options) : callLlm(req, options)\n }\n\n callJson<T = unknown>(\n req: LlmCallRequest,\n per?: LlmClientOptions,\n ): Promise<{ value: T; result: LlmCallResult }> {\n return callLlmJson<T>(req, this.callOptions(per))\n }\n}\n"],"mappings":";;;;;;;AACA,SAAgB,oBACd,GAAG,SACsB;CACzB,MAAM,SAAS,CACb,GAAG,IAAI,IAAI,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS,CAAC,CACpF;CACA,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,IAAI,OAAO,WAAW,GAAG,OAAO,OAAO;CACvC,OAAO,YAAY,IAAI,MAAM;AAC/B;;;;AC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CAAO;AACzB;;;;;;AAOA,IAAa,YAAb,MAAuB;CACrB;CACA;CAEA,YAAY,OAAyB,CAAC,GAAG;EACvC,KAAK,OAAO;EACZ,KAAK,kBAAkB,uBAAuB,KAAK,eAAe;EAClE,qBAAqB,KAAK,aAAa;CACzC;CAEA,YAAoB,KAA0C;EAC5D,MAAM,UAAU;GAAE,GAAG,KAAK;GAAM,GAAG;EAAI;EACvC,aAAa,IAAI,SAAS,eAAe,KAAK,IAAI,CAAC;EACnD,OAAO;CACT;CAEA,KAAK,KAAqB,KAAgD;EACxE,MAAM,UAAU,KAAK,YAAY,GAAG;EACpC,OAAO,IAAI,aAAa,kBAAkB,KAAK,OAAO,IAAI,QAAQ,KAAK,OAAO;CAChF;CAEA,SACE,KACA,KAC8C;EAC9C,OAAO,YAAe,KAAK,KAAK,YAAY,GAAG,CAAC;CAClD;AACF"}
|
|
@@ -10,16 +10,16 @@ import { r as projectCampaignCellQuality, t as campaignCellCostProvenance } from
|
|
|
10
10
|
import { n as CostAccountingIncompleteError, t as CostLedger } from "./cost-ledger-BGZB6yY2.js";
|
|
11
11
|
import { A as surfaceHashMatches, D as surfaceContentHash, E as renderSurfaceDiff, F as assertCampaignSplitIdentity, I as assertCompleteCampaign, L as campaignCoverage, O as surfaceDispatchRef, P as assertCampaignDesign, R as campaignScenarioIdentity, V as formatCoverageFailures, b as FinalEvidenceConflictError, f as campaignBreakdown, j as BackendIntegrityError, k as surfaceHash, m as campaignMeanCompositeOrNull, p as campaignMeanComposite, x as FinalEvidenceError, z as campaignSplitDigest } from "./campaign-evidence-DunzcJGv.js";
|
|
12
12
|
import { t as deepFreezeCanonicalJson } from "./deep-freeze-CurcOQg3.js";
|
|
13
|
-
import { M as fsCampaignStorage, h as isExternalTextCandidate, j as createRunCostLedger } from "./external-optimizer-subprocess-
|
|
13
|
+
import { M as fsCampaignStorage, h as isExternalTextCandidate, j as createRunCostLedger } from "./external-optimizer-subprocess-B_ukPtRD.js";
|
|
14
14
|
import { r as summarizeEvaluationUnits, t as defineEvaluationClaim } from "./claim-BPVuyHuy.js";
|
|
15
15
|
import { d as detectPersonalData, s as redactText, t as REDACTION_VERSION, u as detectCredential } from "./redact-mtkTiJVk.js";
|
|
16
16
|
import { t as detectRewardHacking } from "./reward-hacking-ByuETaIb.js";
|
|
17
|
-
import { t as assertProposalFindings } from "./proposal-findings-
|
|
17
|
+
import { t as assertProposalFindings } from "./proposal-findings-DqLUWsAG.js";
|
|
18
18
|
import { i as runSearch, m as searchExpansionIndex, n as paretoFrontier, o as searchPolicyView, p as SEARCH_KERNEL_SOURCE, r as paretoFrontierWithCrowding, s as EXPANSION_OPERATORS, w as estimateNode } from "./pareto-BiBnQXAE.js";
|
|
19
19
|
import { a as validateSearchLedgerEvent, d as searchNodeId, f as searchTaskSetDigest, i as replaySearchLedgerText, n as openSearchLedger, u as searchCellId } from "./search-ledger-CZRqtFbW.js";
|
|
20
20
|
import { n as searchProposerView, t as renderSearchSummary } from "./search-summary-D4bwYnAE.js";
|
|
21
21
|
import { i as stripFencedJson, n as isRecord } from "./json-BhdsJaOQ.js";
|
|
22
|
-
import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-
|
|
22
|
+
import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-b1ysZVIU.js";
|
|
23
23
|
import { createHash } from "node:crypto";
|
|
24
24
|
import { z } from "zod";
|
|
25
25
|
import { writeFileSync } from "node:fs";
|
|
@@ -5933,4 +5933,4 @@ function firstString(value) {
|
|
|
5933
5933
|
//#endregion
|
|
5934
5934
|
export { planCampaignRun as $, verifySearchHistoryReceipt as A, defaultProductionGate as B, searchEdgeId as C, assertSearchHistoryMatchesState as D, assertSearchHistoryAdmissionOptions as E, asha as F, runCanaries as G, redTeamDataset as H, uniform as I, evaluationUnitMap as J, assertIndependentEvaluationSplit as K, runFinalComparison as L, searchModelIdentity as M, searchProposalExecution as N, createSearchHistoryReceipt as O, searchReceiptAccounting as P, runCampaign as Q, openAutoPr as R, developmentClaim as S, surfaceNode as T, redTeamReport as U, DEFAULT_RED_TEAM_CORPUS as V, scoreRedTeamOutput as W, reserveFinalEvidence as X, exposeFinalEvidence as Y, runEval as Z, beam as _, aggregateRunScore as a, incumbentWithOperatorBandit as b, assertGepaCandidatePopulationSummary as c, costFromLedgerSummary as d, resolveRunDir as et, optimizationTokenUsageFromSummary as f, aide as g, isProposedCandidate as h, transientDispatchFailure as i, campaignCellSearchResult as j, verifySearchHistoryArtifact as k, readGepaCandidatePopulationArtifact as l, runOptimization as m, JudgeParseError as n, cellCachePath as nt, clamp01 as o, runImprovementLoop as p, captureFinalEvidencePolicy as q, isTransientTransportFailure as r, computeManifestHash as rt, executeOptimizationMethod as s, llmJudge as t, buildCellSchedule as tt, combineComparisonCosts as u, crowdedFrontierParent as v, surfaceDiff as w, SearchRecorder as x, incumbent as y, captureJudge as z };
|
|
5935
5935
|
|
|
5936
|
-
//# sourceMappingURL=llm-judge-
|
|
5936
|
+
//# sourceMappingURL=llm-judge-Cybq29bL.js.map
|