@tangle-network/agent-eval 1.0.23 → 1.0.25

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.
Files changed (178) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-C80hNPYb.d.ts → agent-profile-BF1WLMco.d.ts} +3 -3
  4. package/dist/{agent-profile-C80hNPYb.d.ts.map → agent-profile-BF1WLMco.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +14 -14
  6. package/dist/analyst/index.js +9 -9
  7. package/dist/{analyze-runs-DbHQHvDC.d.ts → analyze-runs-BaziIw93.d.ts} +4 -4
  8. package/dist/{analyze-runs-DbHQHvDC.d.ts.map → analyze-runs-BaziIw93.d.ts.map} +1 -1
  9. package/dist/app-grade/index.d.ts +4 -4
  10. package/dist/app-grade/index.js +3 -3
  11. package/dist/{benchmark-command-DkUpd9Q6.js → benchmark-command-DRAHkn4D.js} +8 -9
  12. package/dist/{benchmark-command-DkUpd9Q6.js.map → benchmark-command-DRAHkn4D.js.map} +1 -1
  13. package/dist/benchmarks/index.d.ts +4 -4
  14. package/dist/benchmarks/index.js +3 -3
  15. package/dist/campaign/index.d.ts +7 -7
  16. package/dist/campaign/index.js +4 -4
  17. package/dist/{campaign-D00Tbey-.js → campaign-Cqz2vk2p.js} +6 -6
  18. package/dist/{campaign-D00Tbey-.js.map → campaign-Cqz2vk2p.js.map} +1 -1
  19. package/dist/{chat-client-Zz97O3NB.js → chat-client-PJEzoot9.js} +5 -3
  20. package/dist/chat-client-PJEzoot9.js.map +1 -0
  21. package/dist/{chat-json-call-Dgi7-RH-.js → chat-json-call-CaNO3k0A.js} +2 -2
  22. package/dist/{chat-json-call-Dgi7-RH-.js.map → chat-json-call-CaNO3k0A.js.map} +1 -1
  23. package/dist/cli.js +3 -3
  24. package/dist/{cluster-Cd0MRbr9.d.ts → cluster-CSd0LE_M.d.ts} +4 -2
  25. package/dist/{cluster-Cd0MRbr9.d.ts.map → cluster-CSd0LE_M.d.ts.map} +1 -1
  26. package/dist/{completion-verifier-DFyYFezn.js → completion-verifier-DVZx0x6x.js} +5 -4
  27. package/dist/completion-verifier-DVZx0x6x.js.map +1 -0
  28. package/dist/{completion-verifier-BEpsr3N4.d.ts → completion-verifier-oAgSwdFe.d.ts} +3 -2
  29. package/dist/{completion-verifier-BEpsr3N4.d.ts.map → completion-verifier-oAgSwdFe.d.ts.map} +1 -1
  30. package/dist/contract/index.d.ts +10 -10
  31. package/dist/contract/index.js +7 -8
  32. package/dist/contract/index.js.map +1 -1
  33. package/dist/{cost-ledger-DfhStGcZ.js → cost-ledger-1CwUnVOd.js} +145 -3
  34. package/dist/cost-ledger-1CwUnVOd.js.map +1 -0
  35. package/dist/{decision-point-Di2LATNH.js → decision-point-CQOczIIH.js} +2 -2
  36. package/dist/{decision-point-Di2LATNH.js.map → decision-point-CQOczIIH.js.map} +1 -1
  37. package/dist/{default-registry-CdFbxPnr.js → default-registry-D-xd7KxV.js} +5 -5
  38. package/dist/{default-registry-CdFbxPnr.js.map → default-registry-D-xd7KxV.js.map} +1 -1
  39. package/dist/{default-registry-CjgRr-l7.d.ts → default-registry-DoIBhuS-.d.ts} +7 -7
  40. package/dist/{default-registry-CjgRr-l7.d.ts.map → default-registry-DoIBhuS-.d.ts.map} +1 -1
  41. package/dist/{define-agent-eval-BV16x8C0.js → define-agent-eval-BLVewqJm.js} +3 -3
  42. package/dist/{define-agent-eval-BV16x8C0.js.map → define-agent-eval-BLVewqJm.js.map} +1 -1
  43. package/dist/{define-agent-eval-BQBwKHwF.d.ts → define-agent-eval-Be2Ser8j.d.ts} +7 -7
  44. package/dist/{define-agent-eval-BQBwKHwF.d.ts.map → define-agent-eval-Be2Ser8j.d.ts.map} +1 -1
  45. package/dist/diagnosis/index.d.ts +2 -2
  46. package/dist/{dspy-rlm-engine-cWyn8G1a.js → dspy-rlm-engine-BS_jxE0P.js} +4 -4
  47. package/dist/{dspy-rlm-engine-cWyn8G1a.js.map → dspy-rlm-engine-BS_jxE0P.js.map} +1 -1
  48. package/dist/{engine-s3t6uYH9.d.ts → engine-CPBhCLJR.d.ts} +2 -2
  49. package/dist/{engine-s3t6uYH9.d.ts.map → engine-CPBhCLJR.d.ts.map} +1 -1
  50. package/dist/{evaluation-DRgHKEVV.d.ts → evaluation-BjRgUyst.d.ts} +4 -4
  51. package/dist/{evaluation-DRgHKEVV.d.ts.map → evaluation-BjRgUyst.d.ts.map} +1 -1
  52. package/dist/{evaluation-bU_bhlv-.js → evaluation-C_GJvEEG.js} +2 -2
  53. package/dist/{evaluation-bU_bhlv-.js.map → evaluation-C_GJvEEG.js.map} +1 -1
  54. package/dist/evaluation.d.ts +1 -1
  55. package/dist/evaluation.js +1 -1
  56. package/dist/{exact-types-DTlZSygs.d.ts → exact-types-DEnrf7NX.d.ts} +2 -2
  57. package/dist/{exact-types-DTlZSygs.d.ts.map → exact-types-DEnrf7NX.d.ts.map} +1 -1
  58. package/dist/experiment/index.d.ts +3 -3
  59. package/dist/{external-optimizer-process-2ImGH_LR.js → external-optimizer-process-m9xln7zN.js} +2 -2
  60. package/dist/{external-optimizer-process-2ImGH_LR.js.map → external-optimizer-process-m9xln7zN.js.map} +1 -1
  61. package/dist/{external-optimizer-subprocess-_C_2yriN.js → external-optimizer-subprocess-GO6s84Ov.js} +3 -3
  62. package/dist/{external-optimizer-subprocess-_C_2yriN.js.map → external-optimizer-subprocess-GO6s84Ov.js.map} +1 -1
  63. package/dist/{feedback-trajectory-DrKk79NU.d.ts → feedback-trajectory-DxkG5EPi.d.ts} +3 -3
  64. package/dist/{feedback-trajectory-DrKk79NU.d.ts.map → feedback-trajectory-DxkG5EPi.d.ts.map} +1 -1
  65. package/dist/{findings-store-BSuaV3dN.js → findings-store-CTy71Lnr.js} +5 -5
  66. package/dist/{findings-store-BSuaV3dN.js.map → findings-store-CTy71Lnr.js.map} +1 -1
  67. package/dist/fuzz.js +1 -1
  68. package/dist/{index-DtX456kD.d.ts → index-AjfEHHA8.d.ts} +9 -9
  69. package/dist/{index-DtX456kD.d.ts.map → index-AjfEHHA8.d.ts.map} +1 -1
  70. package/dist/{index-DLZp90hM.d.ts → index-BI9ecONy.d.ts} +10 -10
  71. package/dist/{index-DLZp90hM.d.ts.map → index-BI9ecONy.d.ts.map} +1 -1
  72. package/dist/{index-DAnkXnwF.d.ts → index-BriU7rfL.d.ts} +3 -3
  73. package/dist/{index-DAnkXnwF.d.ts.map → index-BriU7rfL.d.ts.map} +1 -1
  74. package/dist/{index-DjrXBogW.d.ts → index-D-0mg-eu.d.ts} +8 -8
  75. package/dist/{index-DjrXBogW.d.ts.map → index-D-0mg-eu.d.ts.map} +1 -1
  76. package/dist/{index-DNXFzSpc.d.ts → index-DHWFYUVW.d.ts} +2 -2
  77. package/dist/{index-DNXFzSpc.d.ts.map → index-DHWFYUVW.d.ts.map} +1 -1
  78. package/dist/{index-DZ_aqB7v.d.ts → index-JPI2spOx.d.ts} +23 -23
  79. package/dist/{index-DZ_aqB7v.d.ts.map → index-JPI2spOx.d.ts.map} +1 -1
  80. package/dist/{index-DwscLCQX.d.ts → index-VSN1IZQp.d.ts} +3 -3
  81. package/dist/{index-DwscLCQX.d.ts.map → index-VSN1IZQp.d.ts.map} +1 -1
  82. package/dist/index.d.ts +27 -27
  83. package/dist/index.js +62 -21
  84. package/dist/index.js.map +1 -1
  85. package/dist/{integrity-CrmnGB2T.d.ts → integrity-BMyCpnZ8.d.ts} +2 -2
  86. package/dist/{integrity-CrmnGB2T.d.ts.map → integrity-BMyCpnZ8.d.ts.map} +1 -1
  87. package/dist/{judge-gate-CrN0PaAL.js → judge-gate-DsoI5tx7.js} +2 -2
  88. package/dist/{judge-gate-CrN0PaAL.js.map → judge-gate-DsoI5tx7.js.map} +1 -1
  89. package/dist/{kind-factory-CV0FNCMM.js → kind-factory-CJXaE1oF.js} +2 -2
  90. package/dist/{kind-factory-CV0FNCMM.js.map → kind-factory-CJXaE1oF.js.map} +1 -1
  91. package/dist/{llm-client-DMMSg-Ro.js → llm-client-Bj-TooRS.js} +11 -11
  92. package/dist/{llm-client-DMMSg-Ro.js.map → llm-client-Bj-TooRS.js.map} +1 -1
  93. package/dist/{llm-judge-Cbh7OHaO.js → llm-judge-DzAT7Wka.js} +5 -5
  94. package/dist/{llm-judge-Cbh7OHaO.js.map → llm-judge-DzAT7Wka.js.map} +1 -1
  95. package/dist/{matrix-8NhGDcmi.d.ts → matrix-DdniPG_M.d.ts} +3 -4
  96. package/dist/matrix-DdniPG_M.d.ts.map +1 -0
  97. package/dist/meta-eval/index.d.ts +2 -2
  98. package/dist/meta-eval/index.js +2 -2
  99. package/dist/multishot/golden/index.d.ts +1 -1
  100. package/dist/multishot/index.d.ts +3 -2
  101. package/dist/multishot/index.d.ts.map +1 -1
  102. package/dist/multishot/index.js +3 -3
  103. package/dist/multishot/index.js.map +1 -1
  104. package/dist/openapi.json +1 -1
  105. package/dist/{paired-promotion-decision-DJU3fZxH.d.ts → paired-promotion-decision-DawN2o0G.d.ts} +2 -2
  106. package/dist/{paired-promotion-decision-DJU3fZxH.d.ts.map → paired-promotion-decision-DawN2o0G.d.ts.map} +1 -1
  107. package/dist/{prime-protocol-CKxq_-cx.d.ts → prime-protocol-RUPtoYiI.d.ts} +2 -2
  108. package/dist/{prime-protocol-CKxq_-cx.d.ts.map → prime-protocol-RUPtoYiI.d.ts.map} +1 -1
  109. package/dist/{promotion-gate-HDtliGsh.d.ts → promotion-gate-DG_PSJx_.d.ts} +2 -2
  110. package/dist/{promotion-gate-HDtliGsh.d.ts.map → promotion-gate-DG_PSJx_.d.ts.map} +1 -1
  111. package/dist/{proposal-findings-DWs94yT8.js → proposal-findings-CS6LoGGp.js} +2 -2
  112. package/dist/{proposal-findings-DWs94yT8.js.map → proposal-findings-CS6LoGGp.js.map} +1 -1
  113. package/dist/{registry-BnenKvxM.d.ts → registry-BqoX13FD.d.ts} +4 -4
  114. package/dist/{registry-BnenKvxM.d.ts.map → registry-BqoX13FD.d.ts.map} +1 -1
  115. package/dist/reporting.d.ts +4 -4
  116. package/dist/{researcher-DEpedkOZ.d.ts → researcher-BuojS14L.d.ts} +4 -4
  117. package/dist/{researcher-DEpedkOZ.d.ts.map → researcher-BuojS14L.d.ts.map} +1 -1
  118. package/dist/rl.d.ts +8 -8
  119. package/dist/rl.js.map +1 -1
  120. package/dist/rollout/index.d.ts +2 -2
  121. package/dist/rollout/index.js +1 -1
  122. package/dist/{rollout-DWl3Gg6A.js → rollout-B86tqluQ.js} +2 -2
  123. package/dist/{rollout-DWl3Gg6A.js.map → rollout-B86tqluQ.js.map} +1 -1
  124. package/dist/search/index.d.ts +2 -2
  125. package/dist/{search-kernel-CoDJ21q9.d.ts → search-kernel-C4XnLKIW.d.ts} +3 -3
  126. package/dist/{search-kernel-CoDJ21q9.d.ts.map → search-kernel-C4XnLKIW.d.ts.map} +1 -1
  127. package/dist/{sequential-BCzXKQab.d.ts → sequential-1-T2oi1_.d.ts} +2 -2
  128. package/dist/{sequential-BCzXKQab.d.ts.map → sequential-1-T2oi1_.d.ts.map} +1 -1
  129. package/dist/{server-DFVwfoZq.js → server-BQbd__Hr.js} +16 -5
  130. package/dist/server-BQbd__Hr.js.map +1 -0
  131. package/dist/{skillopt-optimization-method-B1Hkfexf.js → skillopt-optimization-method-BtX7xXDd.js} +5 -5
  132. package/dist/{skillopt-optimization-method-B1Hkfexf.js.map → skillopt-optimization-method-BtX7xXDd.js.map} +1 -1
  133. package/dist/{statistical-heldout-e2hbqDui.d.ts → statistical-heldout-Bx1QUDNy.d.ts} +5 -5
  134. package/dist/{statistical-heldout-e2hbqDui.d.ts.map → statistical-heldout-Bx1QUDNy.d.ts.map} +1 -1
  135. package/dist/statistics.d.ts +2 -2
  136. package/dist/{store-otlp-C-jyj3WX.js → store-otlp-CmgKDr0O.js} +2 -2
  137. package/dist/{store-otlp-C-jyj3WX.js.map → store-otlp-CmgKDr0O.js.map} +1 -1
  138. package/dist/{store-tool-spans-DalWlKY8.js → store-tool-spans-CW24axM0.js} +3 -3
  139. package/dist/{store-tool-spans-DalWlKY8.js.map → store-tool-spans-CW24axM0.js.map} +1 -1
  140. package/dist/{store-tool-spans-mlmGj6n3.d.ts → store-tool-spans-kCDPEwjL.d.ts} +5 -5
  141. package/dist/{store-tool-spans-mlmGj6n3.d.ts.map → store-tool-spans-kCDPEwjL.d.ts.map} +1 -1
  142. package/dist/{summary-report-DsiORzPc.d.ts → summary-report-9kwI6jFQ.d.ts} +2 -2
  143. package/dist/{summary-report-DsiORzPc.d.ts.map → summary-report-9kwI6jFQ.d.ts.map} +1 -1
  144. package/dist/supervisor-run/index.d.ts +1 -1
  145. package/dist/{systemone-B93onE_a.d.ts → systemone-CSwi1hp-.d.ts} +7 -7
  146. package/dist/{systemone-B93onE_a.d.ts.map → systemone-CSwi1hp-.d.ts.map} +1 -1
  147. package/dist/{systemone-review-BIggseLt.d.ts → systemone-review-WpWosn3a.d.ts} +2 -2
  148. package/dist/{systemone-review-BIggseLt.d.ts.map → systemone-review-WpWosn3a.d.ts.map} +1 -1
  149. package/dist/systemone.d.ts +3 -3
  150. package/dist/systemone.js +2 -2
  151. package/dist/{tool-groups-CCiATVZw.d.ts → tool-groups-Bcasvncd.d.ts} +3 -3
  152. package/dist/tool-groups-Bcasvncd.d.ts.map +1 -0
  153. package/dist/{trace-questions-B7lkyOlo.d.ts → trace-questions-DI42jXPj.d.ts} +3 -3
  154. package/dist/{trace-questions-B7lkyOlo.d.ts.map → trace-questions-DI42jXPj.d.ts.map} +1 -1
  155. package/dist/trace-repair/index.d.ts +1 -1
  156. package/dist/traces.d.ts +5 -5
  157. package/dist/traces.js +3 -3
  158. package/dist/{types-efIQ03Uo.d.ts → types-ByrbgALT.d.ts} +4 -4
  159. package/dist/{types-efIQ03Uo.d.ts.map → types-ByrbgALT.d.ts.map} +1 -1
  160. package/dist/{types-DUVhW5V1.d.ts → types-CLGrB4Sv.d.ts} +2 -2
  161. package/dist/{types-DUVhW5V1.d.ts.map → types-CLGrB4Sv.d.ts.map} +1 -1
  162. package/dist/{types-3uX8odDK.d.ts → types-D7g2XFTc.d.ts} +2 -2
  163. package/dist/{types-3uX8odDK.d.ts.map → types-D7g2XFTc.d.ts.map} +1 -1
  164. package/dist/{types-Ob1blgI2.d.ts → types-DbGSC2No.d.ts} +2 -2
  165. package/dist/{types-Ob1blgI2.d.ts.map → types-DbGSC2No.d.ts.map} +1 -1
  166. package/dist/wire/index.d.ts +2 -2
  167. package/dist/wire/index.d.ts.map +1 -1
  168. package/dist/wire/index.js +1 -1
  169. package/docs/wire-protocol.md +1 -1
  170. package/package.json +1 -1
  171. package/dist/chat-client-Zz97O3NB.js.map +0 -1
  172. package/dist/completion-verifier-DFyYFezn.js.map +0 -1
  173. package/dist/cost-ledger-DfhStGcZ.js.map +0 -1
  174. package/dist/matrix-8NhGDcmi.d.ts.map +0 -1
  175. package/dist/metrics-zALlR17s.js +0 -146
  176. package/dist/metrics-zALlR17s.js.map +0 -1
  177. package/dist/server-DFVwfoZq.js.map +0 -1
  178. package/dist/tool-groups-CCiATVZw.d.ts.map +0 -1
@@ -1,8 +1,16 @@
1
1
  import { t as AgentEvalError } from "./errors-DeEEV9Vx.js";
2
- import { c as costForTokenPricing } from "./cost-ledger-DfhStGcZ.js";
2
+ import { c as costForTokenPricing } from "./cost-ledger-1CwUnVOd.js";
3
3
  import { a as LlmCallError, o as LlmResponseError, r as parseJsonResult } from "./json-DtvZNAU9.js";
4
4
  import { a as providerFromBaseUrl, i as defaultProviderRedactor } from "./raw-provider-sink-RbaEv2vB.js";
5
5
  import { t as newRecordId } from "./record-id-CWZXFh58.js";
6
+ // src/abort-signal.ts
7
+ /** Combine active cancellation sources without wrapping a single source. */
8
+ function combineAbortSignals(...signals) {
9
+ const active = [...new Set(signals.filter((signal) => signal !== void 0))];
10
+ if (active.length === 0) return void 0;
11
+ if (active.length === 1) return active[0];
12
+ return AbortSignal.any(active);
13
+ }
6
14
  // src/judge-families.ts
7
15
  /** Explicit `provider/...` prefix → family (models.dev / OpenRouter style). */
8
16
  const PROVIDER_PREFIX = {
@@ -276,14 +284,6 @@ function assertCrossFamilyServed(pairs, opts = {}) {
276
284
  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);
277
285
  return list;
278
286
  }
279
- // src/abort-signal.ts
280
- /** Combine active cancellation sources without wrapping a single source. */
281
- function combineAbortSignals(...signals) {
282
- const active = [...new Set(signals.filter((signal) => signal !== void 0))];
283
- if (active.length === 0) return void 0;
284
- if (active.length === 1) return active[0];
285
- return AbortSignal.any(active);
286
- }
287
287
  // src/llm-client/resilience.ts
288
288
  const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 3e5;
289
289
  const DEFAULT_MAXIMUM_ATTEMPTS = process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === void 0 ? 6 : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS);
