@tangle-network/agent-eval 1.0.40 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-hytrwAnN.d.ts → agent-profile-BSgtn-k-.d.ts} +83 -4
  4. package/dist/agent-profile-BSgtn-k-.d.ts.map +1 -0
  5. package/dist/{agent-profile-DgbRJpSi.js → agent-profile-CCw6EXWW.js} +2 -2
  6. package/dist/{agent-profile-DgbRJpSi.js.map → agent-profile-CCw6EXWW.js.map} +1 -1
  7. package/dist/{agent-profile-cell-7Mt0wBkl.js → agent-profile-cell-CUthydZB.js} +2 -2
  8. package/dist/{agent-profile-cell-7Mt0wBkl.js.map → agent-profile-cell-CUthydZB.js.map} +1 -1
  9. package/dist/analyst/index.d.ts +13 -13
  10. package/dist/analyst/index.d.ts.map +1 -1
  11. package/dist/analyst/index.js +15 -15
  12. package/dist/analyst/index.js.map +1 -1
  13. package/dist/{analyze-runs-DqHx3Q_g.js → analyze-runs-C_9cXPZn.js} +9 -9
  14. package/dist/{analyze-runs-DqHx3Q_g.js.map → analyze-runs-C_9cXPZn.js.map} +1 -1
  15. package/dist/{analyze-runs-Ctuz-dd3.d.ts → analyze-runs-zEI7yAH_.d.ts} +2 -2
  16. package/dist/{analyze-runs-Ctuz-dd3.d.ts.map → analyze-runs-zEI7yAH_.d.ts.map} +1 -1
  17. package/dist/app-grade/index.d.ts +3 -3
  18. package/dist/app-grade/index.js +3 -3
  19. package/dist/authenticity/index.d.ts.map +1 -1
  20. package/dist/authenticity/index.js.map +1 -1
  21. package/dist/{benchmark-command-CJw3ijDV.js → benchmark-command-XLXa7I98.js} +14 -13
  22. package/dist/benchmark-command-XLXa7I98.js.map +1 -0
  23. package/dist/benchmarks/index.d.ts +8 -4
  24. package/dist/benchmarks/index.d.ts.map +1 -1
  25. package/dist/benchmarks/index.js +11 -6
  26. package/dist/benchmarks/index.js.map +1 -1
  27. package/dist/builder-eval/index.d.ts +1 -1
  28. package/dist/builder-eval/index.js +3 -3
  29. package/dist/{calibration-BBhY1QM6.js → calibration-Cfoup0xz.js} +3 -3
  30. package/dist/{calibration-BBhY1QM6.js.map → calibration-Cfoup0xz.js.map} +1 -1
  31. package/dist/campaign/index.d.ts +9 -9
  32. package/dist/campaign/index.js +16 -15
  33. package/dist/{campaign-DawSkDag.js → campaign-BlmkAwFD.js} +23 -23
  34. package/dist/campaign-BlmkAwFD.js.map +1 -0
  35. package/dist/{campaign-evidence-C1c6uihA.d.ts → campaign-evidence-BVKG5o32.d.ts} +6 -6
  36. package/dist/{campaign-evidence-C1c6uihA.d.ts.map → campaign-evidence-BVKG5o32.d.ts.map} +1 -1
  37. package/dist/{campaign-evidence-BX8OveG5.js → campaign-evidence-CsUE_lwc.js} +79 -26
  38. package/dist/campaign-evidence-CsUE_lwc.js.map +1 -0
  39. package/dist/{canonical-gLeHiqzd.d.ts → canonical-CGXS21f_.d.ts} +8 -5
  40. package/dist/{canonical-gLeHiqzd.d.ts.map → canonical-CGXS21f_.d.ts.map} +1 -1
  41. package/dist/{canonical-BANK6NOj.js → canonical-DKgL_Wby.js} +30 -8
  42. package/dist/canonical-DKgL_Wby.js.map +1 -0
  43. package/dist/{chat-client-DmPB31_2.js → chat-client-DqAXFLi-.js} +2 -2
  44. package/dist/{chat-client-DmPB31_2.js.map → chat-client-DqAXFLi-.js.map} +1 -1
  45. package/dist/{chat-json-call-Rfhu7JbJ.js → chat-json-call-CB6sQ6sv.js} +2 -2
  46. package/dist/{chat-json-call-Rfhu7JbJ.js.map → chat-json-call-CB6sQ6sv.js.map} +1 -1
  47. package/dist/{claim-C6LRiwz1.js → claim-BWEXwwBk.js} +2 -2
  48. package/dist/{claim-C6LRiwz1.js.map → claim-BWEXwwBk.js.map} +1 -1
  49. package/dist/cli.js +11 -11
  50. package/dist/{client-BIFwUg7I.d.ts → client-DUMIaMob.d.ts} +2 -2
  51. package/dist/{client-BIFwUg7I.d.ts.map → client-DUMIaMob.d.ts.map} +1 -1
  52. package/dist/cluster-CSd0LE_M.d.ts.map +1 -1
  53. package/dist/{cluster-bootstrap-ClPYIWoX.js → cluster-bootstrap-DPzVy3_K.js} +2 -2
  54. package/dist/{cluster-bootstrap-ClPYIWoX.js.map → cluster-bootstrap-DPzVy3_K.js.map} +1 -1
  55. package/dist/{completion-verifier-C3q1T96h.js → completion-verifier-DiG3y43g.js} +6 -6
  56. package/dist/{completion-verifier-C3q1T96h.js.map → completion-verifier-DiG3y43g.js.map} +1 -1
  57. package/dist/containment-order-GCJ-y_FV.js +56 -0
  58. package/dist/containment-order-GCJ-y_FV.js.map +1 -0
  59. package/dist/contract/index.d.ts +11 -11
  60. package/dist/contract/index.js +16 -16
  61. package/dist/contract/index.js.map +1 -1
  62. package/dist/cost-ledger-1CwUnVOd.js.map +1 -1
  63. package/dist/{decision-point-BN1YQNqk.js → decision-point-gt5JgqZ0.js} +8 -8
  64. package/dist/{decision-point-BN1YQNqk.js.map → decision-point-gt5JgqZ0.js.map} +1 -1
  65. package/dist/{default-registry-C5x2jyD6.d.ts → default-registry-DH_tl-V1.d.ts} +7 -7
  66. package/dist/{default-registry-C5x2jyD6.d.ts.map → default-registry-DH_tl-V1.d.ts.map} +1 -1
  67. package/dist/{default-registry-BE5Rj9ba.js → default-registry-Y9AaKLmG.js} +8 -8
  68. package/dist/default-registry-Y9AaKLmG.js.map +1 -0
  69. package/dist/{define-agent-eval-C4yoCqkc.d.ts → define-agent-eval-BDxV_ONM.d.ts} +18 -9
  70. package/dist/define-agent-eval-BDxV_ONM.d.ts.map +1 -0
  71. package/dist/{define-agent-eval-CyU7eAzj.js → define-agent-eval-Cq-bdF4O.js} +13 -11
  72. package/dist/define-agent-eval-Cq-bdF4O.js.map +1 -0
  73. package/dist/diagnosis/index.d.ts +3 -3
  74. package/dist/diagnosis/index.d.ts.map +1 -1
  75. package/dist/diagnosis/index.js +1 -1
  76. package/dist/diagnosis/index.js.map +1 -1
  77. package/dist/{dspy-rlm-engine-aM1RWOUT.js → dspy-rlm-engine-CHpTzYvZ.js} +4 -3
  78. package/dist/dspy-rlm-engine-CHpTzYvZ.js.map +1 -0
  79. package/dist/{emitter-DhQ65mza.js → emitter-BjW3NnX-.js} +15 -6
  80. package/dist/emitter-BjW3NnX-.js.map +1 -0
  81. package/dist/{emitter-mAXC5PSN.d.ts → emitter-Cw8ijO3v.d.ts} +4 -4
  82. package/dist/{emitter-mAXC5PSN.d.ts.map → emitter-Cw8ijO3v.d.ts.map} +1 -1
  83. package/dist/{engine-B2w3ARpj.d.ts → engine-3y87jnX0.d.ts} +2 -2
  84. package/dist/{engine-B2w3ARpj.d.ts.map → engine-3y87jnX0.d.ts.map} +1 -1
  85. package/dist/errors-DeEEV9Vx.js.map +1 -1
  86. package/dist/{eval-campaign-CWWh-1p1.js → eval-campaign-Cyk-tkLh.js} +5 -5
  87. package/dist/{eval-campaign-CWWh-1p1.js.map → eval-campaign-Cyk-tkLh.js.map} +1 -1
  88. package/dist/{evaluation-CQ-uAbqF.d.ts → evaluation-RODuDmCe.d.ts} +4 -4
  89. package/dist/{evaluation-CQ-uAbqF.d.ts.map → evaluation-RODuDmCe.d.ts.map} +1 -1
  90. package/dist/evaluation.d.ts +1 -1
  91. package/dist/{exact-types-B0_jA3V7.d.ts → exact-types-C4Rug7fG.d.ts} +2 -2
  92. package/dist/{exact-types-B0_jA3V7.d.ts.map → exact-types-C4Rug7fG.d.ts.map} +1 -1
  93. package/dist/{execution-insight-9No6Si55.d.ts → execution-insight-iOsr1Zi8.d.ts} +2 -2
  94. package/dist/{execution-insight-9No6Si55.d.ts.map → execution-insight-iOsr1Zi8.d.ts.map} +1 -1
  95. package/dist/experiment/index.d.ts +4 -4
  96. package/dist/experiment/index.d.ts.map +1 -1
  97. package/dist/experiment/index.js +10 -10
  98. package/dist/experiment/index.js.map +1 -1
  99. package/dist/{exporters-C9AwGDDK.js → exporters-CKFtnWmX.js} +2 -2
  100. package/dist/{exporters-C9AwGDDK.js.map → exporters-CKFtnWmX.js.map} +1 -1
  101. package/dist/external-optimizer-contracts-eKQTutGZ.js +123 -0
  102. package/dist/external-optimizer-contracts-eKQTutGZ.js.map +1 -0
  103. package/dist/{external-optimizer-process-DFEPdWJY.js → external-optimizer-process-CkAc1xBa.js} +22 -26
  104. package/dist/external-optimizer-process-CkAc1xBa.js.map +1 -0
  105. package/dist/{external-optimizer-subprocess-BspZ0bZb.js → external-optimizer-subprocess-B48Ie4qQ.js} +10 -124
  106. package/dist/external-optimizer-subprocess-B48Ie4qQ.js.map +1 -0
  107. package/dist/extract-usage-ISFqhfDz.js.map +1 -1
  108. package/dist/{feedback-trajectory-CCWiFzeE.d.ts → feedback-trajectory-B5hTr9w5.d.ts} +4 -4
  109. package/dist/{feedback-trajectory-CCWiFzeE.d.ts.map → feedback-trajectory-B5hTr9w5.d.ts.map} +1 -1
  110. package/dist/{finding-composition-BMgspnVI.js → finding-composition-CyWSTcAY.js} +2 -2
  111. package/dist/{finding-composition-BMgspnVI.js.map → finding-composition-CyWSTcAY.js.map} +1 -1
  112. package/dist/{findings-store-B8pq8Rhr.js → findings-store-Rx9ZJgHV.js} +6 -6
  113. package/dist/{findings-store-B8pq8Rhr.js.map → findings-store-Rx9ZJgHV.js.map} +1 -1
  114. package/dist/fuzz.d.ts.map +1 -1
  115. package/dist/fuzz.js +1 -1
  116. package/dist/fuzz.js.map +1 -1
  117. package/dist/{harness-session-lines-Fd5aeSDV.js → harness-session-lines-CSxKR6no.js} +3 -3
  118. package/dist/{harness-session-lines-Fd5aeSDV.js.map → harness-session-lines-CSxKR6no.js.map} +1 -1
  119. package/dist/{hf-dataset-kthWy7xl.js → hf-dataset-B0s2ZAhQ.js} +4 -4
  120. package/dist/{hf-dataset-kthWy7xl.js.map → hf-dataset-B0s2ZAhQ.js.map} +1 -1
  121. package/dist/hosted/index.d.ts +2 -2
  122. package/dist/hosted/index.js +1 -1
  123. package/dist/{index-BuuUhU_V.d.ts → index-BJTUL2Ff.d.ts} +41 -29
  124. package/dist/index-BJTUL2Ff.d.ts.map +1 -0
  125. package/dist/{index-Bhc7H9e0.d.ts → index-CX8_WfqS.d.ts} +5 -5
  126. package/dist/{index-Bhc7H9e0.d.ts.map → index-CX8_WfqS.d.ts.map} +1 -1
  127. package/dist/{index-DtW7KhyE.d.ts → index-D-nKkzsI.d.ts} +3 -3
  128. package/dist/{index-DtW7KhyE.d.ts.map → index-D-nKkzsI.d.ts.map} +1 -1
  129. package/dist/{index-HdlzN11G.d.ts → index-D1NRaf5U.d.ts} +7 -7
  130. package/dist/{index-HdlzN11G.d.ts.map → index-D1NRaf5U.d.ts.map} +1 -1
  131. package/dist/{index-Bcy00QoN.d.ts → index-DcGHcBpR.d.ts} +86 -86
  132. package/dist/index-DcGHcBpR.d.ts.map +1 -0
  133. package/dist/{index-CXoFLNKI.d.ts → index-FLyheOVA.d.ts} +9 -9
  134. package/dist/index-FLyheOVA.d.ts.map +1 -0
  135. package/dist/{index-lRKqfyg4.d.ts → index-qy6buL6y.d.ts} +2 -2
  136. package/dist/{index-lRKqfyg4.d.ts.map → index-qy6buL6y.d.ts.map} +1 -1
  137. package/dist/index.d.ts +29 -29
  138. package/dist/index.js +41 -41
  139. package/dist/index.js.map +1 -1
  140. package/dist/{integrity-BSs9dgKW.js → integrity-BF0tJK21.js} +3 -3
  141. package/dist/{integrity-BSs9dgKW.js.map → integrity-BF0tJK21.js.map} +1 -1
  142. package/dist/{journal-DQsbHGjX.js → journal-3y-btqaP.js} +2 -2
  143. package/dist/{journal-DQsbHGjX.js.map → journal-3y-btqaP.js.map} +1 -1
  144. package/dist/journal-file-AekB57Er.js.map +1 -1
  145. package/dist/{json-recovery-b7O9WVTF.js → json-recovery-BRUCeQxo.js} +2 -2
  146. package/dist/{json-recovery-b7O9WVTF.js.map → json-recovery-BRUCeQxo.js.map} +1 -1
  147. package/dist/{judge-gate-LbmZU-pA.js → judge-gate-TBv2jeO0.js} +3 -3
  148. package/dist/{judge-gate-LbmZU-pA.js.map → judge-gate-TBv2jeO0.js.map} +1 -1
  149. package/dist/{kind-factory-B5FfFE5G.js → kind-factory-DfNsTe-q.js} +3 -3
  150. package/dist/kind-factory-DfNsTe-q.js.map +1 -0
  151. package/dist/ledger-core/index.d.ts +2 -2
  152. package/dist/ledger-core/index.js +3 -3
  153. package/dist/{ledger-core-7e6sXmhV.js → ledger-core-auznoaD7.js} +3 -3
  154. package/dist/ledger-core-auznoaD7.js.map +1 -0
  155. package/dist/{llm-client-CdHo3SH0.js → llm-client-gRPgIJyz.js} +2 -2
  156. package/dist/{llm-client-CdHo3SH0.js.map → llm-client-gRPgIJyz.js.map} +1 -1
  157. package/dist/{llm-judge-DHgx29ro.js → llm-judge-CThv1Rog.js} +140 -44
  158. package/dist/llm-judge-CThv1Rog.js.map +1 -0
  159. package/dist/{matrix-BKzNwIWb.d.ts → matrix-CfJ5vhfq.d.ts} +2 -2
  160. package/dist/{matrix-BKzNwIWb.d.ts.map → matrix-CfJ5vhfq.d.ts.map} +1 -1
  161. package/dist/meta-eval/index.d.ts +1 -1
  162. package/dist/meta-eval/index.js +9 -9
  163. package/dist/{mint-VN-qtJTc.js → mint-B4n1pRRd.js} +12 -6
  164. package/dist/mint-B4n1pRRd.js.map +1 -0
  165. package/dist/{model-comparison-BZr_Hu00.js → model-comparison-CgnVh4Ph.js} +3 -3
  166. package/dist/{model-comparison-BZr_Hu00.js.map → model-comparison-CgnVh4Ph.js.map} +1 -1
  167. package/dist/multishot/golden/index.d.ts +1 -1
  168. package/dist/multishot/index.d.ts +2 -2
  169. package/dist/multishot/index.js +1 -1
  170. package/dist/multishot/index.js.map +1 -1
  171. package/dist/openapi.json +1 -1
  172. package/dist/{outcome-observations-YFFmdGGW.js → outcome-observations-DL3CC8w1.js} +2 -2
  173. package/dist/{outcome-observations-YFFmdGGW.js.map → outcome-observations-DL3CC8w1.js.map} +1 -1
  174. package/dist/{paired-arms-DH376s4-.js → paired-arms-DZhH3FGu.js} +3 -3
  175. package/dist/{paired-arms-DH376s4-.js.map → paired-arms-DZhH3FGu.js.map} +1 -1
  176. package/dist/{paired-promotion-decision-BoWHWL1i.js → paired-promotion-decision-Dn3-jaq4.js} +2 -2
  177. package/dist/{paired-promotion-decision-BoWHWL1i.js.map → paired-promotion-decision-Dn3-jaq4.js.map} +1 -1
  178. package/dist/{paired-promotion-decision-BBSxTo-h.d.ts → paired-promotion-decision-Il-Nv-n4.d.ts} +2 -2
  179. package/dist/{paired-promotion-decision-BBSxTo-h.d.ts.map → paired-promotion-decision-Il-Nv-n4.d.ts.map} +1 -1
  180. package/dist/{paired-promotion-power-BXH3gzvs.js → paired-promotion-power-BlzXdgMD.js} +3 -3
  181. package/dist/{paired-promotion-power-BXH3gzvs.js.map → paired-promotion-power-BlzXdgMD.js.map} +1 -1
  182. package/dist/{pareto-BNWWbLNl.js → pareto-Bg75Gajo.js} +7 -7
  183. package/dist/{pareto-BNWWbLNl.js.map → pareto-Bg75Gajo.js.map} +1 -1
  184. package/dist/pipelines/index.d.ts +3 -3
  185. package/dist/pipelines/index.d.ts.map +1 -1
  186. package/dist/pipelines/index.js +19 -33
  187. package/dist/pipelines/index.js.map +1 -1
  188. package/dist/{prime-protocol-BR0xy0cF.d.ts → prime-protocol-CdNaCQy5.d.ts} +2 -2
  189. package/dist/{prime-protocol-BR0xy0cF.d.ts.map → prime-protocol-CdNaCQy5.d.ts.map} +1 -1
  190. package/dist/profile-cell.js +1 -1
  191. package/dist/{promotion-gate-XiTqW22r.d.ts → promotion-gate-DKAvMFlS.d.ts} +2 -2
  192. package/dist/{promotion-gate-XiTqW22r.d.ts.map → promotion-gate-DKAvMFlS.d.ts.map} +1 -1
  193. package/dist/{promotion-policy-CfgRPGx0.js → promotion-policy-CxDIh-9p.js} +4 -4
  194. package/dist/{promotion-policy-CfgRPGx0.js.map → promotion-policy-CxDIh-9p.js.map} +1 -1
  195. package/dist/{proposal-findings-DFQvA-k5.js → proposal-findings-DnR7zdUc.js} +2 -2
  196. package/dist/{proposal-findings-DFQvA-k5.js.map → proposal-findings-DnR7zdUc.js.map} +1 -1
  197. package/dist/{query-Ck6KhcDo.js → query-Dhjkwqyx.js} +2 -2
  198. package/dist/{query-Ck6KhcDo.js.map → query-Dhjkwqyx.js.map} +1 -1
  199. package/dist/{registry-D23oO0_f.d.ts → registry-LqAf_laP.d.ts} +3 -3
  200. package/dist/{registry-D23oO0_f.d.ts.map → registry-LqAf_laP.d.ts.map} +1 -1
  201. package/dist/{release-confidence-BdidB0mG.js → release-confidence-BLHOMK5Q.js} +3 -3
  202. package/dist/{release-confidence-BdidB0mG.js.map → release-confidence-BLHOMK5Q.js.map} +1 -1
  203. package/dist/reporting.d.ts +4 -4
  204. package/dist/reporting.js +5 -5
  205. package/dist/{research-report-BGKsOqkF.d.ts → research-report-BauFJiqu.d.ts} +2 -2
  206. package/dist/{research-report-BGKsOqkF.d.ts.map → research-report-BauFJiqu.d.ts.map} +1 -1
  207. package/dist/{researcher-DvFDa1o1.d.ts → researcher-B4e2Z92k.d.ts} +3 -3
  208. package/dist/{researcher-DvFDa1o1.d.ts.map → researcher-B4e2Z92k.d.ts.map} +1 -1
  209. package/dist/{reward-hacking-DNiHskry.js → reward-hacking-DKAflk2c.js} +2 -2
  210. package/dist/{reward-hacking-DNiHskry.js.map → reward-hacking-DKAflk2c.js.map} +1 -1
  211. package/dist/rl.d.ts +155 -39
  212. package/dist/rl.d.ts.map +1 -1
  213. package/dist/rl.js +420 -76
  214. package/dist/rl.js.map +1 -1
  215. package/dist/rollout/index.d.ts +4 -4
  216. package/dist/rollout/index.js +6 -6
  217. package/dist/{rollout-DDMkK_Lw.js → rollout-B6LlGRSq.js} +9 -9
  218. package/dist/rollout-B6LlGRSq.js.map +1 -0
  219. package/dist/{rollout-nodes-DzmHlPAC.js → rollout-nodes-Vas6OSxX.js} +2 -2
  220. package/dist/{rollout-nodes-DzmHlPAC.js.map → rollout-nodes-Vas6OSxX.js.map} +1 -1
  221. package/dist/{rubric-predictive-validity-Cln7r56F.js → rubric-predictive-validity--6z0q8s6.js} +2 -2
  222. package/dist/{rubric-predictive-validity-Cln7r56F.js.map → rubric-predictive-validity--6z0q8s6.js.map} +1 -1
  223. package/dist/{run-improvement-loop-BAxDnaPI.d.ts → run-improvement-loop-B1OKCm2D.d.ts} +112 -70
  224. package/dist/run-improvement-loop-B1OKCm2D.d.ts.map +1 -0
  225. package/dist/{run-record-c860wUR8.js → run-record-Bqg0NZ_e.js} +19 -4
  226. package/dist/run-record-Bqg0NZ_e.js.map +1 -0
  227. package/dist/{run-record-Dx64nPcX.js → run-record-CqUft6Yf.js} +2 -2
  228. package/dist/{run-record-Dx64nPcX.js.map → run-record-CqUft6Yf.js.map} +1 -1
  229. package/dist/{runtime-rollouts-CALol_Y4.js → runtime-rollouts-DdUijr_t.js} +7 -7
  230. package/dist/runtime-rollouts-DdUijr_t.js.map +1 -0
  231. package/dist/{schema-BTTzvMnn.d.ts → schema-BfSoJjD-.d.ts} +5 -1
  232. package/dist/schema-BfSoJjD-.d.ts.map +1 -0
  233. package/dist/{schema-b18jtzZw.js → schema-Bh9CfSZT.js} +3 -1
  234. package/dist/schema-Bh9CfSZT.js.map +1 -0
  235. package/dist/schema-CkIvnmLU.d.ts.map +1 -1
  236. package/dist/schema-D-xu3MU_.js.map +1 -1
  237. package/dist/search/index.d.ts +3 -3
  238. package/dist/search/index.d.ts.map +1 -1
  239. package/dist/search/index.js +3 -3
  240. package/dist/{search-kernel-DRHWY35J.d.ts → search-kernel-CuTvZlPS.d.ts} +5 -5
  241. package/dist/{search-kernel-DRHWY35J.d.ts.map → search-kernel-CuTvZlPS.d.ts.map} +1 -1
  242. package/dist/{search-ledger-oyqxZhry.js → search-ledger-C7t68cmy.js} +7 -7
  243. package/dist/{search-ledger-oyqxZhry.js.map → search-ledger-C7t68cmy.js.map} +1 -1
  244. package/dist/{search-ledger-file-DoHCYYLt.js → search-ledger-file-QuIbgz6b.js} +2 -2
  245. package/dist/search-ledger-file-QuIbgz6b.js.map +1 -0
  246. package/dist/{search-ledger-types-qiYRUo_N.d.ts → search-ledger-types-BhZE848w.d.ts} +2 -2
  247. package/dist/{search-ledger-types-qiYRUo_N.d.ts.map → search-ledger-types-BhZE848w.d.ts.map} +1 -1
  248. package/dist/{search-shipper-BwqeQ61l.js → search-shipper-CmDW9dU6.js} +3 -3
  249. package/dist/{search-shipper-BwqeQ61l.js.map → search-shipper-CmDW9dU6.js.map} +1 -1
  250. package/dist/{search-summary-CNHpHFfw.js → search-summary-B1x1Vmzh.js} +5 -5
  251. package/dist/{search-summary-CNHpHFfw.js.map → search-summary-B1x1Vmzh.js.map} +1 -1
  252. package/dist/{sequential-93xxuiiG.js → sequential-BphITa5b.js} +4 -4
  253. package/dist/{sequential-93xxuiiG.js.map → sequential-BphITa5b.js.map} +1 -1
  254. package/dist/{sequential-B-zx24n_.d.ts → sequential-DqOJZO2V.d.ts} +2 -2
  255. package/dist/{sequential-B-zx24n_.d.ts.map → sequential-DqOJZO2V.d.ts.map} +1 -1
  256. package/dist/{sequential-C6k0Wrb7.js → sequential-ux_XrjBf.js} +3 -3
  257. package/dist/{sequential-C6k0Wrb7.js.map → sequential-ux_XrjBf.js.map} +1 -1
  258. package/dist/{served-model-qhLmbutL.js → served-model-BXmeKm7D.js} +2 -2
  259. package/dist/{served-model-qhLmbutL.js.map → served-model-BXmeKm7D.js.map} +1 -1
  260. package/dist/{server-DnoEi4Sb.js → server-BxHJyclG.js} +4 -4
  261. package/dist/{server-DnoEi4Sb.js.map → server-BxHJyclG.js.map} +1 -1
  262. package/dist/{skillopt-optimization-method-Du3GbReg.js → skillopt-optimization-method-CHW9mphc.js} +389 -68
  263. package/dist/skillopt-optimization-method-CHW9mphc.js.map +1 -0
  264. package/dist/{statistical-heldout-BvcAVtof.js → statistical-heldout-CaS4T-43.js} +3 -3
  265. package/dist/{statistical-heldout-BvcAVtof.js.map → statistical-heldout-CaS4T-43.js.map} +1 -1
  266. package/dist/{statistics-CHs0jlsY.js → statistics-DSidA5I2.js} +184 -184
  267. package/dist/statistics-DSidA5I2.js.map +1 -0
  268. package/dist/statistics.d.ts +1 -1
  269. package/dist/statistics.js +1 -1
  270. package/dist/{store-otlp-DHc_E78m.js → store-otlp-DCQTz9lS.js} +2 -2
  271. package/dist/{store-otlp-DHc_E78m.js.map → store-otlp-DCQTz9lS.js.map} +1 -1
  272. package/dist/{store-tool-spans-C1lZKvvl.d.ts → store-tool-spans-B0UYrcl7.d.ts} +5 -5
  273. package/dist/{store-tool-spans-C1lZKvvl.d.ts.map → store-tool-spans-B0UYrcl7.d.ts.map} +1 -1
  274. package/dist/{store-tool-spans-BR4IhZYZ.js → store-tool-spans-D2-S3OdE.js} +4 -4
  275. package/dist/{store-tool-spans-BR4IhZYZ.js.map → store-tool-spans-D2-S3OdE.js.map} +1 -1
  276. package/dist/storyboard/index.d.ts.map +1 -1
  277. package/dist/storyboard/index.js.map +1 -1
  278. package/dist/{summary-report-CXiE1UrA.js → summary-report-CI4J6gxU.js} +4 -4
  279. package/dist/{summary-report-CXiE1UrA.js.map → summary-report-CI4J6gxU.js.map} +1 -1
  280. package/dist/supervisor-run/index.d.ts +2 -2
  281. package/dist/supervisor-run/index.d.ts.map +1 -1
  282. package/dist/supervisor-run/index.js +3 -3
  283. package/dist/{systemone-B_3Vd395.d.ts → systemone-nAN8fBy9.d.ts} +8 -8
  284. package/dist/{systemone-B_3Vd395.d.ts.map → systemone-nAN8fBy9.d.ts.map} +1 -1
  285. package/dist/systemone-protocol.js +1 -1
  286. package/dist/{systemone-review-ZAN-5m_2.d.ts → systemone-review-e2ElIpD_.d.ts} +3 -3
  287. package/dist/{systemone-review-ZAN-5m_2.d.ts.map → systemone-review-e2ElIpD_.d.ts.map} +1 -1
  288. package/dist/{systemone-review-CqNNZMiD.js → systemone-review-ir3Cbejl.js} +3 -3
  289. package/dist/{systemone-review-CqNNZMiD.js.map → systemone-review-ir3Cbejl.js.map} +1 -1
  290. package/dist/systemone.d.ts +3 -3
  291. package/dist/systemone.js +2 -2
  292. package/dist/{tool-groups-BOH1E-E4.d.ts → tool-groups-sRVCeevR.d.ts} +3 -3
  293. package/dist/tool-groups-sRVCeevR.d.ts.map +1 -0
  294. package/dist/tool-waste-CIhtU1ad.d.ts +217 -0
  295. package/dist/tool-waste-CIhtU1ad.d.ts.map +1 -0
  296. package/dist/{tool-waste-DzLI-JJg.js → tool-waste-u7JJ_BlE.js} +3 -3
  297. package/dist/{tool-waste-DzLI-JJg.js.map → tool-waste-u7JJ_BlE.js.map} +1 -1
  298. package/dist/{trace-questions-DBsrgY_H.d.ts → trace-questions-BN-LSfkA.d.ts} +3 -3
  299. package/dist/{trace-questions-DBsrgY_H.d.ts.map → trace-questions-BN-LSfkA.d.ts.map} +1 -1
  300. package/dist/trace-repair/index.d.ts +1 -1
  301. package/dist/trace-repair/index.d.ts.map +1 -1
  302. package/dist/trace-repair/index.js +4 -4
  303. package/dist/trace-repair/index.js.map +1 -1
  304. package/dist/traces.d.ts +4 -4
  305. package/dist/traces.js +6 -6
  306. package/dist/{training-admission-xaDOlQ_U.d.ts → training-admission-DGZCyntI.d.ts} +2 -2
  307. package/dist/{training-admission-xaDOlQ_U.d.ts.map → training-admission-DGZCyntI.d.ts.map} +1 -1
  308. package/dist/trajectory-CKVZaQoQ.js +144 -0
  309. package/dist/trajectory-CKVZaQoQ.js.map +1 -0
  310. package/dist/trajectory-replay/index.d.ts.map +1 -1
  311. package/dist/trajectory-replay/index.js +24 -11
  312. package/dist/trajectory-replay/index.js.map +1 -1
  313. package/dist/{tree-0r6gPODs.js → tree-DQMlcNFI.js} +18 -6
  314. package/dist/tree-DQMlcNFI.js.map +1 -0
  315. package/dist/{types-DmYd2Igl.d.ts → types-BJ27EWAS.d.ts} +8 -8
  316. package/dist/{types-DmYd2Igl.d.ts.map → types-BJ27EWAS.d.ts.map} +1 -1
  317. package/dist/{types-ClDpBoLt.d.ts → types-CDWfUYOq.d.ts} +2 -2
  318. package/dist/{types-ClDpBoLt.d.ts.map → types-CDWfUYOq.d.ts.map} +1 -1
  319. package/dist/{types-_dfu6Ox2.d.ts → types-DI7YKvDI.d.ts} +3 -3
  320. package/dist/{types-_dfu6Ox2.d.ts.map → types-DI7YKvDI.d.ts.map} +1 -1
  321. package/dist/{types-C8AyaiFi.js → types-_tlhWGUq.js} +2 -2
  322. package/dist/{types-C8AyaiFi.js.map → types-_tlhWGUq.js.map} +1 -1
  323. package/dist/{types-DGqGbNY4.d.ts → types-pMk2rgP9.d.ts} +20 -6
  324. package/dist/{types-DGqGbNY4.d.ts.map → types-pMk2rgP9.d.ts.map} +1 -1
  325. package/dist/{verdict-CKo1iZkI.js → verdict-5PVtsWT_.js} +2 -2
  326. package/dist/{verdict-CKo1iZkI.js.map → verdict-5PVtsWT_.js.map} +1 -1
  327. package/dist/{verdict-cache-DfzlHLdf.js → verdict-cache-BPaYxfG8.js} +2 -2
  328. package/dist/verdict-cache-BPaYxfG8.js.map +1 -0
  329. package/dist/wire/index.d.ts +1 -1
  330. package/dist/wire/index.js +1 -1
  331. package/docs/campaign-proposers.md +14 -1
  332. package/docs/public-api.md +323 -85
  333. package/docs/rollout.md +2 -2
  334. package/docs/search-ledger.md +14 -2
  335. package/docs/statistical-evidence.md +9 -3
  336. package/docs/trajectory-replay.md +4 -0
  337. package/package.json +1 -1
  338. package/dist/agent-profile-hytrwAnN.d.ts.map +0 -1
  339. package/dist/benchmark-command-CJw3ijDV.js.map +0 -1
  340. package/dist/campaign-DawSkDag.js.map +0 -1
  341. package/dist/campaign-evidence-BX8OveG5.js.map +0 -1
  342. package/dist/canonical-BANK6NOj.js.map +0 -1
  343. package/dist/default-registry-BE5Rj9ba.js.map +0 -1
  344. package/dist/define-agent-eval-C4yoCqkc.d.ts.map +0 -1
  345. package/dist/define-agent-eval-CyU7eAzj.js.map +0 -1
  346. package/dist/dspy-rlm-engine-aM1RWOUT.js.map +0 -1
  347. package/dist/emitter-DhQ65mza.js.map +0 -1
  348. package/dist/external-optimizer-process-DFEPdWJY.js.map +0 -1
  349. package/dist/external-optimizer-subprocess-BspZ0bZb.js.map +0 -1
  350. package/dist/index-Bcy00QoN.d.ts.map +0 -1
  351. package/dist/index-BuuUhU_V.d.ts.map +0 -1
  352. package/dist/index-CXoFLNKI.d.ts.map +0 -1
  353. package/dist/kind-factory-B5FfFE5G.js.map +0 -1
  354. package/dist/ledger-core-7e6sXmhV.js.map +0 -1
  355. package/dist/llm-judge-DHgx29ro.js.map +0 -1
  356. package/dist/mint-VN-qtJTc.js.map +0 -1
  357. package/dist/rollout-DDMkK_Lw.js.map +0 -1
  358. package/dist/run-improvement-loop-BAxDnaPI.d.ts.map +0 -1
  359. package/dist/run-record-c860wUR8.js.map +0 -1
  360. package/dist/runtime-rollouts-CALol_Y4.js.map +0 -1
  361. package/dist/schema-BTTzvMnn.d.ts.map +0 -1
  362. package/dist/schema-b18jtzZw.js.map +0 -1
  363. package/dist/search-ledger-file-DoHCYYLt.js.map +0 -1
  364. package/dist/skillopt-optimization-method-Du3GbReg.js.map +0 -1
  365. package/dist/statistics-CHs0jlsY.js.map +0 -1
  366. package/dist/tool-groups-BOH1E-E4.d.ts.map +0 -1
  367. package/dist/tool-waste-CUASoTtk.d.ts +0 -139
  368. package/dist/tool-waste-CUASoTtk.d.ts.map +0 -1
  369. package/dist/trajectory-O3GDHmev.js +0 -55
  370. package/dist/trajectory-O3GDHmev.js.map +0 -1
  371. package/dist/tree-0r6gPODs.js.map +0 -1
  372. package/dist/verdict-cache-DfzlHLdf.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"llm-client-CdHo3SH0.js","names":[],"sources":["../src/abort-signal.ts","../src/llm-client/resilience.ts","../src/llm-client/wire.ts","../src/llm-client/accounting.ts","../src/llm-client/request.ts","../src/llm-client.ts"],"sourcesContent":["/** Combine active cancellation sources without wrapping a single source. */\nexport function combineAbortSignals(\n ...signals: Array<AbortSignal | undefined>\n): AbortSignal | undefined {\n const active = [\n ...new Set(signals.filter((signal): signal is AbortSignal => signal !== undefined)),\n ]\n if (active.length === 0) return undefined\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n","import type { LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\n// Flagship / reasoning models routinely take several minutes on large prompts (a\n// reflection over many failures, a long tool transcript). A tight cap aborts a\n// legitimately-slow but healthy call — and because every retry attempt re-uses\n// the same window, such a model aborts on ALL attempts and the loop throws. The\n// default is generous enough to let those complete, bounded enough that a truly\n// hung call still fails over after retries, and tunable per deployment via\n// TANGLE_LLM_TIMEOUT_MS. Per-call `req.timeoutMs` / `opts.defaultTimeoutMs`\n// still win for callers that know their model's latency.\nexport const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\n\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 6\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nexport function resolveMaximumAttempts(configured: number | undefined): number {\n const attempts = configured ?? DEFAULT_MAXIMUM_ATTEMPTS\n if (!Number.isInteger(attempts) || attempts <= 0) {\n throw new RangeError('LLM maximum attempts must be a positive integer')\n }\n return attempts\n}\n\nexport function resolveMinIntervalMs(configured: number | undefined): number {\n const interval = configured ?? 0\n if (!Number.isFinite(interval) || interval < 0) {\n throw new RangeError('LLM minIntervalMs must be a finite non-negative number')\n }\n return interval\n}\n\n// Weak keys avoid retaining credentials or completed campaigns. LlmClient binds\n// its per-call option copies to the same state as its constructor options.\nexport const pacingStates = new WeakMap<LlmClientOptions, { lastStartedAt?: number }>()\n\nexport function pacingStateFor(opts: LlmClientOptions): { lastStartedAt?: number } {\n let state = pacingStates.get(opts)\n if (!state) {\n state = {}\n pacingStates.set(opts, state)\n }\n return state\n}\n\n// 522/524: Cloudflare edge timeouts (origin connect/respond) — transient\n// exactly like 504. Router deployments serve through Cloudflare, so a long\n// non-streaming call can draw these from the edge, not the origin.\nexport const RETRYABLE_STATUS = new Set([429, 502, 503, 504, 522, 524])\n\n/**\n * Transient transport/network error signatures, matched against an error's\n * name, message, and `code`. Covers fetch/undici network failures, aborts\n * and timeouts, and — critically — HTTP/2 transport faults a keep-alive\n * connection raises mid-response: `terminated`, `NGHTTP2_INTERNAL_ERROR`,\n * `UND_ERR_*`, `other side closed`. Those last ones carry no clean HTTP\n * status; unrecognised, they escape the retry loop and surface as an\n * uncaught rejection.\n */\nconst TRANSIENT_ERROR_PATTERNS: readonly RegExp[] = [\n /AbortError/i,\n /TimeoutError/i,\n /this operation was aborted/i,\n /fetch failed/i,\n /ECONNRESET/i,\n /ETIMEDOUT/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /stream.*ended.*unexpectedly/i,\n /terminated/i,\n /other side closed/i,\n /NGHTTP2/i,\n /UND_ERR/i,\n]\n\n/**\n * True when an error is a transient transport/network fault worth retrying,\n * as opposed to a deterministic failure (4xx schema reject, JSON parse) that\n * a retry cannot fix. Inspects `LlmCallError.status`, then the error's\n * name/message/code, then recurses into `error.cause` — undici nests the\n * real socket fault one or more levels under `.cause`.\n *\n * This is the retry classifier for the package: `callLlm` and\n * `withJudgeRetry` both route through it, so connection failures are treated\n * consistently across transports.\n */\nexport function isTransientLlmError(err: unknown): boolean {\n return classifyTransient(err, 0)\n}\n\nfunction classifyTransient(err: unknown, depth: number): boolean {\n if (err instanceof LlmCallError) return RETRYABLE_STATUS.has(err.status)\n if (!(err instanceof Error)) return false\n // Foreign transport errors can carry a numeric HTTP status without being an\n // LlmCallError. A retryable status is decisive.\n const status = (err as { status?: unknown }).status\n if (typeof status === 'number' && RETRYABLE_STATUS.has(status)) return true\n const code = (err as { code?: unknown }).code\n const haystack = `${err.name}\\n${err.message}\\n${typeof code === 'string' ? code : ''}`\n if (TRANSIENT_ERROR_PATTERNS.some((p) => p.test(haystack))) return true\n const cause = (err as { cause?: unknown }).cause\n if (depth < 4 && cause instanceof Error && cause !== err) {\n return classifyTransient(cause, depth + 1)\n }\n return false\n}\n\nexport function parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')?.trim()\n if (!h) return null\n const asNumber = Number(h)\n if (!Number.isNaN(asNumber)) {\n const delay = asNumber * 1000\n return Number.isFinite(delay) && delay >= 0 ? delay : null\n }\n const asDate = Date.parse(h)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return null\n}\n\n/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */\nexport function backoffMs(attempt: number): number {\n return Math.min(500 * 2 ** attempt, 16_000)\n}\n\n/** Backoff belongs to the caller's operation and must stop when it is cancelled. */\nexport async function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n // A timer above the signed 32-bit limit becomes a near-immediate timeout.\n // Split long server delays rather than truncating Retry-After or overflowing.\n do {\n signal?.throwIfAborted()\n const chunk = Math.min(Math.ceil(ms), 2_147_483_647)\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n reject(signal?.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, chunk)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n ms -= chunk\n } while (ms > 0)\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nexport function deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n","import type {\n LlmCallRequest,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n} from './contract'\n\nexport function providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nexport function buildHeaders(opts: LlmClientOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (opts.authHeader) {\n headers[opts.authHeader.name] = opts.authHeader.value\n } else if (opts.bearer || opts.apiKey) {\n headers.Authorization = `Bearer ${opts.bearer ?? opts.apiKey}`\n }\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n return headers\n}\n\nexport function isSchemaRejection(status: number, body: string): boolean {\n if (status !== 400) return false\n const lower = body.toLowerCase()\n return (\n lower.includes('response_format') ||\n lower.includes('json_schema') ||\n lower.includes('is unavailable') ||\n lower.includes('not supported')\n )\n}\n\nexport function isTemperatureOneRejection(status: number, body: string): boolean {\n if (status !== 400 || !/temperature/i.test(body)) return false\n return (\n /temperature[^.\\n]{0,120}\\b(?:only|must|should|required|requires?)\\b[^.\\n]{0,40}\\b1(?:\\.0+)?\\b/i.test(\n body,\n ) || /\\bonly\\s+1(?:\\.0+)?\\s+is\\s+allowed\\b[^.\\n]{0,120}\\btemperature\\b/i.test(body)\n )\n}\n\nexport function buildBody(\n req: LlmCallRequest,\n forceJsonObject: boolean,\n defaultThinking?: LlmThinkingMode,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model: req.model,\n messages: req.messages.map(encodeWireMessage),\n temperature: req.temperature ?? 0,\n }\n if (req.maxTokens != null) {\n if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens\n else body.max_tokens = req.maxTokens\n }\n if (req.logprobs !== undefined) {\n body.logprobs = true\n body.top_logprobs = req.logprobs.topLogprobs\n }\n if (req.tools !== undefined) body.tools = req.tools\n if (req.toolChoice !== undefined) body.tool_choice = req.toolChoice\n const thinking = req.thinking ?? defaultThinking\n if (thinking !== undefined) {\n body.thinking = { type: thinking }\n }\n\n if (req.jsonSchema && !forceJsonObject) {\n body.response_format = {\n type: 'json_schema',\n json_schema: { name: req.jsonSchema.name, schema: req.jsonSchema.schema, strict: true },\n }\n } else if (req.jsonMode || req.jsonSchema) {\n body.response_format = { type: 'json_object' }\n }\n\n return body\n}\n\nfunction usesMaxCompletionTokens(model: string): boolean {\n return /^gpt-5(?:[.-]|$)/i.test(model)\n}\n\n/** Encode one canonical message as its OpenAI chat-completions wire shape. */\nfunction encodeWireMessage(message: LlmMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content }\n }\n if (message.toolCalls === undefined) {\n return { role: message.role, content: message.content }\n }\n return {\n role: message.role,\n content: message.content,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: call.argumentsJson },\n })),\n }\n}\n\n/**\n * Parse `choices[0].logprobs.content` into the canonical per-token shape.\n * `null` when the provider returned nothing for a request that asked: a\n * provider that ignores `logprobs` is a fact the caller must be able to read,\n * not an error. A malformed entry is a contract violation and throws.\n */\nexport function parseWireLogprobs(\n value: unknown,\n model: string,\n): ReadonlyArray<LlmTokenLogprob> | null {\n if (value === undefined || value === null) return null\n if (!Array.isArray(value)) {\n throw new Error(`LLM response logprobs.content must be an array (model=${model})`)\n }\n return value.map((entry, index) => {\n const record = entry as { token?: unknown; logprob?: unknown; top_logprobs?: unknown } | null\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.token !== 'string' ||\n typeof record.logprob !== 'number' ||\n !Number.isFinite(record.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}] is not a token with a finite logprob (model=${model})`,\n )\n }\n const top = record.top_logprobs\n if (top !== undefined && top !== null && !Array.isArray(top)) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs must be an array (model=${model})`,\n )\n }\n return {\n token: record.token,\n logprob: record.logprob,\n top: (Array.isArray(top) ? top : []).map((alternative, position) => {\n const candidate = alternative as { token?: unknown; logprob?: unknown } | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.token !== 'string' ||\n typeof candidate.logprob !== 'number' ||\n !Number.isFinite(candidate.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs[${position}] is not a token with a finite logprob (model=${model})`,\n )\n }\n return { token: candidate.token, logprob: candidate.logprob }\n }),\n }\n })\n}\n\n/** Parse provider tool_calls into the canonical shape. A malformed entry is a\n * provider-contract violation and throws rather than degrading silently. */\nexport function parseWireToolCalls(value: unknown, model: string): LlmToolCall[] | undefined {\n if (value === undefined || value === null) return undefined\n if (!Array.isArray(value)) {\n throw new Error(`LLM response tool_calls must be an array (model=${model})`)\n }\n if (value.length === 0) return undefined\n return value.map((entry, index) => {\n const record = entry as {\n id?: unknown\n type?: unknown\n function?: { name?: unknown; arguments?: unknown } | null\n } | null\n const fn = record && typeof record === 'object' ? record.function : undefined\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.id !== 'string' ||\n record.id.length === 0 ||\n (record.type !== undefined && record.type !== 'function') ||\n !fn ||\n typeof fn !== 'object' ||\n typeof fn.name !== 'string' ||\n fn.name.length === 0 ||\n typeof fn.arguments !== 'string'\n ) {\n throw new Error(\n `LLM response tool_calls[${index}] is not a function call with string arguments (model=${model})`,\n )\n }\n return { id: record.id, name: fn.name, argumentsJson: fn.arguments }\n })\n}\n","import type { CostReceiptInput, CustomTokenPricing, MaximumCharge } from '../cost-ledger'\nimport type { LlmCallRequest, LlmCallResult, LlmChargeBounds } from './contract'\nimport { LlmResponseError } from './errors'\nimport { resolveMaximumAttempts } from './resilience'\nimport { buildBody } from './wire'\n\nexport function maximumChargeForLlmRequest(\n request: Pick<\n LlmCallRequest,\n 'model' | 'messages' | 'jsonSchema' | 'tools' | 'toolChoice' | 'maxTokens' | 'thinking'\n >,\n options: LlmChargeBounds = {},\n): MaximumCharge | undefined {\n if (request.maxTokens === undefined) return undefined\n if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) {\n throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`)\n }\n if (\n request.messages.some(\n (message) =>\n Array.isArray(message.content) && message.content.some((part) => part.type === 'image_url'),\n )\n ) {\n return undefined\n }\n\n const attempts = resolveMaximumAttempts(options.maximumAttempts)\n const forceJsonObject = options.jsonSchemaTransport === 'json-object'\n // A byte-level tokenizer cannot emit more input tokens than request bytes.\n // Pricing the complete body also covers role/schema framing omitted from content-only estimates.\n const requestBytes = new TextEncoder().encode(\n JSON.stringify(buildBody(request, forceJsonObject, options.thinking)),\n ).byteLength\n // Schema fallback shares the same physical-attempt budget; it cannot buy a second batch.\n const usage = {\n inputTokens: requestBytes * attempts,\n outputTokens: request.maxTokens * attempts,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\n/** Convert a provider result into the canonical paid-call receipt input.\n * The receipt is JSON-clean: absent optional fields are omitted, never carried\n * as explicit-undefined keys. Receipts cross JSON boundaries (the external\n * optimizer's loopback proxy validates them with `assertJsonValue`), where an\n * explicit-undefined value is rejected as non-serializable. */\nexport function costReceiptFromLlm(\n result: LlmCallResult,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput {\n const cachedTokens = result.usage.cachedPromptTokens ?? 0\n const inputTokens = Math.max(0, result.usage.promptTokens - cachedTokens)\n const providerCostUsd = providerReportedCost(result.raw)\n return {\n model: result.model,\n inputTokens,\n outputTokens: result.usage.completionTokens,\n ...(result.usage.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: result.usage.reasoningTokens }),\n ...(cachedTokens > 0 ? { cachedTokens } : {}),\n ...(providerCostUsd === undefined\n ? customTokenPricing && result.usage.captured !== false\n ? { customTokenPricing }\n : result.costUsd === null\n ? {}\n : { estimatedCostUsd: result.costUsd }\n : { actualCostUsd: providerCostUsd }),\n usageUnknown: result.usage.captured === false,\n }\n}\n\nexport function providerReportedCost(raw: Record<string, unknown>): number | undefined {\n const value = raw._response_cost ?? raw.cost_usd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/** Structured-response failures retain their completed provider receipt. */\nexport function costReceiptFromLlmError(\n error: Error,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput | undefined {\n return error instanceof LlmResponseError\n ? costReceiptFromLlm(error.result, customTokenPricing)\n : undefined\n}\n","import { combineAbortSignals } from '../abort-signal'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { assertServedModel as assertServedModelIdentity } from '../integrity/served-model'\nimport { newRecordId } from '../record-id'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from '../trace/raw-provider-sink'\nimport { providerReportedCost } from './accounting'\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\nimport {\n backoffMs,\n DEFAULT_TIMEOUT_MS,\n deadlineExceeded,\n isTransientLlmError,\n pacingStateFor,\n parseRetryAfter,\n RETRYABLE_STATUS,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n sleep,\n} from './resilience'\nimport {\n buildBody,\n buildHeaders,\n isSchemaRejection,\n isTemperatureOneRejection,\n parseWireLogprobs,\n parseWireToolCalls,\n providerTokenCount,\n} from './wire'\n\n/**\n * Low-level call. Returns raw content + usage + cost. Retries on transient\n * failures; does NOT degrade schema here — callers that want graceful\n * degrade use `callLlmJson`.\n */\nexport async function callLlm(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts(req, opts, false)\n}\n\n/** One retry owner for raw and structured calls. Fallback changes the next\n * request, not the attempt allowance, deadline origin, or raw-event sequence. */\n/** What one call shares across its attempts: the resolved options, pacing, deadline and the request as it now stands. */\ninterface AttemptRun {\n readonly req: LlmCallRequest\n readonly opts: LlmClientOptions\n readonly allowSchemaFallback: boolean\n readonly baseUrl: string\n readonly url: string\n readonly timeoutMs: number\n readonly maximumAttempts: number\n readonly minIntervalMs: number\n readonly pacing: ReturnType<typeof pacingStateFor>\n readonly headers: ReturnType<typeof buildHeaders>\n readonly provider: string\n readonly deadlineStart: number\n readonly remainingMs: () => number\n readonly retryDelay: (ms: number) => Promise<void>\n effectiveRequest: LlmCallRequest\n lastErr: unknown\n}\n\n/** How one attempt ended without a result or a thrown error. */\ntype AttemptOutcome =\n | { kind: 'result'; result: LlmCallResult }\n | { kind: 'retry' }\n | { kind: 'exhausted' }\n\n/** Which of an attempt's raw events were already written, so the failure path records at most one error. */\ninterface AttemptState {\n dispatched: boolean\n errorRecorded: boolean\n}\n\nconst ENDPOINT = '/chat/completions'\n\nfunction startAttemptRun(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): AttemptRun {\n // No default endpoint. This client is internal to the `agent-eval` binary\n // and the loopback optimizer proxy; both name their endpoint explicitly, and\n // a fallback would let a misconfigured caller bill an unintended provider.\n if (!opts.baseUrl) throw new Error('callLlm: opts.baseUrl is required')\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n const remainingMs = () =>\n deadlineMs === undefined ? Infinity : Math.max(0, deadlineMs - (Date.now() - deadlineStart))\n const run: AttemptRun = {\n req,\n opts,\n allowSchemaFallback,\n baseUrl,\n url: `${baseUrl}${ENDPOINT}`,\n timeoutMs: req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS,\n maximumAttempts: resolveMaximumAttempts(opts.maximumAttempts),\n minIntervalMs: resolveMinIntervalMs(opts.minIntervalMs),\n pacing: pacingStateFor(opts),\n headers: buildHeaders(opts),\n provider: opts.provider ?? providerFromBaseUrl(baseUrl),\n deadlineStart,\n remainingMs,\n retryDelay: (ms) => sleep(Math.min(ms, remainingMs()), opts.signal),\n effectiveRequest: req,\n lastErr: undefined,\n }\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n return run\n}\n\nfunction deadlineError(run: AttemptRun): Error | DOMException {\n return run.lastErr instanceof Error\n ? run.lastErr\n : new DOMException('callLlm deadline exceeded', 'TimeoutError')\n}\n\n/** Write one raw provider event for this attempt. Does nothing without a sink. */\nasync function recordAttemptEvent(\n run: AttemptRun,\n attempt: number,\n fields: Pick<RawProviderEvent, 'direction' | 'timestamp'> & Partial<RawProviderEvent>,\n): Promise<void> {\n const { opts } = run\n if (!opts.rawSink) return\n await recordRaw(opts.rawSink, opts.redactor ?? defaultProviderRedactor, {\n eventId: newRecordId(),\n runId: opts.traceContext?.runId,\n spanId: opts.traceContext?.spanId,\n provider: run.provider,\n model: run.req.model,\n endpoint: ENDPOINT,\n baseUrl: run.baseUrl,\n attemptIndex: attempt,\n ...fields,\n redactedFields: [],\n })\n}\n\n/**\n * Wait for this client's pacing slot, and claim it. Every wake rechecks, so concurrent waiters\n * cannot dispatch a catch-up burst; the claim is made in the same synchronous step that finds the\n * slot free, so no other waiter can slip in between the check and the claim.\n */\nasync function awaitPacingSlot(run: AttemptRun): Promise<number> {\n const { opts, pacing, minIntervalMs } = run\n while (true) {\n opts.signal?.throwIfAborted()\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const waitMs =\n pacing.lastStartedAt === undefined ? 0 : pacing.lastStartedAt + minIntervalMs - Date.now()\n if (waitMs <= 0) {\n // Queue time consumes the operation deadline, not the HTTP timeout.\n const started = Date.now()\n pacing.lastStartedAt = started\n return started\n }\n await run.retryDelay(waitMs)\n }\n}\n\n/** Answer a non-2xx response: retry with an adjusted request or after a wait, give up, or throw its error. */\nasync function handleHttpFailure(\n run: AttemptRun,\n attempt: number,\n res: Response,\n body: string,\n responseHeaders: Record<string, string> | undefined,\n started: number,\n state: AttemptState,\n): Promise<AttemptOutcome> {\n const { req, opts, maximumAttempts, deadlineStart } = run\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: body,\n errorMessage: `HTTP ${res.status}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n const canRetry =\n attempt < maximumAttempts - 1 && !deadlineExceeded(deadlineStart, opts.deadlineMs)\n if (\n isTemperatureOneRejection(res.status, body) &&\n run.effectiveRequest.temperature !== 1 &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, temperature: 1 }\n return { kind: 'retry' }\n }\n if (\n run.allowSchemaFallback &&\n opts.jsonSchemaTransport !== 'json-object' &&\n run.effectiveRequest.jsonSchema &&\n isSchemaRejection(res.status, body) &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, jsonMode: true, jsonSchema: undefined }\n return { kind: 'retry' }\n }\n if (RETRYABLE_STATUS.has(res.status) && canRetry) {\n run.lastErr = err\n const wait = parseRetryAfter(res.headers) ?? backoffMs(attempt)\n // A wait the deadline cannot cover ends the call with this answer. Sleeping to the\n // deadline let a timer that fired a millisecond early start one more attempt with no time\n // left, whose abort replaced the server's status (agent-eval publish run 37238259408).\n if (wait >= run.remainingMs()) {\n // A caller abort that landed while the answer was recorded still wins, as the\n // retry wait would have reported it.\n opts.signal?.throwIfAborted()\n return { kind: 'exhausted' }\n }\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n throw err\n}\n\n/** Turn a parsed completion into the call result: content, tool calls, usage with its completeness, and cost. */\nfunction parseCompletion(\n run: AttemptRun,\n json: Record<string, unknown>,\n started: number,\n): LlmCallResult {\n const { req, opts } = run\n const choice = (\n json.choices as\n | Array<{\n message?: { content?: string | null; tool_calls?: unknown }\n finish_reason?: string | null\n logprobs?: { content?: unknown } | null\n }>\n | undefined\n )?.[0]\n const toolCalls = parseWireToolCalls(choice?.message?.tool_calls, req.model)\n const usageRaw =\n json.usage && typeof json.usage === 'object' && !Array.isArray(json.usage)\n ? (json.usage as Record<string, unknown>)\n : undefined\n const promptTokens = providerTokenCount(usageRaw?.prompt_tokens)\n const completionTokens = providerTokenCount(usageRaw?.completion_tokens)\n const totalTokens = providerTokenCount(usageRaw?.total_tokens)\n const completionDetails =\n usageRaw?.completion_tokens_details &&\n typeof usageRaw.completion_tokens_details === 'object' &&\n !Array.isArray(usageRaw.completion_tokens_details)\n ? (usageRaw.completion_tokens_details as Record<string, unknown>)\n : undefined\n const reasoningRaw = completionDetails?.reasoning_tokens\n const reasoningTokens = reasoningRaw === undefined ? undefined : providerTokenCount(reasoningRaw)\n const cachedRaw =\n usageRaw?.prompt_tokens_details &&\n typeof usageRaw.prompt_tokens_details === 'object' &&\n !Array.isArray(usageRaw.prompt_tokens_details)\n ? (usageRaw.prompt_tokens_details as Record<string, unknown>).cached_tokens\n : undefined\n const cachedPromptTokens = cachedRaw === undefined ? undefined : providerTokenCount(cachedRaw)\n const usageCaptured =\n promptTokens !== undefined &&\n completionTokens !== undefined &&\n (reasoningRaw === undefined ||\n (reasoningTokens !== undefined && reasoningTokens <= completionTokens)) &&\n (cachedRaw === undefined ||\n (cachedPromptTokens !== undefined && cachedPromptTokens <= promptTokens)) &&\n (totalTokens === undefined || totalTokens === promptTokens + completionTokens)\n const costFromProxy = providerReportedCost(json)\n const content = choice?.message?.content ?? ''\n\n const configuredCost =\n typeof costFromProxy !== 'number' && usageCaptured && opts.customTokenPricing\n ? costForTokenPricing(opts.customTokenPricing, {\n inputTokens: promptTokens! - (cachedPromptTokens ?? 0),\n ...(cachedPromptTokens ? { cachedTokens: cachedPromptTokens } : {}),\n outputTokens: completionTokens!,\n })\n : undefined\n\n // The echoed id, kept separate from the attribution id: a provider that\n // omits it must read as \"unproven\", never as \"the model I asked for\".\n const servedModel = typeof json.model === 'string' && json.model.trim() !== '' ? json.model : null\n if (opts.assertServedModel) {\n assertServedModelIdentity(\n req.model,\n servedModel,\n opts.assertServedModel === true ? {} : opts.assertServedModel,\n )\n }\n\n return {\n content,\n ...(toolCalls === undefined ? {} : { toolCalls }),\n ...(req.logprobs === undefined\n ? {}\n : { logprobs: parseWireLogprobs(choice?.logprobs?.content, req.model) }),\n finishReason: choice?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n usage: {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: totalTokens ?? (promptTokens ?? 0) + (completionTokens ?? 0),\n captured: usageCaptured,\n reasoningTokens,\n cachedPromptTokens,\n },\n costUsd: typeof costFromProxy === 'number' ? costFromProxy : (configuredCost ?? null),\n model: servedModel ?? req.model,\n servedModel,\n durationMs: Date.now() - started,\n raw: json,\n }\n}\n\n/** One attempt: pace, dispatch, read the answer. A failure either becomes a retry outcome or is thrown. */\nasync function runAttempt(run: AttemptRun, attempt: number): Promise<AttemptOutcome> {\n const { opts } = run\n const callerSignal = opts.signal\n // A caller cancel is fatal — never retried. Checking before each attempt\n // means an already-aborted signal short-circuits without firing fetch.\n if (callerSignal?.aborted) {\n throw new DOMException('callLlm aborted by caller signal', 'AbortError')\n }\n // Stop retrying once the cross-attempt budget is spent rather than burning\n // a full per-attempt timeout on each remaining retry.\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const requestBody = buildBody(\n run.effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n const controller = new AbortController()\n const attemptSignal = combineAbortSignals(controller.signal, callerSignal)!\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n let started = Date.now()\n // An attempt cancelled or timed out while queued never reached the\n // provider, so it leaves no request or error event in the raw log.\n const state: AttemptState = { dispatched: false, errorRecorded: false }\n try {\n if (run.minIntervalMs > 0) {\n started = await awaitPacingSlot(run)\n } else {\n // Claim the slot before any await so a concurrent waiter cannot take it.\n run.pacing.lastStartedAt = started\n }\n state.dispatched = true\n timeoutHandle = setTimeout(() => controller.abort(), Math.min(run.timeoutMs, run.remainingMs()))\n await recordAttemptEvent(run, attempt, {\n direction: 'request',\n timestamp: started,\n requestHeaders: run.headers,\n requestBody,\n })\n attemptSignal.throwIfAborted()\n const res = await (opts.fetch ?? globalThis.fetch)(run.url, {\n method: 'POST',\n headers: run.headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n const responseHeaders = opts.rawSink ? headersToObject(res.headers) : undefined\n // Headers are not completion: the same timeout/cancellation covers either response body.\n const text = await res.text()\n attemptSignal.throwIfAborted()\n clearTimeout(timeoutHandle)\n\n if (!res.ok) {\n return await handleHttpFailure(run, attempt, res, text, responseHeaders, started, state)\n }\n\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: text,\n errorMessage: `non-JSON response: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n throw parseErr\n }\n await recordAttemptEvent(run, attempt, {\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n })\n return { kind: 'result', result: parseCompletion(run, json, started) }\n } catch (err) {\n clearTimeout(timeoutHandle)\n run.lastErr = err\n // Record only if neither the !res.ok branch nor the JSON.parse catch\n // already produced an error event for this attempt. Covers network\n // failures, timeouts, and aborts.\n if (state.dispatched && !state.errorRecorded) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n }\n // A caller cancel is fatal even though an AbortError matches the\n // transient patterns — a cancelled call must surface immediately, not\n // be retried against the same dead intent.\n if (callerSignal?.aborted) throw err\n const wait = backoffMs(attempt)\n if (\n attempt < run.maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(run.deadlineStart, opts.deadlineMs) &&\n wait < run.remainingMs()\n ) {\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n callerSignal?.throwIfAborted()\n throw err\n } finally {\n clearTimeout(timeoutHandle)\n }\n}\n\nasync function callLlmAttempts(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): Promise<LlmCallResult> {\n const run = startAttemptRun(req, opts, allowSchemaFallback)\n for (let attempt = 0; attempt < run.maximumAttempts; attempt++) {\n const outcome = await runAttempt(run, attempt)\n if (outcome.kind === 'result') return outcome.result\n if (outcome.kind === 'exhausted') break\n }\n throw run.lastErr instanceof Error ? run.lastErr : new Error(String(run.lastErr))\n}\n\nasync function recordRaw(\n sink: RawProviderSink,\n redactor: ProviderRedactor,\n event: RawProviderEvent,\n): Promise<void> {\n // Errors from sinks must not crash the LLM call. Forensic capture is\n // best-effort; the structured trace is the system of record.\n try {\n await sink.record(redactor(event))\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction headersToObject(h: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n h.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nexport async function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts, true)\n}\n","/**\n * OpenAI-compatible client. The CLASS is internal; one transport now drives it\n * for public callers.\n *\n * agent-eval never goes looking for a credential — it reads no environment\n * variable to find one — and this module is still not reachable through any\n * export subpath. What reaches a consumer is `createChatClient({ transport:\n * 'openai-compatible', baseUrl, apiKey })`, the sanctioned public route, which\n * constructs this client from an endpoint and a credential the caller passed as\n * values. Anything richer than that transport's options stays in-repo.\n *\n * Three in-repo callers hold the class directly:\n * - `src/analyst/chat-client.ts`, the public transport above;\n * - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose\n * caller is a JSON-RPC client in another language and which therefore\n * configures its own endpoint from its own environment;\n * - the loopback optimizer proxy path (`src/analyst/benchmark-public-model.ts`,\n * `src/analyst/dspy-rlm-engine.ts`), which targets `http://127.0.0.1:<port>/v1`\n * with an ephemeral token and executes nothing itself.\n *\n * The canonical request/result TYPES it defines ARE public — they are the\n * contract every caller-owned transport speaks.\n *\n * OpenAI-compatible `/v1/chat/completions` client with:\n * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).\n * - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).\n * - One retry at temperature 1 when a model explicitly requires it.\n * - Graceful json_schema → json_object degrade on 400 with schema-reject body.\n * - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.\n * - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI\n * directly, cli-bridge subscriptions, and any router that speaks the spec.\n *\n * Usage:\n * const { value, result } = await callLlmJson<MyType>(\n * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },\n * { baseUrl: process.env.AGENT_EVAL_LLM_BASE_URL, apiKey: process.env.AGENT_EVAL_LLM_API_KEY },\n * )\n *\n */\n\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './llm-client/contract'\nimport { parseJsonResult } from './llm-client/json'\nimport { callLlm, callLlmStructured } from './llm-client/request'\nimport {\n pacingStateFor,\n pacingStates,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n} from './llm-client/resilience'\n\nexport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client/accounting'\nexport type {\n LlmCallMetadata,\n LlmCallRequest,\n LlmCallResult,\n LlmChargeBounds,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n LlmToolChoice,\n LlmToolDefinition,\n LlmUsage,\n} from './llm-client/contract'\nexport { LlmCallError, LlmResponseError } from './llm-client/errors'\nexport { extractJsonPayload, stripFencedJson } from './llm-client/json'\nexport { callLlm } from './llm-client/request'\nexport { backoffMs, isTransientLlmError } from './llm-client/resilience'\n\n/**\n * Structured-output call. Returns parsed JSON plus the raw result envelope.\n * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —\n * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept\n * the `response_format.json_schema` shape but DO accept `json_object`.\n */\nexport async function callLlmJson<T = unknown>(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<{ value: T; result: LlmCallResult }> {\n const result = await callLlmStructured(req, opts)\n const value = parseJsonResult<T>(result, opts.jsonPayloadMode ?? 'extract')\n return { value, result }\n}\n\n/**\n * Stateful client — construct once with defaults, call many times.\n * Thin wrapper around the free functions; exists for callers that want\n * to inject a single configured instance into multiple primitives.\n */\nexport class LlmClient {\n readonly maximumAttempts: number\n private readonly opts: LlmClientOptions\n\n constructor(opts: LlmClientOptions = {}) {\n this.opts = opts\n this.maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n resolveMinIntervalMs(opts.minIntervalMs)\n }\n\n private callOptions(per?: LlmClientOptions): LlmClientOptions {\n const options = { ...this.opts, ...per }\n pacingStates.set(options, pacingStateFor(this.opts))\n return options\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = this.callOptions(per)\n return req.jsonSchema ? callLlmStructured(req, options) : callLlm(req, options)\n }\n\n callJson<T = unknown>(\n req: LlmCallRequest,\n per?: LlmClientOptions,\n ): Promise<{ value: T; result: LlmCallResult }> {\n return callLlmJson<T>(req, this.callOptions(per))\n }\n}\n"],"mappings":";;;;;;;AACA,SAAgB,oBACd,GAAG,SACsB;CACzB,MAAM,SAAS,CACb,GAAG,IAAI,IAAI,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS,CAAC,CACpF;CACA,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,IAAI,OAAO,WAAW,GAAG,OAAO,OAAO;CACvC,OAAO,YAAY,IAAI,MAAM;AAC/B;;ACGA,MAAa,qBAAqB,OAAO,QAAQ,IAAI,qBAAqB,KAAK;AAE/E,MAAM,2BACJ,QAAQ,IAAI,gCAAgC,KAAA,IACxC,IACA,OAAO,QAAQ,IAAI,2BAA2B;AAEpD,SAAgB,uBAAuB,YAAwC;CAC7E,MAAM,WAAW,cAAc;CAC/B,IAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,YAAY,GAC7C,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e,KAAK,KAAK,YAAY,GAAG,CAAC;CAClD;AACF"}
