@tangle-network/agent-eval 2.0.9 → 2.0.11

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 (235) hide show
  1. package/CHANGELOG.md +68 -16
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-ORN4aArD.d.ts → agent-profile-_JzxgLDM.d.ts} +11 -5
  4. package/dist/{agent-profile-ORN4aArD.d.ts.map → agent-profile-_JzxgLDM.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +14 -14
  6. package/dist/analyst/index.js +31 -10
  7. package/dist/analyst/index.js.map +1 -1
  8. package/dist/{analyze-runs-DT693FJ7.d.ts → analyze-runs-Izz_ZeWg.d.ts} +2 -2
  9. package/dist/{analyze-runs-DT693FJ7.d.ts.map → analyze-runs-Izz_ZeWg.d.ts.map} +1 -1
  10. package/dist/{analyze-runs-CE_5VKh2.js → analyze-runs-xhH2Qxoc.js} +5 -5
  11. package/dist/{analyze-runs-CE_5VKh2.js.map → analyze-runs-xhH2Qxoc.js.map} +1 -1
  12. package/dist/app-grade/index.d.ts +4 -4
  13. package/dist/{benchmark-command-DLg8E4y8.js → benchmark-command-CGQXNFj7.js} +8 -7
  14. package/dist/benchmark-command-CGQXNFj7.js.map +1 -0
  15. package/dist/benchmarks/index.d.ts +5 -5
  16. package/dist/benchmarks/index.d.ts.map +1 -1
  17. package/dist/benchmarks/index.js +18 -9
  18. package/dist/benchmarks/index.js.map +1 -1
  19. package/dist/campaign/index.d.ts +7 -7
  20. package/dist/campaign/index.js +11 -11
  21. package/dist/{campaign-C_S3MOYa.js → campaign-eus7YRs2.js} +13 -13
  22. package/dist/{campaign-C_S3MOYa.js.map → campaign-eus7YRs2.js.map} +1 -1
  23. package/dist/{campaign-evidence-CM4FBOkX.d.ts → campaign-evidence-BOcX4w0r.d.ts} +5 -5
  24. package/dist/{campaign-evidence-CM4FBOkX.d.ts.map → campaign-evidence-BOcX4w0r.d.ts.map} +1 -1
  25. package/dist/{campaign-evidence-BTfzZo1u.js → campaign-evidence-KM5GTsHG.js} +3 -3
  26. package/dist/{campaign-evidence-BTfzZo1u.js.map → campaign-evidence-KM5GTsHG.js.map} +1 -1
  27. package/dist/{chat-client-uQNXGuO4.d.ts → chat-client-BlTooBDA.d.ts} +7 -2
  28. package/dist/{chat-client-uQNXGuO4.d.ts.map → chat-client-BlTooBDA.d.ts.map} +1 -1
  29. package/dist/{chat-client-CvyDOQBv.js → chat-client-Oyot5tyo.js} +2 -2
  30. package/dist/{chat-client-CvyDOQBv.js.map → chat-client-Oyot5tyo.js.map} +1 -1
  31. package/dist/{chat-json-call-DMrwmB-k.js → chat-json-call-DTmv2uNY.js} +2 -2
  32. package/dist/{chat-json-call-DMrwmB-k.js.map → chat-json-call-DTmv2uNY.js.map} +1 -1
  33. package/dist/cli.js +7 -7
  34. package/dist/{cluster-C-K0N2br.d.ts → cluster-BJ0nW3P7.d.ts} +2 -2
  35. package/dist/{cluster-C-K0N2br.d.ts.map → cluster-BJ0nW3P7.d.ts.map} +1 -1
  36. package/dist/{cluster-bootstrap-DXbnIdm8.js → cluster-bootstrap-CTC8Dd30.js} +2 -2
  37. package/dist/{cluster-bootstrap-DXbnIdm8.js.map → cluster-bootstrap-CTC8Dd30.js.map} +1 -1
  38. package/dist/{completion-verifier-DsotH2l3.js → completion-verifier-CCPG2Yc0.js} +3 -3
  39. package/dist/{completion-verifier-DsotH2l3.js.map → completion-verifier-CCPG2Yc0.js.map} +1 -1
  40. package/dist/{completion-verifier-C7wipJOK.d.ts → completion-verifier-CQOC3_bm.d.ts} +2 -2
  41. package/dist/{completion-verifier-C7wipJOK.d.ts.map → completion-verifier-CQOC3_bm.d.ts.map} +1 -1
  42. package/dist/contract/index.d.ts +11 -11
  43. package/dist/contract/index.js +12 -12
  44. package/dist/{default-registry-kps1SOaD.js → default-registry-Rs5uzlfJ.js} +3 -3
  45. package/dist/{default-registry-kps1SOaD.js.map → default-registry-Rs5uzlfJ.js.map} +1 -1
  46. package/dist/{default-registry-Bskl2HzV.d.ts → default-registry-X8McMoUV.d.ts} +6 -6
  47. package/dist/{default-registry-Bskl2HzV.d.ts.map → default-registry-X8McMoUV.d.ts.map} +1 -1
  48. package/dist/{define-agent-eval-Dnh4jXLX.js → define-agent-eval-D8ntOXqV.js} +3 -3
  49. package/dist/{define-agent-eval-Dnh4jXLX.js.map → define-agent-eval-D8ntOXqV.js.map} +1 -1
  50. package/dist/{define-agent-eval-tu3anVlk.d.ts → define-agent-eval-DH5-xi-F.d.ts} +4 -4
  51. package/dist/{define-agent-eval-tu3anVlk.d.ts.map → define-agent-eval-DH5-xi-F.d.ts.map} +1 -1
  52. package/dist/diagnosis/index.d.ts +2 -2
  53. package/dist/diagnosis/index.js +1 -1
  54. package/dist/{dspy-rlm-engine-DQbPdT_o.js → dspy-rlm-engine-ChE1PUM5.js} +3 -3
  55. package/dist/{dspy-rlm-engine-DQbPdT_o.js.map → dspy-rlm-engine-ChE1PUM5.js.map} +1 -1
  56. package/dist/{eval-campaign-DswSn7Gm.js → eval-campaign-BciGnrGy.js} +2 -2
  57. package/dist/{eval-campaign-DswSn7Gm.js.map → eval-campaign-BciGnrGy.js.map} +1 -1
  58. package/dist/{evaluation-C4-tf3Z_.d.ts → evaluation-CjZH6gW0.d.ts} +4 -4
  59. package/dist/{evaluation-C4-tf3Z_.d.ts.map → evaluation-CjZH6gW0.d.ts.map} +1 -1
  60. package/dist/evaluation.d.ts +1 -1
  61. package/dist/{exact-types-CUsSMW3n.d.ts → exact-types-BIHqYBYf.d.ts} +2 -2
  62. package/dist/{exact-types-CUsSMW3n.d.ts.map → exact-types-BIHqYBYf.d.ts.map} +1 -1
  63. package/dist/experiment/index.d.ts +5 -5
  64. package/dist/experiment/index.js +8 -8
  65. package/dist/{external-optimizer-contracts-ZDBfbZ_s.js → external-optimizer-contracts-BFV8lnhl.js} +7 -2
  66. package/dist/{external-optimizer-contracts-ZDBfbZ_s.js.map → external-optimizer-contracts-BFV8lnhl.js.map} +1 -1
  67. package/dist/{external-optimizer-process-CVi1x2nb.js → external-optimizer-process-B6emPodQ.js} +3 -3
  68. package/dist/{external-optimizer-process-CVi1x2nb.js.map → external-optimizer-process-B6emPodQ.js.map} +1 -1
  69. package/dist/{external-optimizer-subprocess-mV-2swJI.js → external-optimizer-subprocess-_O06eDVA.js} +33 -20
  70. package/dist/external-optimizer-subprocess-_O06eDVA.js.map +1 -0
  71. package/dist/{feedback-trajectory-D7hgL6y5.d.ts → feedback-trajectory-CoQPmSJV.d.ts} +3 -3
  72. package/dist/{feedback-trajectory-D7hgL6y5.d.ts.map → feedback-trajectory-CoQPmSJV.d.ts.map} +1 -1
  73. package/dist/{findings-store-CZy5kUDo.js → findings-store-CvYUzQBR.js} +4 -4
  74. package/dist/{findings-store-CZy5kUDo.js.map → findings-store-CvYUzQBR.js.map} +1 -1
  75. package/dist/{index-Cav3abKy.d.ts → index-BSb3fJyZ.d.ts} +81 -19
  76. package/dist/{index-Cav3abKy.d.ts.map → index-BSb3fJyZ.d.ts.map} +1 -1
  77. package/dist/{index-CIqYaySd.d.ts → index-Bk1XEkP7.d.ts} +26 -16
  78. package/dist/index-Bk1XEkP7.d.ts.map +1 -0
  79. package/dist/{index-DmMHTDjT.d.ts → index-BmWw8zN6.d.ts} +9 -9
  80. package/dist/{index-DmMHTDjT.d.ts.map → index-BmWw8zN6.d.ts.map} +1 -1
  81. package/dist/{index--vDCtdaj.d.ts → index-CCOaNmh2.d.ts} +7 -7
  82. package/dist/{index--vDCtdaj.d.ts.map → index-CCOaNmh2.d.ts.map} +1 -1
  83. package/dist/{index-moZnazVj.d.ts → index-Cn9gB5Ca.d.ts} +21 -21
  84. package/dist/{index-moZnazVj.d.ts.map → index-Cn9gB5Ca.d.ts.map} +1 -1
  85. package/dist/{index-Er8TKQ3q.d.ts → index-aRalB_Ma.d.ts} +3 -3
  86. package/dist/{index-Er8TKQ3q.d.ts.map → index-aRalB_Ma.d.ts.map} +1 -1
  87. package/dist/index.d.ts +29 -29
  88. package/dist/index.js +23 -23
  89. package/dist/{integrity-BF0tJK21.js → integrity-DacT3oJ1.js} +2 -2
  90. package/dist/{integrity-BF0tJK21.js.map → integrity-DacT3oJ1.js.map} +1 -1
  91. package/dist/{integrity-BJGstiCh.d.ts → integrity-DotDLWtj.d.ts} +2 -2
  92. package/dist/{integrity-BJGstiCh.d.ts.map → integrity-DotDLWtj.d.ts.map} +1 -1
  93. package/dist/{judge-gate-DANg5FLq.js → judge-gate-CpD3wmcf.js} +2 -2
  94. package/dist/{judge-gate-DANg5FLq.js.map → judge-gate-CpD3wmcf.js.map} +1 -1
  95. package/dist/{llm-client-Dw4x6EdE.js → llm-client-Dk8lBnMh.js} +15 -2
  96. package/dist/{llm-client-Dw4x6EdE.js.map → llm-client-Dk8lBnMh.js.map} +1 -1
  97. package/dist/{llm-judge-DFoSy4Qn.js → llm-judge-DYmEdo3M.js} +3 -3
  98. package/dist/{llm-judge-DFoSy4Qn.js.map → llm-judge-DYmEdo3M.js.map} +1 -1
  99. package/dist/{matrix-OgdWQBQa.d.ts → matrix-BDl7hoBr.d.ts} +2 -2
  100. package/dist/{matrix-OgdWQBQa.d.ts.map → matrix-BDl7hoBr.d.ts.map} +1 -1
  101. package/dist/{measure-validity-plan-B1_qYlsk.d.ts → measure-validity-plan-BReXzcVh.d.ts} +62 -4
  102. package/dist/measure-validity-plan-BReXzcVh.d.ts.map +1 -0
  103. package/dist/{measure-validity-plan-t0YQRzJQ.js → measure-validity-plan-CJkBNzX_.js} +43 -6
  104. package/dist/measure-validity-plan-CJkBNzX_.js.map +1 -0
  105. package/dist/meta-eval/index.d.ts +2 -2
  106. package/dist/meta-eval/index.js +178 -35
  107. package/dist/meta-eval/index.js.map +1 -1
  108. package/dist/multishot/golden/index.d.ts +1 -1
  109. package/dist/multishot/index.d.ts +56 -17
  110. package/dist/multishot/index.d.ts.map +1 -1
  111. package/dist/multishot/index.js +93 -20
  112. package/dist/multishot/index.js.map +1 -1
  113. package/dist/node-transport-DJno8V46.js +62 -0
  114. package/dist/node-transport-DJno8V46.js.map +1 -0
  115. package/dist/openapi.json +1 -1
  116. package/dist/{optimization-method-D4CpYsVA.js → optimization-method-4JlbMxd2.js} +27 -38
  117. package/dist/optimization-method-4JlbMxd2.js.map +1 -0
  118. package/dist/{paired-arms-B6EXnI47.js → paired-arms-CJH5Q0wx.js} +2 -2
  119. package/dist/{paired-arms-B6EXnI47.js.map → paired-arms-CJH5Q0wx.js.map} +1 -1
  120. package/dist/{paired-promotion-decision-xYe881cD.js → paired-promotion-decision-BtfVwEAk.js} +2 -2
  121. package/dist/{paired-promotion-decision-xYe881cD.js.map → paired-promotion-decision-BtfVwEAk.js.map} +1 -1
  122. package/dist/{paired-promotion-decision-DuvRdnsW.d.ts → paired-promotion-decision-DJlI4z_k.d.ts} +2 -2
  123. package/dist/{paired-promotion-decision-DuvRdnsW.d.ts.map → paired-promotion-decision-DJlI4z_k.d.ts.map} +1 -1
  124. package/dist/{paired-promotion-power-DirShsIs.js → paired-promotion-power-DG1avBKf.js} +3 -3
  125. package/dist/{paired-promotion-power-DirShsIs.js.map → paired-promotion-power-DG1avBKf.js.map} +1 -1
  126. package/dist/pipelines/index.js +1 -1
  127. package/dist/{power-DTg6u30w.js → power-COie_o6E.js} +3 -3
  128. package/dist/{power-DTg6u30w.js.map → power-COie_o6E.js.map} +1 -1
  129. package/dist/{prime-protocol-Jm2pWh--.d.ts → prime-protocol-BRMk6dGI.d.ts} +2 -2
  130. package/dist/{prime-protocol-Jm2pWh--.d.ts.map → prime-protocol-BRMk6dGI.d.ts.map} +1 -1
  131. package/dist/{promotion-gate-BXgcORnM.d.ts → promotion-gate-B0VTBoXg.d.ts} +2 -2
  132. package/dist/{promotion-gate-BXgcORnM.d.ts.map → promotion-gate-B0VTBoXg.d.ts.map} +1 -1
  133. package/dist/{promotion-policy-Z5E-C32U.js → promotion-policy-BgI7PsQn.js} +3 -3
  134. package/dist/{promotion-policy-Z5E-C32U.js.map → promotion-policy-BgI7PsQn.js.map} +1 -1
  135. package/dist/{registry-DEZDECdr.d.ts → registry-BeInzotS.d.ts} +4 -4
  136. package/dist/{registry-DEZDECdr.d.ts.map → registry-BeInzotS.d.ts.map} +1 -1
  137. package/dist/reporting.d.ts +4 -4
  138. package/dist/reporting.js +3 -3
  139. package/dist/{research-report-CIgUe1lv.d.ts → research-report-CL5_UqCX.d.ts} +2 -2
  140. package/dist/{research-report-CIgUe1lv.d.ts.map → research-report-CL5_UqCX.d.ts.map} +1 -1
  141. package/dist/{researcher-CY_byuZl.d.ts → researcher-BOpZP_Ja.d.ts} +4 -4
  142. package/dist/{researcher-CY_byuZl.d.ts.map → researcher-BOpZP_Ja.d.ts.map} +1 -1
  143. package/dist/rl.d.ts +7 -7
  144. package/dist/rl.js +4 -4
  145. package/dist/rollout/index.d.ts +2 -2
  146. package/dist/rollout/index.js +1 -1
  147. package/dist/{rollout-B_lrpd9a.js → rollout--rSr43Pd.js} +2 -2
  148. package/dist/{rollout-B_lrpd9a.js.map → rollout--rSr43Pd.js.map} +1 -1
  149. package/dist/{rollout-nodes-Vas6OSxX.js → rollout-nodes-DFxKpIr2.js} +39 -10
  150. package/dist/rollout-nodes-DFxKpIr2.js.map +1 -0
  151. package/dist/{run-improvement-loop-BaPDVbW8.d.ts → run-improvement-loop-BeHu5D9Z.d.ts} +22 -10
  152. package/dist/run-improvement-loop-BeHu5D9Z.d.ts.map +1 -0
  153. package/dist/{runtime-rollouts-Vv-BAqmq.js → runtime-rollouts-CE0MbQPq.js} +54 -7
  154. package/dist/runtime-rollouts-CE0MbQPq.js.map +1 -0
  155. package/dist/search/index.d.ts +2 -2
  156. package/dist/search/index.js +2 -2
  157. package/dist/{search-kernel-BzTeb89p.d.ts → search-kernel-CJZ-ZSV1.d.ts} +3 -3
  158. package/dist/{search-kernel-BzTeb89p.d.ts.map → search-kernel-CJZ-ZSV1.d.ts.map} +1 -1
  159. package/dist/{search-kernel-DOPW08Hx.js → search-kernel-mZc79S6N.js} +4 -4
  160. package/dist/{search-kernel-DOPW08Hx.js.map → search-kernel-mZc79S6N.js.map} +1 -1
  161. package/dist/{search-summary-CYOHZAAy.js → search-summary-CCgP2qXz.js} +3 -3
  162. package/dist/{search-summary-CYOHZAAy.js.map → search-summary-CCgP2qXz.js.map} +1 -1
  163. package/dist/{self-improve-DY8ZY4lY.d.ts → self-improve-B1fsNejr.d.ts} +6 -6
  164. package/dist/{self-improve-DY8ZY4lY.d.ts.map → self-improve-B1fsNejr.d.ts.map} +1 -1
  165. package/dist/{self-improve-CIFqccHV.js → self-improve-C_Bcdmv8.js} +5 -4
  166. package/dist/{self-improve-CIFqccHV.js.map → self-improve-C_Bcdmv8.js.map} +1 -1
  167. package/dist/{sequential-B9iROM1S.d.ts → sequential-CHplorpC.d.ts} +2 -2
  168. package/dist/{sequential-B9iROM1S.d.ts.map → sequential-CHplorpC.d.ts.map} +1 -1
  169. package/dist/{sequential-tZjGysXY.js → sequential-DR-pnYQ7.js} +3 -3
  170. package/dist/{sequential-tZjGysXY.js.map → sequential-DR-pnYQ7.js.map} +1 -1
  171. package/dist/{server-1fzBCxMh.js → server-aZFmRucn.js} +3 -3
  172. package/dist/{server-1fzBCxMh.js.map → server-aZFmRucn.js.map} +1 -1
  173. package/dist/{skillopt-optimization-method-CbHBkopM.js → skillopt-optimization-method-DHk1K757.js} +93 -39
  174. package/dist/skillopt-optimization-method-DHk1K757.js.map +1 -0
  175. package/dist/{statistical-heldout-C7Jjo5nP.js → statistical-heldout-CL_7mI5C.js} +2 -2
  176. package/dist/{statistical-heldout-C7Jjo5nP.js.map → statistical-heldout-CL_7mI5C.js.map} +1 -1
  177. package/dist/{statistics-BPl13X3G.js → statistics-AKnVFnK-.js} +67 -42
  178. package/dist/statistics-AKnVFnK-.js.map +1 -0
  179. package/dist/statistics.d.ts +3 -3
  180. package/dist/statistics.js +1 -1
  181. package/dist/{store-tool-spans-Dq8r0PbJ.d.ts → store-tool-spans-M3WxeRrG.d.ts} +4 -4
  182. package/dist/{store-tool-spans-Dq8r0PbJ.d.ts.map → store-tool-spans-M3WxeRrG.d.ts.map} +1 -1
  183. package/dist/{summary-report-DzbnK81K.js → summary-report-DyBkOC6V.js} +3 -3
  184. package/dist/{summary-report-DzbnK81K.js.map → summary-report-DyBkOC6V.js.map} +1 -1
  185. package/dist/supervisor-run/index.d.ts +12 -2
  186. package/dist/supervisor-run/index.d.ts.map +1 -1
  187. package/dist/supervisor-run/index.js +3 -3
  188. package/dist/{systemone-BuSZTI88.d.ts → systemone-4PadCE4C.d.ts} +7 -7
  189. package/dist/{systemone-BuSZTI88.d.ts.map → systemone-4PadCE4C.d.ts.map} +1 -1
  190. package/dist/{systemone-review-mlfxWdLz.d.ts → systemone-review-DpAXWDkL.d.ts} +2 -2
  191. package/dist/{systemone-review-mlfxWdLz.d.ts.map → systemone-review-DpAXWDkL.d.ts.map} +1 -1
  192. package/dist/systemone.d.ts +3 -3
  193. package/dist/{tool-groups-PNDX8fd-.d.ts → tool-groups-SlnoQNyT.d.ts} +2 -2
  194. package/dist/tool-groups-SlnoQNyT.d.ts.map +1 -0
  195. package/dist/{tool-waste-783VCo1y.js → tool-waste-BZnYSa6J.js} +2 -2
  196. package/dist/{tool-waste-783VCo1y.js.map → tool-waste-BZnYSa6J.js.map} +1 -1
  197. package/dist/{trace-questions-DBtr4jWi.d.ts → trace-questions-ybyF0B6N.d.ts} +2 -2
  198. package/dist/{trace-questions-DBtr4jWi.d.ts.map → trace-questions-ybyF0B6N.d.ts.map} +1 -1
  199. package/dist/trace-repair/index.d.ts +1 -1
  200. package/dist/traces.d.ts +4 -4
  201. package/dist/{tree-CtlQQL1w.js → tree-CiIe-f3f.js} +4 -4
  202. package/dist/{tree-CtlQQL1w.js.map → tree-CiIe-f3f.js.map} +1 -1
  203. package/dist/{types-CKNAzCSA.d.ts → types-B1W3v8dT.d.ts} +3 -3
  204. package/dist/{types-CKNAzCSA.d.ts.map → types-B1W3v8dT.d.ts.map} +1 -1
  205. package/dist/{types-DbeIGi73.d.ts → types-Bte3EsFQ.d.ts} +52 -5
  206. package/dist/types-Bte3EsFQ.d.ts.map +1 -0
  207. package/dist/{types-BO948H-U.d.ts → types-D5XtEH9Q.d.ts} +8 -4
  208. package/dist/{types-BO948H-U.d.ts.map → types-D5XtEH9Q.d.ts.map} +1 -1
  209. package/dist/{types-D-WF1KM3.d.ts → types-xVtEOBhO.d.ts} +31 -8
  210. package/dist/types-xVtEOBhO.d.ts.map +1 -0
  211. package/dist/wire/index.d.ts +4 -4
  212. package/dist/wire/index.js +1 -1
  213. package/dist/world/index.d.ts +1 -1
  214. package/docs/design/statistics-decisions.md +18 -1
  215. package/docs/eval-surface-map.md +1 -1
  216. package/docs/feature-guide.md +1 -1
  217. package/docs/multi-turn-optimization.md +6 -2
  218. package/docs/outcome-validity.md +51 -12
  219. package/docs/public-api.md +17 -16
  220. package/docs/{multi-shot-optimization.md → trajectory-optimization.md} +1 -1
  221. package/package.json +1 -1
  222. package/dist/benchmark-command-DLg8E4y8.js.map +0 -1
  223. package/dist/external-optimizer-subprocess-mV-2swJI.js.map +0 -1
  224. package/dist/index-CIqYaySd.d.ts.map +0 -1
  225. package/dist/measure-validity-plan-B1_qYlsk.d.ts.map +0 -1
  226. package/dist/measure-validity-plan-t0YQRzJQ.js.map +0 -1
  227. package/dist/optimization-method-D4CpYsVA.js.map +0 -1
  228. package/dist/rollout-nodes-Vas6OSxX.js.map +0 -1
  229. package/dist/run-improvement-loop-BaPDVbW8.d.ts.map +0 -1
  230. package/dist/runtime-rollouts-Vv-BAqmq.js.map +0 -1
  231. package/dist/skillopt-optimization-method-CbHBkopM.js.map +0 -1
  232. package/dist/statistics-BPl13X3G.js.map +0 -1
  233. package/dist/tool-groups-PNDX8fd-.d.ts.map +0 -1
  234. package/dist/types-D-WF1KM3.d.ts.map +0 -1
  235. package/dist/types-DbeIGi73.d.ts.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { d as CostReceipt, f as CostReceiptInput, h as MaximumCharge, i as CostChannel, o as CostLedgerHandle } from "./cost-ledger-CSP-OfFe.js";
2
- import { i as AnalystFinding, n as AnalystContext, t as Analyst } from "./types-CKNAzCSA.js";
3
- import { R as Scenario, S as JudgeConfig, w as JudgeScore } from "./types-BO948H-U.js";
4
- import { l as ExactCapableAnalyst } from "./exact-types-CUsSMW3n.js";
2
+ import { i as AnalystFinding, n as AnalystContext, t as Analyst } from "./types-B1W3v8dT.js";
3
+ import { R as Scenario, S as JudgeConfig, w as JudgeScore } from "./types-D5XtEH9Q.js";
4
+ import { l as ExactCapableAnalyst } from "./exact-types-BIHqYBYf.js";
5
5
  interface EvaluationResult<T> {
6
6
  value: T;
7
7
  receipt: CostReceipt;
@@ -72,4 +72,4 @@ interface EvaluationAnalystOptions<I, O> {
72
72
  /** Registry, graph, and trace consumers keep the same Analyst interface. */
73
73
  declare function asAnalyst<I, O>(options: EvaluationAnalystOptions<I, O>): Analyst<I>;
74
74
  export { EvaluationResult as a, asJudge as c, EvaluationJudgeOptions as i, createEvaluator as l, EvaluationAnalystOptions as n, EvaluatorOptions as o, EvaluationContext as r, asAnalyst as s, CostedEvaluator as t };
75
- //# sourceMappingURL=evaluation-C4-tf3Z_.d.ts.map
75
+ //# sourceMappingURL=evaluation-CjZH6gW0.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"evaluation-C4-tf3Z_.d.ts","names":[],"sources":["../src/evaluation.ts"],"mappings":";;;;UAaiB,iBAAiB;EAChC,OAAO;EACP,SAAS;EACT;;UAGe;;;EAGf;EACA,SAAS;EACT,aAAa;EACb;EACA,UAAU;EACV;EACA,WAAW;EACX,gBAAgB;;EAEhB,aAAa,SAAS,uBAAuB;;KAGnC,gBAAgB,GAAG,MAC7B,OAAO,GACP,UAAU,sBACP,QAAQ,iBAAiB;UAEb,iBAAiB,GAAG;EACnC,UAAU,OAAO,GAAG;IAAW,QAAQ;IAAa;QAA6B,QAAQ;EACzF,UAAU,OAAO,MAAM;EACvB,oBAAoB,OAAO,UAAU;E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AAQ;EACzF,UAAU,OAAO,MAAM;EACvB,oBAAoB,OAAO,UAAU;EACrC,mBAAmB,OAAO;EAC1B,aAAa;EACb,gBAAgB;;EAEhB,YAAY,OAAO,GAAG,OAAO,aAAa;;;iBAI5B,gBAAgB,GAAG,GAAG,SAAS,iBAAiB,GAAG,KAAK,gBAAgB,GAAG;UA6B1E,uBAAuB,GAAG,UAAU,UAAU;EAC7D;EACA;EACA,YAAY,YAAY,GAAG;EAC3B,UAAU;IAAkB,UAAU;IAAG,UAAU;KAAK;EACxD,MAAM,OAAO,GAAG;IAAS,UAAU;IAAG,UAAU;QAAQ,aAAa,QAAQ;;EAE7E,UACE,QAAQ,iBAAiB,IACzB;IAAS,UAAU;IAAG,UAAU;eACtB;EACZ,aAAa,UAAU;;;iBAIT,QAAQ,GAAG,UAAU,UAAU,GAC7C,SAAS,uBAAuB,GAAG,GAAG,KACrC,YAAY,GAAG;UA4BD,yBAAyB,GAAG;EAC3C;EACA;EACA;EACA,WAAW,QAAQ;EACnB,MAAM,QAAQ;EACd,kBAAkB,oBAAoB;EACtC,WACE,OAAO,GACP,SAAS,mBACT,gBAAgB,mBACb,QAAQ,iBAAiB;EAC9B,MAAM,OAAO,GAAG,OAAO,GAAG,SAAS,mBAAmB,mBAAmB,QAAQ;EACjF,UAAU,QAAQ,iBAAiB,IAAI,OAAO,GAAG,SAAS,0BAA0B;;;iBAItE,UAAU,GAAG,GAAG,SAAS,yBAAyB,GAAG,KAAK,QAAQ"}
@@ -1,2 +1,2 @@
1
- import { a as EvaluationResult, c as asJudge, i as EvaluationJudgeOptions, l as createEvaluator, n as EvaluationAnalystOptions, o as EvaluatorOptions, r as EvaluationContext, s as asAnalyst, t as CostedEvaluator } from "./evaluation-C4-tf3Z_.js";
1
+ import { a as EvaluationResult, c as asJudge, i as EvaluationJudgeOptions, l as createEvaluator, n as EvaluationAnalystOptions, o as EvaluatorOptions, r as EvaluationContext, s as asAnalyst, t as CostedEvaluator } from "./evaluation-CjZH6gW0.js";
2
2
  export { CostedEvaluator, EvaluationAnalystOptions, EvaluationContext, EvaluationJudgeOptions, EvaluationResult, EvaluatorOptions, asAnalyst, asJudge, createEvaluator };
@@ -1,4 +1,4 @@
1
- import { c as AnalystRunEvent, d as AnalystRunSummary, t as Analyst, u as AnalystRunResult } from "./types-CKNAzCSA.js";
1
+ import { c as AnalystRunEvent, d as AnalystRunSummary, t as Analyst, u as AnalystRunResult } from "./types-B1W3v8dT.js";
2
2
  import { z } from "zod";
3
3
  /** Analyst metadata required before the exact registry path will execute it. */
4
4
  interface ExactCapableAnalyst<TInput = unknown> extends Analyst<TInput> {
@@ -229,4 +229,4 @@ declare const exactExecutionPlanSchema: z.ZodObject<{
229
229
  digest: z.ZodString;
230
230
  }, z.core.$strict>;
231
231
  export { ExactAnalystRunPolicySnapshot as a, ExactAnalystSnapshot as c, ExactExecutionComponentSnapshot as d, ExactAnalystRunEvent as i, ExactCapableAnalyst as l, ExactAnalystExecutionPlanSnapshot as n, ExactAnalystRunResult as o, ExactAnalystRunCompletion as r, ExactAnalystRunSummary as s, ExactAnalystBudgetSnapshot as t, ExactExecutionComponentIdentity as u };
232
- //# sourceMappingURL=exact-types-CUsSMW3n.d.ts.map
232
+ //# sourceMappingURL=exact-types-BIHqYBYf.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"exact-types-CUsSMW3n.d.ts","names":[],"sources":["../src/analyst/exact-types.ts"],"mappings":";;;UAMiB,oBAAoB,0BAA0B,QAAQ;;WAE5D,iBAAiB,SAAS;;KAGhC,aAAa,KAAK,0BAA0B,mBACpC,aAAa,UACtB,+BACc,aAAa,IAAI,aAAa,EAAE,WAC5C;KAEM,uBAAuB,aAAa,EAAE,aAAa;KACnD,6BAA6B,aAAa,EAAE,aAAa;;UAGpD;EACf;EACA;EACA,QAAQ,SAAS;;;UAIF;EACf;EACA;EACA;;KAyBU,gCAAgC,aAAa,EAAE,aAAa;KAC5D,oCAAoC,aAC9C,EAAE,aAAa;KAGL,yBAAy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AAgB;MAEjB,KAAK,QAAQ;EAAmB;;EAC/B,SAAS;KAEX,QAAQ;EAAmB;MAC1B,KAAK,QAAQ;EAAmB;;EAC/B,SAAS;MAEV,KAAK,QAAQ;EAAmB;;EAC/B,QAAQ;;cAwCR,uBAAqB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAOzB,EAAA,KAAA;cAII,sBAAoB,EAAA,uBAAA,EAAA;;;;;;;;;;;GAaxB,EAAA,KAAA;cAiBI,sBAAoB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAYxB,EAAA,KAAA;cAEI,0BAAwB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+E1B,EAAA,KAAA"}
@@ -1,8 +1,8 @@
1
- import { A as pairedBootstrap, C as BOOTSTRAP_GATE_MIN_N, E as PairedBootstrapResult, G as pairedRiskDifferenceScore, J as wilson, L as ProportionInterval, S as requiredSampleSize, T as PairedBootstrapOptions, U as pairedRiskDifference, V as mcnemar, W as pairedRiskDifferenceExact, X as bonferroni, Y as benjaminiHochberg, Z as holm, _ as mulberry32, a as eProcess, b as pairedMde, i as EProcessStep, n as EProcessOptions, r as EProcessState, t as EProcess, v as mcnemarPower, x as requiredPairedSampleSize, y as mcnemarRequiredN } from "../index-CIqYaySd.js";
1
+ import { A as pairedBootstrap, C as BOOTSTRAP_GATE_MIN_N, E as PairedBootstrapResult, G as pairedRiskDifferenceScore, J as wilson, L as ProportionInterval, S as requiredSampleSize, T as PairedBootstrapOptions, U as pairedRiskDifference, V as mcnemar, W as pairedRiskDifferenceExact, X as bonferroni, Y as benjaminiHochberg, Z as holm, _ as mulberry32, a as eProcess, b as pairedMde, i as EProcessStep, n as EProcessOptions, r as EProcessState, t as EProcess, v as mcnemarPower, x as requiredPairedSampleSize, y as mcnemarRequiredN } from "../index-Bk1XEkP7.js";
2
2
  import { at as summarizeEvaluationUnits, it as defineEvaluationClaim, nt as EvaluationClaim, rt as EvaluationUnitSummary } from "../search-ledger-types-BhZE848w.js";
3
- import { A as SequentialPairedGateOptions, B as signManifest, C as heldoutSignificance, Ct as FinalEvidenceError, D as SequentialGateDecision, Dt as FinalEvidenceRecord, Et as FinalEvidenceOutcome, F as HypothesisResult, G as EvidenceVector, I as SignedManifest, L as SignedManifestAlgo, M as sequentialDecide, N as sequentialPairedGate, O as SequentialObservation, Ot as FinalEvidenceReservation, P as HypothesisManifest, Q as paretoSignificanceGate, R as hashJson, St as FinalEvidenceConflictError, Tt as FinalEvidenceMeasurement, V as verifyManifest, X as buildEvidenceVector, Y as PromotionPolicy, Z as paretoPolicy, _t as pairArms, a as EvidenceAuthorityKind, at as powerPreflight, b as HeldoutSignificanceOptions, bt as ArmPopulationReading, c as EvidenceReceiptVerification, d as verifyEvidenceReceipt, ft as PairedArmRow, gt as comparePairedArms, i as EvidenceAuthority, it as PowerPreflightOptions, k as SequentialPairedGate, kt as openFinalEvidenceLedger, l as createEvidenceReceipt, lt as PairArmsOptions, n as createCampaignEvidenceReceipt, o as EvidenceBinding, r as CreateEvidenceReceiptInput, rt as PowerPreflight, s as EvidenceReceipt, st as MatchedPair, t as CampaignEvidenceContext, u as isIndependentEvidence, ut as PairArmsResult, vt as pairRunRecords, w as pairHoldout, wt as FinalEvidenceLedger, x as PairedHoldout, xt as ArmPopulationSummary, y as HeldoutSignificance, yt as ArmAssignment, z as manifestContentDigest } from "../campaign-evidence-CM4FBOkX.js";
4
- import { a as MeasureValiditySelectionRules, c as verifyMeasureValidityPlan, d as computeInterval, f as EvidenceRecord, i as MeasureValidityPlanInput, l as ComputedInterval, n as MeasureValidityOutcome, o as SealedMeasureValidityPlan, p as JsonValue, r as MeasureValidityPlan, s as sealMeasureValidityPlan, t as MeasureValidityMeasure, u as IntervalSpec } from "../measure-validity-plan-B1_qYlsk.js";
5
- import { a as PairedEvalueStep, i as PairedEvalueSequence, o as SequentialCrossingHorizon, r as PairedEvalueOptions, s as SequentialCrossingHorizonOptions, u as pairedEvalueSequence } from "../sequential-B9iROM1S.js";
3
+ import { A as SequentialPairedGateOptions, B as signManifest, C as heldoutSignificance, Ct as FinalEvidenceError, D as SequentialGateDecision, Dt as FinalEvidenceRecord, Et as FinalEvidenceOutcome, F as HypothesisResult, G as EvidenceVector, I as SignedManifest, L as SignedManifestAlgo, M as sequentialDecide, N as sequentialPairedGate, O as SequentialObservation, Ot as FinalEvidenceReservation, P as HypothesisManifest, Q as paretoSignificanceGate, R as hashJson, St as FinalEvidenceConflictError, Tt as FinalEvidenceMeasurement, V as verifyManifest, X as buildEvidenceVector, Y as PromotionPolicy, Z as paretoPolicy, _t as pairArms, a as EvidenceAuthorityKind, at as powerPreflight, b as HeldoutSignificanceOptions, bt as ArmPopulationReading, c as EvidenceReceiptVerification, d as verifyEvidenceReceipt, ft as PairedArmRow, gt as comparePairedArms, i as EvidenceAuthority, it as PowerPreflightOptions, k as SequentialPairedGate, kt as openFinalEvidenceLedger, l as createEvidenceReceipt, lt as PairArmsOptions, n as createCampaignEvidenceReceipt, o as EvidenceBinding, r as CreateEvidenceReceiptInput, rt as PowerPreflight, s as EvidenceReceipt, st as MatchedPair, t as CampaignEvidenceContext, u as isIndependentEvidence, ut as PairArmsResult, vt as pairRunRecords, w as pairHoldout, wt as FinalEvidenceLedger, x as PairedHoldout, xt as ArmPopulationSummary, y as HeldoutSignificance, yt as ArmAssignment, z as manifestContentDigest } from "../campaign-evidence-BOcX4w0r.js";
4
+ import { a as MeasureValidityPlanInput, c as MeasureValiditySelectionRules, d as verifyMeasureValidityPlan, f as ComputedInterval, g as JsonValue, h as EvidenceRecord, i as MeasureValidityPlan, l as SealedMeasureValidityPlan, m as computeInterval, n as MeasureValidityMeasure, o as MeasureValidityPlanOutcome, p as IntervalSpec, r as MeasureValidityOutcome, s as MeasureValidityPlanSelection, t as MeasureValidityExposure, u as sealMeasureValidityPlan } from "../measure-validity-plan-BReXzcVh.js";
5
+ import { a as PairedEvalueStep, i as PairedEvalueSequence, o as SequentialCrossingHorizon, r as PairedEvalueOptions, s as SequentialCrossingHorizonOptions, u as pairedEvalueSequence } from "../sequential-CHplorpC.js";
6
6
  import { z } from "zod";
7
7
  /**
8
8
  * Closed-key comparison over a declared record schema. The only leaf node.
@@ -955,5 +955,5 @@ interface ProspectiveCanaryJoinInput {
955
955
  * randomization and the pre-traffic witness in `decideRandomizedCanary`.
956
956
  */
957
957
  export declare function joinProspectiveCanaryReceipts(input: ProspectiveCanaryJoinInput): CanaryObservation[];
958
- export { type AdmissionExecution, type AdmissionPartition, type AdmissionRule, type AdmissionStage, type ArmAssignment, type ArmPopulationReading, type ArmPopulationSummary, type ArmRealizedBudget, type ArmSpec, BOOTSTRAP_GATE_MIN_N, type BudgetRule, type CampaignEvidenceContext, type CanaryArm, type CanaryAssignmentReceipt, type CanaryCohortReceipt, type CanaryCohortVerifier, type CanaryObservation, type CanaryRefusal, type ClusteredPowerOptions, type ClusteredPowerPoint, type ClusteredPowerRefusal, type ClusteredPowerResult, type ComputedInterval, type Condition, type CreateEvidenceReceiptInput, type DecisionBranch, type DecisionOutcome, type DecisionRule, type DerivedQuantities, type EProcess, type EProcessOptions, type EProcessState, type EProcessStep, type Estimand, type EstimandResult, type EvaluationClaim, type EvaluationUnitSummary, type EvidenceAuthority, type EvidenceAuthorityKind, type EvidenceBinding, type EvidenceDenominator, type EvidenceReceipt, type EvidenceReceiptVerification, type EvidenceRecord, type EvidenceRegistryRecord, type EvidenceState, type EvidenceVector, type ExperimentFunnel, type ExperimentGateEvidence, type ExperimentSpec, FinalEvidenceConflictError, FinalEvidenceError, type FinalEvidenceLedger, type FinalEvidenceMeasurement, type FinalEvidenceOutcome, type FinalEvidenceRecord, type FinalEvidenceReservation, type FunnelPartitionCount, type FunnelStageCount, type FunnelStageInput, type HaltOutcome, type HaltRule, type HeldoutSignificance, type HeldoutSignificanceOptions, type HypothesisManifest, type HypothesisResult, type IntervalSpec, type JsonValue, type MatchedBudgetRule, type MatchedBudgetVerdict, type MatchedPair, type MeasureValidityMeasure, type MeasureValidityOutcome, type MeasureValidityPlan, type MeasureValidityPlanInput, type MeasureValiditySelectionRules, type NLadderProjection, type Obligation, type OutcomeSpec, type PairArmsOptions, type PairArmsResult, type PairedArmRow, type PairedBootstrapOptions, type PairedBootstrapResult, type PairedEvalueOptions, type PairedEvalueSequence, type PairedEvalueStep, type PairedHoldout, type PowerPreflight, type PowerPreflightOptions, type Predicate, type PromotionPolicy, type ProportionInterval, type ProspectiveCanaryAssignment, type ProspectiveCanaryBilling, type ProspectiveCanaryExecution, type ProspectiveCanaryJoinInput, type ProspectiveCanaryOutcome, type RandomizedCanaryDecision, type RandomizedCanaryRule, type RegisteredExperiment, type ReissuePolicy, type ReissueVerdict, type SealAmendment, type SealedExperiment, type SealedMeasureValidityPlan, type SealedRandomizedCanaryRule, type SeedDerivation, type SelectionRule, type SequentialCrossingHorizon, type SequentialCrossingHorizonOptions, type SequentialGateDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SetExpr, type SignFlipFloor, type SignedManifest, type SignedManifestAlgo, type UniformPassDecision, type UniformPassSchedule, type ValidityGate, type ValidityGateResult, benjaminiHochberg, bonferroni, buildEvidenceVector, comparePairedArms, computeInterval, createCampaignEvidenceReceipt, createEvidenceReceipt, defineEvaluationClaim, eProcess, hashJson, heldoutSignificance, holm, isIndependentEvidence, manifestContentDigest, mcnemar, mcnemarPower, mcnemarRequiredN, mulberry32, openFinalEvidenceLedger, pairArms, pairHoldout, pairRunRecords, pairedBootstrap, pairedEvalueSequence, pairedMde, pairedRiskDifference, pairedRiskDifferenceExact, pairedRiskDifferenceScore, paretoPolicy, paretoSignificanceGate, powerPreflight, requiredPairedSampleSize, requiredSampleSize, sealMeasureValidityPlan, sequentialDecide, sequentialPairedGate, signManifest, summarizeEvaluationUnits, verifyEvidenceReceipt, verifyManifest, verifyMeasureValidityPlan, wilson };
958
+ export { type AdmissionExecution, type AdmissionPartition, type AdmissionRule, type AdmissionStage, type ArmAssignment, type ArmPopulationReading, type ArmPopulationSummary, type ArmRealizedBudget, type ArmSpec, BOOTSTRAP_GATE_MIN_N, type BudgetRule, type CampaignEvidenceContext, type CanaryArm, type CanaryAssignmentReceipt, type CanaryCohortReceipt, type CanaryCohortVerifier, type CanaryObservation, type CanaryRefusal, type ClusteredPowerOptions, type ClusteredPowerPoint, type ClusteredPowerRefusal, type ClusteredPowerResult, type ComputedInterval, type Condition, type CreateEvidenceReceiptInput, type DecisionBranch, type DecisionOutcome, type DecisionRule, type DerivedQuantities, type EProcess, type EProcessOptions, type EProcessState, type EProcessStep, type Estimand, type EstimandResult, type EvaluationClaim, type EvaluationUnitSummary, type EvidenceAuthority, type EvidenceAuthorityKind, type EvidenceBinding, type EvidenceDenominator, type EvidenceReceipt, type EvidenceReceiptVerification, type EvidenceRecord, type EvidenceRegistryRecord, type EvidenceState, type EvidenceVector, type ExperimentFunnel, type ExperimentGateEvidence, type ExperimentSpec, FinalEvidenceConflictError, FinalEvidenceError, type FinalEvidenceLedger, type FinalEvidenceMeasurement, type FinalEvidenceOutcome, type FinalEvidenceRecord, type FinalEvidenceReservation, type FunnelPartitionCount, type FunnelStageCount, type FunnelStageInput, type HaltOutcome, type HaltRule, type HeldoutSignificance, type HeldoutSignificanceOptions, type HypothesisManifest, type HypothesisResult, type IntervalSpec, type JsonValue, type MatchedBudgetRule, type MatchedBudgetVerdict, type MatchedPair, type MeasureValidityExposure, type MeasureValidityMeasure, type MeasureValidityOutcome, type MeasureValidityPlan, type MeasureValidityPlanInput, type MeasureValidityPlanOutcome, type MeasureValidityPlanSelection, type MeasureValiditySelectionRules, type NLadderProjection, type Obligation, type OutcomeSpec, type PairArmsOptions, type PairArmsResult, type PairedArmRow, type PairedBootstrapOptions, type PairedBootstrapResult, type PairedEvalueOptions, type PairedEvalueSequence, type PairedEvalueStep, type PairedHoldout, type PowerPreflight, type PowerPreflightOptions, type Predicate, type PromotionPolicy, type ProportionInterval, type ProspectiveCanaryAssignment, type ProspectiveCanaryBilling, type ProspectiveCanaryExecution, type ProspectiveCanaryJoinInput, type ProspectiveCanaryOutcome, type RandomizedCanaryDecision, type RandomizedCanaryRule, type RegisteredExperiment, type ReissuePolicy, type ReissueVerdict, type SealAmendment, type SealedExperiment, type SealedMeasureValidityPlan, type SealedRandomizedCanaryRule, type SeedDerivation, type SelectionRule, type SequentialCrossingHorizon, type SequentialCrossingHorizonOptions, type SequentialGateDecision, type SequentialObservation, type SequentialPairedGate, type SequentialPairedGateOptions, type SetExpr, type SignFlipFloor, type SignedManifest, type SignedManifestAlgo, type UniformPassDecision, type UniformPassSchedule, type ValidityGate, type ValidityGateResult, benjaminiHochberg, bonferroni, buildEvidenceVector, comparePairedArms, computeInterval, createCampaignEvidenceReceipt, createEvidenceReceipt, defineEvaluationClaim, eProcess, hashJson, heldoutSignificance, holm, isIndependentEvidence, manifestContentDigest, mcnemar, mcnemarPower, mcnemarRequiredN, mulberry32, openFinalEvidenceLedger, pairArms, pairHoldout, pairRunRecords, pairedBootstrap, pairedEvalueSequence, pairedMde, pairedRiskDifference, pairedRiskDifferenceExact, pairedRiskDifferenceScore, paretoPolicy, paretoSignificanceGate, powerPreflight, requiredPairedSampleSize, requiredSampleSize, sealMeasureValidityPlan, sequentialDecide, sequentialPairedGate, signManifest, summarizeEvaluationUnits, verifyEvidenceReceipt, verifyManifest, verifyMeasureValidityPlan, wilson };
959
959
  //# sourceMappingURL=index.d.ts.map
@@ -1,19 +1,19 @@
1
1
  import { n as CaptureIntegrityError, s as ValidationError } from "../errors-DeEEV9Vx.js";
2
2
  import { a as hashCanonical, t as LEDGER_HASH_PATTERN } from "../canonical-DKgL_Wby.js";
3
3
  import { d as signManifest, f as verifyManifest, l as hashJson, u as manifestContentDigest } from "../agent-profile-cell-CUthydZB.js";
4
- import { n as pairArms, r as pairRunRecords, t as comparePairedArms } from "../paired-arms-B6EXnI47.js";
4
+ import { n as pairArms, r as pairRunRecords, t as comparePairedArms } from "../paired-arms-CJH5Q0wx.js";
5
5
  import { D as studentTCdf, O as studentTQuantile, r as pairedBootstrap, t as BOOTSTRAP_GATE_MIN_N } from "../paired-tests-CXcD_B80.js";
6
6
  import { t as mulberry32 } from "../random-DrzcgC7F.js";
7
- import { S as holm, b as benjaminiHochberg, c as pairedMde, f as mcnemar, g as pairedRiskDifferenceScore, h as pairedRiskDifferenceExact, l as requiredPairedSampleSize, m as pairedRiskDifference, o as mcnemarPower, s as mcnemarRequiredN, t as eProcess, u as requiredSampleSize, x as bonferroni, y as wilson } from "../statistics-BPl13X3G.js";
8
- import { a as heldoutSignificance, o as pairHoldout } from "../statistical-heldout-C7Jjo5nP.js";
9
- import { C as FinalEvidenceError, S as FinalEvidenceConflictError, i as verifyEvidenceReceipt, n as createEvidenceReceipt, r as isIndependentEvidence, t as createCampaignEvidenceReceipt, w as openFinalEvidenceLedger, x as powerPreflight } from "../campaign-evidence-BTfzZo1u.js";
7
+ import { S as holm, b as benjaminiHochberg, c as pairedMde, f as mcnemar, g as pairedRiskDifferenceScore, h as pairedRiskDifferenceExact, l as requiredPairedSampleSize, m as pairedRiskDifference, o as mcnemarPower, s as mcnemarRequiredN, t as eProcess, u as requiredSampleSize, x as bonferroni, y as wilson } from "../statistics-AKnVFnK-.js";
8
+ import { a as heldoutSignificance, o as pairHoldout } from "../statistical-heldout-CL_7mI5C.js";
9
+ import { C as FinalEvidenceError, S as FinalEvidenceConflictError, i as verifyEvidenceReceipt, n as createEvidenceReceipt, r as isIndependentEvidence, t as createCampaignEvidenceReceipt, w as openFinalEvidenceLedger, x as powerPreflight } from "../campaign-evidence-KM5GTsHG.js";
10
10
  import { n as evaluatePredicate, r as readField, t as compareValues } from "../predicate-BYHA4MBn.js";
11
11
  import { r as summarizeEvaluationUnits, t as defineEvaluationClaim } from "../claim-BWEXwwBk.js";
12
- import { n as pairedEvalueSequence } from "../sequential-tZjGysXY.js";
12
+ import { n as pairedEvalueSequence } from "../sequential-DR-pnYQ7.js";
13
13
  import { n as intervalSpecProblems, r as computeEstimand, t as computeInterval } from "../interval-Bd2f4CRT.js";
14
- import { n as paretoPolicy, r as paretoSignificanceGate, t as buildEvidenceVector } from "../promotion-policy-Z5E-C32U.js";
15
- import { i as sequentialPairedGate, n as clusteredPower, r as sequentialDecide, t as assertDesignAdequate } from "../power-DTg6u30w.js";
16
- import { n as verifyMeasureValidityPlan, t as sealMeasureValidityPlan } from "../measure-validity-plan-t0YQRzJQ.js";
14
+ import { n as paretoPolicy, r as paretoSignificanceGate, t as buildEvidenceVector } from "../promotion-policy-BgI7PsQn.js";
15
+ import { i as sequentialPairedGate, n as clusteredPower, r as sequentialDecide, t as assertDesignAdequate } from "../power-COie_o6E.js";
16
+ import { n as verifyMeasureValidityPlan, t as sealMeasureValidityPlan } from "../measure-validity-plan-CJkBNzX_.js";
17
17
  import { z } from "zod";
18
18
  // src/experiment/ast/decision.ts
19
19
  /** A decision rule's branches did not cover the evidence. */
@@ -34,6 +34,11 @@ function resolveExternalOptimizerCallbackLimits(value, label = "external optimiz
34
34
  assertBoundedPositiveInteger(resolved.maxResponseBytes, `${label}.maxResponseBytes`, MAXIMUM_JSON_BYTES);
35
35
  return resolved;
36
36
  }
37
+ /**
38
+ * Response header on a proxy budget refusal; its value is the fixed ASCII
39
+ * `ExternalOptimizerRefusalKind`, while the reason text stays in the JSON body.
40
+ */
41
+ const EXTERNAL_OPTIMIZER_REFUSAL_HEADER = "x-agent-eval-refusal";
37
42
  function isCandidateText(value, maxChars) {
38
43
  return typeof value === "string" && value.trim().length > 0 && value.length <= maxChars;
39
44
  }
@@ -118,6 +123,6 @@ function freezeJsonSnapshot(value, label) {
118
123
  assertJsonValue(value, label);
119
124
  return deepFreezeCanonicalJson(JSON.parse(canonicalJson(value)));
120
125
  }
121
- export { assertNoCredentialValues as a, isExternalTextCandidate as c, resolveExternalOptimizerProcessLimits as d, safePathComponent as f, assertJsonValue as i, removeCredentialEnvironment as l, DEFAULT_EXTERNAL_OPTIMIZER_PROCESS_LIMITS as n, freezeJsonSnapshot as o, assertExternalOptimizerModelBudget as r, isCandidateText as s, DEFAULT_EXTERNAL_OPTIMIZER_CALLBACK_LIMITS as t, resolveExternalOptimizerCallbackLimits as u };
126
+ export { assertJsonValue as a, isCandidateText as c, resolveExternalOptimizerCallbackLimits as d, resolveExternalOptimizerProcessLimits as f, assertExternalOptimizerModelBudget as i, isExternalTextCandidate as l, DEFAULT_EXTERNAL_OPTIMIZER_PROCESS_LIMITS as n, assertNoCredentialValues as o, safePathComponent as p, EXTERNAL_OPTIMIZER_REFUSAL_HEADER as r, freezeJsonSnapshot as s, DEFAULT_EXTERNAL_OPTIMIZER_CALLBACK_LIMITS as t, removeCredentialEnvironment as u };
122
127
 
123
- //# sourceMappingURL=external-optimizer-contracts-ZDBfbZ_s.js.map
128
+ //# sourceMappingURL=external-optimizer-contracts-BFV8lnhl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"external-optimizer-contracts-ZDBfbZ_s.js","names":["bufferConstants","deepFreezeJson"],"sources":["../src/campaign/external-optimizer-contracts.ts"],"sourcesContent":["import { constants as bufferConstants } from 'node:buffer'\nimport type { ChatRequest, ChatResponse } from '../analyst/chat-client'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { deepFreezeCanonicalJson as deepFreezeJson } from '../ledger-core/deep-freeze'\nimport { isRecord } from '../llm-client/json'\nimport { canonicalJson } from '../verdict-cache'\nimport type { CampaignCellMeasurement } from './search-campaign-cell'\n\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst MAXIMUM_JSON_BYTES = Math.min(\n bufferConstants.MAX_LENGTH - 1,\n bufferConstants.MAX_STRING_LENGTH,\n)\n\nexport interface ExternalOptimizerProcessLimits {\n /** Maximum serialized input written for the child process. */\n maxInputBytes: number\n /** Maximum JSON result read from the child process. */\n maxResultBytes: number\n /** Maximum stdout or stderr characters retained for diagnostics. */\n maxOutputChars: number\n}\n\nexport const DEFAULT_EXTERNAL_OPTIMIZER_PROCESS_LIMITS: Readonly<ExternalOptimizerProcessLimits> =\n Object.freeze({\n maxInputBytes: 64 * 1024 * 1024,\n maxResultBytes: 4 * 1024 * 1024,\n maxOutputChars: 64_000,\n })\n\nexport interface ExternalOptimizerCallbackLimits {\n /** Maximum serialized request accepted by the loopback callback. */\n maxRequestBytes: number\n /** Maximum serialized response returned by the loopback callback. */\n maxResponseBytes: number\n}\n\nexport const DEFAULT_EXTERNAL_OPTIMIZER_CALLBACK_LIMITS: Readonly<ExternalOptimizerCallbackLimits> =\n Object.freeze({\n maxRequestBytes: 1_000_000,\n maxResponseBytes: 4_000_000,\n })\n\nexport interface ExternalOptimizerRunnerCommand {\n command?: string\n args?: readonly string[]\n env?: NodeJS.ProcessEnv\n /** Child-process resource limits. Omitted fields use finite defaults. */\n limits?: Partial<ExternalOptimizerProcessLimits>\n}\n\nexport type ExternalOptimizerResumeMode = 'never' | 'if-compatible' | 'required'\n\nexport type ExternalTextCandidate = string | Record<string, string>\n\nexport interface ExternalTextEvaluationRequest {\n candidate: ExternalTextCandidate\n exampleId: string\n}\n\nexport interface ExternalOptimizerCallback {\n url: string\n token: string\n evaluations: () => number\n close: () => Promise<void>\n}\n\nexport function resolveExternalOptimizerProcessLimits(\n value: Partial<ExternalOptimizerProcessLimits> | undefined,\n label = 'external optimizer process limits',\n): ExternalOptimizerProcessLimits {\n const resolved = {\n ...DEFAULT_EXTERNAL_OPTIMIZER_PROCESS_LIMITS,\n ...value,\n }\n assertBoundedPositiveInteger(resolved.maxInputBytes, `${label}.maxInputBytes`, MAXIMUM_JSON_BYTES)\n assertBoundedPositiveInteger(\n resolved.maxResultBytes,\n `${label}.maxResultBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n resolved.maxOutputChars,\n `${label}.maxOutputChars`,\n bufferConstants.MAX_STRING_LENGTH,\n )\n return resolved\n}\n\nexport function resolveExternalOptimizerCallbackLimits(\n value: Partial<ExternalOptimizerCallbackLimits> | undefined,\n label = 'external optimizer callback limits',\n): ExternalOptimizerCallbackLimits {\n const resolved = {\n ...DEFAULT_EXTERNAL_OPTIMIZER_CALLBACK_LIMITS,\n ...value,\n }\n assertBoundedPositiveInteger(\n resolved.maxRequestBytes,\n `${label}.maxRequestBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n resolved.maxResponseBytes,\n `${label}.maxResponseBytes`,\n MAXIMUM_JSON_BYTES,\n )\n return resolved\n}\n\ntype DeepReadonly<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends readonly (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T\n\n/** Provider-neutral request parsed once from the optimizer's loopback protocol. */\nexport type ExternalOptimizerChatRequest = DeepReadonly<\n Omit<ChatRequest, 'model'> & { model: string }\n>\n\nexport type ExternalOptimizerEndpointFormat =\n | 'chat-completions'\n | 'responses'\n | 'anthropic-messages'\n\n/** One exact model request admitted by the loopback proxy. */\nexport interface ExternalOptimizerModelCallRequest {\n /** Stable identity allocated by the cost ledger for this paid call. */\n readonly callId: string\n /** Deeply immutable canonical request; HTTP protocol fields never cross this boundary. */\n readonly request: ExternalOptimizerChatRequest\n /** Child response shape, when the execution owner needs to retain it as evidence. */\n readonly endpointFormat?: ExternalOptimizerEndpointFormat\n readonly signal: AbortSignal\n}\n\n/** Runtime-owned result for one admitted optimizer-model call. */\nexport type ExternalOptimizerModelCallResult =\n | {\n readonly succeeded: true\n /** Canonical response encoded back into the child's protocol by Agent Eval. */\n readonly response: ChatResponse\n /**\n * Canonical measured usage/cost input retained by Agent Eval's cost ledger.\n * `inputTokens` is the non-cached portion, `cachedTokens` is the cache-read\n * portion, and response `promptTokens` equals their sum. Cache-write tokens\n * remain a separately billed class and are never silently added to that total.\n */\n readonly receipt: import('../cost-ledger').CostReceiptInput\n /** Opaque, finite JSON proof of the exact execution retained in provenance. */\n readonly execution: unknown\n }\n | {\n readonly succeeded: false\n /** Public failure text safe to retain and return to the child process. */\n readonly error: string\n /** Usage/cost state for the failed Runtime call. Unknown values stay unknown. */\n readonly receipt: import('../cost-ledger').CostReceiptInput\n /** Opaque, finite JSON proof of the failed exact execution. */\n readonly execution: unknown\n }\n\n/**\n * Execution-neutral model-call seam for an external optimizer.\n *\n * The package that owns execution implements this with its exact execution\n * path. For Discovery that owner is Runtime and the identity is an\n * AgentProfile. The loopback proxy owns request validation, limits, response\n * bounds, and cost-ledger recording. Once invoked, the callback must resolve\n * with one success/failure result. Rejecting loses the execution record and\n * therefore fails the optimizer attempt.\n */\nexport type ExternalOptimizerModelCall = (\n request: ExternalOptimizerModelCallRequest,\n) => Promise<ExternalOptimizerModelCallResult>\n\n/** One opaque Runtime execution record retained for one admitted model call. */\nexport type ExternalOptimizerModelExecutionObservation =\n | {\n readonly sequence: number\n readonly callId: string\n readonly callRef: string\n readonly path: '/v1/chat/completions' | '/v1/responses' | '/v1/messages'\n readonly model: string\n readonly succeeded: true\n readonly responseStatus: number\n readonly execution: unknown\n }\n | {\n readonly sequence: number\n readonly callId: string\n readonly callRef: string\n readonly path: '/v1/chat/completions' | '/v1/responses' | '/v1/messages'\n readonly model: string\n readonly succeeded: false\n readonly error: string\n readonly execution: unknown\n }\n\n/**\n * Which campaign cells answered one evaluation request. `measured`: this\n * request ran them. `reused`: an earlier request for the same candidate and\n * case ran them, and this one was answered from its result. The search ledger\n * records each distinct cell once, so a reused request adds no cell.\n */\nexport interface ExternalEvaluationMeasurement {\n readonly source: 'measured' | 'reused'\n readonly cells: readonly CampaignCellMeasurement[]\n}\n\nexport type ExternalOptimizerEvaluationRefusalReason =\n | 'invalid-request'\n | 'evaluation-limit'\n | 'evaluation-failed'\n\n/**\n * Durable callback-side record of every candidate submitted for scoring,\n * scored task, and callback refusal. Optimizer-internal proposals that never\n * reach this callback are outside this record's scope.\n */\nexport type ExternalOptimizerEvaluationObservation =\n | {\n readonly kind: 'proposal'\n readonly sequence: number\n readonly candidate: ExternalTextCandidate\n readonly candidateHash: string\n }\n | {\n readonly kind: 'evaluation'\n readonly sequence: number\n readonly candidate: ExternalTextCandidate\n readonly candidateHash: string\n readonly exampleId: string\n /** One-based accepted evaluation number for this optimizer attempt. */\n readonly evaluationNumber: number\n readonly response: unknown\n /** The campaign cells behind `response`. Absent in logs written before\n * the callback recorded them, and for an evaluator that reports none. */\n readonly measurement?: ExternalEvaluationMeasurement\n }\n | {\n readonly kind: 'refusal'\n readonly sequence: number\n readonly reason: ExternalOptimizerEvaluationRefusalReason\n readonly candidate?: ExternalTextCandidate\n readonly candidateHash?: string\n readonly exampleId?: string\n /** The campaign cells an `evaluation-failed` refusal measured before it\n * was refused, such as evidence no excerpt fits the bound; their spend\n * is real. When the evaluation's campaign threw, these are the cells it\n * settled, then each cell the throw interrupted, whose accounting is\n * unknown. Absent for a refusal that measured nothing, and in logs\n * written before refusals recorded them. */\n readonly measurement?: ExternalEvaluationMeasurement\n }\n\nexport interface ExternalOptimizerModelBudget {\n /** Optional optimizer-model spend ceiling, independent of task-evaluation spend. */\n maxCostUsd?: number\n /** Maximum calls into the execution owner; owner-internal retries are reported there. */\n maxRequests: number\n /** Reject a request body above this byte count. */\n maxRequestBytes: number\n /** Reject a provider response above this byte count. */\n maxResponseBytes: number\n /** Reject a request asking the provider for more output tokens. */\n maxOutputTokensPerRequest: number\n /**\n * Reasoning tokens a single response may bill beyond its completion limit.\n *\n * A reasoning model bounds only the completion by `max_tokens` and bills\n * thinking on top, so a reservation sized to the completion alone is always\n * too small and the ledger refuses the real charge. Callers that route a\n * reasoning model declare its thinking budget here; the reservation covers\n * it and a response exceeding it still fails loudly. Default: 0.\n */\n maxReasoningTokensPerRequest?: number\n /**\n * Optional rates used to estimate cost when the provider omits a valid\n * `usage.cost`. Omit when billed USD is unknown; catalog estimates are not\n * enforcement evidence.\n */\n pricing?: CustomTokenPricing\n /** Per-provider-request deadline. Default: 300,000 ms. */\n requestTimeoutMs?: number\n}\n\n/** Per-wire request accounting for the loopback proxy. */\nexport interface ExternalOptimizerWireCounts {\n /** Execution-owner calls admitted on this wire, including failures. */\n requestAttempts: number\n /** Successful 2xx responses recorded on this wire. */\n successfulCompletions: number\n}\n\nexport interface ExternalOptimizerModelProxy {\n /** OpenAI-compatible base URL supplied to the optimizer process. */\n baseUrl: string\n /** Ephemeral credential supplied only to the local proxy. */\n apiKey: string\n /** Execution-owner calls admitted during this proxy process, including failures. */\n requestAttempts: () => number\n /** Successful 2xx responses recorded during this proxy process. */\n successfulCompletions: () => number\n /**\n * Per-wire traffic breakdown of the totals above. The `openai` wire carries\n * the optimizer process's own client calls; the `anthropic` wire carries\n * `claude` CLI traffic when the Anthropic endpoint is enabled.\n */\n wireUsage: () => { openai: ExternalOptimizerWireCounts; anthropic: ExternalOptimizerWireCounts }\n /** Fail if an invoked caller-owned model path omitted its execution record. */\n assertExecutionComplete: () => void\n /** Failures retained by the proxy after converting them to loopback responses. */\n failures: () => readonly Error[]\n close: () => Promise<void>\n}\n\nexport function isCandidateText(value: unknown, maxChars: number): value is string {\n return typeof value === 'string' && value.trim().length > 0 && value.length <= maxChars\n}\n\nexport function isExternalTextCandidate(value: unknown): value is ExternalTextCandidate {\n if (typeof value === 'string') return value.trim().length > 0\n if (!isRecord(value)) return false\n const entries = Object.entries(value)\n return (\n entries.length > 0 &&\n entries.every(\n ([name, content]) =>\n name.trim().length > 0 && name.trim() === name && typeof content === 'string',\n )\n )\n}\n\nexport function assertJsonValue(value: unknown, label: string, seen = new Set<object>()): void {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return\n if (typeof value === 'number' && Number.isFinite(value)) return\n if (Array.isArray(value)) {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n seen.add(value)\n for (const item of value) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n if (typeof value === 'object') {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be JSON-serializable`)\n }\n seen.add(value)\n for (const item of Object.values(value)) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n throw new Error(`${label} must be JSON-serializable`)\n}\n\nexport function assertNoCredentialValues(\n value: unknown,\n path: string,\n credentialLocation = 'runner.env',\n): void {\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n assertNoCredentialValues(item, `${path}[${index}]`, credentialLocation)\n }\n return\n }\n if (!isRecord(value)) return\n for (const [key, item] of Object.entries(value)) {\n if (isCredentialKey(key)) {\n throw new Error(`${path}.${key} must be supplied through ${credentialLocation}`)\n }\n assertNoCredentialValues(item, `${path}.${key}`, credentialLocation)\n }\n}\n\nexport function removeCredentialEnvironment(\n environment: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n const sanitized: Record<string, string> = {}\n for (const [key, value] of Object.entries(environment)) {\n if (value !== undefined && !isCredentialKey(key)) sanitized[key] = value\n }\n return sanitized\n}\n\nexport function assertExternalOptimizerModelBudget(\n value: ExternalOptimizerModelBudget,\n label: string,\n): void {\n if (!value || typeof value !== 'object') {\n throw new Error(`${label} is required`)\n }\n for (const [field, entry] of [\n ['maxRequests', value.maxRequests],\n ['maxOutputTokensPerRequest', value.maxOutputTokensPerRequest],\n ] as const) {\n if (!Number.isSafeInteger(entry) || entry <= 0) {\n throw new Error(`${label}.${field} must be a positive safe integer`)\n }\n }\n assertBoundedPositiveInteger(\n value.maxRequestBytes,\n `${label}.maxRequestBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n value.maxResponseBytes,\n `${label}.maxResponseBytes`,\n MAXIMUM_JSON_BYTES,\n )\n if (\n value.maxReasoningTokensPerRequest !== undefined &&\n (!Number.isSafeInteger(value.maxReasoningTokensPerRequest) ||\n value.maxReasoningTokensPerRequest < 0)\n ) {\n throw new Error(`${label}.maxReasoningTokensPerRequest must be a non-negative safe integer`)\n }\n if (\n value.maxCostUsd !== undefined &&\n (!Number.isFinite(value.maxCostUsd) || value.maxCostUsd <= 0)\n ) {\n throw new Error(`${label}.maxCostUsd must be positive and finite when supplied`)\n }\n if (\n value.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(value.requestTimeoutMs) ||\n value.requestTimeoutMs <= 0 ||\n value.requestTimeoutMs > MAX_TIMER_DELAY_MS)\n ) {\n throw new Error(`${label}.requestTimeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n if (value.pricing !== undefined) {\n costForTokenPricing(value.pricing, { inputTokens: 1, outputTokens: 1 })\n }\n if (value.maxCostUsd !== undefined && value.pricing === undefined) {\n throw new Error(`${label}.pricing is required when maxCostUsd is supplied`)\n }\n}\n\nexport function safePathComponent(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, '_')\n}\n\nfunction assertBoundedPositiveInteger(value: number, label: string, maximum: number): void {\n if (!Number.isSafeInteger(value) || value <= 0 || value > maximum) {\n throw new Error(`${label} must be an integer between 1 and ${maximum}`)\n }\n}\n\nfunction isCredentialKey(key: string): boolean {\n const normalized = key\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/-/g, '_')\n .toLowerCase()\n const segments = normalized.split('_')\n return segments.some((segment) =>\n [\n 'auth',\n 'authorization',\n 'cookie',\n 'credential',\n 'credentials',\n 'key',\n 'password',\n 'secret',\n 'session',\n 'token',\n ].includes(segment),\n )\n}\n\nexport function freezeJsonSnapshot(value: unknown, label: string): unknown {\n assertJsonValue(value, label)\n return deepFreezeJson(JSON.parse(canonicalJson(value)))\n}\n"],"mappings":";;;;;;AASA,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB,KAAK,IAC9BA,UAAgB,aAAa,GAC7BA,UAAgB,iBAClB;AAWA,MAAa,4CACX,OAAO,OAAO;CACZ,eAAe;CACf,gBAAgB;CAChB,gBAAgB;AAClB,CAAC;AASH,MAAa,6CACX,OAAO,OAAO;CACZ,iBAAiB;CACjB,kBAAkB;AACpB,CAAC;A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AAsB,OAAO,CAAC,CACtC,QAAQ,MAAM,GAAG,CAAC,CAClB,YACuB,CAAC,CAAC,MAAM,GACpB,CAAC,CAAC,MAAM,YACpB;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,SAAS,OAAO,CACpB;AACF;AAEA,SAAgB,mBAAmB,OAAgB,OAAwB;CACzE,gBAAgB,OAAO,KAAK;CAC5B,OAAOC,wBAAe,KAAK,MAAM,cAAc,KAAK,CAAC,CAAC;AACxD"}
1
+ {"version":3,"file":"external-optimizer-contracts-BFV8lnhl.js","names":["bufferConstants","deepFreezeJson"],"sources":["../src/campaign/external-optimizer-contracts.ts"],"sourcesContent":["import { constants as bufferConstants } from 'node:buffer'\nimport type { ChatRequest, ChatResponse } from '../analyst/chat-client'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { deepFreezeCanonicalJson as deepFreezeJson } from '../ledger-core/deep-freeze'\nimport { isRecord } from '../llm-client/json'\nimport { canonicalJson } from '../verdict-cache'\nimport type { CampaignCellMeasurement } from './search-campaign-cell'\n\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst MAXIMUM_JSON_BYTES = Math.min(\n bufferConstants.MAX_LENGTH - 1,\n bufferConstants.MAX_STRING_LENGTH,\n)\n\nexport interface ExternalOptimizerProcessLimits {\n /** Maximum serialized input written for the child process. */\n maxInputBytes: number\n /** Maximum JSON result read from the child process. */\n maxResultBytes: number\n /** Maximum stdout or stderr characters retained for diagnostics. */\n maxOutputChars: number\n}\n\nexport const DEFAULT_EXTERNAL_OPTIMIZER_PROCESS_LIMITS: Readonly<ExternalOptimizerProcessLimits> =\n Object.freeze({\n maxInputBytes: 64 * 1024 * 1024,\n maxResultBytes: 4 * 1024 * 1024,\n maxOutputChars: 64_000,\n })\n\nexport interface ExternalOptimizerCallbackLimits {\n /** Maximum serialized request accepted by the loopback callback. */\n maxRequestBytes: number\n /** Maximum serialized response returned by the loopback callback. */\n maxResponseBytes: number\n}\n\nexport const DEFAULT_EXTERNAL_OPTIMIZER_CALLBACK_LIMITS: Readonly<ExternalOptimizerCallbackLimits> =\n Object.freeze({\n maxRequestBytes: 1_000_000,\n maxResponseBytes: 4_000_000,\n })\n\nexport interface ExternalOptimizerRunnerCommand {\n command?: string\n args?: readonly string[]\n env?: NodeJS.ProcessEnv\n /** Child-process resource limits. Omitted fields use finite defaults. */\n limits?: Partial<ExternalOptimizerProcessLimits>\n}\n\nexport type ExternalOptimizerResumeMode = 'never' | 'if-compatible' | 'required'\n\nexport type ExternalTextCandidate = string | Record<string, string>\n\nexport interface ExternalTextEvaluationRequest {\n candidate: ExternalTextCandidate\n exampleId: string\n}\n\nexport interface ExternalOptimizerCallback {\n url: string\n token: string\n evaluations: () => number\n close: () => Promise<void>\n}\n\nexport function resolveExternalOptimizerProcessLimits(\n value: Partial<ExternalOptimizerProcessLimits> | undefined,\n label = 'external optimizer process limits',\n): ExternalOptimizerProcessLimits {\n const resolved = {\n ...DEFAULT_EXTERNAL_OPTIMIZER_PROCESS_LIMITS,\n ...value,\n }\n assertBoundedPositiveInteger(resolved.maxInputBytes, `${label}.maxInputBytes`, MAXIMUM_JSON_BYTES)\n assertBoundedPositiveInteger(\n resolved.maxResultBytes,\n `${label}.maxResultBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n resolved.maxOutputChars,\n `${label}.maxOutputChars`,\n bufferConstants.MAX_STRING_LENGTH,\n )\n return resolved\n}\n\nexport function resolveExternalOptimizerCallbackLimits(\n value: Partial<ExternalOptimizerCallbackLimits> | undefined,\n label = 'external optimizer callback limits',\n): ExternalOptimizerCallbackLimits {\n const resolved = {\n ...DEFAULT_EXTERNAL_OPTIMIZER_CALLBACK_LIMITS,\n ...value,\n }\n assertBoundedPositiveInteger(\n resolved.maxRequestBytes,\n `${label}.maxRequestBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n resolved.maxResponseBytes,\n `${label}.maxResponseBytes`,\n MAXIMUM_JSON_BYTES,\n )\n return resolved\n}\n\ntype DeepReadonly<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends readonly (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T\n\n/** Provider-neutral request parsed once from the optimizer's loopback protocol. */\nexport type ExternalOptimizerChatRequest = DeepReadonly<\n Omit<ChatRequest, 'model'> & { model: string }\n>\n\nexport type ExternalOptimizerEndpointFormat =\n | 'chat-completions'\n | 'responses'\n | 'anthropic-messages'\n\n/** One exact model request admitted by the loopback proxy. */\nexport interface ExternalOptimizerModelCallRequest {\n /** Stable identity allocated by the cost ledger for this paid call. */\n readonly callId: string\n /** Deeply immutable canonical request; HTTP protocol fields never cross this boundary. */\n readonly request: ExternalOptimizerChatRequest\n /** Child response shape, when the execution owner needs to retain it as evidence. */\n readonly endpointFormat?: ExternalOptimizerEndpointFormat\n readonly signal: AbortSignal\n}\n\n/** Runtime-owned result for one admitted optimizer-model call. */\nexport type ExternalOptimizerModelCallResult =\n | {\n readonly succeeded: true\n /** Canonical response encoded back into the child's protocol by Agent Eval. */\n readonly response: ChatResponse\n /**\n * Canonical measured usage/cost input retained by Agent Eval's cost ledger.\n * `inputTokens` is the non-cached portion, `cachedTokens` is the cache-read\n * portion, and response `promptTokens` equals their sum. Cache-write tokens\n * remain a separately billed class and are never silently added to that total.\n */\n readonly receipt: import('../cost-ledger').CostReceiptInput\n /** Opaque, finite JSON proof of the exact execution retained in provenance. */\n readonly execution: unknown\n }\n | {\n readonly succeeded: false\n /** Public failure text safe to retain and return to the child process. */\n readonly error: string\n /** Usage/cost state for the failed Runtime call. Unknown values stay unknown. */\n readonly receipt: import('../cost-ledger').CostReceiptInput\n /** Opaque, finite JSON proof of the failed exact execution. */\n readonly execution: unknown\n }\n\n/**\n * Execution-neutral model-call seam for an external optimizer.\n *\n * The package that owns execution implements this with its exact execution\n * path. For Discovery that owner is Runtime and the identity is an\n * AgentProfile. The loopback proxy owns request validation, limits, response\n * bounds, and cost-ledger recording. Once invoked, the callback must resolve\n * with one success/failure result. Rejecting loses the execution record and\n * therefore fails the optimizer attempt.\n */\nexport type ExternalOptimizerModelCall = (\n request: ExternalOptimizerModelCallRequest,\n) => Promise<ExternalOptimizerModelCallResult>\n\n/** One opaque Runtime execution record retained for one admitted model call. */\nexport type ExternalOptimizerModelExecutionObservation =\n | {\n readonly sequence: number\n readonly callId: string\n readonly callRef: string\n readonly path: '/v1/chat/completions' | '/v1/responses' | '/v1/messages'\n readonly model: string\n readonly succeeded: true\n readonly responseStatus: number\n readonly execution: unknown\n }\n | {\n readonly sequence: number\n readonly callId: string\n readonly callRef: string\n readonly path: '/v1/chat/completions' | '/v1/responses' | '/v1/messages'\n readonly model: string\n readonly succeeded: false\n readonly error: string\n readonly execution: unknown\n }\n\n/**\n * Which campaign cells answered one evaluation request. `measured`: this\n * request ran them. `reused`: an earlier request for the same candidate and\n * case ran them, and this one was answered from its result. The search ledger\n * records each distinct cell once, so a reused request adds no cell.\n */\nexport interface ExternalEvaluationMeasurement {\n readonly source: 'measured' | 'reused'\n readonly cells: readonly CampaignCellMeasurement[]\n}\n\nexport type ExternalOptimizerEvaluationRefusalReason =\n | 'invalid-request'\n | 'evaluation-limit'\n | 'evaluation-failed'\n\n/**\n * Durable callback-side record of every candidate submitted for scoring,\n * scored task, and callback refusal. Optimizer-internal proposals that never\n * reach this callback are outside this record's scope.\n */\nexport type ExternalOptimizerEvaluationObservation =\n | {\n readonly kind: 'proposal'\n readonly sequence: number\n readonly candidate: ExternalTextCandidate\n readonly candidateHash: string\n }\n | {\n readonly kind: 'evaluation'\n readonly sequence: number\n readonly candidate: ExternalTextCandidate\n readonly candidateHash: string\n readonly exampleId: string\n /** One-based accepted evaluation number for this optimizer attempt. */\n readonly evaluationNumber: number\n readonly response: unknown\n /** The campaign cells behind `response`. Absent in logs written before\n * the callback recorded them, and for an evaluator that reports none. */\n readonly measurement?: ExternalEvaluationMeasurement\n }\n | {\n readonly kind: 'refusal'\n readonly sequence: number\n readonly reason: ExternalOptimizerEvaluationRefusalReason\n readonly candidate?: ExternalTextCandidate\n readonly candidateHash?: string\n readonly exampleId?: string\n /** The campaign cells an `evaluation-failed` refusal measured before it\n * was refused, such as evidence no excerpt fits the bound; their spend\n * is real. When the evaluation's campaign threw, these are the cells it\n * settled, then each cell the throw interrupted, whose accounting is\n * unknown. Absent for a refusal that measured nothing, and in logs\n * written before refusals recorded them. */\n readonly measurement?: ExternalEvaluationMeasurement\n }\n\nexport interface ExternalOptimizerModelBudget {\n /** Optional optimizer-model spend ceiling, independent of task-evaluation spend. */\n maxCostUsd?: number\n /** Maximum calls into the execution owner; owner-internal retries are reported there. */\n maxRequests: number\n /** Reject a request body above this byte count. */\n maxRequestBytes: number\n /** Reject a provider response above this byte count. */\n maxResponseBytes: number\n /** Reject a request asking the provider for more output tokens. */\n maxOutputTokensPerRequest: number\n /**\n * Reasoning tokens a single response may bill beyond its completion limit.\n *\n * A reasoning model bounds only the completion by `max_tokens` and bills\n * thinking on top, so a reservation sized to the completion alone is always\n * too small and the ledger refuses the real charge. Callers that route a\n * reasoning model declare its thinking budget here; the reservation covers\n * it and a response exceeding it still fails loudly. Default: 0.\n */\n maxReasoningTokensPerRequest?: number\n /**\n * Optional rates used to estimate cost when the provider omits a valid\n * `usage.cost`. Omit when billed USD is unknown; catalog estimates are not\n * enforcement evidence.\n */\n pricing?: CustomTokenPricing\n /** Per-provider-request deadline. Default: 300,000 ms. */\n requestTimeoutMs?: number\n}\n\n/** Per-wire request accounting for the loopback proxy. */\nexport interface ExternalOptimizerWireCounts {\n /** Execution-owner calls admitted on this wire, including failures. */\n requestAttempts: number\n /** Successful 2xx responses recorded on this wire. */\n successfulCompletions: number\n /**\n * Requests refused because the request or cost limit was reached. They never\n * reach the execution owner, and each refusal carries\n * `EXTERNAL_OPTIMIZER_REFUSAL_HEADER` so the optimizer process counts it too.\n */\n refusedRequests: number\n}\n\n/**\n * Fixed ASCII codes carried in `EXTERNAL_OPTIMIZER_REFUSAL_HEADER` for the two\n * budget refusal kinds. A header value must be Latin-1 without control\n * characters, so the free-text reason stays in the JSON body and only the kind\n * code crosses into the header.\n */\nexport type ExternalOptimizerRefusalKind = 'request-limit' | 'cost-limit'\n\n/**\n * Response header on a proxy budget refusal; its value is the fixed ASCII\n * `ExternalOptimizerRefusalKind`, while the reason text stays in the JSON body.\n */\nexport const EXTERNAL_OPTIMIZER_REFUSAL_HEADER = 'x-agent-eval-refusal'\n\nexport interface ExternalOptimizerModelProxy {\n /** OpenAI-compatible base URL supplied to the optimizer process. */\n baseUrl: string\n /** Ephemeral credential supplied only to the local proxy. */\n apiKey: string\n /** Execution-owner calls admitted during this proxy process, including failures. */\n requestAttempts: () => number\n /** Successful 2xx responses recorded during this proxy process. */\n successfulCompletions: () => number\n /**\n * Per-wire traffic breakdown of the totals above. The `openai` wire carries\n * the optimizer process's own client calls; the `anthropic` wire carries\n * `claude` CLI traffic when the Anthropic endpoint is enabled.\n */\n wireUsage: () => { openai: ExternalOptimizerWireCounts; anthropic: ExternalOptimizerWireCounts }\n /** Fail if an invoked caller-owned model path omitted its execution record. */\n assertExecutionComplete: () => void\n /** Failures retained by the proxy after converting them to loopback responses. */\n failures: () => readonly Error[]\n close: () => Promise<void>\n}\n\nexport function isCandidateText(value: unknown, maxChars: number): value is string {\n return typeof value === 'string' && value.trim().length > 0 && value.length <= maxChars\n}\n\nexport function isExternalTextCandidate(value: unknown): value is ExternalTextCandidate {\n if (typeof value === 'string') return value.trim().length > 0\n if (!isRecord(value)) return false\n const entries = Object.entries(value)\n return (\n entries.length > 0 &&\n entries.every(\n ([name, content]) =>\n name.trim().length > 0 && name.trim() === name && typeof content === 'string',\n )\n )\n}\n\nexport function assertJsonValue(value: unknown, label: string, seen = new Set<object>()): void {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return\n if (typeof value === 'number' && Number.isFinite(value)) return\n if (Array.isArray(value)) {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n seen.add(value)\n for (const item of value) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n if (typeof value === 'object') {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be JSON-serializable`)\n }\n seen.add(value)\n for (const item of Object.values(value)) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n throw new Error(`${label} must be JSON-serializable`)\n}\n\nexport function assertNoCredentialValues(\n value: unknown,\n path: string,\n credentialLocation = 'runner.env',\n): void {\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n assertNoCredentialValues(item, `${path}[${index}]`, credentialLocation)\n }\n return\n }\n if (!isRecord(value)) return\n for (const [key, item] of Object.entries(value)) {\n if (isCredentialKey(key)) {\n throw new Error(`${path}.${key} must be supplied through ${credentialLocation}`)\n }\n assertNoCredentialValues(item, `${path}.${key}`, credentialLocation)\n }\n}\n\nexport function removeCredentialEnvironment(\n environment: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n const sanitized: Record<string, string> = {}\n for (const [key, value] of Object.entries(environment)) {\n if (value !== undefined && !isCredentialKey(key)) sanitized[key] = value\n }\n return sanitized\n}\n\nexport function assertExternalOptimizerModelBudget(\n value: ExternalOptimizerModelBudget,\n label: string,\n): void {\n if (!value || typeof value !== 'object') {\n throw new Error(`${label} is required`)\n }\n for (const [field, entry] of [\n ['maxRequests', value.maxRequests],\n ['maxOutputTokensPerRequest', value.maxOutputTokensPerRequest],\n ] as const) {\n if (!Number.isSafeInteger(entry) || entry <= 0) {\n throw new Error(`${label}.${field} must be a positive safe integer`)\n }\n }\n assertBoundedPositiveInteger(\n value.maxRequestBytes,\n `${label}.maxRequestBytes`,\n MAXIMUM_JSON_BYTES,\n )\n assertBoundedPositiveInteger(\n value.maxResponseBytes,\n `${label}.maxResponseBytes`,\n MAXIMUM_JSON_BYTES,\n )\n if (\n value.maxReasoningTokensPerRequest !== undefined &&\n (!Number.isSafeInteger(value.maxReasoningTokensPerRequest) ||\n value.maxReasoningTokensPerRequest < 0)\n ) {\n throw new Error(`${label}.maxReasoningTokensPerRequest must be a non-negative safe integer`)\n }\n if (\n value.maxCostUsd !== undefined &&\n (!Number.isFinite(value.maxCostUsd) || value.maxCostUsd <= 0)\n ) {\n throw new Error(`${label}.maxCostUsd must be positive and finite when supplied`)\n }\n if (\n value.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(value.requestTimeoutMs) ||\n value.requestTimeoutMs <= 0 ||\n value.requestTimeoutMs > MAX_TIMER_DELAY_MS)\n ) {\n throw new Error(`${label}.requestTimeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n if (value.pricing !== undefined) {\n costForTokenPricing(value.pricing, { inputTokens: 1, outputTokens: 1 })\n }\n if (value.maxCostUsd !== undefined && value.pricing === undefined) {\n throw new Error(`${label}.pricing is required when maxCostUsd is supplied`)\n }\n}\n\nexport function safePathComponent(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, '_')\n}\n\nfunction assertBoundedPositiveInteger(value: number, label: string, maximum: number): void {\n if (!Number.isSafeInteger(value) || value <= 0 || value > maximum) {\n throw new Error(`${label} must be an integer between 1 and ${maximum}`)\n }\n}\n\nfunction isCredentialKey(key: string): boolean {\n const normalized = key\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/-/g, '_')\n .toLowerCase()\n const segments = normalized.split('_')\n return segments.some((segment) =>\n [\n 'auth',\n 'authorization',\n 'cookie',\n 'credential',\n 'credentials',\n 'key',\n 'password',\n 'secret',\n 'session',\n 'token',\n ].includes(segment),\n )\n}\n\nexport function freezeJsonSnapshot(value: unknown, label: string): unknown {\n assertJsonValue(value, label)\n return deepFreezeJson(JSON.parse(canonicalJson(value)))\n}\n"],"mappings":";;;;;;AASA,MAAM,qBAAqB;AAC3B,MAAM,qBAAq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AoB,GAAG;AAC9C;AAEA,SAAS,6BAA6B,OAAe,OAAe,SAAuB;CACzF,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,SAAS,KAAK,QAAQ,SACxD,MAAM,IAAI,MAAM,GAAG,MAAM,oCAAoC,SAAS;AAE1E;AAEA,SAAS,gBAAgB,KAAsB;CAM7C,OALmB,IAChB,QAAQ,sBAAsB,OAAO,CAAC,CACtC,QAAQ,MAAM,GAAG,CAAC,CAClB,YACuB,CAAC,CAAC,MAAM,GACpB,CAAC,CAAC,MAAM,YACpB;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,SAAS,OAAO,CACpB;AACF;AAEA,SAAgB,mBAAmB,OAAgB,OAAwB;CACzE,gBAAgB,OAAO,KAAK;CAC5B,OAAOC,wBAAe,KAAK,MAAM,cAAc,KAAK,CAAC,CAAC;AACxD"}
@@ -1,7 +1,7 @@
1
1
  import { n as contentHash } from "./verdict-cache-BPaYxfG8.js";
2
2
  import { n as isRecord } from "./json-DtvZNAU9.js";
3
- import { c as isExternalTextCandidate, u as resolveExternalOptimizerCallbackLimits } from "./external-optimizer-contracts-ZDBfbZ_s.js";
4
- import { a as closeServer, c as waitForActiveHandlers, o as listenLocal, s as sendJsonIfOpen } from "./external-optimizer-subprocess-mV-2swJI.js";
3
+ import { d as resolveExternalOptimizerCallbackLimits, l as isExternalTextCandidate } from "./external-optimizer-contracts-BFV8lnhl.js";
4
+ import { a as closeServer, c as waitForActiveHandlers, o as listenLocal, s as sendJsonIfOpen } from "./external-optimizer-subprocess-_O06eDVA.js";
5
5
  import { createServer } from "node:http";
6
6
  // src/campaign/external-optimizer-callback.ts
7
7
  async function startExternalOptimizerCallback(args) {
@@ -228,4 +228,4 @@ function cloneCandidate(candidate) {
228
228
  }
229
229
  export { startExternalOptimizerCallback as t };
230
230
 
231
- //# sourceMappingURL=external-optimizer-process-CVi1x2nb.js.map
231
+ //# sourceMappingURL=external-optimizer-process-B6emPodQ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"external-optimizer-process-CVi1x2nb.js","names":[],"sources":["../src/campaign/external-optimizer-callback.ts"],"sourcesContent":["import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { isRecord } from '../llm-client/json'\nimport { contentHash } from '../verdict-cache'\nimport {\n type ExternalEvaluationMeasurement,\n type ExternalOptimizerCallback,\n type ExternalOptimizerCallbackLimits,\n type ExternalOptimizerEvaluationObservation,\n type ExternalTextCandidate,\n type ExternalTextEvaluationRequest,\n isExternalTextCandidate,\n resolveExternalOptimizerCallbackLimits,\n} from './external-optimizer-contracts'\nimport {\n closeServer,\n listenLocal,\n sendJsonIfOpen,\n waitForActiveHandlers,\n} from './external-optimizer-http'\n\n/**\n * Scores one callback request. An evaluator that measures with campaign cells\n * reports them through `measured`; the callback keeps them on the evaluation\n * observation, never in the optimizer's response.\n */\nexport type ExternalOptimizerEvaluate<TResponse> = (\n request: ExternalTextEvaluationRequest,\n signal: AbortSignal,\n measured: (measurement: ExternalEvaluationMeasurement) => void,\n) => Promise<TResponse>\n\ntype UnsequencedObservation = ExternalOptimizerEvaluationObservation extends infer T\n ? T extends ExternalOptimizerEvaluationObservation\n ? Omit<T, 'sequence'>\n : never\n : never\n\nexport async function startExternalOptimizerCallback<TResponse>(args: {\n token: string\n maxEvaluations: number\n acceptEvaluation?: () => number | undefined\n evaluate: ExternalOptimizerEvaluate<TResponse>\n observe?: (observation: ExternalOptimizerEvaluationObservation) => void\n /** Loopback JSON byte limits. Omitted fields use finite defaults. */\n limits?: Partial<ExternalOptimizerCallbackLimits>\n signal?: AbortSignal\n}): Promise<ExternalOptimizerCallback> {\n assertCallbackConfig(args)\n const limits = resolveExternalOptimizerCallbackLimits(args.limits)\n args.signal?.throwIfAborted()\n let evaluations = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const proposedCandidateHashes = new Set<string>()\n let observationSequence = 0\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'external optimizer callback is closing' })\n return\n }\n\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleCallback(\n request,\n response,\n controller.signal,\n args,\n limits,\n () => {\n const accepted = args.acceptEvaluation ? args.acceptEvaluation() : evaluations + 1\n if (accepted === undefined) return undefined\n if (!Number.isSafeInteger(accepted) || accepted <= 0) {\n throw new Error('external optimizer callback: invalid accepted evaluation count')\n }\n if (accepted > args.maxEvaluations) return undefined\n evaluations += 1\n return accepted\n },\n (observation) => {\n if (!args.observe) return\n args.observe({ ...observation, sequence: ++observationSequence })\n },\n proposedCandidateHashes,\n ).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallbackServer()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n return {\n url: `http://127.0.0.1:${port}/evaluate`,\n token: args.token,\n evaluations: () => evaluations,\n close,\n }\n\n async function closeCallbackServer(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('external optimizer callback closed with active request work')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nasync function handleCallback<TResponse>(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n args: {\n token: string\n maxEvaluations: number\n acceptEvaluation?: () => number | undefined\n evaluate: ExternalOptimizerEvaluate<TResponse>\n observe?: (observation: ExternalOptimizerEvaluationObservation) => void\n },\n limits: ExternalOptimizerCallbackLimits,\n nextEvaluation: () => number | undefined,\n observe: (observation: UnsequencedObservation) => void,\n proposedCandidateHashes: Set<string>,\n): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/evaluate') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${args.token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n let body: unknown\n try {\n body = await readJson(request, limits.maxRequestBytes)\n } catch {\n observe({ kind: 'refusal', reason: 'invalid-request' })\n sendJsonIfOpen(response, 400, { error: 'request body must be bounded valid JSON' })\n return\n }\n if (\n !isRecord(body) ||\n !isExternalTextCandidate(body.candidate) ||\n typeof body.exampleId !== 'string'\n ) {\n observe({ kind: 'refusal', reason: 'invalid-request' })\n sendJsonIfOpen(response, 400, { error: 'candidate and exampleId are required strings' })\n return\n }\n const candidate = cloneCandidate(body.candidate)\n const candidateHash = contentHash({ kind: 'external-text-candidate', candidate })\n if (!proposedCandidateHashes.has(candidateHash)) {\n observe({ kind: 'proposal', candidate, candidateHash })\n proposedCandidateHashes.add(candidateHash)\n }\n const count = nextEvaluation()\n if (count === undefined) {\n observe({\n kind: 'refusal',\n reason: 'evaluation-limit',\n candidate,\n candidateHash,\n exampleId: body.exampleId,\n })\n sendJsonIfOpen(response, 429, { error: 'evaluation limit reached' })\n return\n }\n let result: TResponse\n const reported: { measurement?: ExternalEvaluationMeasurement } = {}\n const exampleId = body.exampleId\n // Every refusal after `evaluate` ran keeps what it measured: the cells\n // were paid for whether or not the optimizer receives their score.\n const refuseFailedEvaluation = (): void =>\n observe({\n kind: 'refusal',\n reason: 'evaluation-failed',\n candidate,\n candidateHash,\n exampleId,\n ...(reported.measurement ? { measurement: reported.measurement } : {}),\n })\n try {\n result = await args.evaluate({ candidate, exampleId: body.exampleId }, signal, (measured) => {\n reported.measurement = structuredClone(measured)\n })\n } catch (error) {\n refuseFailedEvaluation()\n // The thrown detail is the only diagnostic for a failed evaluation —\n // an opaque 500 costs the caller a blind debugging round.\n sendJsonIfOpen(response, 500, {\n error: `evaluation failed: ${String(error).slice(0, 400)}`,\n })\n return\n }\n let encoded: string\n try {\n encoded = encodeJsonResponse(result)\n } catch {\n refuseFailedEvaluation()\n sendJsonIfOpen(response, 500, { error: 'evaluation response must be valid JSON' })\n return\n }\n if (Buffer.byteLength(encoded) > limits.maxResponseBytes) {\n refuseFailedEvaluation()\n sendJsonIfOpen(response, 413, { error: 'evaluation response too large' })\n return\n }\n observe({\n kind: 'evaluation',\n candidate,\n candidateHash,\n exampleId: body.exampleId,\n evaluationNumber: count,\n response: structuredClone(result),\n ...(reported.measurement ? { measurement: reported.measurement } : {}),\n })\n sendEncodedJsonIfOpen(response, 200, encoded)\n } catch {\n sendJsonIfOpen(response, 500, { error: 'evaluation failed' })\n }\n}\n\nfunction readJson(request: IncomingMessage, maxRequestBytes: number): Promise<unknown> {\n return new Promise((resolvePromise, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > maxRequestBytes) {\n reject(new Error('callback body too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolvePromise(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nfunction encodeJsonResponse(value: unknown): string {\n const encoded = JSON.stringify(value)\n if (encoded === undefined) throw new Error('evaluation response must be JSON-serializable')\n return encoded\n}\n\nfunction sendEncodedJsonIfOpen(response: ServerResponse, status: number, encoded: string): void {\n if (response.destroyed || response.writableEnded) return\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n}\n\nfunction assertCallbackConfig(args: {\n token: string\n maxEvaluations: number\n acceptEvaluation?: () => number | undefined\n evaluate: ExternalOptimizerEvaluate<unknown>\n observe?: (observation: ExternalOptimizerEvaluationObservation) => void\n limits?: Partial<ExternalOptimizerCallbackLimits>\n signal?: AbortSignal\n}): void {\n if (typeof args.token !== 'string' || !args.token.trim()) {\n throw new Error('external optimizer callback: token must be non-empty')\n }\n if (!Number.isSafeInteger(args.maxEvaluations) || args.maxEvaluations <= 0) {\n throw new Error('external optimizer callback: maxEvaluations must be a positive safe integer')\n }\n if (args.acceptEvaluation !== undefined && typeof args.acceptEvaluation !== 'function') {\n throw new Error('external optimizer callback: acceptEvaluation must be a function')\n }\n if (typeof args.evaluate !== 'function') {\n throw new Error('external optimizer callback: evaluate must be a function')\n }\n if (args.observe !== undefined && typeof args.observe !== 'function') {\n throw new Error('external optimizer callback: observe must be a function')\n }\n}\n\nfunction cloneCandidate(candidate: ExternalTextCandidate): ExternalTextCandidate {\n return typeof candidate === 'string' ? candidate : { ...candidate }\n}\n"],"mappings":";;;;;;AAqCA,eAAsB,+BAA0C,MASzB;CACrC,qBAAqB,IAAI;CACzB,MAAM,SAAS,uCAAuC,KAAK,MAAM;CACjE,KAAK,QAAQ,eAAe;CAC5B,IAAI,cAAc;CAClB,IAAI,YAAY;CAChB,IAAI;CACJ,MAAM,oCAAoB,IAAI,IAAqB;CACnD,MAAM,iCAAiB,IAAI,IAAmB;CAC9C,MAAM,0CAA0B,IAAI,IAAY;CAChD,IAAI,sBAAsB;CAC1B,MAAM,SAAS,cAAc,SAAS,aAAa;EACjD,IAAI,CAAC,WAAW;GACd,eAAe,UAAU,KAAK,EAAE,OAAO,yCAAyC,CAAC;GACjF;EACF;EAEA,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,qBAA2B;GAC/B,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB;EACA,kBAAkB,IAAI,UAAU;EAChC,WAAW,OAAO,iBAAiB,SAAS,cAAc,EAAE,MAAM,KAA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["../src/campaign/external-optimizer-callback.ts"],"sourcesContent":["import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { isRecord } from '../llm-client/json'\nimport { contentHash } from '../verdict-cache'\nimport {\n type ExternalEvaluationMeasurement,\n type ExternalOptimizerCallback,\n type ExternalOptimizerCallbackLimits,\n type ExternalOptimizerEvaluationObservation,\n type ExternalTextCandidate,\n type ExternalTextEvaluationRequest,\n isExternalTextCandidate,\n resolveExternalOptimizerCallbackLimits,\n} from './external-optimizer-contracts'\nimport {\n closeServer,\n listenLocal,\n sendJsonIfOpen,\n waitForActiveHandlers,\n} from './external-optimizer-http'\n\n/**\n * Scores one callback request. An evaluator that measures with campaign cells\n * reports them through `measured`; the callback keeps them on the evaluation\n * observation, never in the optimizer's response.\n */\nexport type ExternalOptimizerEvaluate<TResponse> = (\n request: ExternalTextEvaluationRequest,\n signal: AbortSignal,\n measured: (measurement: ExternalEvaluationMeasurement) => void,\n) => Promise<TResponse>\n\ntype UnsequencedObservation = ExternalOptimizerEvaluationObservation extends infer T\n ? T extends ExternalOptimizerEvaluationObservation\n ? Omit<T, 'sequence'>\n : never\n : never\n\nexport async function startExternalOptimizerCallback<TResponse>(args: {\n token: string\n maxEvaluations: number\n acceptEvaluation?: () => number | undefined\n evaluate: ExternalOptimizerEvaluate<TResponse>\n observe?: (observation: ExternalOptimizerEvaluationObservation) => void\n /** Loopback JSON byte limits. Omitted fields use finite defaults. */\n limits?: Partial<ExternalOptimizerCallbackLimits>\n signal?: AbortSignal\n}): Promise<ExternalOptimizerCallback> {\n assertCallbackConfig(args)\n const limits = resolveExternalOptimizerCallbackLimits(args.limits)\n args.signal?.throwIfAborted()\n let evaluations = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const proposedCandidateHashes = new Set<string>()\n let observationSequence = 0\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'external optimizer callback is closing' })\n return\n }\n\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleCallback(\n request,\n response,\n controller.signal,\n args,\n limits,\n () => {\n const accepted = args.acceptEvaluation ? args.acceptEvaluation() : evaluations + 1\n if (accepted === undefined) return undefined\n if (!Number.isSafeInteger(accepted) || accepted <= 0) {\n throw new Error('external optimizer callback: invalid accepted evaluation count')\n }\n if (accepted > args.maxEvaluations) return undefined\n evaluations += 1\n return accepted\n },\n (observation) => {\n if (!args.observe) return\n args.observe({ ...observation, sequence: ++observationSequence })\n },\n proposedCandidateHashes,\n ).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallbackServer()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n return {\n url: `http://127.0.0.1:${port}/evaluate`,\n token: args.token,\n evaluations: () => evaluations,\n close,\n }\n\n async function closeCallbackServer(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('external optimizer callback closed with active request work')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nasync function handleCallback<TResponse>(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n args: {\n token: string\n maxEvaluations: number\n acceptEvaluation?: () => number | undefined\n evaluate: ExternalOptimizerEvaluate<TResponse>\n observe?: (observation: ExternalOptimizerEvaluationObservation) => void\n },\n limits: ExternalOptimizerCallbackLimits,\n nextEvaluation: () => number | undefined,\n observe: (observation: UnsequencedObservation) => void,\n proposedCandidateHashes: Set<string>,\n): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/evaluate') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${args.token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n let body: unknown\n try {\n body = await readJson(request, limits.maxRequestBytes)\n } catch {\n observe({ kind: 'refusal', reason: 'invalid-request' })\n sendJsonIfOpen(response, 400, { error: 'request body must be bounded valid JSON' })\n return\n }\n if (\n !isRecord(body) ||\n !isExternalTextCandidate(body.candidate) ||\n typeof body.exampleId !== 'string'\n ) {\n observe({ kind: 'refusal', reason: 'invalid-request' })\n sendJsonIfOpen(response, 400, { error: 'candidate and exampleId are required strings' })\n return\n }\n const candidate = cloneCandidate(body.candidate)\n const candidateHash = contentHash({ kind: 'external-text-candidate', candidate })\n if (!proposedCandidateHashes.has(candidateHash)) {\n observe({ kind: 'proposal', candidate, candidateHash })\n proposedCandidateHashes.add(candidateHash)\n }\n const count = nextEvaluation()\n if (count === undefined) {\n observe({\n kind: 'refusal',\n reason: 'evaluation-limit',\n candidate,\n candidateHash,\n exampleId: body.exampleId,\n })\n sendJsonIfOpen(response, 429, { error: 'evaluation limit reached' })\n return\n }\n let result: TResponse\n const reported: { measurement?: ExternalEvaluationMeasurement } = {}\n const exampleId = body.exampleId\n // Every refusal after `evaluate` ran keeps what it measured: the cells\n // were paid for whether or not the optimizer receives their score.\n const refuseFailedEvaluation = (): void =>\n observe({\n kind: 'refusal',\n reason: 'evaluation-failed',\n candidate,\n candidateHash,\n exampleId,\n ...(reported.measurement ? { measurement: reported.measurement } : {}),\n })\n try {\n result = await args.evaluate({ candidate, exampleId: body.exampleId }, signal, (measured) => {\n reported.measurement = structuredClone(measured)\n })\n } catch (error) {\n refuseFailedEvaluation()\n // The thrown detail is the only diagnostic for a failed evaluation —\n // an opaque 500 costs the caller a blind debugging round.\n sendJsonIfOpen(response, 500, {\n error: `evaluation failed: ${String(error).slice(0, 400)}`,\n })\n return\n }\n let encoded: string\n try {\n encoded = encodeJsonResponse(result)\n } catch {\n refuseFailedEvaluation()\n sendJsonIfOpen(response, 500, { error: 'evaluation response must be valid JSON' })\n return\n }\n if (Buffer.byteLength(encoded) > limits.maxResponseBytes) {\n refuseFailedEvaluation()\n sendJsonIfOpen(response, 413, { error: 'evaluation response too large' })\n return\n }\n observe({\n kind: 'evaluation',\n candidate,\n candidateHash,\n exampleId: body.exampleId,\n evaluationNumber: count,\n response: structuredClone(result),\n ...(reported.measurement ? { measurement: reported.measurement } : {}),\n })\n sendEncodedJsonIfOpen(response, 200, encoded)\n } catch {\n sendJsonIfOpen(response, 500, { error: 'evaluation failed' })\n }\n}\n\nfunction readJson(request: IncomingMessage, maxRequestBytes: number): Promise<unknown> {\n return new Promise((resolvePromise, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > maxRequestBytes) {\n reject(new Error('callback body too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolvePromise(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nfunction encodeJsonResponse(value: unknown): string {\n const encoded = JSON.stringify(value)\n if (encoded === undefined) throw new Error('evaluation response must be JSON-serializable')\n return encoded\n}\n\nfunction sendEncodedJsonIfOpen(response: ServerResponse, status: number, encoded: string): void {\n if (response.destroyed || response.writableEnded) return\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n}\n\nfunction assertCallbackConfig(args: {\n token: string\n maxEvaluations: number\n acceptEvaluation?: () => number | undefined\n evaluate: ExternalOptimizerEvaluate<unknown>\n observe?: (observation: ExternalOptimizerEvaluationObservation) => void\n limits?: Partial<ExternalOptimizerCallbackLimits>\n signal?: AbortSignal\n}): void {\n if (typeof args.token !== 'string' || !args.token.trim()) {\n throw new Error('external optimizer callback: token must be non-empty')\n }\n if (!Number.isSafeInteger(args.maxEvaluations) || args.maxEvaluations <= 0) {\n throw new Error('external optimizer callback: maxEvaluations must be a positive safe integer')\n }\n if (args.acceptEvaluation !== undefined && typeof args.acceptEvaluation !== 'function') {\n throw new Error('external optimizer callback: acceptEvaluation must be a function')\n }\n if (typeof args.evaluate !== 'function') {\n throw new Error('external optimizer callback: evaluate must be a function')\n }\n if (args.observe !== undefined && typeof args.observe !== 'function') {\n throw new Error('external optimizer callback: observe must be a function')\n }\n}\n\nfunction cloneCandidate(candidate: ExternalTextCandidate): ExternalTextCandidate {\n return typeof candidate === 'string' ? candidate : { ...candidate }\n}\n"],"mappings":";;;;;;AAqCA,eAAsB,+BAA0C,MASzB;CACrC,qBAAqB,IAAI;CACzB,MAAM,SAAS,uCAAuC,KAAK,MAAM;CACjE,KAAK,QAAQ,eAAe;CAC5B,IAAI,cAAc;CAClB,IAAI,YAAY;CAChB,IAAI;CACJ,MAAM,oCAAoB,IAAI,IAAqB;CACnD,MAAM,iCAAiB,IAAI,IAAmB;CAC9C,MAAM,0CAA0B,IAAI,IAAY;CAChD,IAAI,sBAAsB;CAC1B,MAAM,SAAS,cAAc,SAAS,aAAa;EACjD,IAAI,CAAC,WAAW;GACd,eAAe,UAAU,KAAK,EAAE,OAAO,yCAAyC,CAAC;GACjF;EACF;EAEA,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,qBAA2B;GAC/B,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB;EACA,kBAAkB,IAAI,UAAU;EAChC,WAAW,OAAO,iBAAiB,SAAS,cAAc,EAAE,MAAM,KAAK,CAAC;EAExE,IAAI;EACJ,UAAU,eACR,SACA,UACA,WAAW,QACX,MACA,cACM;GACJ,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D,QAAQ,GAAG,SAAS,MAAM;EAC1B,QAAQ,GAAG,aAAa;GACtB,IAAI;IACF,eAAe,KAAK,MAAM,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC;GACnE,SAAS,OAAO;IACd,OAAO,KAAK;GACd;EACF,CAAC;CACH,CAAC;AACH;AAEA,SAAS,mBAAmB,OAAwB;CAClD,MAAM,UAAU,KAAK,UAAU,KAAK;CACpC,IAAI,YAAY,KAAA,GAAW,MAAM,IAAI,MAAM,+CAA+C;CAC1F,OAAO;AACT;AAEA,SAAS,sBAAsB,UAA0B,QAAgB,SAAuB;CAC9F,IAAI,SAAS,aAAa,SAAS,eAAe;CAClD,SAAS,UAAU,QAAQ;EACzB,gBAAgB;EAChB,kBAAkB,OAAO,OAAO,WAAW,OAAO,CAAC;CACrD,CAAC;CACD,SAAS,IAAI,OAAO;AACtB;AAEA,SAAS,qBAAqB,MAQrB;CACP,IAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,KAAK,GACrD,MAAM,IAAI,MAAM,sDAAsD;CAExE,IAAI,CAAC,OAAO,cAAc,KAAK,cAAc,KAAK,KAAK,kBAAkB,GACvE,MAAM,IAAI,MAAM,6EAA6E;CAE/F,IAAI,KAAK,qBAAqB,KAAA,KAAa,OAAO,KAAK,qBAAqB,YAC1E,MAAM,IAAI,MAAM,kEAAkE;CAEpF,IAAI,OAAO,KAAK,aAAa,YAC3B,MAAM,IAAI,MAAM,0DAA0D;CAE5E,IAAI,KAAK,YAAY,KAAA,KAAa,OAAO,KAAK,YAAY,YACxD,MAAM,IAAI,MAAM,yDAAyD;AAE7E;AAEA,SAAS,eAAe,WAAyD;CAC/E,OAAO,OAAO,cAAc,WAAW,YAAY,EAAE,GAAG,UAAU;AACpE"}
@@ -4,7 +4,7 @@ import { t as canonicalJson } from "./verdict-cache-BPaYxfG8.js";
4
4
  import { c as costForTokenPricing } from "./cost-ledger-C5CCidPm.js";
5
5
  import { t as deepFreezeCanonicalJson } from "./deep-freeze-CK8-2W7p.js";
6
6
  import { n as isRecord } from "./json-DtvZNAU9.js";
7
- import { d as resolveExternalOptimizerProcessLimits, i as assertJsonValue, o as freezeJsonSnapshot, r as assertExternalOptimizerModelBudget } from "./external-optimizer-contracts-ZDBfbZ_s.js";
7
+ import { a as assertJsonValue, f as resolveExternalOptimizerProcessLimits, i as assertExternalOptimizerModelBudget, r as EXTERNAL_OPTIMIZER_REFUSAL_HEADER, s as freezeJsonSnapshot } from "./external-optimizer-contracts-BFV8lnhl.js";
8
8
  import { t as isNonnegativeFiniteNumber } from "./nonnegative-number-lEYbOsuh.js";
9
9
  import { randomBytes } from "node:crypto";
10
10
  import { isAbsolute, join, resolve } from "node:path";
@@ -32,8 +32,11 @@ function closeServer(server) {
32
32
  server.close((error) => error ? reject(error) : resolvePromise());
33
33
  });
34
34
  }
35
- function sendJson(response, status, body) {
36
- response.writeHead(status, { "content-type": "application/json; charset=utf-8" });
35
+ function sendJson(response, status, body, headers = {}) {
36
+ response.writeHead(status, {
37
+ ...headers,
38
+ "content-type": "application/json; charset=utf-8"
39
+ });
37
40
  response.end(JSON.stringify(body));
38
41
  }
39
42
  /**
@@ -43,9 +46,9 @@ function sendJson(response, status, body) {
43
46
  * already ended — must not write again; Node throws `ERR_STREAM_WRITE_AFTER_END`
44
47
  * and the throw escapes into the server's error path rather than the caller's.
45
48
  */
46
- function sendJsonIfOpen(response, status, body) {
49
+ function sendJsonIfOpen(response, status, body, headers = {}) {
47
50
  if (response.destroyed || response.writableEnded) return;
48
- sendJson(response, status, body);
51
+ sendJson(response, status, body, headers);
49
52
  }
50
53
  /**
51
54
  * Wait until every in-flight handler has settled.
@@ -1071,13 +1074,13 @@ const MODEL_PROXY_PATHS = /* @__PURE__ */ new Set(["/v1/chat/completions", "/v1/
1071
1074
  async function handleModelProxyRequest(args) {
1072
1075
  const { controller, request, response } = args;
1073
1076
  let wire = "openai";
1074
- const respondError = (status, message, errorType) => {
1077
+ const respondError = (status, message, errorType, headers = {}) => {
1075
1078
  if (wire === "anthropic") {
1076
1079
  const mapped = status === 429 ? 402 : status;
1077
- sendJsonIfOpen(response, mapped, anthropicErrorEnvelope(errorType ?? anthropicErrorTypeForStatus(mapped), message));
1080
+ sendJsonIfOpen(response, mapped, anthropicErrorEnvelope(errorType ?? anthropicErrorTypeForStatus(mapped), message), headers);
1078
1081
  return;
1079
1082
  }
1080
- sendJsonIfOpen(response, status, { error: message });
1083
+ sendJsonIfOpen(response, status, { error: message }, headers);
1081
1084
  };
1082
1085
  try {
1083
1086
  const path = request.url ? new URL(request.url, "http://127.0.0.1").pathname : "";
@@ -1098,7 +1101,7 @@ async function handleModelProxyRequest(args) {
1098
1101
  const maximumCostUsd = args.args.budget.pricing ? costForTokenPricing(args.args.budget.pricing, maximumUsage) : void 0;
1099
1102
  const reservation = args.nextReservation(maximumCostUsd, wire);
1100
1103
  if (!reservation.accepted) {
1101
- respondError(429, reservation.reason);
1104
+ respondError(429, reservation.reason, void 0, { [EXTERNAL_OPTIMIZER_REFUSAL_HEADER]: reservation.kind });
1102
1105
  return;
1103
1106
  }
1104
1107
  const timeout = setTimeout(() => controller.abort(), args.args.budget.requestTimeoutMs ?? 3e5);
@@ -1237,11 +1240,13 @@ async function startExternalOptimizerModelProxy(args) {
1237
1240
  const wireCounts = {
1238
1241
  openai: {
1239
1242
  requestAttempts: 0,
1240
- successfulCompletions: 0
1243
+ successfulCompletions: 0,
1244
+ refusedRequests: 0
1241
1245
  },
1242
1246
  anthropic: {
1243
1247
  requestAttempts: 0,
1244
- successfulCompletions: 0
1248
+ successfulCompletions: 0,
1249
+ refusedRequests: 0
1245
1250
  }
1246
1251
  };
1247
1252
  let modelCallInvocations = 0;
@@ -1275,14 +1280,22 @@ async function startExternalOptimizerModelProxy(args) {
1275
1280
  token,
1276
1281
  args,
1277
1282
  nextReservation: (maximumCostUsd, wire) => {
1278
- if (totalRequestCount >= args.budget.maxRequests) return {
1279
- accepted: false,
1280
- reason: "optimizer model request limit reached"
1281
- };
1282
- if (args.budget.maxCostUsd !== void 0 && maximumCostUsd !== void 0 && committedForBudget + reservedForBudget + maximumCostUsd > args.budget.maxCostUsd + Number.EPSILON) return {
1283
- accepted: false,
1284
- reason: "optimizer model cost limit reached"
1285
- };
1283
+ if (totalRequestCount >= args.budget.maxRequests) {
1284
+ wireCounts[wire].refusedRequests += 1;
1285
+ return {
1286
+ accepted: false,
1287
+ kind: "request-limit",
1288
+ reason: "optimizer model request limit reached"
1289
+ };
1290
+ }
1291
+ if (args.budget.maxCostUsd !== void 0 && maximumCostUsd !== void 0 && committedForBudget + reservedForBudget + maximumCostUsd > args.budget.maxCostUsd + Number.EPSILON) {
1292
+ wireCounts[wire].refusedRequests += 1;
1293
+ return {
1294
+ accepted: false,
1295
+ kind: "cost-limit",
1296
+ reason: "optimizer model cost limit reached"
1297
+ };
1298
+ }
1286
1299
  requestCount += 1;
1287
1300
  wireCounts[wire].requestAttempts += 1;
1288
1301
  totalRequestCount += 1;
@@ -1661,4 +1674,4 @@ function summarizeProcessOutput(capture, max = 4e3) {
1661
1674
  }
1662
1675
  export { closeServer as a, waitForActiveHandlers as c, startExternalOptimizerModelProxy as i, closeExternalOptimizerResources as n, listenLocal as o, runWithCleanup as r, sendJsonIfOpen as s, runExternalOptimizerProcess as t };
1663
1676
 
1664
- //# sourceMappingURL=external-optimizer-subprocess-mV-2swJI.js.map
1677
+ //# sourceMappingURL=external-optimizer-subprocess-_O06eDVA.js.map