@@ -899,6 +899,6 @@ var LlmClient = class {
899
899
  return callLlmJson(req, this.callOptions(per));
900
900
  }
901
901
  };
902
- export { assertCrossFamily as _, maximumChargeForLlmRequest as a, combineAbortSignals as c, assertServedModel as d, assertServedModelPolicy as f, CrossFamilyError as g, describeServedModelCheck as h, costReceiptFromLlmError as i, ModelSubstitutionError as l, checkServedModel as m, callLlmJson as n, backoffMs as o, assertServedModels as p, costReceiptFromLlm as r, isTransientLlmError as s, LlmClient as t, assertCrossFamilyServed as u, judgeFamily as v };
902
+ 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 };
903
903
 
904
- //# sourceMappingURL=llm-client-DMMSg-Ro.js.map
904
+ //# sourceMappingURL=llm-client-Bj-TooRS.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"llm-client-DMMSg-Ro.js","names":[],"sources":["../src/judge-families.ts","../src/integrity/served-model.ts","../src/abort-signal.ts","../src/llm-client/resilience.ts","../src/llm-client/wire.ts","../src/llm-client/accounting.ts","../src/llm-client/request.ts","../src/llm-client.ts"],"sourcesContent":["/**\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","/** Combine active cancellation sources without wrapping a single source. */\nexport function combineAbortSignals(\n ...signals: Array<AbortSignal | undefined>\n): AbortSignal | undefined {\n const active = [\n ...new Set(signals.filter((signal): signal is AbortSignal => signal !== undefined)),\n ]\n if (active.length === 0) return undefined\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n","import type { LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\n// Flagship / reasoning models routinely take several minutes on large prompts (a\n// reflection over many failures, a long tool transcript). A tight cap aborts a\n// legitimately-slow but healthy call — and because every retry attempt re-uses\n// the same window, such a model aborts on ALL attempts and the loop throws. The\n// default is generous enough to let those complete, bounded enough that a truly\n// hung call still fails over after retries, and tunable per deployment via\n// TANGLE_LLM_TIMEOUT_MS. Per-call `req.timeoutMs` / `opts.defaultTimeoutMs`\n// still win for callers that know their model's latency.\nexport const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\n\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 6\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nexport function resolveMaximumAttempts(configured: number | undefined): number {\n const attempts = configured ?? DEFAULT_MAXIMUM_ATTEMPTS\n if (!Number.isInteger(attempts) || attempts <= 0) {\n throw new RangeError('LLM maximum attempts must be a positive integer')\n }\n return attempts\n}\n\nexport function resolveMinIntervalMs(configured: number | undefined): number {\n const interval = configured ?? 0\n if (!Number.isFinite(interval) || interval < 0) {\n throw new RangeError('LLM minIntervalMs must be a finite non-negative number')\n }\n return interval\n}\n\n// Weak keys avoid retaining credentials or completed campaigns. LlmClient binds\n// its per-call option copies to the same state as its constructor options.\nexport const pacingStates = new WeakMap<LlmClientOptions, { lastStartedAt?: number }>()\n\nexport function pacingStateFor(opts: LlmClientOptions): { lastStartedAt?: number } {\n let state = pacingStates.get(opts)\n if (!state) {\n state = {}\n pacingStates.set(opts, state)\n }\n return state\n}\n\n// 522/524: Cloudflare edge timeouts (origin connect/respond) — transient\n// exactly like 504. Router deployments serve through Cloudflare, so a long\n// non-streaming call can draw these from the edge, not the origin.\nexport const RETRYABLE_STATUS = new Set([429, 502, 503, 504, 522, 524])\n\n/**\n * Transient transport/network error signatures, matched against an error's\n * name, message, and `code`. Covers fetch/undici network failures, aborts\n * and timeouts, and — critically — HTTP/2 transport faults a keep-alive\n * connection raises mid-response: `terminated`, `NGHTTP2_INTERNAL_ERROR`,\n * `UND_ERR_*`, `other side closed`. Those last ones carry no clean HTTP\n * status; unrecognised, they escape the retry loop and surface as an\n * uncaught rejection.\n */\nconst TRANSIENT_ERROR_PATTERNS: readonly RegExp[] = [\n /AbortError/i,\n /TimeoutError/i,\n /this operation was aborted/i,\n /fetch failed/i,\n /ECONNRESET/i,\n /ETIMEDOUT/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /stream.*ended.*unexpectedly/i,\n /terminated/i,\n /other side closed/i,\n /NGHTTP2/i,\n /UND_ERR/i,\n]\n\n/**\n * True when an error is a transient transport/network fault worth retrying,\n * as opposed to a deterministic failure (4xx schema reject, JSON parse) that\n * a retry cannot fix. Inspects `LlmCallError.status`, then the error's\n * name/message/code, then recurses into `error.cause` — undici nests the\n * real socket fault one or more levels under `.cause`.\n *\n * This is the retry classifier for the package: `callLlm` and\n * `withJudgeRetry` both route through it, so connection failures are treated\n * consistently across transports.\n */\nexport function isTransientLlmError(err: unknown): boolean {\n return classifyTransient(err, 0)\n}\n\nfunction classifyTransient(err: unknown, depth: number): boolean {\n if (err instanceof LlmCallError) return RETRYABLE_STATUS.has(err.status)\n if (!(err instanceof Error)) return false\n // Foreign transport errors can carry a numeric HTTP status without being an\n // LlmCallError. A retryable status is decisive.\n const status = (err as { status?: unknown }).status\n if (typeof status === 'number' && RETRYABLE_STATUS.has(status)) return true\n const code = (err as { code?: unknown }).code\n const haystack = `${err.name}\\n${err.message}\\n${typeof code === 'string' ? code : ''}`\n if (TRANSIENT_ERROR_PATTERNS.some((p) => p.test(haystack))) return true\n const cause = (err as { cause?: unknown }).cause\n if (depth < 4 && cause instanceof Error && cause !== err) {\n return classifyTransient(cause, depth + 1)\n }\n return false\n}\n\nexport function parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')?.trim()\n if (!h) return null\n const asNumber = Number(h)\n if (!Number.isNaN(asNumber)) {\n const delay = asNumber * 1000\n return Number.isFinite(delay) && delay >= 0 ? delay : null\n }\n const asDate = Date.parse(h)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return null\n}\n\n/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */\nexport function backoffMs(attempt: number): number {\n return Math.min(500 * 2 ** attempt, 16_000)\n}\n\n/** Backoff belongs to the caller's operation and must stop when it is cancelled. */\nexport async function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n // A timer above the signed 32-bit limit becomes a near-immediate timeout.\n // Split long server delays rather than truncating Retry-After or overflowing.\n do {\n signal?.throwIfAborted()\n const chunk = Math.min(Math.ceil(ms), 2_147_483_647)\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n reject(signal?.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, chunk)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n ms -= chunk\n } while (ms > 0)\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nexport function deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n","import type {\n LlmCallRequest,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n} from './contract'\n\nexport function providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nexport function buildHeaders(opts: LlmClientOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (opts.authHeader) {\n headers[opts.authHeader.name] = opts.authHeader.value\n } else if (opts.bearer || opts.apiKey) {\n headers.Authorization = `Bearer ${opts.bearer ?? opts.apiKey}`\n }\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n return headers\n}\n\nexport function isSchemaRejection(status: number, body: string): boolean {\n if (status !== 400) return false\n const lower = body.toLowerCase()\n return (\n lower.includes('response_format') ||\n lower.includes('json_schema') ||\n lower.includes('is unavailable') ||\n lower.includes('not supported')\n )\n}\n\nexport function isTemperatureOneRejection(status: number, body: string): boolean {\n if (status !== 400 || !/temperature/i.test(body)) return false\n return (\n /temperature[^.\\n]{0,120}\\b(?:only|must|should|required|requires?)\\b[^.\\n]{0,40}\\b1(?:\\.0+)?\\b/i.test(\n body,\n ) || /\\bonly\\s+1(?:\\.0+)?\\s+is\\s+allowed\\b[^.\\n]{0,120}\\btemperature\\b/i.test(body)\n )\n}\n\nexport function buildBody(\n req: LlmCallRequest,\n forceJsonObject: boolean,\n defaultThinking?: LlmThinkingMode,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model: req.model,\n messages: req.messages.map(encodeWireMessage),\n temperature: req.temperature ?? 0,\n }\n if (req.maxTokens != null) {\n if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens\n else body.max_tokens = req.maxTokens\n }\n if (req.logprobs !== undefined) {\n body.logprobs = true\n body.top_logprobs = req.logprobs.topLogprobs\n }\n if (req.tools !== undefined) body.tools = req.tools\n if (req.toolChoice !== undefined) body.tool_choice = req.toolChoice\n const thinking = req.thinking ?? defaultThinking\n if (thinking !== undefined) {\n body.thinking = { type: thinking }\n }\n\n if (req.jsonSchema && !forceJsonObject) {\n body.response_format = {\n type: 'json_schema',\n json_schema: { name: req.jsonSchema.name, schema: req.jsonSchema.schema, strict: true },\n }\n } else if (req.jsonMode || req.jsonSchema) {\n body.response_format = { type: 'json_object' }\n }\n\n return body\n}\n\nfunction usesMaxCompletionTokens(model: string): boolean {\n return /^gpt-5(?:[.-]|$)/i.test(model)\n}\n\n/** Encode one canonical message as its OpenAI chat-completions wire shape. */\nfunction encodeWireMessage(message: LlmMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content }\n }\n if (message.toolCalls === undefined) {\n return { role: message.role, content: message.content }\n }\n return {\n role: message.role,\n content: message.content,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: call.argumentsJson },\n })),\n }\n}\n\n/**\n * Parse `choices[0].logprobs.content` into the canonical per-token shape.\n * `null` when the provider returned nothing for a request that asked: a\n * provider that ignores `logprobs` is a fact the caller must be able to read,\n * not an error. A malformed entry is a contract violation and throws.\n */\nexport function parseWireLogprobs(\n value: unknown,\n model: string,\n): ReadonlyArray<LlmTokenLogprob> | null {\n if (value === undefined || value === null) return null\n if (!Array.isArray(value)) {\n throw new Error(`LLM response logprobs.content must be an array (model=${model})`)\n }\n return value.map((entry, index) => {\n const record = entry as { token?: unknown; logprob?: unknown; top_logprobs?: unknown } | null\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.token !== 'string' ||\n typeof record.logprob !== 'number' ||\n !Number.isFinite(record.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}] is not a token with a finite logprob (model=${model})`,\n )\n }\n const top = record.top_logprobs\n if (top !== undefined && top !== null && !Array.isArray(top)) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs must be an array (model=${model})`,\n )\n }\n return {\n token: record.token,\n logprob: record.logprob,\n top: (Array.isArray(top) ? top : []).map((alternative, position) => {\n const candidate = alternative as { token?: unknown; logprob?: unknown } | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.token !== 'string' ||\n typeof candidate.logprob !== 'number' ||\n !Number.isFinite(candidate.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs[${position}] is not a token with a finite logprob (model=${model})`,\n )\n }\n return { token: candidate.token, logprob: candidate.logprob }\n }),\n }\n })\n}\n\n/** Parse provider tool_calls into the canonical shape. A malformed entry is a\n * provider-contract violation and throws rather than degrading silently. */\nexport function parseWireToolCalls(value: unknown, model: string): LlmToolCall[] | undefined {\n if (value === undefined || value === null) return undefined\n if (!Array.isArray(value)) {\n throw new Error(`LLM response tool_calls must be an array (model=${model})`)\n }\n if (value.length === 0) return undefined\n return value.map((entry, index) => {\n const record = entry as {\n id?: unknown\n type?: unknown\n function?: { name?: unknown; arguments?: unknown } | null\n } | null\n const fn = record && typeof record === 'object' ? record.function : undefined\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.id !== 'string' ||\n record.id.length === 0 ||\n (record.type !== undefined && record.type !== 'function') ||\n !fn ||\n typeof fn !== 'object' ||\n typeof fn.name !== 'string' ||\n fn.name.length === 0 ||\n typeof fn.arguments !== 'string'\n ) {\n throw new Error(\n `LLM response tool_calls[${index}] is not a function call with string arguments (model=${model})`,\n )\n }\n return { id: record.id, name: fn.name, argumentsJson: fn.arguments }\n })\n}\n","import type { CostReceiptInput, CustomTokenPricing, MaximumCharge } from '../cost-ledger'\nimport type { LlmCallRequest, LlmCallResult, LlmChargeBounds } from './contract'\nimport { LlmResponseError } from './errors'\nimport { resolveMaximumAttempts } from './resilience'\nimport { buildBody } from './wire'\n\nexport function maximumChargeForLlmRequest(\n request: Pick<\n LlmCallRequest,\n 'model' | 'messages' | 'jsonSchema' | 'tools' | 'toolChoice' | 'maxTokens' | 'thinking'\n >,\n options: LlmChargeBounds = {},\n): MaximumCharge | undefined {\n if (request.maxTokens === undefined) return undefined\n if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) {\n throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`)\n }\n if (\n request.messages.some(\n (message) =>\n Array.isArray(message.content) && message.content.some((part) => part.type === 'image_url'),\n )\n ) {\n return undefined\n }\n\n const attempts = resolveMaximumAttempts(options.maximumAttempts)\n const forceJsonObject = options.jsonSchemaTransport === 'json-object'\n // A byte-level tokenizer cannot emit more input tokens than request bytes.\n // Pricing the complete body also covers role/schema framing omitted from content-only estimates.\n const requestBytes = new TextEncoder().encode(\n JSON.stringify(buildBody(request, forceJsonObject, options.thinking)),\n ).byteLength\n // Schema fallback shares the same physical-attempt budget; it cannot buy a second batch.\n const usage = {\n inputTokens: requestBytes * attempts,\n outputTokens: request.maxTokens * attempts,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\n/** Convert a provider result into the canonical paid-call receipt input.\n * The receipt is JSON-clean: absent optional fields are omitted, never carried\n * as explicit-undefined keys. Receipts cross JSON boundaries (the external\n * optimizer's loopback proxy validates them with `assertJsonValue`), where an\n * explicit-undefined value is rejected as non-serializable. */\nexport function costReceiptFromLlm(\n result: LlmCallResult,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput {\n const cachedTokens = result.usage.cachedPromptTokens ?? 0\n const inputTokens = Math.max(0, result.usage.promptTokens - cachedTokens)\n const providerCostUsd = providerReportedCost(result.raw)\n return {\n model: result.model,\n inputTokens,\n outputTokens: result.usage.completionTokens,\n ...(result.usage.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: result.usage.reasoningTokens }),\n ...(cachedTokens > 0 ? { cachedTokens } : {}),\n ...(providerCostUsd === undefined\n ? customTokenPricing && result.usage.captured !== false\n ? { customTokenPricing }\n : result.costUsd === null\n ? {}\n : { estimatedCostUsd: result.costUsd }\n : { actualCostUsd: providerCostUsd }),\n usageUnknown: result.usage.captured === false,\n }\n}\n\nexport function providerReportedCost(raw: Record<string, unknown>): number | undefined {\n const value = raw._response_cost ?? raw.cost_usd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/** Structured-response failures retain their completed provider receipt. */\nexport function costReceiptFromLlmError(\n error: Error,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput | undefined {\n return error instanceof LlmResponseError\n ? costReceiptFromLlm(error.result, customTokenPricing)\n : undefined\n}\n","import { combineAbortSignals } from '../abort-signal'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { assertServedModel as assertServedModelIdentity } from '../integrity/served-model'\nimport { newRecordId } from '../record-id'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from '../trace/raw-provider-sink'\nimport { providerReportedCost } from './accounting'\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\nimport {\n backoffMs,\n DEFAULT_TIMEOUT_MS,\n deadlineExceeded,\n isTransientLlmError,\n pacingStateFor,\n parseRetryAfter,\n RETRYABLE_STATUS,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n sleep,\n} from './resilience'\nimport {\n buildBody,\n buildHeaders,\n isSchemaRejection,\n isTemperatureOneRejection,\n parseWireLogprobs,\n parseWireToolCalls,\n providerTokenCount,\n} from './wire'\n\n/**\n * Low-level call. Returns raw content + usage + cost. Retries on transient\n * failures; does NOT degrade schema here — callers that want graceful\n * degrade use `callLlmJson`.\n */\nexport async function callLlm(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts(req, opts, false)\n}\n\n/** One retry owner for raw and structured calls. Fallback changes the next\n * request, not the attempt allowance, deadline origin, or raw-event sequence. */\n/** What one call shares across its attempts: the resolved options, pacing, deadline and the request as it now stands. */\ninterface AttemptRun {\n readonly req: LlmCallRequest\n readonly opts: LlmClientOptions\n readonly allowSchemaFallback: boolean\n readonly baseUrl: string\n readonly url: string\n readonly timeoutMs: number\n readonly maximumAttempts: number\n readonly minIntervalMs: number\n readonly pacing: ReturnType<typeof pacingStateFor>\n readonly headers: ReturnType<typeof buildHeaders>\n readonly provider: string\n readonly deadlineStart: number\n readonly remainingMs: () => number\n readonly retryDelay: (ms: number) => Promise<void>\n effectiveRequest: LlmCallRequest\n lastErr: unknown\n}\n\n/** How one attempt ended without a result or a thrown error. */\ntype AttemptOutcome =\n | { kind: 'result'; result: LlmCallResult }\n | { kind: 'retry' }\n | { kind: 'exhausted' }\n\n/** Which of an attempt's raw events were already written, so the failure path records at most one error. */\ninterface AttemptState {\n dispatched: boolean\n errorRecorded: boolean\n}\n\nconst ENDPOINT = '/chat/completions'\n\nfunction startAttemptRun(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): AttemptRun {\n // No default endpoint. This client is internal to the `agent-eval` binary\n // and the loopback optimizer proxy; both name their endpoint explicitly, and\n // a fallback would let a misconfigured caller bill an unintended provider.\n if (!opts.baseUrl) throw new Error('callLlm: opts.baseUrl is required')\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n const remainingMs = () =>\n deadlineMs === undefined ? Infinity : Math.max(0, deadlineMs - (Date.now() - deadlineStart))\n const run: AttemptRun = {\n req,\n opts,\n allowSchemaFallback,\n baseUrl,\n url: `${baseUrl}${ENDPOINT}`,\n timeoutMs: req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS,\n maximumAttempts: resolveMaximumAttempts(opts.maximumAttempts),\n minIntervalMs: resolveMinIntervalMs(opts.minIntervalMs),\n pacing: pacingStateFor(opts),\n headers: buildHeaders(opts),\n provider: opts.provider ?? providerFromBaseUrl(baseUrl),\n deadlineStart,\n remainingMs,\n retryDelay: (ms) => sleep(Math.min(ms, remainingMs()), opts.signal),\n effectiveRequest: req,\n lastErr: undefined,\n }\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n return run\n}\n\nfunction deadlineError(run: AttemptRun): Error | DOMException {\n return run.lastErr instanceof Error\n ? run.lastErr\n : new DOMException('callLlm deadline exceeded', 'TimeoutError')\n}\n\n/** Write one raw provider event for this attempt. Does nothing without a sink. */\nasync function recordAttemptEvent(\n run: AttemptRun,\n attempt: number,\n fields: Pick<RawProviderEvent, 'direction' | 'timestamp'> & Partial<RawProviderEvent>,\n): Promise<void> {\n const { opts } = run\n if (!opts.rawSink) return\n await recordRaw(opts.rawSink, opts.redactor ?? defaultProviderRedactor, {\n eventId: newRecordId(),\n runId: opts.traceContext?.runId,\n spanId: opts.traceContext?.spanId,\n provider: run.provider,\n model: run.req.model,\n endpoint: ENDPOINT,\n baseUrl: run.baseUrl,\n attemptIndex: attempt,\n ...fields,\n redactedFields: [],\n })\n}\n\n/**\n * Wait for this client's pacing slot, and claim it. Every wake rechecks, so concurrent waiters\n * cannot dispatch a catch-up burst; the claim is made in the same synchronous step that finds the\n * slot free, so no other waiter can slip in between the check and the claim.\n */\nasync function awaitPacingSlot(run: AttemptRun): Promise<number> {\n const { opts, pacing, minIntervalMs } = run\n while (true) {\n opts.signal?.throwIfAborted()\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const waitMs =\n pacing.lastStartedAt === undefined ? 0 : pacing.lastStartedAt + minIntervalMs - Date.now()\n if (waitMs <= 0) {\n // Queue time consumes the operation deadline, not the HTTP timeout.\n const started = Date.now()\n pacing.lastStartedAt = started\n return started\n }\n await run.retryDelay(waitMs)\n }\n}\n\n/** Answer a non-2xx response: retry with an adjusted request or after a wait, give up, or throw its error. */\nasync function handleHttpFailure(\n run: AttemptRun,\n attempt: number,\n res: Response,\n body: string,\n responseHeaders: Record<string, string> | undefined,\n started: number,\n state: AttemptState,\n): Promise<AttemptOutcome> {\n const { req, opts, maximumAttempts, deadlineStart } = run\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: body,\n errorMessage: `HTTP ${res.status}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n const canRetry =\n attempt < maximumAttempts - 1 && !deadlineExceeded(deadlineStart, opts.deadlineMs)\n if (\n isTemperatureOneRejection(res.status, body) &&\n run.effectiveRequest.temperature !== 1 &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, temperature: 1 }\n return { kind: 'retry' }\n }\n if (\n run.allowSchemaFallback &&\n opts.jsonSchemaTransport !== 'json-object' &&\n run.effectiveRequest.jsonSchema &&\n isSchemaRejection(res.status, body) &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, jsonMode: true, jsonSchema: undefined }\n return { kind: 'retry' }\n }\n if (RETRYABLE_STATUS.has(res.status) && canRetry) {\n run.lastErr = err\n const wait = parseRetryAfter(res.headers) ?? backoffMs(attempt)\n // A wait the deadline cannot cover ends the call with this answer. Sleeping to the\n // deadline let a timer that fired a millisecond early start one more attempt with no time\n // left, whose abort replaced the server's status (agent-eval publish run 37238259408).\n if (wait >= run.remainingMs()) {\n // A caller abort that landed while the answer was recorded still wins, as the\n // retry wait would have reported it.\n opts.signal?.throwIfAborted()\n return { kind: 'exhausted' }\n }\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n throw err\n}\n\n/** Turn a parsed completion into the call result: content, tool calls, usage with its completeness, and cost. */\nfunction parseCompletion(\n run: AttemptRun,\n json: Record<string, unknown>,\n started: number,\n): LlmCallResult {\n const { req, opts } = run\n const choice = (\n json.choices as\n | Array<{\n message?: { content?: string | null; tool_calls?: unknown }\n finish_reason?: string | null\n logprobs?: { content?: unknown } | null\n }>\n | undefined\n )?.[0]\n const toolCalls = parseWireToolCalls(choice?.message?.tool_calls, req.model)\n const usageRaw =\n json.usage && typeof json.usage === 'object' && !Array.isArray(json.usage)\n ? (json.usage as Record<string, unknown>)\n : undefined\n const promptTokens = providerTokenCount(usageRaw?.prompt_tokens)\n const completionTokens = providerTokenCount(usageRaw?.completion_tokens)\n const totalTokens = providerTokenCount(usageRaw?.total_tokens)\n const completionDetails =\n usageRaw?.completion_tokens_details &&\n typeof usageRaw.completion_tokens_details === 'object' &&\n !Array.isArray(usageRaw.completion_tokens_details)\n ? (usageRaw.completion_tokens_details as Record<string, unknown>)\n : undefined\n const reasoningRaw = completionDetails?.reasoning_tokens\n const reasoningTokens = reasoningRaw === undefined ? undefined : providerTokenCount(reasoningRaw)\n const cachedRaw =\n usageRaw?.prompt_tokens_details &&\n typeof usageRaw.prompt_tokens_details === 'object' &&\n !Array.isArray(usageRaw.prompt_tokens_details)\n ? (usageRaw.prompt_tokens_details as Record<string, unknown>).cached_tokens\n : undefined\n const cachedPromptTokens = cachedRaw === undefined ? undefined : providerTokenCount(cachedRaw)\n const usageCaptured =\n promptTokens !== undefined &&\n completionTokens !== undefined &&\n (reasoningRaw === undefined ||\n (reasoningTokens !== undefined && reasoningTokens <= completionTokens)) &&\n (cachedRaw === undefined ||\n (cachedPromptTokens !== undefined && cachedPromptTokens <= promptTokens)) &&\n (totalTokens === undefined || totalTokens === promptTokens + completionTokens)\n const costFromProxy = providerReportedCost(json)\n const content = choice?.message?.content ?? ''\n\n const configuredCost =\n typeof costFromProxy !== 'number' && usageCaptured && opts.customTokenPricing\n ? costForTokenPricing(opts.customTokenPricing, {\n inputTokens: promptTokens! - (cachedPromptTokens ?? 0),\n ...(cachedPromptTokens ? { cachedTokens: cachedPromptTokens } : {}),\n outputTokens: completionTokens!,\n })\n : undefined\n\n // The echoed id, kept separate from the attribution id: a provider that\n // omits it must read as \"unproven\", never as \"the model I asked for\".\n const servedModel = typeof json.model === 'string' && json.model.trim() !== '' ? json.model : null\n if (opts.assertServedModel) {\n assertServedModelIdentity(\n req.model,\n servedModel,\n opts.assertServedModel === true ? {} : opts.assertServedModel,\n )\n }\n\n return {\n content,\n ...(toolCalls === undefined ? {} : { toolCalls }),\n ...(req.logprobs === undefined\n ? {}\n : { logprobs: parseWireLogprobs(choice?.logprobs?.content, req.model) }),\n finishReason: choice?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n usage: {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: totalTokens ?? (promptTokens ?? 0) + (completionTokens ?? 0),\n captured: usageCaptured,\n reasoningTokens,\n cachedPromptTokens,\n },\n costUsd: typeof costFromProxy === 'number' ? costFromProxy : (configuredCost ?? null),\n model: servedModel ?? req.model,\n servedModel,\n durationMs: Date.now() - started,\n raw: json,\n }\n}\n\n/** One attempt: pace, dispatch, read the answer. A failure either becomes a retry outcome or is thrown. */\nasync function runAttempt(run: AttemptRun, attempt: number): Promise<AttemptOutcome> {\n const { opts } = run\n const callerSignal = opts.signal\n // A caller cancel is fatal — never retried. Checking before each attempt\n // means an already-aborted signal short-circuits without firing fetch.\n if (callerSignal?.aborted) {\n throw new DOMException('callLlm aborted by caller signal', 'AbortError')\n }\n // Stop retrying once the cross-attempt budget is spent rather than burning\n // a full per-attempt timeout on each remaining retry.\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const requestBody = buildBody(\n run.effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n const controller = new AbortController()\n const attemptSignal = combineAbortSignals(controller.signal, callerSignal)!\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n let started = Date.now()\n // An attempt cancelled or timed out while queued never reached the\n // provider, so it leaves no request or error event in the raw log.\n const state: AttemptState = { dispatched: false, errorRecorded: false }\n try {\n if (run.minIntervalMs > 0) {\n started = await awaitPacingSlot(run)\n } else {\n // Claim the slot before any await so a concurrent waiter cannot take it.\n run.pacing.lastStartedAt = started\n }\n state.dispatched = true\n timeoutHandle = setTimeout(() => controller.abort(), Math.min(run.timeoutMs, run.remainingMs()))\n await recordAttemptEvent(run, attempt, {\n direction: 'request',\n timestamp: started,\n requestHeaders: run.headers,\n requestBody,\n })\n attemptSignal.throwIfAborted()\n const res = await (opts.fetch ?? globalThis.fetch)(run.url, {\n method: 'POST',\n headers: run.headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n const responseHeaders = opts.rawSink ? headersToObject(res.headers) : undefined\n // Headers are not completion: the same timeout/cancellation covers either response body.\n const text = await res.text()\n attemptSignal.throwIfAborted()\n clearTimeout(timeoutHandle)\n\n if (!res.ok) {\n return await handleHttpFailure(run, attempt, res, text, responseHeaders, started, state)\n }\n\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: text,\n errorMessage: `non-JSON response: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n throw parseErr\n }\n await recordAttemptEvent(run, attempt, {\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n })\n return { kind: 'result', result: parseCompletion(run, json, started) }\n } catch (err) {\n clearTimeout(timeoutHandle)\n run.lastErr = err\n // Record only if neither the !res.ok branch nor the JSON.parse catch\n // already produced an error event for this attempt. Covers network\n // failures, timeouts, and aborts.\n if (state.dispatched && !state.errorRecorded) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n }\n // A caller cancel is fatal even though an AbortError matches the\n // transient patterns — a cancelled call must surface immediately, not\n // be retried against the same dead intent.\n if (callerSignal?.aborted) throw err\n const wait = backoffMs(attempt)\n if (\n attempt < run.maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(run.deadlineStart, opts.deadlineMs) &&\n wait < run.remainingMs()\n ) {\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n callerSignal?.throwIfAborted()\n throw err\n } finally {\n clearTimeout(timeoutHandle)\n }\n}\n\nasync function callLlmAttempts(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): Promise<LlmCallResult> {\n const run = startAttemptRun(req, opts, allowSchemaFallback)\n for (let attempt = 0; attempt < run.maximumAttempts; attempt++) {\n const outcome = await runAttempt(run, attempt)\n if (outcome.kind === 'result') return outcome.result\n if (outcome.kind === 'exhausted') break\n }\n throw run.lastErr instanceof Error ? run.lastErr : new Error(String(run.lastErr))\n}\n\nasync function recordRaw(\n sink: RawProviderSink,\n redactor: ProviderRedactor,\n event: RawProviderEvent,\n): Promise<void> {\n // Errors from sinks must not crash the LLM call. Forensic capture is\n // best-effort; the structured trace is the system of record.\n try {\n await sink.record(redactor(event))\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction headersToObject(h: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n h.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nexport async function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts, true)\n}\n","/**\n * OpenAI-compatible client. The CLASS is internal; one transport now drives it\n * for public callers.\n *\n * agent-eval never goes looking for a credential — it reads no environment\n * variable to find one — and this module is still not reachable through any\n * export subpath. What reaches a consumer is `createChatClient({ transport:\n * 'openai-compatible', baseUrl, apiKey })`, the sanctioned public route, which\n * constructs this client from an endpoint and a credential the caller passed as\n * values. Anything richer than that transport's options stays in-repo.\n *\n * Three in-repo callers hold the class directly:\n * - `src/analyst/chat-client.ts`, the public transport above;\n * - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose\n * caller is a JSON-RPC client in another language and which therefore\n * configures its own endpoint from its own environment;\n * - the loopback optimizer proxy path (`src/analyst/benchmark-public-model.ts`,\n * `src/analyst/dspy-rlm-engine.ts`), which targets `http://127.0.0.1:<port>/v1`\n * with an ephemeral token and executes nothing itself.\n *\n * The canonical request/result TYPES it defines ARE public — they are the\n * contract every caller-owned transport speaks.\n *\n * OpenAI-compatible `/v1/chat/completions` client with:\n * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).\n * - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).\n * - One retry at temperature 1 when a model explicitly requires it.\n * - Graceful json_schema → json_object degrade on 400 with schema-reject body.\n * - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.\n * - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI\n * directly, cli-bridge subscriptions, and any router that speaks the spec.\n *\n * Usage:\n * const { value, result } = await callLlmJson<MyType>(\n * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },\n * { baseUrl: process.env.AGENT_EVAL_LLM_BASE_URL, apiKey: process.env.AGENT_EVAL_LLM_API_KEY },\n * )\n *\n */\n\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './llm-client/contract'\nimport { parseJsonResult } from './llm-client/json'\nimport { callLlm, callLlmStructured } from './llm-client/request'\nimport {\n pacingStateFor,\n pacingStates,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n} from './llm-client/resilience'\n\nexport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client/accounting'\nexport type {\n LlmCallMetadata,\n LlmCallRequest,\n LlmCallResult,\n LlmChargeBounds,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n LlmToolChoice,\n LlmToolDefinition,\n LlmUsage,\n} from './llm-client/contract'\nexport { LlmCallError, LlmResponseError } from './llm-client/errors'\nexport { extractJsonPayload, stripFencedJson } from './llm-client/json'\nexport { callLlm } from './llm-client/request'\nexport { backoffMs, isTransientLlmError } from './llm-client/resilience'\n\n/**\n * Structured-output call. Returns parsed JSON plus the raw result envelope.\n * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —\n * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept\n * the `response_format.json_schema` shape but DO accept `json_object`.\n */\nexport async function callLlmJson<T = unknown>(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<{ value: T; result: LlmCallResult }> {\n const result = await callLlmStructured(req, opts)\n const value = parseJsonResult<T>(result, opts.jsonPayloadMode ?? 'extract')\n return { value, result }\n}\n\n/**\n * Stateful client — construct once with defaults, call many times.\n * Thin wrapper around the free functions; exists for callers that want\n * to inject a single configured instance into multiple primitives.\n */\nexport class LlmClient {\n readonly maximumAttempts: number\n private readonly opts: LlmClientOptions\n\n constructor(opts: LlmClientOptions = {}) {\n this.opts = opts\n this.maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n resolveMinIntervalMs(opts.minIntervalMs)\n }\n\n private callOptions(per?: LlmClientOptions): LlmClientOptions {\n const options = { ...this.opts, ...per }\n pacingStates.set(options, pacingStateFor(this.opts))\n return options\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = this.callOptions(per)\n return req.jsonSchema ? callLlmStructured(req, options) : callLlm(req, options)\n }\n\n callJson<T = unknown>(\n req: LlmCallRequest,\n per?: LlmClientOptions,\n ): Promise<{ value: T; result: LlmCallResult }> {\n return callLlmJson<T>(req, this.callOptions(per))\n }\n}\n"],"mappings":";;;;;;;AA2BA,MAAM,kBAA+C;CACnD,WAAW;CACX,QAAQ;CACR,gBAAgB;CAChB,QAAQ;CACR,iBAAiB;CACjB,MAAM;CACN,cAAc;CACd,SAAS;CACT,WAAW;CACX,UAAU;CACV,KAAK;CACL,MAAM;CACN,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,UAAU;CACV,YAAY;CACZ,MAAM;CACN,aAAa;CACb,OAAO;CACP,SAAS;CACT,KAAK;CACL,QAAQ;CACR,KAAK;AACP;;AAGA,MAAM,gBAA8C;CAClD,CAAC,WAAW,WAAW;CAIvB,CAAC,uCAAuC,WAAW;CACnD,CAAC,0DAA0D,QAAQ;CACnE,CAAC,4BAA4B,QAAQ;CACrC,CAAC,UAAU,MAAM;CACjB,CAAC,oCAAoC,SAAS;CAC9C,CAAC,aAAa,UAAU;CACxB,CAAC,SAAS,KAAK;CACf,CAAC,SAAS,MAAM;CAChB,CAAC,oBAAoB,QAAQ;CAC7B,CAAC,qBAAqB,QAAQ;CAC9B,CAAC,sBAAsB,UAAU;CACjC,CAAC,4BAA4B,OAAO;AACtC;;;;;;;AAQA,SAAgB,YAAY,SAA8B;CACxD,MAAM,KAAK,QAAQ,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,YAAY;CACrD,MAAM,QAAQ,GAAG,QAAQ,GAAG;CAC5B,IAAI,QAAQ,GAAG;EACb,MAAM,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I,UAAU,IAAI,MAAM,OAAO,IAAI,OAAO,CAAC;AAClF;AAEA,eAAe,UACb,MACA,UACA,OACe;CAGf,IAAI;EACF,MAAM,KAAK,OAAO,SAAS,KAAK,CAAC;CACnC,QAAQ,CAER;AACF;AAEA,SAAS,gBAAgB,GAAoC;CAC3D,MAAM,MAA8B,CAAC;CACrC,EAAE,SAAS,OAAO,QAAQ;EACxB,IAAI,OAAO;CACb,CAAC;CACD,OAAO;AACT;;AAGA,eAAsB,kBACpB,KACA,OAAyB,CAAC,GACF;CACxB,OAAO,gBAAgB;EAAE,GAAG;EAAK,UAAU,IAAI,YAAY,CAAC,IAAI;CAAW,GAAG,MAAM,IAAI;AAC1F;;;;;;;;AC3ZA,eAAsB,YACpB,KACA,OAAyB,CAAC,GACoB;CAC9C,MAAM,SAAS,MAAM,kBAAkB,KAAK,IAAI;CAEhD,OAAO;EAAE,OADK,gBAAmB,QAAQ,KAAK,mBAAmB,SACpD;EAAG;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"}
1
+ {"version":3,"file":"llm-client-Bj-TooRS.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;;;ACiBA,MAAM,kBAA+C;CACnD,WAAW;CACX,QAAQ;CACR,gBAAgB;CAChB,QAAQ;CACR,iBAAiB;CACjB,MAAM;CACN,cAAc;CACd,SAAS;CACT,WAAW;CACX,UAAU;CACV,KAAK;CACL,MAAM;CACN,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,UAAU;CACV,YAAY;CACZ,MAAM;CACN,aAAa;CACb,OAAO;CACP,SAAS;CACT,KAAK;CACL,QAAQ;CACR,KAAK;AACP;;AAGA,MAAM,gBAA8C;CAClD,CAAC,WAAW,WAAW;CAIvB,CAAC,uCAAuC,WAAW;CACnD,CAAC,0DAA0D,QAAQ;CACnE,CAAC,4BAA4B,QAAQ;CACrC,CAAC,UAAU,MAAM;CACjB,CAAC,oCAAoC,SAAS;CAC9C,CAAC,aAAa,UAAU;CACxB,CAAC,SAAS,KAAK;CACf,CAAC,SAAS,MAAM;CAChB,CAAC,oBAAoB,QAAQ;CAC7B,CAAC,qBAAqB,QAAQ;CAC9B,CAAC,sBAAsB,UAAU;CACjC,CAAC,4BAA4B,OAAO;AACtC;;;;;;;AAQA,SAAgB,YAAY,SAA8B;CACxD,MAAM,KAAK,QAAQ,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,YAAY;CACrD,MAAM,QAAQ,GAAG,QAAQ,GAAG;CAC5B,IAAI,QAAQ,GAAG;EACb,MAAM,SAAS,GAAG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AO;CACb,CAAC;CACD,OAAO;AACT;;AAGA,eAAsB,kBACpB,KACA,OAAyB,CAAC,GACF;CACxB,OAAO,gBAAgB;EAAE,GAAG;EAAK,UAAU,IAAI,YAAY,CAAC,IAAI;CAAW,GAAG,MAAM,IAAI;AAC1F;;;;;;;;AC3ZA,eAAsB,YACpB,KACA,OAAyB,CAAC,GACoB;CAC9C,MAAM,SAAS,MAAM,kBAAkB,KAAK,IAAI;CAEhD,OAAO;EAAE,OADK,gBAAmB,QAAQ,KAAK,mBAAmB,SACpD;EAAG;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"}
@@ -8,20 +8,20 @@ import { a as heldoutSignificance, i as dimensionRegressions, o as pairHoldout }
8
8
  import { d as mapConcurrent } from "./journal-CTX5uK-n.js";