1
+ {"version":3,"file":"llm-client-gRPgIJyz.js","names":[],"sources":["../src/abort-signal.ts","../src/llm-client/resilience.ts","../src/llm-client/wire.ts","../src/llm-client/accounting.ts","../src/llm-client/request.ts","../src/llm-client.ts"],"sourcesContent":["/** Combine active cancellation sources without wrapping a single source. */\nexport function combineAbortSignals(\n ...signals: Array<AbortSignal | undefined>\n): AbortSignal | undefined {\n const active = [\n ...new Set(signals.filter((signal): signal is AbortSignal => signal !== undefined)),\n ]\n if (active.length === 0) return undefined\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n","import type { LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\n// Flagship / reasoning models routinely take several minutes on large prompts (a\n// reflection over many failures, a long tool transcript). A tight cap aborts a\n// legitimately-slow but healthy call — and because every retry attempt re-uses\n// the same window, such a model aborts on ALL attempts and the loop throws. The\n// default is generous enough to let those complete, bounded enough that a truly\n// hung call still fails over after retries, and tunable per deployment via\n// TANGLE_LLM_TIMEOUT_MS. Per-call `req.timeoutMs` / `opts.defaultTimeoutMs`\n// still win for callers that know their model's latency.\nexport const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\n\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 6\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nexport function resolveMaximumAttempts(configured: number | undefined): number {\n const attempts = configured ?? DEFAULT_MAXIMUM_ATTEMPTS\n if (!Number.isInteger(attempts) || attempts <= 0) {\n throw new RangeError('LLM maximum attempts must be a positive integer')\n }\n return attempts\n}\n\nexport function resolveMinIntervalMs(configured: number | undefined): number {\n const interval = configured ?? 0\n if (!Number.isFinite(interval) || interval < 0) {\n throw new RangeError('LLM minIntervalMs must be a finite non-negative number')\n }\n return interval\n}\n\n// Weak keys avoid retaining credentials or completed campaigns. LlmClient binds\n// its per-call option copies to the same state as its constructor options.\nexport const pacingStates = new WeakMap<LlmClientOptions, { lastStartedAt?: number }>()\n\nexport function pacingStateFor(opts: LlmClientOptions): { lastStartedAt?: number } {\n let state = pacingStates.get(opts)\n if (!state) {\n state = {}\n pacingStates.set(opts, state)\n }\n return state\n}\n\n// 522/524: Cloudflare edge timeouts (origin connect/respond) — transient\n// exactly like 504. Router deployments serve through Cloudflare, so a long\n// non-streaming call can draw these from the edge, not the origin.\nexport const RETRYABLE_STATUS = new Set([429, 502, 503, 504, 522, 524])\n\n/**\n * Transient transport/network error signatures, matched against an error's\n * name, message, and `code`. Covers fetch/undici network failures, aborts\n * and timeouts, and — critically — HTTP/2 transport faults a keep-alive\n * connection raises mid-response: `terminated`, `NGHTTP2_INTERNAL_ERROR`,\n * `UND_ERR_*`, `other side closed`. Those last ones carry no clean HTTP\n * status; unrecognised, they escape the retry loop and surface as an\n * uncaught rejection.\n */\nconst TRANSIENT_ERROR_PATTERNS: readonly RegExp[] = [\n /AbortError/i,\n /TimeoutError/i,\n /this operation was aborted/i,\n /fetch failed/i,\n /ECONNRESET/i,\n /ETIMEDOUT/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /stream.*ended.*unexpectedly/i,\n /terminated/i,\n /other side closed/i,\n /NGHTTP2/i,\n /UND_ERR/i,\n]\n\n/**\n * True when an error is a transient transport/network fault worth retrying,\n * as opposed to a deterministic failure (4xx schema reject, JSON parse) that\n * a retry cannot fix. Inspects `LlmCallError.status`, then the error's\n * name/message/code, then recurses into `error.cause` — undici nests the\n * real socket fault one or more levels under `.cause`.\n *\n * This is the retry classifier for the package: `callLlm` and\n * `withJudgeRetry` both route through it, so connection failures are treated\n * consistently across transports.\n */\nexport function isTransientLlmError(err: unknown): boolean {\n return classifyTransient(err, 0)\n}\n\nfunction classifyTransient(err: unknown, depth: number): boolean {\n if (err instanceof LlmCallError) return RETRYABLE_STATUS.has(err.status)\n if (!(err instanceof Error)) return false\n // Foreign transport errors can carry a numeric HTTP status without being an\n // LlmCallError. A retryable status is decisive.\n const status = (err as { status?: unknown }).status\n if (typeof status === 'number' && RETRYABLE_STATUS.has(status)) return true\n const code = (err as { code?: unknown }).code\n const haystack = `${err.name}\\n${err.message}\\n${typeof code === 'string' ? code : ''}`\n if (TRANSIENT_ERROR_PATTERNS.some((p) => p.test(haystack))) return true\n const cause = (err as { cause?: unknown }).cause\n if (depth < 4 && cause instanceof Error && cause !== err) {\n return classifyTransient(cause, depth + 1)\n }\n return false\n}\n\nexport function parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')?.trim()\n if (!h) return null\n const asNumber = Number(h)\n if (!Number.isNaN(asNumber)) {\n const delay = asNumber * 1000\n return Number.isFinite(delay) && delay >= 0 ? delay : null\n }\n const asDate = Date.parse(h)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return null\n}\n\n/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */\nexport function backoffMs(attempt: number): number {\n return Math.min(500 * 2 ** attempt, 16_000)\n}\n\n/** Backoff belongs to the caller's operation and must stop when it is cancelled. */\nexport async function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n // A timer above the signed 32-bit limit becomes a near-immediate timeout.\n // Split long server delays rather than truncating Retry-After or overflowing.\n do {\n signal?.throwIfAborted()\n const chunk = Math.min(Math.ceil(ms), 2_147_483_647)\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n reject(signal?.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, chunk)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n ms -= chunk\n } while (ms > 0)\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nexport function deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n","import type {\n LlmCallRequest,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n} from './contract'\n\nexport function providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nexport function buildHeaders(opts: LlmClientOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (opts.authHeader) {\n headers[opts.authHeader.name] = opts.authHeader.value\n } else if (opts.bearer || opts.apiKey) {\n headers.Authorization = `Bearer ${opts.bearer ?? opts.apiKey}`\n }\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n return headers\n}\n\nexport function isSchemaRejection(status: number, body: string): boolean {\n if (status !== 400) return false\n const lower = body.toLowerCase()\n return (\n lower.includes('response_format') ||\n lower.includes('json_schema') ||\n lower.includes('is unavailable') ||\n lower.includes('not supported')\n )\n}\n\nexport function isTemperatureOneRejection(status: number, body: string): boolean {\n if (status !== 400 || !/temperature/i.test(body)) return false\n return (\n /temperature[^.\\n]{0,120}\\b(?:only|must|should|required|requires?)\\b[^.\\n]{0,40}\\b1(?:\\.0+)?\\b/i.test(\n body,\n ) || /\\bonly\\s+1(?:\\.0+)?\\s+is\\s+allowed\\b[^.\\n]{0,120}\\btemperature\\b/i.test(body)\n )\n}\n\nexport function buildBody(\n req: LlmCallRequest,\n forceJsonObject: boolean,\n defaultThinking?: LlmThinkingMode,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model: req.model,\n messages: req.messages.map(encodeWireMessage),\n temperature: req.temperature ?? 0,\n }\n if (req.maxTokens != null) {\n if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens\n else body.max_tokens = req.maxTokens\n }\n if (req.logprobs !== undefined) {\n body.logprobs = true\n body.top_logprobs = req.logprobs.topLogprobs\n }\n if (req.tools !== undefined) body.tools = req.tools\n if (req.toolChoice !== undefined) body.tool_choice = req.toolChoice\n const thinking = req.thinking ?? defaultThinking\n if (thinking !== undefined) {\n body.thinking = { type: thinking }\n }\n\n if (req.jsonSchema && !forceJsonObject) {\n body.response_format = {\n type: 'json_schema',\n json_schema: { name: req.jsonSchema.name, schema: req.jsonSchema.schema, strict: true },\n }\n } else if (req.jsonMode || req.jsonSchema) {\n body.response_format = { type: 'json_object' }\n }\n\n return body\n}\n\nfunction usesMaxCompletionTokens(model: string): boolean {\n return /^gpt-5(?:[.-]|$)/i.test(model)\n}\n\n/** Encode one canonical message as its OpenAI chat-completions wire shape. */\nfunction encodeWireMessage(message: LlmMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content }\n }\n if (message.toolCalls === undefined) {\n return { role: message.role, content: message.content }\n }\n return {\n role: message.role,\n content: message.content,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: call.argumentsJson },\n })),\n }\n}\n\n/**\n * Parse `choices[0].logprobs.content` into the canonical per-token shape.\n * `null` when the provider returned nothing for a request that asked: a\n * provider that ignores `logprobs` is a fact the caller must be able to read,\n * not an error. A malformed entry is a contract violation and throws.\n */\nexport function parseWireLogprobs(\n value: unknown,\n model: string,\n): ReadonlyArray<LlmTokenLogprob> | null {\n if (value === undefined || value === null) return null\n if (!Array.isArray(value)) {\n throw new Error(`LLM response logprobs.content must be an array (model=${model})`)\n }\n return value.map((entry, index) => {\n const record = entry as { token?: unknown; logprob?: unknown; top_logprobs?: unknown } | null\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.token !== 'string' ||\n typeof record.logprob !== 'number' ||\n !Number.isFinite(record.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}] is not a token with a finite logprob (model=${model})`,\n )\n }\n const top = record.top_logprobs\n if (top !== undefined && top !== null && !Array.isArray(top)) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs must be an array (model=${model})`,\n )\n }\n return {\n token: record.token,\n logprob: record.logprob,\n top: (Array.isArray(top) ? top : []).map((alternative, position) => {\n const candidate = alternative as { token?: unknown; logprob?: unknown } | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.token !== 'string' ||\n typeof candidate.logprob !== 'number' ||\n !Number.isFinite(candidate.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs[${position}] is not a token with a finite logprob (model=${model})`,\n )\n }\n return { token: candidate.token, logprob: candidate.logprob }\n }),\n }\n })\n}\n\n/** Parse provider tool_calls into the canonical shape. A malformed entry is a\n * provider-contract violation and throws rather than degrading silently. */\nexport function parseWireToolCalls(value: unknown, model: string): LlmToolCall[] | undefined {\n if (value === undefined || value === null) return undefined\n if (!Array.isArray(value)) {\n throw new Error(`LLM response tool_calls must be an array (model=${model})`)\n }\n if (value.length === 0) return undefined\n return value.map((entry, index) => {\n const record = entry as {\n id?: unknown\n type?: unknown\n function?: { name?: unknown; arguments?: unknown } | null\n } | null\n const fn = record && typeof record === 'object' ? record.function : undefined\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.id !== 'string' ||\n record.id.length === 0 ||\n (record.type !== undefined && record.type !== 'function') ||\n !fn ||\n typeof fn !== 'object' ||\n typeof fn.name !== 'string' ||\n fn.name.length === 0 ||\n typeof fn.arguments !== 'string'\n ) {\n throw new Error(\n `LLM response tool_calls[${index}] is not a function call with string arguments (model=${model})`,\n )\n }\n return { id: record.id, name: fn.name, argumentsJson: fn.arguments }\n })\n}\n","import type { CostReceiptInput, CustomTokenPricing, MaximumCharge } from '../cost-ledger'\nimport type { LlmCallRequest, LlmCallResult, LlmChargeBounds } from './contract'\nimport { LlmResponseError } from './errors'\nimport { resolveMaximumAttempts } from './resilience'\nimport { buildBody } from './wire'\n\nexport function maximumChargeForLlmRequest(\n request: Pick<\n LlmCallRequest,\n 'model' | 'messages' | 'jsonSchema' | 'tools' | 'toolChoice' | 'maxTokens' | 'thinking'\n >,\n options: LlmChargeBounds = {},\n): MaximumCharge | undefined {\n if (request.maxTokens === undefined) return undefined\n if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) {\n throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`)\n }\n if (\n request.messages.some(\n (message) =>\n Array.isArray(message.content) && message.content.some((part) => part.type === 'image_url'),\n )\n ) {\n return undefined\n }\n\n const attempts = resolveMaximumAttempts(options.maximumAttempts)\n const forceJsonObject = options.jsonSchemaTransport === 'json-object'\n // A byte-level tokenizer cannot emit more input tokens than request bytes.\n // Pricing the complete body also covers role/schema framing omitted from content-only estimates.\n const requestBytes = new TextEncoder().encode(\n JSON.stringify(buildBody(request, forceJsonObject, options.thinking)),\n ).byteLength\n // Schema fallback shares the same physical-attempt budget; it cannot buy a second batch.\n const usage = {\n inputTokens: requestBytes * attempts,\n outputTokens: request.maxTokens * attempts,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\n/** Convert a provider result into the canonical paid-call receipt input.\n * The receipt is JSON-clean: absent optional fields are omitted, never carried\n * as explicit-undefined keys. Receipts cross JSON boundaries (the external\n * optimizer's loopback proxy validates them with `assertJsonValue`), where an\n * explicit-undefined value is rejected as non-serializable. */\nexport function costReceiptFromLlm(\n result: LlmCallResult,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput {\n const cachedTokens = result.usage.cachedPromptTokens ?? 0\n const inputTokens = Math.max(0, result.usage.promptTokens - cachedTokens)\n const providerCostUsd = providerReportedCost(result.raw)\n return {\n model: result.model,\n inputTokens,\n outputTokens: result.usage.completionTokens,\n ...(result.usage.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: result.usage.reasoningTokens }),\n ...(cachedTokens > 0 ? { cachedTokens } : {}),\n ...(providerCostUsd === undefined\n ? customTokenPricing && result.usage.captured !== false\n ? { customTokenPricing }\n : result.costUsd === null\n ? {}\n : { estimatedCostUsd: result.costUsd }\n : { actualCostUsd: providerCostUsd }),\n usageUnknown: result.usage.captured === false,\n }\n}\n\nexport function providerReportedCost(raw: Record<string, unknown>): number | undefined {\n const value = raw._response_cost ?? raw.cost_usd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/** Structured-response failures retain their completed provider receipt. */\nexport function costReceiptFromLlmError(\n error: Error,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput | undefined {\n return error instanceof LlmResponseError\n ? costReceiptFromLlm(error.result, customTokenPricing)\n : undefined\n}\n","import { combineAbortSignals } from '../abort-signal'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { assertServedModel as assertServedModelIdentity } from '../integrity/served-model'\nimport { newRecordId } from '../record-id'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from '../trace/raw-provider-sink'\nimport { providerReportedCost } from './accounting'\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\nimport {\n backoffMs,\n DEFAULT_TIMEOUT_MS,\n deadlineExceeded,\n isTransientLlmError,\n pacingStateFor,\n parseRetryAfter,\n RETRYABLE_STATUS,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n sleep,\n} from './resilience'\nimport {\n buildBody,\n buildHeaders,\n isSchemaRejection,\n isTemperatureOneRejection,\n parseWireLogprobs,\n parseWireToolCalls,\n providerTokenCount,\n} from './wire'\n\n/**\n * Low-level call. Returns raw content + usage + cost. Retries on transient\n * failures; does NOT degrade schema here — callers that want graceful\n * degrade use `callLlmJson`.\n */\nexport async function callLlm(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts(req, opts, false)\n}\n\n/** One retry owner for raw and structured calls. Fallback changes the next\n * request, not the attempt allowance, deadline origin, or raw-event sequence. */\n/** What one call shares across its attempts: the resolved options, pacing, deadline and the request as it now stands. */\ninterface AttemptRun {\n readonly req: LlmCallRequest\n readonly opts: LlmClientOptions\n readonly allowSchemaFallback: boolean\n readonly baseUrl: string\n readonly url: string\n readonly timeoutMs: number\n readonly maximumAttempts: number\n readonly minIntervalMs: number\n readonly pacing: ReturnType<typeof pacingStateFor>\n readonly headers: ReturnType<typeof buildHeaders>\n readonly provider: string\n readonly deadlineStart: number\n readonly remainingMs: () => number\n readonly retryDelay: (ms: number) => Promise<void>\n effectiveRequest: LlmCallRequest\n lastErr: unknown\n}\n\n/** How one attempt ended without a result or a thrown error. */\ntype AttemptOutcome =\n | { kind: 'result'; result: LlmCallResult }\n | { kind: 'retry' }\n | { kind: 'exhausted' }\n\n/** Which of an attempt's raw events were already written, so the failure path records at most one error. */\ninterface AttemptState {\n dispatched: boolean\n errorRecorded: boolean\n}\n\nconst ENDPOINT = '/chat/completions'\n\nfunction startAttemptRun(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): AttemptRun {\n // No default endpoint. This client is internal to the `agent-eval` binary\n // and the loopback optimizer proxy; both name their endpoint explicitly, and\n // a fallback would let a misconfigured caller bill an unintended provider.\n if (!opts.baseUrl) throw new Error('callLlm: opts.baseUrl is required')\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n const remainingMs = () =>\n deadlineMs === undefined ? Infinity : Math.max(0, deadlineMs - (Date.now() - deadlineStart))\n const run: AttemptRun = {\n req,\n opts,\n allowSchemaFallback,\n baseUrl,\n url: `${baseUrl}${ENDPOINT}`,\n timeoutMs: req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS,\n maximumAttempts: resolveMaximumAttempts(opts.maximumAttempts),\n minIntervalMs: resolveMinIntervalMs(opts.minIntervalMs),\n pacing: pacingStateFor(opts),\n headers: buildHeaders(opts),\n provider: opts.provider ?? providerFromBaseUrl(baseUrl),\n deadlineStart,\n remainingMs,\n retryDelay: (ms) => sleep(Math.min(ms, remainingMs()), opts.signal),\n effectiveRequest: req,\n lastErr: undefined,\n }\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n return run\n}\n\nfunction deadlineError(run: AttemptRun): Error | DOMException {\n return run.lastErr instanceof Error\n ? run.lastErr\n : new DOMException('callLlm deadline exceeded', 'TimeoutError')\n}\n\n/** Write one raw provider event for this attempt. Does nothing without a sink. */\nasync function recordAttemptEvent(\n run: AttemptRun,\n attempt: number,\n fields: Pick<RawProviderEvent, 'direction' | 'timestamp'> & Partial<RawProviderEvent>,\n): Promise<void> {\n const { opts } = run\n if (!opts.rawSink) return\n await recordRaw(opts.rawSink, opts.redactor ?? defaultProviderRedactor, {\n eventId: newRecordId(),\n runId: opts.traceContext?.runId,\n spanId: opts.traceContext?.spanId,\n provider: run.provider,\n model: run.req.model,\n endpoint: ENDPOINT,\n baseUrl: run.baseUrl,\n attemptIndex: attempt,\n ...fields,\n redactedFields: [],\n })\n}\n\n/**\n * Wait for this client's pacing slot, and claim it. Every wake rechecks, so concurrent waiters\n * cannot dispatch a catch-up burst; the claim is made in the same synchronous step that finds the\n * slot free, so no other waiter can slip in between the check and the claim.\n */\nasync function awaitPacingSlot(run: AttemptRun): Promise<number> {\n const { opts, pacing, minIntervalMs } = run\n while (true) {\n opts.signal?.throwIfAborted()\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const waitMs =\n pacing.lastStartedAt === undefined ? 0 : pacing.lastStartedAt + minIntervalMs - Date.now()\n if (waitMs <= 0) {\n // Queue time consumes the operation deadline, not the HTTP timeout.\n const started = Date.now()\n pacing.lastStartedAt = started\n return started\n }\n await run.retryDelay(waitMs)\n }\n}\n\n/** Answer a non-2xx response: retry with an adjusted request or after a wait, give up, or throw its error. */\nasync function handleHttpFailure(\n run: AttemptRun,\n attempt: number,\n res: Response,\n body: string,\n responseHeaders: Record<string, string> | undefined,\n started: number,\n state: AttemptState,\n): Promise<AttemptOutcome> {\n const { req, opts, maximumAttempts, deadlineStart } = run\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: body,\n errorMessage: `HTTP ${res.status}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n const canRetry =\n attempt < maximumAttempts - 1 && !deadlineExceeded(deadlineStart, opts.deadlineMs)\n if (\n isTemperatureOneRejection(res.status, body) &&\n run.effectiveRequest.temperature !== 1 &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, temperature: 1 }\n return { kind: 'retry' }\n }\n if (\n run.allowSchemaFallback &&\n opts.jsonSchemaTransport !== 'json-object' &&\n run.effectiveRequest.jsonSchema &&\n isSchemaRejection(res.status, body) &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, jsonMode: true, jsonSchema: undefined }\n return { kind: 'retry' }\n }\n if (RETRYABLE_STATUS.has(res.status) && canRetry) {\n run.lastErr = err\n const wait = parseRetryAfter(res.headers) ?? backoffMs(attempt)\n // A wait the deadline cannot cover ends the call with this answer. Sleeping to the\n // deadline let a timer that fired a millisecond early start one more attempt with no time\n // left, whose abort replaced the server's status (agent-eval publish run 37238259408).\n if (wait >= run.remainingMs()) {\n // A caller abort that landed while the answer was recorded still wins, as the\n // retry wait would have reported it.\n opts.signal?.throwIfAborted()\n return { kind: 'exhausted' }\n }\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n throw err\n}\n\n/** Turn a parsed completion into the call result: content, tool calls, usage with its completeness, and cost. */\nfunction parseCompletion(\n run: AttemptRun,\n json: Record<string, unknown>,\n started: number,\n): LlmCallResult {\n const { req, opts } = run\n const choice = (\n json.choices as\n | Array<{\n message?: { content?: string | null; tool_calls?: unknown }\n finish_reason?: string | null\n logprobs?: { content?: unknown } | null\n }>\n | undefined\n )?.[0]\n const toolCalls = parseWireToolCalls(choice?.message?.tool_calls, req.model)\n const usageRaw =\n json.usage && typeof json.usage === 'object' && !Array.isArray(json.usage)\n ? (json.usage as Record<string, unknown>)\n : undefined\n const promptTokens = providerTokenCount(usageRaw?.prompt_tokens)\n const completionTokens = providerTokenCount(usageRaw?.completion_tokens)\n const totalTokens = providerTokenCount(usageRaw?.total_tokens)\n const completionDetails =\n usageRaw?.completion_tokens_details &&\n typeof usageRaw.completion_tokens_details === 'object' &&\n !Array.isArray(usageRaw.completion_tokens_details)\n ? (usageRaw.completion_tokens_details as Record<string, unknown>)\n : undefined\n const reasoningRaw = completionDetails?.reasoning_tokens\n const reasoningTokens = reasoningRaw === undefined ? undefined : providerTokenCount(reasoningRaw)\n const cachedRaw =\n usageRaw?.prompt_tokens_details &&\n typeof usageRaw.prompt_tokens_details === 'object' &&\n !Array.isArray(usageRaw.prompt_tokens_details)\n ? (usageRaw.prompt_tokens_details as Record<string, unknown>).cached_tokens\n : undefined\n const cachedPromptTokens = cachedRaw === undefined ? undefined : providerTokenCount(cachedRaw)\n const usageCaptured =\n promptTokens !== undefined &&\n completionTokens !== undefined &&\n (reasoningRaw === undefined ||\n (reasoningTokens !== undefined && reasoningTokens <= completionTokens)) &&\n (cachedRaw === undefined ||\n (cachedPromptTokens !== undefined && cachedPromptTokens <= promptTokens)) &&\n (totalTokens === undefined || totalTokens === promptTokens + completionTokens)\n const costFromProxy = providerReportedCost(json)\n const content = choice?.message?.content ?? ''\n\n const configuredCost =\n typeof costFromProxy !== 'number' && usageCaptured && opts.customTokenPricing\n ? costForTokenPricing(opts.customTokenPricing, {\n inputTokens: promptTokens! - (cachedPromptTokens ?? 0),\n ...(cachedPromptTokens ? { cachedTokens: cachedPromptTokens } : {}),\n outputTokens: completionTokens!,\n })\n : undefined\n\n // The echoed id, kept separate from the attribution id: a provider that\n // omits it must read as \"unproven\", never as \"the model I asked for\".\n const servedModel = typeof json.model === 'string' && json.model.trim() !== '' ? json.model : null\n if (opts.assertServedModel) {\n assertServedModelIdentity(\n req.model,\n servedModel,\n opts.assertServedModel === true ? {} : opts.assertServedModel,\n )\n }\n\n return {\n content,\n ...(toolCalls === undefined ? {} : { toolCalls }),\n ...(req.logprobs === undefined\n ? {}\n : { logprobs: parseWireLogprobs(choice?.logprobs?.content, req.model) }),\n finishReason: choice?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n usage: {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: totalTokens ?? (promptTokens ?? 0) + (completionTokens ?? 0),\n captured: usageCaptured,\n reasoningTokens,\n cachedPromptTokens,\n },\n costUsd: typeof costFromProxy === 'number' ? costFromProxy : (configuredCost ?? null),\n model: servedModel ?? req.model,\n servedModel,\n durationMs: Date.now() - started,\n raw: json,\n }\n}\n\n/** One attempt: pace, dispatch, read the answer. A failure either becomes a retry outcome or is thrown. */\nasync function runAttempt(run: AttemptRun, attempt: number): Promise<AttemptOutcome> {\n const { opts } = run\n const callerSignal = opts.signal\n // A caller cancel is fatal — never retried. Checking before each attempt\n // means an already-aborted signal short-circuits without firing fetch.\n if (callerSignal?.aborted) {\n throw new DOMException('callLlm aborted by caller signal', 'AbortError')\n }\n // Stop retrying once the cross-attempt budget is spent rather than burning\n // a full per-attempt timeout on each remaining retry.\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const requestBody = buildBody(\n run.effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n const controller = new AbortController()\n const attemptSignal = combineAbortSignals(controller.signal, callerSignal)!\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n let started = Date.now()\n // An attempt cancelled or timed out while queued never reached the\n // provider, so it leaves no request or error event in the raw log.\n const state: AttemptState = { dispatched: false, errorRecorded: false }\n try {\n if (run.minIntervalMs > 0) {\n started = await awaitPacingSlot(run)\n } else {\n // Claim the slot before any await so a concurrent waiter cannot take it.\n run.pacing.lastStartedAt = started\n }\n state.dispatched = true\n timeoutHandle = setTimeout(() => controller.abort(), Math.min(run.timeoutMs, run.remainingMs()))\n await recordAttemptEvent(run, attempt, {\n direction: 'request',\n timestamp: started,\n requestHeaders: run.headers,\n requestBody,\n })\n attemptSignal.throwIfAborted()\n const res = await (opts.fetch ?? globalThis.fetch)(run.url, {\n method: 'POST',\n headers: run.headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n const responseHeaders = opts.rawSink ? headersToObject(res.headers) : undefined\n // Headers are not completion: the same timeout/cancellation covers either response body.\n const text = await res.text()\n attemptSignal.throwIfAborted()\n clearTimeout(timeoutHandle)\n\n if (!res.ok) {\n return await handleHttpFailure(run, attempt, res, text, responseHeaders, started, state)\n }\n\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: text,\n errorMessage: `non-JSON response: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n throw parseErr\n }\n await recordAttemptEvent(run, attempt, {\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n })\n return { kind: 'result', result: parseCompletion(run, json, started) }\n } catch (err) {\n clearTimeout(timeoutHandle)\n run.lastErr = err\n // Record only if neither the !res.ok branch nor the JSON.parse catch\n // already produced an error event for this attempt. Covers network\n // failures, timeouts, and aborts.\n if (state.dispatched && !state.errorRecorded) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n }\n // A caller cancel is fatal even though an AbortError matches the\n // transient patterns — a cancelled call must surface immediately, not\n // be retried against the same dead intent.\n if (callerSignal?.aborted) throw err\n const wait = backoffMs(attempt)\n if (\n attempt < run.maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(run.deadlineStart, opts.deadlineMs) &&\n wait < run.remainingMs()\n ) {\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n callerSignal?.throwIfAborted()\n throw err\n } finally {\n clearTimeout(timeoutHandle)\n }\n}\n\nasync function callLlmAttempts(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): Promise<LlmCallResult> {\n const run = startAttemptRun(req, opts, allowSchemaFallback)\n for (let attempt = 0; attempt < run.maximumAttempts; attempt++) {\n const outcome = await runAttempt(run, attempt)\n if (outcome.kind === 'result') return outcome.result\n if (outcome.kind === 'exhausted') break\n }\n throw run.lastErr instanceof Error ? run.lastErr : new Error(String(run.lastErr))\n}\n\nasync function recordRaw(\n sink: RawProviderSink,\n redactor: ProviderRedactor,\n event: RawProviderEvent,\n): Promise<void> {\n // Errors from sinks must not crash the LLM call. Forensic capture is\n // best-effort; the structured trace is the system of record.\n try {\n await sink.record(redactor(event))\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction headersToObject(h: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n h.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nexport async function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts, true)\n}\n","/**\n * OpenAI-compatible client. The CLASS is internal; one transport now drives it\n * for public callers.\n *\n * agent-eval never goes looking for a credential — it reads no environment\n * variable to find one — and this module is still not reachable through any\n * export subpath. What reaches a consumer is `createChatClient({ transport:\n * 'openai-compatible', baseUrl, apiKey })`, the sanctioned public route, which\n * constructs this client from an endpoint and a credential the caller passed as\n * values. Anything richer than that transport's options stays in-repo.\n *\n * Three in-repo callers hold the class directly:\n * - `src/analyst/chat-client.ts`, the public transport above;\n * - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose\n * caller is a JSON-RPC client in another language and which therefore\n * configures its own endpoint from its own environment;\n * - the loopback optimizer proxy path (`src/analyst/benchmark-public-model.ts`,\n * `src/analyst/dspy-rlm-engine.ts`), which targets `http://127.0.0.1:<port>/v1`\n * with an ephemeral token and executes nothing itself.\n *\n * The canonical request/result TYPES it defines ARE public — they are the\n * contract every caller-owned transport speaks.\n *\n * OpenAI-compatible `/v1/chat/completions` client with:\n * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).\n * - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).\n * - One retry at temperature 1 when a model explicitly requires it.\n * - Graceful json_schema → json_object degrade on 400 with schema-reject body.\n * - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.\n * - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI\n * directly, cli-bridge subscriptions, and any router that speaks the spec.\n *\n * Usage:\n * const { value, result } = await callLlmJson<MyType>(\n * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },\n * { baseUrl: process.env.AGENT_EVAL_LLM_BASE_URL, apiKey: process.env.AGENT_EVAL_LLM_API_KEY },\n * )\n *\n */\n\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './llm-client/contract'\nimport { parseJsonResult } from './llm-client/json'\nimport { callLlm, callLlmStructured } from './llm-client/request'\nimport {\n pacingStateFor,\n pacingStates,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n} from './llm-client/resilience'\n\nexport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client/accounting'\nexport type {\n LlmCallMetadata,\n LlmCallRequest,\n LlmCallResult,\n LlmChargeBounds,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n LlmToolChoice,\n LlmToolDefinition,\n LlmUsage,\n} from './llm-client/contract'\nexport { LlmCallError, LlmResponseError } from './llm-client/errors'\nexport { extractJsonPayload, stripFencedJson } from './llm-client/json'\nexport { callLlm } from './llm-client/request'\nexport { backoffMs, isTransientLlmError } from './llm-client/resilience'\n\n/**\n * Structured-output call. Returns parsed JSON plus the raw result envelope.\n * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —\n * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept\n * the `response_format.json_schema` shape but DO accept `json_object`.\n */\nexport async function callLlmJson<T = unknown>(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<{ value: T; result: LlmCallResult }> {\n const result = await callLlmStructured(req, opts)\n const value = parseJsonResult<T>(result, opts.jsonPayloadMode ?? 'extract')\n return { value, result }\n}\n\n/**\n * Stateful client — construct once with defaults, call many times.\n * Thin wrapper around the free functions; exists for callers that want\n * to inject a single configured instance into multiple primitives.\n */\nexport class LlmClient {\n readonly maximumAttempts: number\n private readonly opts: LlmClientOptions\n\n constructor(opts: LlmClientOptions = {}) {\n this.opts = opts\n this.maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n resolveMinIntervalMs(opts.minIntervalMs)\n }\n\n private callOptions(per?: LlmClientOptions): LlmClientOptions {\n const options = { ...this.opts, ...per }\n pacingStates.set(options, pacingStateFor(this.opts))\n return options\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = this.callOptions(per)\n return req.jsonSchema ? callLlmStructured(req, options) : callLlm(req, options)\n }\n\n callJson<T = unknown>(\n req: LlmCallRequest,\n per?: LlmClientOptions,\n ): Promise<{ value: T; result: LlmCallResult }> {\n return callLlmJson<T>(req, this.callOptions(per))\n }\n}\n"],"mappings":";;;;;;;AACA,SAAgB,oBACd,GAAG,SACsB;CACzB,MAAM,SAAS,CACb,GAAG,IAAI,IAAI,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS,CAAC,CACpF;CACA,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,IAAI,OAAO,WAAW,GAAG,OA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0C;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,33 +1,35 @@
1
1
  import { s as ValidationError } from "./errors-DeEEV9Vx.js";
2
- import { a as hashCanonical, i as compareCodeUnits, r as canonicalString, t as LEDGER_HASH_PATTERN } from "./canonical-BANK6NOj.js";
3
- import { c as searchCellRunId, i as modelHasSnapshot } from "./run-record-Dx64nPcX.js";
4
- import { n as compareModelIdentities, t as captureModelTreatment } from "./model-comparison-BZr_Hu00.js";
5
- import { dt as weightedComposite, pt as mean$1, rt as confidenceInterval, ut as summarizeNumberSeries } from "./statistics-CHs0jlsY.js";
2
+ import { a as hashCanonical, i as compareCodeUnits, r as canonicalString, t as LEDGER_HASH_PATTERN } from "./canonical-DKgL_Wby.js";
3
+ import { c as searchCellRunId, i as modelHasSnapshot } from "./run-record-CqUft6Yf.js";
4
+ import { n as compareModelIdentities, t as captureModelTreatment } from "./model-comparison-CgnVh4Ph.js";
5
+ import { dt as weightedComposite, pt as mean$1, rt as confidenceInterval, ut as summarizeNumberSeries } from "./statistics-DSidA5I2.js";
6
6
  import { t as mulberry32 } from "./random-DrzcgC7F.js";
7
- import { r as minimumPairsForPairedDeltaTest } from "./paired-promotion-decision-BoWHWL1i.js";
8
- import { a as heldoutSignificance, i as dimensionRegressions, o as pairHoldout } from "./statistical-heldout-BvcAVtof.js";
9
- import { a as mapConcurrent } from "./journal-DQsbHGjX.js";
10
- import { n as contentHash } from "./verdict-cache-DfzlHLdf.js";
11
- import { r as projectCampaignCellQuality, t as campaignCellCostProvenance } from "./run-record-c860wUR8.js";
7
+ import { r as minimumPairsForPairedDeltaTest } from "./paired-promotion-decision-Dn3-jaq4.js";
8
+ import { a as heldoutSignificance, i as dimensionRegressions, o as pairHoldout } from "./statistical-heldout-CaS4T-43.js";
9
+ import { a as mapConcurrent } from "./journal-3y-btqaP.js";
10
+ import { n as contentHash } from "./verdict-cache-BPaYxfG8.js";
11
+ import { r as projectCampaignCellQuality, t as campaignCellCostProvenance } from "./run-record-Bqg0NZ_e.js";
12
12
  import { n as CostAccountingIncompleteError, t as CostLedger } from "./cost-ledger-1CwUnVOd.js";
13
- import { A as campaignSplitDigest, D as assertCompleteCampaign, E as assertCampaignSplitIdentity, M as formatCoverageFailures, O as campaignCoverage, S as BackendIntegrityError, T as assertCampaignDesign, b as FinalEvidenceError, f as campaignBreakdown, k as campaignScenarioIdentity, m as campaignMeanCompositeOrNull, p as campaignMeanComposite, y as FinalEvidenceConflictError } from "./campaign-evidence-BX8OveG5.js";
13
+ import { A as campaignCoverage, D as assertCampaignDesign, M as campaignSplitDigest, O as assertCampaignSplitIdentity, P as formatCoverageFailures, S as FinalEvidenceError, f as campaignBreakdown, h as campaignMeanCompositeOrNull, j as campaignScenarioIdentity, k as assertCompleteCampaign, m as campaignMeanComposite, w as BackendIntegrityError, x as FinalEvidenceConflictError } from "./campaign-evidence-CsUE_lwc.js";
14
14
  import { t as deepFreezeCanonicalJson } from "./deep-freeze-CK8-2W7p.js";
15
- import { M as fsCampaignStorage, h as isExternalTextCandidate, j as createRunCostLedger } from "./external-optimizer-subprocess-BspZ0bZb.js";
16
- import { c as surfaceDispatchRef, l as surfaceHash, o as renderSurfaceDiff, s as surfaceContentHash, u as surfaceHashMatches } from "./json-recovery-b7O9WVTF.js";
17
- import { r as summarizeEvaluationUnits, t as defineEvaluationClaim } from "./claim-C6LRiwz1.js";
18
- import { a as validateSearchLedgerEvent, d as searchNodeId, f as searchTaskSetDigest, i as replaySearchLedgerText, n as openSearchLedger, u as searchCellId } from "./search-ledger-oyqxZhry.js";
19
- import { D as CLAIM_OPERATION, O as SEARCH_KERNEL_SOURCE, b as estimateNode, i as runSearch, k as searchExpansionIndex, n as paretoFrontier, o as searchPolicyView, r as paretoFrontierWithCrowding, s as EXPANSION_OPERATORS } from "./pareto-BNWWbLNl.js";
15
+ import { b as createRunCostLedger, x as fsCampaignStorage } from "./external-optimizer-subprocess-B48Ie4qQ.js";
16
+ import { c as surfaceDispatchRef, l as surfaceHash, o as renderSurfaceDiff, s as surfaceContentHash, u as surfaceHashMatches } from "./json-recovery-BRUCeQxo.js";
17
+ import { r as summarizeEvaluationUnits, t as defineEvaluationClaim } from "./claim-BWEXwwBk.js";
18
+ import { a as validateSearchLedgerEvent, d as searchNodeId, f as searchTaskSetDigest, i as replaySearchLedgerText, n as openSearchLedger, u as searchCellId } from "./search-ledger-C7t68cmy.js";
19
+ import { D as CLAIM_OPERATION, O as SEARCH_KERNEL_SOURCE, b as estimateNode, i as runSearch, k as searchExpansionIndex, n as paretoFrontier, o as searchPolicyView, r as paretoFrontierWithCrowding, s as EXPANSION_OPERATORS } from "./pareto-Bg75Gajo.js";
20
20
  import { c as redactText, m as detectPersonalData, n as REDACTION_VERSION, p as detectCredential } from "./redact-zp_ILC4l.js";
21
- import { t as detectRewardHacking } from "./reward-hacking-DNiHskry.js";
22
- import { t as assertProposalFindings } from "./proposal-findings-DFQvA-k5.js";
23
- import { n as searchProposerView, t as renderSearchSummary } from "./search-summary-CNHpHFfw.js";
21
+ import { t as detectRewardHacking } from "./reward-hacking-DKAflk2c.js";
22
+ import { t as assertProposalFindings } from "./proposal-findings-DnR7zdUc.js";
24
23
  import { i as stripFencedJson, n as isRecord } from "./json-DtvZNAU9.js";
25
- import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-CdHo3SH0.js";
24
+ import { c as isExternalTextCandidate } from "./external-optimizer-contracts-eKQTutGZ.js";
25
+ import { n as searchProposerView, t as renderSearchSummary } from "./search-summary-B1x1Vmzh.js";
26
+ import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-gRPgIJyz.js";
26
27
  import { t as JudgeParseError } from "./judges-BLxg5p8E.js";
27
28
  import { createHash } from "node:crypto";
28
29
  import { z } from "zod";
29
30
  import { writeFileSync } from "node:fs";
30
31
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
32
+ import { toW3CTraceId } from "@tangle-network/agent-trace-contract";
31
33
  import { homedir, tmpdir } from "node:os";
32
34
  import { execSync } from "node:child_process";
33
35
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -436,13 +438,13 @@ function openAttempt(args, cellDir, attemptCostTags) {
436
438
  }, null, 2));