9
9
  import { n as contentHash } from "./verdict-cache-BVH-fl18.js";
10
10
  import { r as projectCampaignCellQuality, t as campaignCellCostProvenance } from "./run-record-DTTx9Ktr.js";
11
- import { n as CostAccountingIncompleteError, t as CostLedger } from "./cost-ledger-DfhStGcZ.js";
11
+ import { n as CostAccountingIncompleteError, t as CostLedger } from "./cost-ledger-1CwUnVOd.js";
12
12
  import { A as campaignSplitDigest, D as assertCompleteCampaign, E as assertCampaignSplitIdentity, M as formatCoverageFailures, O as campaignCoverage, S as BackendIntegrityError, T as assertCampaignDesign, b as FinalEvidenceError, f as campaignBreakdown, k as campaignScenarioIdentity, m as campaignMeanCompositeOrNull, p as campaignMeanComposite, y as FinalEvidenceConflictError } from "./campaign-evidence-CVNKiK0q.js";
13
13
  import { t as deepFreezeCanonicalJson } from "./deep-freeze-CK8-2W7p.js";
14
- import { M as fsCampaignStorage, h as isExternalTextCandidate, j as createRunCostLedger } from "./external-optimizer-subprocess-_C_2yriN.js";
14
+ import { M as fsCampaignStorage, h as isExternalTextCandidate, j as createRunCostLedger } from "./external-optimizer-subprocess-GO6s84Ov.js";
15
15
  import { c as surfaceDispatchRef, l as surfaceHash, o as renderSurfaceDiff, s as surfaceContentHash, u as surfaceHashMatches } from "./json-recovery-DK4MDm5r.js";
16
16
  import { r as summarizeEvaluationUnits, t as defineEvaluationClaim } from "./claim-Dod_mjk3.js";
17
17
  import { c as redactText, m as detectPersonalData, n as REDACTION_VERSION, p as detectCredential } from "./redact-zp_ILC4l.js";
18
18
  import { t as detectRewardHacking } from "./reward-hacking-BYiDFbIl.js";
19
- import { t as assertProposalFindings } from "./proposal-findings-DWs94yT8.js";
19
+ import { t as assertProposalFindings } from "./proposal-findings-CS6LoGGp.js";
20
20
  import { S as estimateNode, i as runSearch, m as searchExpansionIndex, n as paretoFrontier, o as searchPolicyView, p as SEARCH_KERNEL_SOURCE, r as paretoFrontierWithCrowding, s as EXPANSION_OPERATORS } from "./pareto-UzjB3ZBk.js";
21
21
  import { a as validateSearchLedgerEvent, d as searchNodeId, f as searchTaskSetDigest, i as replaySearchLedgerText, n as openSearchLedger, u as searchCellId } from "./search-ledger-9liYyZf5.js";
22
22
  import { n as searchProposerView, t as renderSearchSummary } from "./search-summary-CISbbxyr.js";
23
23
  import { i as stripFencedJson, n as isRecord } from "./json-DtvZNAU9.js";