437
439
  artifactsByPath[`${args.slot.cellId}/${attemptPrefix}/identity.json`] = identityPath;
438
440
  storage.write(join(cellDir, "latest-attempt.json"), JSON.stringify(attempt));
439
- const trace = args.buildTraceWriter(args.slot.cellId, traceDir);
441
+ const trace = args.buildTraceWriter(args.slot.cellId, traceDir, attempt);
440
442
  const paid = { started: false };
441
443
  const artifacts = {
442
444
  async write(path, content) {
443
445
  const fullPath = resolve(artifactDir, path);
444
446
  const artifactPath = relative(artifactDir, fullPath);
445
- if (!artifactPath || artifactPath === ".." || artifactPath.startsWith(".." + sep) || isAbsolute(artifactPath)) throw new Error("Artifact path must remain inside this execution attempt");
447
+ if (!artifactPath || artifactPath === ".." || artifactPath.startsWith(`..${sep}`) || isAbsolute(artifactPath)) throw new Error("Artifact path must remain inside this execution attempt");
446
448
  storage.ensureDir(join(fullPath, ".."));
447
449
  storage.write(fullPath, content);
448
450
  artifactsByPath[`${args.slot.cellId}/${attemptPrefix}/artifacts/${artifactPath.split(sep).join("/")}`] = fullPath;
@@ -708,6 +710,8 @@ async function executeCell(args) {
708
710
  timeoutMs: args.dispatchShutdownTimeoutMs
709
711
  });
710
712
  const costCallIds = args.costLedger.list({ tags: costTags }).map((receipt) => receipt.callId).sort();
713
+ await trace.flush();
714
+ const traceRef = trace.traceRef?.() ?? { unknown: `the trace writer of campaign cell ${args.slot.cellId} exposes no trace identity` };
711
715
  const cell = withCurrentAgentEvidence({
712
716
  manifestHash: args.manifestHash,
713
717
  attempt,
@@ -724,13 +728,13 @@ async function executeCell(args) {
724
728
  durationMs: Date.now() - startMs,
725
729
  seed: args.slot.cellSeed,
726
730
  cached: false,
731
+ traceRef,
727
732
  ...args.attempt > 1 ? { retryAttempts: args.attempt - 1 } : {},
728
733
  ...failure ? { errorStage: failure.stage } : {},
729
734
  ...failure?.judge ? { errorJudge: failure.judge } : {},
730
735
  error: errorMessage
731
736
  }, args.costLedger, costTags);
732
737
  let retry = failure ? recordCellFailure(args, run, failure, cell, costTags, fatalCellError) : false;
733
- await trace.flush();
734
738
  const resultPath = join(attemptDir, "result.json");
735
739
  storage.write(resultPath, JSON.stringify(cell));
736
740
  artifactsByPath[`${args.slot.cellId}/${attemptPrefix}/result.json`] = resultPath;
@@ -809,9 +813,19 @@ function enforceDispatchUsage(cell, mode) {
809
813
  }
810
814
  console.warn(`[runCampaign] expectUsage: ${msg}`);
811
815
  }
816
+ /**
817
+ * The default writer keeps an attempt's ended spans in `<attempt>/trace/spans.jsonl`.
818
+ * Its trace id is the W3C id of the attempt's run, `<runAttemptId>/<cellId>/attempt-<n>`,
819
+ * derived by the trace contract's one run-id rule, and every span it writes
820
+ * carries it as `traceId`, so the id finds the file and the file proves the id.
821
+ * A span opened and never ended is not written; `traceRef` counts it as dropped.
822
+ */
812
823
  function defaultBuildTraceWriter(storage) {
813
- return (cellId, dir) => {
824
+ return (cellId, dir, attempt) => {
825
+ const traceId = toW3CTraceId(`${attempt.runAttemptId}/${cellId}/attempt-${attempt.number}`);
814
826
  const spans = [];
827
+ const open = /* @__PURE__ */ new Set();
828
+ let flushed;
815
829
  return {
816
830
  span(name, attributes) {
817
831
  const startMs = Date.now();
@@ -819,12 +833,16 @@ function defaultBuildTraceWriter(storage) {
819
833
  name,
820
834
  cellId,
821
835
  startMs,
822
- ...attributes ?? {}
836
+ ...attributes ?? {},
837
+ traceId
823
838
  };
839
+ open.add(record);
824
840
  return {
825
841
  end(endAttrs) {
826
842
  record.durationMs = Date.now() - startMs;
827
843
  if (endAttrs) Object.assign(record, endAttrs);
844
+ record.traceId = traceId;
845
+ open.delete(record);
828
846
  spans.push(record);
829
847
  },
830
848
  setAttribute(key, value) {
@@ -834,6 +852,19 @@ function defaultBuildTraceWriter(storage) {
834
852
  },
835
853
  async flush() {
836
854
  storage.write(join(dir, "spans.jsonl"), spans.map((s) => JSON.stringify(s)).join("\n"));
855
+ flushed = {
856
+ written: spans.length,
857
+ dropped: open.size
858
+ };
859
+ },
860
+ traceRef() {
861
+ if (flushed === void 0) return { unknown: `the trace of campaign cell ${cellId} was never flushed` };
862
+ return {
863
+ traceId,
864
+ execRunId: null,
865
+ spansWritten: flushed.written,
866
+ spansDropped: flushed.dropped
867
+ };
837
868
  }
838
869
  };
839
870
  };
@@ -955,6 +986,18 @@ function planCampaignRun(opts) {
955
986
  * primitive but live in `presets/run-improvement-loop.ts`. This file keeps
956
987
  * the core orchestrator minimal — Phase 1 of the Pass A track.
957
988
  */
989
+ /** The writer `tracing: 'off'` gives every attempt: it keeps no span and names no trace. */
990
+ function discardingTraceWriter(cellId) {
991
+ const span = {
992
+ end: () => void 0,
993
+ setAttribute: () => void 0
994
+ };
995
+ return {
996
+ span: () => span,
997
+ flush: async () => void 0,
998
+ traceRef: () => ({ unknown: `tracing is off for the campaign that measured cell ${cellId}` })
999
+ };
1000
+ }
958
1001
  /**
959
1002
  * Core campaign orchestrator: fan scenarios through dispatch, score with judges, aggregate bootstrap CIs, and persist reproducible `CampaignResult` records.
960
1003
  */
@@ -975,6 +1018,9 @@ async function runCampaign(opts) {
975
1018
  if (typeof cellRetry.retryable !== "function") throw new Error("runCampaign: cellRetry.retryable must be a function");
976
1019
  if (cellRetry.retryResult !== void 0 && typeof cellRetry.retryResult !== "function") throw new Error("runCampaign: cellRetry.retryResult must be a function");
977
1020
  }
1021
+ if (opts.tracing !== void 0 && opts.tracing !== "on" && opts.tracing !== "off") throw new Error("runCampaign: tracing must be 'on' or 'off'");
1022
+ if (opts.tracing === "off" && opts.buildTraceWriter !== void 0) throw new Error("runCampaign: tracing 'off' discards every span, so it cannot be combined with buildTraceWriter; set one");
1023
+ const buildTraceWriter = opts.tracing === "off" ? discardingTraceWriter : opts.buildTraceWriter ?? defaultBuildTraceWriter(storage);
978
1024
  if (typeof opts.runDir !== "string" || opts.runDir.trim().length === 0) throw new Error("runCampaign: runDir is required and must be a non-empty string");
979
1025
  opts.runDir = resolveRunDir(opts.runDir, opts.repo);
980
1026
  storage.ensureDir(opts.runDir);
@@ -1031,7 +1077,7 @@ async function runCampaign(opts) {
1031
1077
  resumable,
1032
1078
  now,
1033
1079
  storage,
1034
- buildTraceWriter: opts.buildTraceWriter ?? defaultBuildTraceWriter(storage),
1080
+ buildTraceWriter,
1035
1081
  signal,
1036
1082
  dispatchTimeoutMs: opts.dispatchTimeoutMs,
1037
1083
  dispatchShutdownTimeoutMs,
@@ -3175,28 +3221,63 @@ function round(value) {
3175
3221
  }
3176
3222
  // src/campaign/search-campaign-cell.ts
3177
3223
  /**
3178
- * What `cell-settled` records for one campaign cell: `passed` with the
3179
- * composite (and each judge's) when every judge scored it, else `errored`,
3180
- * never retryable, because `runCampaign` already applied its own retry policy;
3181
- * its tokens and cost, with an uncaptured cost kept as a lower bound; the
3182
- * model the cell resolved, else the declared one.
3224
+ * Project a campaign cell onto what `cell-settled` records: `passed` with the
3225
+ * composite, each judge's composite and each judge dimension when every judge
3226
+ * scored it, else `errored`, never retryable, because `runCampaign` already
3227
+ * applied its own retry policy; its tokens and cost, with an uncaptured cost
3228
+ * kept as a lower bound; the attempt that produced it and the trace its spans
3229
+ * went to.
3183
3230
  */
3184
- function campaignCellSearchResult(cell, input) {
3185
- return {
3231
+ function campaignCellMeasurement(cell) {
3232
+ const measurement = {
3233
+ cellId: cell.cellId,
3234
+ scenarioId: cell.scenarioId,
3235
+ rep: cell.rep,
3236
+ attempt: cell.attempt ? {
3237
+ runAttemptId: cell.attempt.runAttemptId,
3238
+ number: cell.attempt.number
3239
+ } : null,
3240
+ cached: cell.cached,
3186
3241
  outcome: campaignCellOutcome(cell),
3187
3242
  accounting: campaignCellAccounting(cell),
3243
+ ...cell.resolvedModel === void 0 ? {} : { resolvedModel: cell.resolvedModel },
3244
+ durationMs: cell.durationMs
3245
+ };
3246
+ return {
3247
+ ...measurement,
3248
+ traceRef: cell.traceRef ?? campaignCellTraceUnknown(measurement)
3249
+ };
3250
+ }
3251
+ /**
3252
+ * What `cell-settled` records for one campaign cell, or for its measurement:
3253
+ * the outcome and accounting of `campaignCellMeasurement`, the model the cell
3254
+ * resolved, else the declared one, its duration, and the trace its trace
3255
+ * writer named. A cell or measurement recorded before cells carried a trace
3256
+ * keeps an unknown reference that names the attempt whose trace writer
3257
+ * received its spans.
3258
+ */
3259
+ function campaignCellSearchResult(cell, input) {
3260
+ const measurement = "outcome" in cell ? cell : campaignCellMeasurement(cell);
3261
+ return {
3262
+ outcome: measurement.outcome,
3263
+ accounting: measurement.accounting,
3188
3264
  identity: {
3189
3265
  ...input.execution,
3190
- model: cell.resolvedModel === void 0 ? input.execution.model : searchModelIdentity(cell.resolvedModel, input.execution.model.provider)
3266
+ model: measurement.resolvedModel === void 0 ? input.execution.model : searchModelIdentity(measurement.resolvedModel, input.execution.model.provider)
3191
3267
  },
3192
- wallMs: cell.durationMs,
3268
+ wallMs: measurement.durationMs,
3193
3269
  placement: {
3194
3270
  lane: input.lane,
3195
3271
  boxId: null
3196
3272
  },
3197
- traceRef: { unknown: "runCampaign reports no trace id per cell" }
3273
+ traceRef: measurement.traceRef ?? campaignCellTraceUnknown(measurement)
3198
3274
  };
3199
3275
  }
3276
+ /** The trace reference of a cell recorded before cells carried one. */
3277
+ function campaignCellTraceUnknown({ cellId, attempt }) {
3278
+ const prefix = `runCampaign assigns no trace id; campaign cell ${cellId}`;
3279
+ return { unknown: attempt === null ? `${prefix} records no attempt` : `${prefix} wrote its spans through the trace writer of attempt ${attempt.runAttemptId}/attempt-${attempt.number}` };
3280
+ }
3200
3281
  /** A provider-reported model: a snapshot when its name pins one, else a moving alias. */
3201
3282
  function searchModelIdentity(model, provider) {
3202
3283
  return modelHasSnapshot(model) ? {
@@ -3220,7 +3301,14 @@ function campaignCellOutcome(cell) {
3220
3301
  }
3221
3302
  };
3222
3303
  const metrics = { composite: quality.score };
3223
- for (const [judge, score] of Object.entries(quality.successfulJudgeScores)) metrics[`judge.${judge}`] = score.composite;
3304
+ for (const [judge, score] of Object.entries(quality.successfulJudgeScores)) {
3305
+ metrics[`judge.${judge}`] = score.composite;
3306
+ for (const [dimension, value] of Object.entries(score.dimensions)) {
3307
+ const key = `dimension.${judge}.${dimension}`;
3308
+ if (Object.hasOwn(metrics, key)) throw new Error(`campaign cell ${cell.cellId}: two dimensions share the metric '${key}'`);
3309
+ metrics[key] = value;
3310
+ }
3311
+ }
3224
3312
  return {
3225
3313
  status: "passed",
3226
3314
  score: quality.score,
@@ -3237,7 +3325,7 @@ function campaignCellAccounting(cell) {
3237
3325
  status: "known",
3238
3326
  inputTokens: usage.input,
3239
3327
  outputTokens: usage.output,
3240
- cachedTokens: 0
3328
+ cachedTokens: usage.cached ?? 0
3241
3329
  },
3242
3330
  cost: cell.costProvenance.kind === "uncaptured" ? {
3243
3331
  status: "unknown",
@@ -4490,7 +4578,15 @@ var SurfaceNodes = class {
4490
4578
  const reps = this.opts.reps ?? 1;
4491
4579
  const coverage = campaignCoverage(campaign.cells, this.opts.scenarios, reps, (this.opts.judges?.length ?? 0) > 0);
4492
4580
  const expansion = nodeId === state.rootNodeId ? -1 : this.generationOf(state, this.origin(state, nodeId).expansion);
4493
- return toScoredSurfaceOutcome(surfaceHash(this.surface(state, nodeId)), campaign, coverage, expansion);
4581
+ return toScoredSurfaceOutcome(surfaceHash(this.surface(state, nodeId)), campaign, coverage, expansion, this.evidence());
4582
+ }
4583
+ /** How a breakdown shows each scenario's evidence: the hook the external
4584
+ * optimizers' callbacks use, with the scenarios it receives. */
4585
+ evidence() {
4586
+ return {
4587
+ scenarios: this.opts.scenarios,
4588
+ ...this.opts.describeArtifact ? { describeArtifact: this.opts.describeArtifact } : {}
4589
+ };
4494
4590
  }
4495
4591
  /** The Pareto frontier over every measured, complete node. */
4496
4592
  frontier(state) {
@@ -4547,7 +4643,7 @@ var SurfaceNodes = class {
4547
4643
  candidate(state, nodeId, expansion) {
4548
4644
  const campaign = this.campaign(state, nodeId);
4549
4645
  const coverage = campaignCoverage(campaign.cells, this.opts.scenarios, this.opts.reps ?? 1, (this.opts.judges?.length ?? 0) > 0);
4550
- const breakdown = campaignBreakdown(campaign);
4646
+ const breakdown = campaignBreakdown(campaign, this.evidence());
4551
4647
  const child = this.proposal(state, expansion).children.find((entry) => state.nodeIdForDigest(entry.node.artifactDigest) === nodeId);
4552
4648
  return {
4553
4649
  surfaceHash: surfaceHash(this.surface(state, nodeId)),
@@ -4588,7 +4684,7 @@ var SurfaceNodes = class {
4588
4684
  return blob;
4589
4685
  }
4590
4686
  async campaignRun(runDir, surface, input) {
4591
- const { baselineSurface: _baselineSurface, premeasuredBaseline: _premeasuredBaseline, dispatchWithSurface, proposer: _proposer, populationSize: _populationSize, maxGenerations: _maxGenerations, candidateConcurrency: _candidateConcurrency, maxImprovementShots: _maxImprovementShots, findings: _findings, analyzeGeneration: _analyzeGeneration, policy: _policy, searchLedger: _searchLedger, ...campaignOptions } = this.opts;
4687
+ const { baselineSurface: _baselineSurface, premeasuredBaseline: _premeasuredBaseline, dispatchWithSurface, proposer: _proposer, populationSize: _populationSize, maxGenerations: _maxGenerations, candidateConcurrency: _candidateConcurrency, maxImprovementShots: _maxImprovementShots, findings: _findings, analyzeGeneration: _analyzeGeneration, policy: _policy, searchLedger: _searchLedger, describeArtifact: _describeArtifact, ...campaignOptions } = this.opts;
4592
4688
  return runCampaign({
4593
4689
  ...campaignOptions,
4594
4690
  signal: input.signal ?? this.opts.signal,
@@ -4674,8 +4770,8 @@ function computeParetoFrontier(scored) {
4674
4770
  }));
4675
4771
  return paretoFrontier(scored, objectives).frontier;
4676
4772
  }
4677
- function toScoredSurfaceOutcome(hash, campaign, coverage, generation) {
4678
- const breakdown = campaignBreakdown(campaign);
4773
+ function toScoredSurfaceOutcome(hash, campaign, coverage, generation, evidence) {
4774
+ const breakdown = campaignBreakdown(campaign, evidence);
4679
4775
  return {
4680
4776
  split: "search",
4681
4777
  generation,
@@ -6076,6 +6172,6 @@ function parseResponse(name, response, schema, llmCall) {
6076
6172
  function firstString(value) {
6077
6173
  return typeof value === "string" && value.trim() ? value : void 0;
6078
6174
  }
6079
- export { withFinalEvidenceSources as $, campaignCellSearchResult as A, defaultProductionGate as B, surfaceDiff as C, createSearchHistoryReceipt as D, assertSearchHistoryMatchesState as E, uniform as F, Dataset as G, redTeamDataset as H, finalComparisonCampaigns as I, captureFinalEvidencePolicy as J, runCanaries as K, runFinalComparison as L, searchProposalExecution as M, searchReceiptAccounting as N, verifySearchHistoryArtifact as O, asha as P, reserveFinalEvidence as Q, openAutoPr as R, searchEdgeId as S, assertSearchHistoryAdmissionOptions as T, redTeamReport as U, DEFAULT_RED_TEAM_CORPUS as V, scoreRedTeamOutput as W, exposeFinalEvidence as X, evaluationUnitMap as Y, prepareSearchFinalEvidence as Z, crowdedFrontierParent as _, clamp01 as a, buildCellSchedule as at, SearchRecorder as b, readGepaCandidatePopulationArtifact as c, computeManifestHash as ct, optimizationTokenUsageFromSummary as d, runEval as et, runImprovementLoop as f, beam as g, aide as h, aggregateRunScore as i, cellReceiptModels as it, searchModelIdentity as j, verifySearchHistoryReceipt as k, combineComparisonCosts as l, isProposedCandidate as m, isTransientTransportFailure as n, planCampaignRun as nt, executeOptimizationMethod as o, cellCachePath as ot, runOptimization as p, assertIndependentEvaluationSplit as q, transientDispatchFailure as r, resolveRunDir as rt, assertGepaCandidatePopulationSummary as s, withUncapturedAgentSpend as st, llmJudge as t, runCampaign as tt, costFromLedgerSummary as u, incumbent as v, surfaceNode as w, developmentClaim as x, incumbentWithOperatorBandit as y, captureJudge as z };
6175
+ export { reserveFinalEvidence as $, campaignCellMeasurement as A, captureJudge as B, surfaceDiff as C, createSearchHistoryReceipt as D, assertSearchHistoryMatchesState as E, asha as F, scoreRedTeamOutput as G, DEFAULT_RED_TEAM_CORPUS as H, uniform as I, assertIndependentEvaluationSplit as J, Dataset as K, finalComparisonCampaigns as L, searchModelIdentity as M, searchProposalExecution as N, verifySearchHistoryArtifact as O, searchReceiptAccounting as P, prepareSearchFinalEvidence as Q, runFinalComparison as R, searchEdgeId as S, assertSearchHistoryAdmissionOptions as T, redTeamDataset as U, defaultProductionGate as V, redTeamReport as W, evaluationUnitMap as X, captureFinalEvidencePolicy as Y, exposeFinalEvidence as Z, crowdedFrontierParent as _, clamp01 as a, cellReceiptModels as at, SearchRecorder as b, readGepaCandidatePopulationArtifact as c, withUncapturedAgentSpend as ct, optimizationTokenUsageFromSummary as d, withFinalEvidenceSources as et, runImprovementLoop as f, beam as g, aide as h, aggregateRunScore as i, resolveRunDir as it, campaignCellSearchResult as j, verifySearchHistoryReceipt as k, combineComparisonCosts as l, computeManifestHash as lt, isProposedCandidate as m, isTransientTransportFailure as n, runCampaign as nt, executeOptimizationMethod as o, buildCellSchedule as ot, runOptimization as p, runCanaries as q, transientDispatchFailure as r, planCampaignRun as rt, assertGepaCandidatePopulationSummary as s, cellCachePath as st, llmJudge as t, runEval as tt, costFromLedgerSummary as u, incumbent as v, surfaceNode as w, developmentClaim as x, incumbentWithOperatorBandit as y, openAutoPr as z };
6080
6176
 
6081
- //# sourceMappingURL=llm-judge-DHgx29ro.js.map
6177
+ //# sourceMappingURL=llm-judge-CThv1Rog.js.map