24
- import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-DMMSg-Ro.js";
24
+ import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-Bj-TooRS.js";
25
25
  import { t as JudgeParseError } from "./judges-BLxg5p8E.js";
26
26
  import { createHash } from "node:crypto";
27
27
  import { z } from "zod";
@@ -5875,4 +5875,4 @@ function firstString(value) {
5875
5875
  }
5876
5876
  export { resolveRunDir as $, campaignCellSearchResult as A, DEFAULT_RED_TEAM_CORPUS as B, surfaceDiff as C, createSearchHistoryReceipt as D, assertSearchHistoryMatchesState as E, uniform as F, assertIndependentEvaluationSplit as G, redTeamReport as H, runFinalComparison as I, exposeFinalEvidence as J, captureFinalEvidencePolicy as K, openAutoPr as L, searchProposalExecution as M, searchReceiptAccounting as N, verifySearchHistoryArtifact as O, asha as P, planCampaignRun as Q, captureJudge as R, searchEdgeId as S, assertSearchHistoryAdmissionOptions as T, scoreRedTeamOutput as U, redTeamDataset as V, runCanaries as W, runEval as X, reserveFinalEvidence as Y, runCampaign as Z, crowdedFrontierParent as _, clamp01 as a, SearchRecorder as b, readGepaCandidatePopulationArtifact as c, optimizationTokenUsageFromSummary as d, buildCellSchedule as et, runImprovementLoop as f, beam as g, aide as h, aggregateRunScore as i, searchModelIdentity as j, verifySearchHistoryReceipt as k, combineComparisonCosts as l, isProposedCandidate as m, isTransientTransportFailure as n, computeManifestHash as nt, executeOptimizationMethod as o, runOptimization as p, evaluationUnitMap as q, transientDispatchFailure as r, assertGepaCandidatePopulationSummary as s, llmJudge as t, cellCachePath as tt, costFromLedgerSummary as u, incumbent as v, surfaceNode as w, developmentClaim as x, incumbentWithOperatorBandit as y, defaultProductionGate as z };
5877
5877
 
5878
- //# sourceMappingURL=llm-judge-Cbh7OHaO.js.map
5878
+ //# sourceMappingURL=llm-judge-DzAT7Wka.js.map