@tangle-network/agent-eval 0.163.2 → 0.171.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +2 -0
  3. package/dist/adapters/http.d.ts +108 -0
  4. package/dist/adapters/http.d.ts.map +1 -0
  5. package/dist/adapters/http.js +208 -0
  6. package/dist/adapters/http.js.map +1 -0
  7. package/dist/analyst/index.d.ts +40 -70
  8. package/dist/analyst/index.d.ts.map +1 -1
  9. package/dist/analyst/index.js +18 -311
  10. package/dist/analyst/index.js.map +1 -1
  11. package/dist/{backend-integrity-DxuQCu_A.d.ts → backend-integrity-e79K3UPD.d.ts} +3 -3
  12. package/dist/{backend-integrity-DxuQCu_A.d.ts.map → backend-integrity-e79K3UPD.d.ts.map} +1 -1
  13. package/dist/{benchmark-BhT16ep9.js → benchmark-C4wk_Sjr.js} +10 -3
  14. package/dist/benchmark-C4wk_Sjr.js.map +1 -0
  15. package/dist/{benchmark-command-CF-4GEWZ.js → benchmark-command-D8k3Gf0J.js} +236 -251
  16. package/dist/benchmark-command-D8k3Gf0J.js.map +1 -0
  17. package/dist/{benchmark-CGPp-kDC.d.ts → benchmark-h-h4bfqj.d.ts} +3 -3
  18. package/dist/{benchmark-CGPp-kDC.d.ts.map → benchmark-h-h4bfqj.d.ts.map} +1 -1
  19. package/dist/benchmarks/index.d.ts +5 -5
  20. package/dist/benchmarks/index.js +3 -3
  21. package/dist/builder-eval/index.d.ts +3 -3
  22. package/dist/builder-eval/index.js +1 -1
  23. package/dist/campaign/index.d.ts +8 -8
  24. package/dist/campaign/index.js +7 -7
  25. package/dist/{campaign-DQZmc2Dq.js → campaign-B72njjHj.js} +15 -14
  26. package/dist/campaign-B72njjHj.js.map +1 -0
  27. package/dist/{canonical-IL-Bu-14.js → canonical-DPyQ_rpt.js} +22 -2
  28. package/dist/{canonical-IL-Bu-14.js.map → canonical-DPyQ_rpt.js.map} +1 -1
  29. package/dist/{chat-client-DlMlAeYI.js → chat-client-DEtybj5i.js} +5 -5
  30. package/dist/{chat-client-DlMlAeYI.js.map → chat-client-DEtybj5i.js.map} +1 -1
  31. package/dist/cli.js +2 -2
  32. package/dist/{client-CX7KqIdB.js → client-BvwNkIRN.js} +2 -2
  33. package/dist/{client-CX7KqIdB.js.map → client-BvwNkIRN.js.map} +1 -1
  34. package/dist/{client-L9VVPkim.d.ts → client-CDtcZ3p9.d.ts} +4 -4
  35. package/dist/{client-L9VVPkim.d.ts.map → client-CDtcZ3p9.d.ts.map} +1 -1
  36. package/dist/contract/index.d.ts +12 -703
  37. package/dist/contract/index.js +11 -11
  38. package/dist/{counterfactual-BaFUWK3H.d.ts → counterfactual-Bee5_BIn.d.ts} +4 -4
  39. package/dist/{counterfactual-BaFUWK3H.d.ts.map → counterfactual-Bee5_BIn.d.ts.map} +1 -1
  40. package/dist/{default-registry-G9CKMNkc.d.ts → default-registry-B0s2zU-s.d.ts} +6 -6
  41. package/dist/{default-registry-G9CKMNkc.d.ts.map → default-registry-B0s2zU-s.d.ts.map} +1 -1
  42. package/dist/{define-agent-eval-Dx1JnPEa.d.ts → define-agent-eval-Cjy2yhqP.d.ts} +7 -7
  43. package/dist/{define-agent-eval-Dx1JnPEa.d.ts.map → define-agent-eval-Cjy2yhqP.d.ts.map} +1 -1
  44. package/dist/{define-agent-eval-D08pWIJb.js → define-agent-eval-Dy8QgxAI.js} +20 -8
  45. package/dist/{define-agent-eval-D08pWIJb.js.map → define-agent-eval-Dy8QgxAI.js.map} +1 -1
  46. package/dist/{dspy-rlm-engine-DhA9qKIm.js → dspy-rlm-engine-CS3qcCEk.js} +3 -10
  47. package/dist/dspy-rlm-engine-CS3qcCEk.js.map +1 -0
  48. package/dist/{emitter-D_jYSGRd.d.ts → emitter-Bvnu0VzL.d.ts} +3 -3
  49. package/dist/{emitter-D_jYSGRd.d.ts.map → emitter-Bvnu0VzL.d.ts.map} +1 -1
  50. package/dist/{engine-Cu5qD5Fc.d.ts → engine-CAmTUk52.d.ts} +7 -7
  51. package/dist/{engine-Cu5qD5Fc.d.ts.map → engine-CAmTUk52.d.ts.map} +1 -1
  52. package/dist/{eval-campaign-BfohKmzx.js → eval-campaign-JDTeE6Pl.js} +4 -4
  53. package/dist/{eval-campaign-BfohKmzx.js.map → eval-campaign-JDTeE6Pl.js.map} +1 -1
  54. package/dist/{exact-types-qnexxJ1Z.d.ts → exact-types-BEecmnWm.d.ts} +2 -2
  55. package/dist/{exact-types-qnexxJ1Z.d.ts.map → exact-types-BEecmnWm.d.ts.map} +1 -1
  56. package/dist/experiment/index.d.ts +5 -5
  57. package/dist/experiment/index.js +4 -4
  58. package/dist/{experiment-tracker-DCO6Cz4s.d.ts → experiment-tracker-Dm8yQMqb.d.ts} +2 -2
  59. package/dist/{experiment-tracker-DCO6Cz4s.d.ts.map → experiment-tracker-Dm8yQMqb.d.ts.map} +1 -1
  60. package/dist/{external-optimizer-process-BFmh36vW.js → external-optimizer-process-CQxylYeG.js} +4 -11
  61. package/dist/external-optimizer-process-CQxylYeG.js.map +1 -0
  62. package/dist/{external-optimizer-subprocess-CqLMW3nh.js → external-optimizer-subprocess-Cex8Da2i.js} +25 -11
  63. package/dist/external-optimizer-subprocess-Cex8Da2i.js.map +1 -0
  64. package/dist/{failure-cluster-CXL8NbEw.d.ts → failure-cluster-6YSvsKlp.d.ts} +3 -3
  65. package/dist/{failure-cluster-CXL8NbEw.d.ts.map → failure-cluster-6YSvsKlp.d.ts.map} +1 -1
  66. package/dist/{feedback-trajectory-B3ZHaHV_.d.ts → feedback-trajectory-DIqpCyF0.d.ts} +6 -6
  67. package/dist/{feedback-trajectory-B3ZHaHV_.d.ts.map → feedback-trajectory-DIqpCyF0.d.ts.map} +1 -1
  68. package/dist/fuzz.d.ts +1 -1
  69. package/dist/{skillopt-optimization-method-x7TTF23P.d.ts → heldout-gate-Dh2b62w8.d.ts} +111 -111
  70. package/dist/heldout-gate-Dh2b62w8.d.ts.map +1 -0
  71. package/dist/hosted/index.d.ts +2 -2
  72. package/dist/hosted/index.js +1 -1
  73. package/dist/{index-D-V8gCs_.d.ts → index-8VIogTyS.d.ts} +30 -22
  74. package/dist/index-8VIogTyS.d.ts.map +1 -0
  75. package/dist/{index-D-IiQIBB.d.ts → index-DMoxLG8P.d.ts} +3 -3
  76. package/dist/{index-D-IiQIBB.d.ts.map → index-DMoxLG8P.d.ts.map} +1 -1
  77. package/dist/{index-D_P7Ye43.d.ts → index-DNgf5gyG.d.ts} +2 -2
  78. package/dist/{index-D_P7Ye43.d.ts.map → index-DNgf5gyG.d.ts.map} +1 -1
  79. package/dist/{index-CGtH1piv.d.ts → index-DT73JraI.d.ts} +7 -38
  80. package/dist/index-DT73JraI.d.ts.map +1 -0
  81. package/dist/index-fNXZMCzX.d.ts +704 -0
  82. package/dist/index-fNXZMCzX.d.ts.map +1 -0
  83. package/dist/index.d.ts +197 -38
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +736 -28
  86. package/dist/index.js.map +1 -1
  87. package/dist/{insight-report-DRe8LB6d.d.ts → insight-report-08F022xN.d.ts} +4 -4
  88. package/dist/{insight-report-DRe8LB6d.d.ts.map → insight-report-08F022xN.d.ts.map} +1 -1
  89. package/dist/{integrity-DUNX9Fao.d.ts → integrity-B_EDELom.d.ts} +2 -2
  90. package/dist/{integrity-DUNX9Fao.d.ts.map → integrity-B_EDELom.d.ts.map} +1 -1
  91. package/dist/internal-BMFSR8Ns.js.map +1 -1
  92. package/dist/{kind-factory-DY8FdoXf.js → kind-factory-DMeEoMQZ.js} +3 -10
  93. package/dist/kind-factory-DMeEoMQZ.js.map +1 -0
  94. package/dist/ledger-core/index.js +2 -2
  95. package/dist/{ledger-core-BOzlRygb.js → ledger-core-PIfjCbKn.js} +2 -2
  96. package/dist/{ledger-core-BOzlRygb.js.map → ledger-core-PIfjCbKn.js.map} +1 -1
  97. package/dist/{llm-judge-Du7WQPh7.js → llm-judge-BtJ2Sfk_.js} +101 -20
  98. package/dist/llm-judge-BtJ2Sfk_.js.map +1 -0
  99. package/dist/matrix/index.d.ts +2 -2
  100. package/dist/{matrix-eXKRMHnL.d.ts → matrix-DiHmUobV.d.ts} +3 -3
  101. package/dist/{matrix-eXKRMHnL.d.ts.map → matrix-DiHmUobV.d.ts.map} +1 -1
  102. package/dist/meta-eval/index.d.ts +3 -3
  103. package/dist/meta-eval/index.js +1 -1
  104. package/dist/{mint-DfODW1KW.js → mint-DjfDUMHr.js} +2 -2
  105. package/dist/{mint-DfODW1KW.js.map → mint-DjfDUMHr.js.map} +1 -1
  106. package/dist/multishot/golden/index.d.ts +1 -1
  107. package/dist/multishot/index.d.ts +2 -2
  108. package/dist/openapi.json +4 -4
  109. package/dist/pipelines/index.d.ts +5 -5
  110. package/dist/pipelines/index.js +3 -3
  111. package/dist/{pareto-BqNW3LJR.d.ts → power-preflight-Ptse_Kq7.d.ts} +43 -43
  112. package/dist/power-preflight-Ptse_Kq7.d.ts.map +1 -0
  113. package/dist/{pre-registration-KN9jkh58.js → pre-registration-D94b7Of5.js} +2 -2
  114. package/dist/{pre-registration-KN9jkh58.js.map → pre-registration-D94b7Of5.js.map} +1 -1
  115. package/dist/{pre-registration-CzFCcwYk.d.ts → pre-registration-DHz6P_6f.d.ts} +2 -2
  116. package/dist/{pre-registration-CzFCcwYk.d.ts.map → pre-registration-DHz6P_6f.d.ts.map} +1 -1
  117. package/dist/{produced-state-Be0BK3RN.js → produced-state-Cm6DU_Ao.js} +4 -4
  118. package/dist/{produced-state-Be0BK3RN.js.map → produced-state-Cm6DU_Ao.js.map} +1 -1
  119. package/dist/profile-cell.js +1 -1
  120. package/dist/{promotion-policy-DtnOIZvk.d.ts → promotion-policy-WSXtBgBb.d.ts} +3 -3
  121. package/dist/{promotion-policy-DtnOIZvk.d.ts.map → promotion-policy-WSXtBgBb.d.ts.map} +1 -1
  122. package/dist/{run-score-lDzV0X8j.js → proposal-findings-bko3GGy-.js} +2 -31
  123. package/dist/proposal-findings-bko3GGy-.js.map +1 -0
  124. package/dist/{transient-failure-DKF5Mofa.d.ts → provenance-CafMdZKM.d.ts} +895 -891
  125. package/dist/provenance-CafMdZKM.d.ts.map +1 -0
  126. package/dist/{query-_5g6re3_.js → query-BPGMVlbM.js} +3 -3
  127. package/dist/{query-_5g6re3_.js.map → query-BPGMVlbM.js.map} +1 -1
  128. package/dist/{query-CwnHlu5p.d.ts → query-Na5gEIGd.d.ts} +3 -3
  129. package/dist/{query-CwnHlu5p.d.ts.map → query-Na5gEIGd.d.ts.map} +1 -1
  130. package/dist/{registry-8You7OK1.d.ts → registry-xEb_xfns.d.ts} +3 -3
  131. package/dist/{registry-8You7OK1.d.ts.map → registry-xEb_xfns.d.ts.map} +1 -1
  132. package/dist/{release-confidence-nGDJiiwc.js → release-confidence-CzUHc4z4.js} +3 -3
  133. package/dist/{release-confidence-nGDJiiwc.js.map → release-confidence-CzUHc4z4.js.map} +1 -1
  134. package/dist/{release-confidence-Dqt0NFep.d.ts → release-confidence-D6lQw_o7.d.ts} +4 -4
  135. package/dist/{release-confidence-Dqt0NFep.d.ts.map → release-confidence-D6lQw_o7.d.ts.map} +1 -1
  136. package/dist/reporting.d.ts +3 -3
  137. package/dist/reporting.js +2 -2
  138. package/dist/{researcher-Cz565b7D.d.ts → researcher-CMUTQXD7.d.ts} +6 -6
  139. package/dist/{researcher-Cz565b7D.d.ts.map → researcher-CMUTQXD7.d.ts.map} +1 -1
  140. package/dist/{reward-hacking-MBf7qpSB.d.ts → reward-hacking-CgPRUesA.d.ts} +2 -2
  141. package/dist/{reward-hacking-MBf7qpSB.d.ts.map → reward-hacking-CgPRUesA.d.ts.map} +1 -1
  142. package/dist/{reward-hacking-O5zKDANP.js → reward-hacking-SkxYgT0x.js} +2 -2
  143. package/dist/{reward-hacking-O5zKDANP.js.map → reward-hacking-SkxYgT0x.js.map} +1 -1
  144. package/dist/rl.d.ts +8 -8
  145. package/dist/rl.d.ts.map +1 -1
  146. package/dist/rl.js +6 -5
  147. package/dist/rl.js.map +1 -1
  148. package/dist/rollout/index.d.ts +1 -1
  149. package/dist/rollout/index.js +2 -2
  150. package/dist/{rollout-Dm2tSdiQ.js → rollout-Crypdx8s.js} +2 -2
  151. package/dist/{rollout-Dm2tSdiQ.js.map → rollout-Crypdx8s.js.map} +1 -1
  152. package/dist/{rubric-predictive-validity-CxycqzX5.d.ts → rubric-predictive-validity-DluJLCKQ.d.ts} +2 -2
  153. package/dist/{rubric-predictive-validity-CxycqzX5.d.ts.map → rubric-predictive-validity-DluJLCKQ.d.ts.map} +1 -1
  154. package/dist/{run-record-BC0ebuRP.js → run-record-DLORoL7t.js} +2 -2
  155. package/dist/{run-record-BC0ebuRP.js.map → run-record-DLORoL7t.js.map} +1 -1
  156. package/dist/{run-record-VVy4T9OW.d.ts → run-record-DQjRcYwA.d.ts} +3 -3
  157. package/dist/{run-record-VVy4T9OW.d.ts.map → run-record-DQjRcYwA.d.ts.map} +1 -1
  158. package/dist/{schema-k6ZBftVv.js → schema-CdIX2aHu.js} +5 -1
  159. package/dist/{schema-k6ZBftVv.js.map → schema-CdIX2aHu.js.map} +1 -1
  160. package/dist/{schema-Bjgdsn73.d.ts → schema-DID1Cqct.d.ts} +7 -3
  161. package/dist/{schema-Bjgdsn73.d.ts.map → schema-DID1Cqct.d.ts.map} +1 -1
  162. package/dist/{semantic-concept-judge-BsDMOwJr.js → semantic-concept-judge-I36eejJx.js} +2 -2
  163. package/dist/{semantic-concept-judge-BsDMOwJr.js.map → semantic-concept-judge-I36eejJx.js.map} +1 -1
  164. package/dist/{sequential-BLMbdrD7.js → sequential-B51qAYE4.js} +2 -2
  165. package/dist/{sequential-BLMbdrD7.js.map → sequential-B51qAYE4.js.map} +1 -1
  166. package/dist/{server-BjYiJHoJ.js → server-CCEnywOR.js} +26 -18
  167. package/dist/server-CCEnywOR.js.map +1 -0
  168. package/dist/{skillopt-optimization-method-UArRo-nr.js → skillopt-optimization-method-DzlF2RM7.js} +9 -9
  169. package/dist/{skillopt-optimization-method-UArRo-nr.js.map → skillopt-optimization-method-DzlF2RM7.js.map} +1 -1
  170. package/dist/{statistical-heldout-Cy3EhjlC.d.ts → statistical-heldout-UhiexnjU.d.ts} +3 -3
  171. package/dist/{statistical-heldout-Cy3EhjlC.d.ts.map → statistical-heldout-UhiexnjU.d.ts.map} +1 -1
  172. package/dist/{store-B06JdC56.d.ts → store-Cq9oOrI1.d.ts} +2 -2
  173. package/dist/{store-B06JdC56.d.ts.map → store-Cq9oOrI1.d.ts.map} +1 -1
  174. package/dist/{store-otlp-C_Rq5I4D.js → store-otlp-CHjBvWQY.js} +2 -2
  175. package/dist/{store-otlp-C_Rq5I4D.js.map → store-otlp-CHjBvWQY.js.map} +1 -1
  176. package/dist/{store-tool-spans-BVga3c37.js → store-tool-spans-B9o6tU8f.js} +3 -3
  177. package/dist/{store-tool-spans-BVga3c37.js.map → store-tool-spans-B9o6tU8f.js.map} +1 -1
  178. package/dist/{store-tool-spans-DPUG7UUY.d.ts → store-tool-spans-D_qMl2__.d.ts} +102 -36
  179. package/dist/store-tool-spans-D_qMl2__.d.ts.map +1 -0
  180. package/dist/storyboard/index.d.ts +1 -1
  181. package/dist/{summary-report-BXeQ5Ues.js → summary-report-Bgh8CpNK.js} +2 -2
  182. package/dist/{summary-report-BXeQ5Ues.js.map → summary-report-Bgh8CpNK.js.map} +1 -1
  183. package/dist/{summary-report-CC07PhEL.d.ts → summary-report-DRstQNBX.d.ts} +3 -3
  184. package/dist/{summary-report-CC07PhEL.d.ts.map → summary-report-DRstQNBX.d.ts.map} +1 -1
  185. package/dist/{task-failure-attributes-DTl-7-Kw.js → task-failure-attributes-CBGtLS_H.js} +3 -3
  186. package/dist/{task-failure-attributes-DTl-7-Kw.js.map → task-failure-attributes-CBGtLS_H.js.map} +1 -1
  187. package/dist/{tool-groups-Ci8i9ErB.d.ts → tool-groups-RGYfVWpc.d.ts} +3 -3
  188. package/dist/tool-groups-RGYfVWpc.d.ts.map +1 -0
  189. package/dist/{tool-waste-CKc7bYIg.d.ts → tool-waste-BrmLKxMw.d.ts} +4 -4
  190. package/dist/{tool-waste-CKc7bYIg.d.ts.map → tool-waste-BrmLKxMw.d.ts.map} +1 -1
  191. package/dist/{tool-waste-8BQiUc8K.js → tool-waste-CwGHzBzX.js} +2 -2
  192. package/dist/{tool-waste-8BQiUc8K.js.map → tool-waste-CwGHzBzX.js.map} +1 -1
  193. package/dist/trace-repair/index.d.ts +3 -3
  194. package/dist/trace-repair/index.d.ts.map +1 -1
  195. package/dist/trace-repair/index.js +4 -3
  196. package/dist/trace-repair/index.js.map +1 -1
  197. package/dist/traces.d.ts +59 -61
  198. package/dist/traces.d.ts.map +1 -1
  199. package/dist/traces.js +7 -7
  200. package/dist/{trajectory-Bi157Gun.d.ts → trajectory-r1bQqvBQ.d.ts} +3 -3
  201. package/dist/{trajectory-Bi157Gun.d.ts.map → trajectory-r1bQqvBQ.d.ts.map} +1 -1
  202. package/dist/trajectory-replay/index.d.ts +3 -3
  203. package/dist/trajectory-replay/index.js +1 -1
  204. package/dist/{types-BPb2Kf_C.d.ts → types-CMyW4GnH.d.ts} +3 -3
  205. package/dist/{types-BPb2Kf_C.d.ts.map → types-CMyW4GnH.d.ts.map} +1 -1
  206. package/dist/{types-BI4fT3HN.js → types-CiWITkGo.js} +11 -2
  207. package/dist/types-CiWITkGo.js.map +1 -0
  208. package/dist/{types-D9ssmxKL.d.ts → types-DMoNFDWi.d.ts} +6 -3
  209. package/dist/{types-D9ssmxKL.d.ts.map → types-DMoNFDWi.d.ts.map} +1 -1
  210. package/dist/{types-D4s7Z6nq.d.ts → types-JHMOqZI4.d.ts} +13 -3
  211. package/dist/types-JHMOqZI4.d.ts.map +1 -0
  212. package/dist/{verdict-B0xltqu6.js → verdict-BQ3pCFf8.js} +2 -2
  213. package/dist/{verdict-B0xltqu6.js.map → verdict-BQ3pCFf8.js.map} +1 -1
  214. package/dist/{verdict-cache-CdVVTVmn.js → verdict-cache-B3eCVQtY.js} +2 -2
  215. package/dist/{verdict-cache-CdVVTVmn.js.map → verdict-cache-B3eCVQtY.js.map} +1 -1
  216. package/dist/wire/index.d.ts +26 -11
  217. package/dist/wire/index.d.ts.map +1 -1
  218. package/dist/wire/index.js +2 -2
  219. package/docs/campaign-proposers.md +4 -0
  220. package/docs/code-agent-intake.md +64 -0
  221. package/docs/concepts.md +1 -1
  222. package/docs/design/statistics-decisions.md +1 -1
  223. package/docs/distributed-driver.md +3 -6
  224. package/docs/public-api.md +122 -106
  225. package/docs/wire-protocol.md +5 -3
  226. package/package.json +27 -19
  227. package/dist/benchmark-BhT16ep9.js.map +0 -1
  228. package/dist/benchmark-command-CF-4GEWZ.js.map +0 -1
  229. package/dist/campaign-DQZmc2Dq.js.map +0 -1
  230. package/dist/capture-fetch-CqwsJkkG.d.ts +0 -68
  231. package/dist/capture-fetch-CqwsJkkG.d.ts.map +0 -1
  232. package/dist/contract/index.d.ts.map +0 -1
  233. package/dist/dspy-rlm-engine-DhA9qKIm.js.map +0 -1
  234. package/dist/external-optimizer-process-BFmh36vW.js.map +0 -1
  235. package/dist/external-optimizer-subprocess-CqLMW3nh.js.map +0 -1
  236. package/dist/index-CGtH1piv.d.ts.map +0 -1
  237. package/dist/index-D-V8gCs_.d.ts.map +0 -1
  238. package/dist/index-vrJugRal.d.ts +0 -1
  239. package/dist/kind-factory-DY8FdoXf.js.map +0 -1
  240. package/dist/llm-judge-Du7WQPh7.js.map +0 -1
  241. package/dist/pareto-BqNW3LJR.d.ts.map +0 -1
  242. package/dist/run-score-lDzV0X8j.js.map +0 -1
  243. package/dist/server-BjYiJHoJ.js.map +0 -1
  244. package/dist/skillopt-optimization-method-x7TTF23P.d.ts.map +0 -1
  245. package/dist/store-tool-spans-DPUG7UUY.d.ts.map +0 -1
  246. package/dist/tool-groups-Ci8i9ErB.d.ts.map +0 -1
  247. package/dist/transient-failure-DKF5Mofa.d.ts.map +0 -1
  248. package/dist/types-BI4fT3HN.js.map +0 -1
  249. package/dist/types-D4s7Z6nq.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"external-optimizer-subprocess-CqLMW3nh.js","names":["MAX_TIMER_DELAY_MS","bufferConstants"],"sources":["../src/campaign/search-ledger-errors.ts","../src/campaign/search-ledger-file.ts","../src/campaign/storage.ts","../src/campaign/external-optimizer-contracts.ts","../src/campaign/external-optimizer-anthropic.ts","../src/campaign/external-optimizer-http.ts","../src/campaign/external-optimizer-model-proxy.ts","../src/campaign/external-optimizer-resources.ts","../src/campaign/external-optimizer-subprocess.ts"],"sourcesContent":["import { ValidationError } from '../errors'\n\n/** Base error for invalid search-ledger input or operations. */\nexport class SearchLedgerError extends ValidationError {}\n\n/** Error raised when durable search-ledger data fails an integrity check. */\nexport class SearchLedgerIntegrityError extends SearchLedgerError {}\n\n/** Error raised when an event identifier is reused with different content. */\nexport class SearchLedgerConflictError extends SearchLedgerError {}\n","/** Campaign binding of the generic journal file layer to search-ledger errors. */\n\nimport {\n appendLedgerLine,\n type FileLockResult,\n type LedgerFileContext,\n tryWithLedgerFileLock,\n withLedgerFileLock,\n} from '../ledger-core'\nimport { SearchLedgerIntegrityError } from './search-ledger-errors'\n\nexport const SEARCH_LEDGER_FILE_CONTEXT: LedgerFileContext = {\n subject: 'search ledger',\n integrityError: (message, options) => new SearchLedgerIntegrityError(message, options),\n}\n\nexport function appendSearchLedgerLine(path: string, line: string): void {\n appendLedgerLine(path, line, SEARCH_LEDGER_FILE_CONTEXT)\n}\n\nexport function withSearchLedgerFileLock<T>(ledgerPath: string, run: () => T): T {\n return withLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run)\n}\n\nexport type { FileLockResult }\n\nexport function tryWithSearchLedgerFileLock<T>(\n ledgerPath: string,\n run: () => T,\n): FileLockResult<T> {\n return tryWithLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run)\n}\n","import { createRequire } from 'node:module'\nimport { join } from 'node:path'\nimport { CostLedger } from '../cost-ledger'\nimport { appendSearchLedgerLine, tryWithSearchLedgerFileLock } from './search-ledger-file'\n\n/**\n * `CampaignStorage` — the filesystem seam `runCampaign` writes through\n * (run/cell dirs, the resumability cache, per-cell artifacts, trace spans).\n *\n * The default (`fsCampaignStorage`) is the Node filesystem — identical\n * behavior to the inline `node:fs` calls it replaces, so existing CLI\n * consumers are unaffected. `inMemoryCampaignStorage` keeps everything in a\n * `Map`, so the substrate runs in environments WITHOUT a filesystem\n * (Cloudflare Workers, Deno Deploy, other edge runtimes) — the campaign\n * still produces its `CampaignResult` (cells + aggregates) in memory;\n * artifacts/traces simply aren't persisted to disk.\n *\n * Paths are opaque keys to the in-memory adapter — it does not parse them,\n * so the same `join(...)`-built paths work unchanged across both adapters.\n */\nexport interface CampaignStorage {\n /** Ensure a directory exists (recursive). No-op for in-memory. */\n ensureDir(dir: string): void\n /** Does this path exist (as a written file or an ensured dir)? */\n exists(path: string): boolean\n /** Read a UTF-8 file; `undefined` when missing or unreadable. */\n read(path: string): string | undefined\n /** Write a file (string or bytes). Parent dir is assumed ensured. */\n write(path: string, content: string | Uint8Array): void\n /** Append only when the current UTF-8 byte length matches `expectedBytes`.\n * Returns the new length, or undefined when another writer won. */\n append(path: string, content: string, expectedBytes: number): number | undefined\n}\n\n/** Node-filesystem storage — the default. Lazily requires `node:fs` so the\n * module imports cleanly in non-Node runtimes (where the caller passes\n * `inMemoryCampaignStorage` instead and never constructs this).\n *\n * `createRequire(import.meta.url)` is the ESM-native lazy require — a bare\n * `require` is a ReferenceError under `\"type\": \"module\"`, which is exactly\n * the shape this package publishes. */\nexport function fsCampaignStorage(): CampaignStorage {\n const nodeRequire = createRequire(import.meta.url)\n const { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } = nodeRequire(\n 'node:fs',\n ) as typeof import('node:fs')\n return {\n ensureDir(dir) {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n },\n exists(path) {\n return existsSync(path)\n },\n read(path) {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n },\n write(path, content) {\n writeFileSync(path, content as Uint8Array)\n },\n append(path, content, expectedBytes) {\n const result = tryWithSearchLedgerFileLock(path, () => {\n let actualBytes = 0\n try {\n actualBytes = statSync(path).size\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n if (actualBytes !== expectedBytes) return undefined\n appendSearchLedgerLine(path, content)\n return expectedBytes + Buffer.byteLength(content)\n })\n return result.acquired ? result.value : undefined\n },\n }\n}\n\n/** In-memory storage for filesystem-less runtimes. Artifacts + trace spans\n * live in a `Map` for the duration of the run; the `CampaignResult` is\n * fully populated, but nothing is persisted to disk. */\nexport function inMemoryCampaignStorage(): CampaignStorage {\n const files = new Map<string, string | Uint8Array>()\n const dirs = new Set<string>()\n return {\n ensureDir(dir) {\n dirs.add(dir)\n },\n exists(path) {\n return files.has(path) || dirs.has(path)\n },\n read(path) {\n const value = files.get(path)\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : new TextDecoder().decode(value)\n },\n write(path, content) {\n files.set(path, content)\n },\n append(path, content, expectedBytes) {\n const current = files.get(path)\n const currentText =\n current === undefined\n ? ''\n : typeof current === 'string'\n ? current\n : new TextDecoder().decode(current)\n const currentBytes = new TextEncoder().encode(currentText).byteLength\n if (currentBytes !== expectedBytes) return undefined\n files.set(path, `${currentText}${content}`)\n return currentBytes + new TextEncoder().encode(content).byteLength\n },\n }\n}\n\n/** Open the durable spend account stored beside a logical run. */\nexport function createRunCostLedger(input: {\n storage: CampaignStorage\n runDir: string\n costCeilingUsd?: number\n /** Set false for read-only inspection that must not create the run directory. */\n ensureRunDir?: boolean\n}): CostLedger {\n const path = join(input.runDir, 'cost-ledger.jsonl')\n if (input.ensureRunDir ?? true) input.storage.ensureDir(input.runDir)\n return new CostLedger({\n costCeilingUsd: input.costCeilingUsd,\n persistence: {\n read: () => {\n const stored = input.storage.read(path)\n if (stored === undefined && input.storage.exists(path)) {\n throw new Error(`CostLedger: cannot read existing event log '${path}'`)\n }\n const events = stored ?? ''\n return {\n revision: String(new TextEncoder().encode(events).byteLength),\n events,\n }\n },\n append: (expectedRevision, event) => {\n const expectedBytes = Number(expectedRevision)\n if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) {\n throw new Error(`CostLedger: invalid storage revision '${expectedRevision}'`)\n }\n const next = input.storage.append(path, event, expectedBytes)\n return next === undefined ? undefined : String(next)\n },\n },\n })\n}\n","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'\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\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 }\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 }\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 isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","import type { ChatResponse } from '../analyst/chat-client'\nimport type { LlmToolCall, LlmToolChoice, LlmToolDefinition } from '../llm-client'\nimport { isRecord } from './external-optimizer-contracts'\n\n/**\n * Translate between the Anthropic Messages API and the canonical owner-call\n * contract used by the metered optimizer model proxy.\n *\n * The `claude` CLI driven by GEPA agent engines speaks `POST /v1/messages`.\n * Each request becomes one canonical `ExternalOptimizerChatRequest`, so the\n * shared reservation, receipt, and execution-evidence pipeline applies\n * unchanged. Tool use translates in both directions: Anthropic `tools`,\n * `tool_choice`, `tool_use`, and `tool_result` map onto the canonical\n * function-tool contract, and a tool-calling response is synthesized back as\n * the Anthropic stream shape the CLI expects.\n *\n * Anything without a full-fidelity mapping onto the canonical contract is\n * refused with a loud Anthropic error envelope, with two exceptions:\n *\n * - `metadata` and `cache_control` are dropped silently: the CLI always sends\n * both, neither has a canonical slot, and dropping them changes no content.\n * - Claude-specific control fields (`thinking`, `context_management`,\n * `output_config`, replayed reasoning blocks, and unknown tool-entry keys)\n * are STRIPPED AND RECORDED. They carry no token-billing semantics on the\n * owner wire, and the real CLI sends them on every request — refusing them\n * makes every real CLI call impossible. The dropped names are returned in\n * `strippedFields` so accounting discloses exactly what the shim removed.\n */\n\nexport class AnthropicRequestRefusal extends Error {\n readonly status: number\n readonly errorType: string\n\n constructor(status: number, errorType: string, message: string) {\n super(message)\n this.status = status\n this.errorType = errorType\n }\n}\n\ninterface TranslatedMessage {\n role: 'system' | 'user' | 'assistant' | 'tool'\n content: string\n toolCalls?: LlmToolCall[]\n toolCallId?: string\n}\n\nexport interface TranslatedAnthropicRequest {\n request: {\n model: string\n messages: TranslatedMessage[]\n maxTokens: number\n temperature?: number\n tools?: LlmToolDefinition[]\n toolChoice?: LlmToolChoice\n }\n maxOutputTokens: number\n /** SSE was requested; the stream is synthesized from the completed call. */\n stream: boolean\n /** Sorted names of control fields dropped from the canonical request. */\n strippedFields: readonly string[]\n}\n\nconst REQUEST_FIELDS = new Set([\n 'model',\n 'max_tokens',\n 'messages',\n 'system',\n 'temperature',\n 'stream',\n 'metadata',\n 'tools',\n 'tool_choice',\n])\n\n// Claude-specific control fields with no token-billing semantics on the owner\n// wire. The CLI sends `thinking` even under CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING,\n// and `output_config` leaks from user settings through the engine sandbox.\nconst STRIPPED_REQUEST_FIELDS = new Set(['thinking', 'context_management', 'output_config'])\n\nconst REFUSED_REQUEST_FIELDS: Record<string, string> = {\n top_p: 'top_p has no canonical execution-owner slot',\n top_k: 'top_k has no canonical execution-owner slot',\n stop_sequences: 'stop_sequences has no canonical execution-owner slot',\n}\n\nexport function translateAnthropicMessagesRequest(\n raw: Uint8Array,\n expectedModel: string,\n maxOutputTokensPerRequest: number,\n): TranslatedAnthropicRequest {\n let parsed: unknown\n try {\n parsed = JSON.parse(Buffer.from(raw).toString('utf8'))\n } catch {\n throw refuse('request must be valid JSON')\n }\n if (!isRecord(parsed)) throw refuse('request must be a JSON object')\n const stripped = new Set<string>()\n for (const key of Object.keys(parsed)) {\n if (REQUEST_FIELDS.has(key)) continue\n if (STRIPPED_REQUEST_FIELDS.has(key)) {\n stripped.add(key)\n continue\n }\n const reason = REFUSED_REQUEST_FIELDS[key]\n throw refuse(reason ?? `request field '${key}' has no metered translation and is not supported`)\n }\n if (parsed.model !== expectedModel) {\n throw refuse(`request must use configured model '${expectedModel}'`)\n }\n const maxTokens = parsed.max_tokens\n if (!Number.isSafeInteger(maxTokens) || (maxTokens as number) <= 0) {\n throw refuse('request requires a positive integer max_tokens')\n }\n if ((maxTokens as number) > maxOutputTokensPerRequest) {\n throw refuse('request max_tokens exceeds maxOutputTokensPerRequest')\n }\n if (parsed.stream !== undefined && typeof parsed.stream !== 'boolean') {\n throw refuse('request stream must be a boolean')\n }\n if (\n parsed.temperature !== undefined &&\n (typeof parsed.temperature !== 'number' || !Number.isFinite(parsed.temperature))\n ) {\n throw refuse('request temperature must be a finite number')\n }\n\n const messages: TranslatedMessage[] = []\n const systemText = translateSystem(parsed.system)\n if (systemText !== undefined) messages.push({ role: 'system', content: systemText })\n messages.push(...translateConversation(parsed.messages, stripped))\n const tools = translateTools(parsed.tools, stripped)\n const toolChoice = translateToolChoice(parsed.tool_choice, stripped)\n\n return {\n request: {\n model: expectedModel,\n messages,\n maxTokens: maxTokens as number,\n ...(parsed.temperature !== undefined ? { temperature: parsed.temperature } : {}),\n ...(tools === undefined ? {} : { tools }),\n ...(toolChoice === undefined ? {} : { toolChoice }),\n },\n maxOutputTokens: maxTokens as number,\n stream: parsed.stream === true,\n strippedFields: [...stripped].sort(),\n }\n}\n\nconst TOOL_ENTRY_FIELDS = new Set(['name', 'description', 'input_schema', 'type', 'cache_control'])\n\nfunction translateTools(value: unknown, stripped: Set<string>): LlmToolDefinition[] | undefined {\n if (value === undefined) return undefined\n if (!Array.isArray(value) || value.length === 0) {\n throw refuse('tools must be a non-empty array of tool definitions')\n }\n return value.map((entry, index) => {\n if (!isRecord(entry)) throw refuse(`tools[${index}] must be an object`)\n // Server tools carry versioned `type` values and execute on Anthropic\n // infrastructure; they have no metered translation onto the owner wire.\n if (entry.type !== undefined && entry.type !== 'custom') {\n throw refuse(\n `tools[${index}] type '${String(entry.type)}' has no metered translation; only client function tools are served`,\n )\n }\n if (typeof entry.name !== 'string' || !entry.name.trim()) {\n throw refuse(`tools[${index}] requires a non-empty name`)\n }\n if (entry.description !== undefined && typeof entry.description !== 'string') {\n throw refuse(`tools[${index}] description must be a string`)\n }\n if (!isRecord(entry.input_schema)) {\n throw refuse(`tools[${index}] requires an input_schema object`)\n }\n // `cache_control` alters no tool content and is dropped like elsewhere.\n // Any other unknown key is Claude control surface with no canonical slot:\n // dropped and disclosed instead of failing every real CLI call.\n for (const key of Object.keys(entry)) {\n if (TOOL_ENTRY_FIELDS.has(key)) continue\n stripped.add(`tools.${key}`)\n }\n return {\n type: 'function' as const,\n function: {\n name: entry.name,\n ...(entry.description === undefined ? {} : { description: entry.description }),\n parameters: entry.input_schema as Record<string, unknown>,\n },\n }\n })\n}\n\nfunction translateToolChoice(value: unknown, stripped: Set<string>): LlmToolChoice | undefined {\n if (value === undefined) return undefined\n if (!isRecord(value) || typeof value.type !== 'string') {\n throw refuse('tool_choice must be an object with a type')\n }\n for (const key of Object.keys(value)) {\n if (key === 'type') continue\n if (key === 'name' && value.type === 'tool') continue\n if (key === 'disable_parallel_tool_use') {\n // No canonical slot; the owner wire decides its own parallelism.\n stripped.add('tool_choice.disable_parallel_tool_use')\n continue\n }\n throw refuse(`tool_choice field '${key}' has no metered translation`)\n }\n if (value.type === 'auto') return 'auto'\n if (value.type === 'none') return 'none'\n if (value.type === 'any') return 'required'\n if (value.type === 'tool') {\n if (typeof value.name !== 'string' || !value.name.trim()) {\n throw refuse('tool_choice type tool requires a tool name')\n }\n return { type: 'function', function: { name: value.name } }\n }\n throw refuse(`tool_choice type '${String(value.type)}' has no metered translation`)\n}\n\nfunction translateSystem(value: unknown): string | undefined {\n if (value === undefined) return undefined\n if (typeof value === 'string') return value\n if (!Array.isArray(value)) throw refuse('system must be a string or an array of text blocks')\n return joinTextBlocks(value, 'system')\n}\n\nfunction translateConversation(value: unknown, stripped: Set<string>): TranslatedMessage[] {\n if (!Array.isArray(value) || value.length === 0) {\n throw refuse('request requires a non-empty messages array')\n }\n const out: TranslatedMessage[] = []\n for (const entry of value) {\n if (!isRecord(entry)) throw refuse('each message must be an object')\n // The claude CLI injects `system`-role turns mid-conversation (budget\n // status lines, session listings, task reminders); the canonical contract\n // allows the system role at any position, so they translate in place.\n if (entry.role !== 'system' && entry.role !== 'user' && entry.role !== 'assistant') {\n throw refuse(`message role must be 'system', 'user', or 'assistant'`)\n }\n if (typeof entry.content === 'string') {\n out.push({ role: entry.role, content: entry.content })\n continue\n }\n if (!Array.isArray(entry.content) || entry.content.length === 0) {\n throw refuse(`${entry.role} message content must be a string or a non-empty block array`)\n }\n if (entry.role === 'system') {\n out.push({ role: 'system', content: joinTextBlocks(entry.content, 'system') })\n } else if (entry.role === 'assistant') {\n out.push(translateAssistantBlocks(entry.content, stripped))\n } else {\n out.push(...translateUserBlocks(entry.content, stripped))\n }\n }\n return out\n}\n\nfunction translateAssistantBlocks(\n blocks: readonly unknown[],\n stripped: Set<string>,\n): TranslatedMessage {\n const parts: string[] = []\n const toolCalls: LlmToolCall[] = []\n for (const block of blocks) {\n if (!isRecord(block)) throw refuse('assistant message content blocks must be objects')\n if (block.type === 'text') {\n if (typeof block.text !== 'string') {\n throw refuse('assistant message text blocks require string text')\n }\n parts.push(block.text)\n continue\n }\n if (block.type === 'tool_use') {\n if (typeof block.id !== 'string' || !block.id.trim()) {\n throw refuse('assistant tool_use blocks require a string id')\n }\n if (typeof block.name !== 'string' || !block.name.trim()) {\n throw refuse('assistant tool_use blocks require a string name')\n }\n if (!isRecord(block.input)) throw refuse('assistant tool_use blocks require an input object')\n toolCalls.push({ id: block.id, name: block.name, argumentsJson: JSON.stringify(block.input) })\n continue\n }\n // Replayed reasoning blocks have no canonical slot and no billing effect\n // on the owner wire: dropped and disclosed instead of failing every\n // thinking-enabled CLI conversation.\n if (block.type === 'thinking' || block.type === 'redacted_thinking') {\n stripped.add(`messages.${String(block.type)}`)\n continue\n }\n throw refuse(\n `assistant message content block type '${String(block.type)}' has no metered translation`,\n )\n }\n return {\n role: 'assistant',\n content: parts.join('\\n\\n'),\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n }\n}\n\nfunction translateUserBlocks(\n blocks: readonly unknown[],\n stripped: Set<string>,\n): TranslatedMessage[] {\n const out: TranslatedMessage[] = []\n const textParts: string[] = []\n const flushText = () => {\n if (textParts.length === 0) return\n out.push({ role: 'user', content: textParts.join('\\n\\n') })\n textParts.length = 0\n }\n for (const block of blocks) {\n if (!isRecord(block)) throw refuse('user message content blocks must be objects')\n if (block.type === 'text') {\n if (typeof block.text !== 'string')\n throw refuse('user message text blocks require string text')\n textParts.push(block.text)\n continue\n }\n if (block.type === 'tool_result') {\n if (typeof block.tool_use_id !== 'string' || !block.tool_use_id.trim()) {\n throw refuse('user tool_result blocks require a string tool_use_id')\n }\n // `is_error` has no canonical slot; the failure text already lives in\n // the result content, so only the flag itself is dropped and disclosed.\n if (block.is_error === true) stripped.add('messages.tool_result.is_error')\n flushText()\n out.push({\n role: 'tool',\n content: toolResultText(block.content),\n toolCallId: block.tool_use_id,\n })\n continue\n }\n throw refuse(\n `user message content block type '${String(block.type)}' has no metered translation`,\n )\n }\n flushText()\n return out\n}\n\nfunction toolResultText(value: unknown): string {\n if (value === undefined) return ''\n if (typeof value === 'string') return value\n if (!Array.isArray(value)) {\n throw refuse('user tool_result content must be a string or a block array')\n }\n const parts: string[] = []\n for (const block of value) {\n if (!isRecord(block) || block.type !== 'text' || typeof block.text !== 'string') {\n throw refuse('user tool_result content blocks must be text blocks')\n }\n parts.push(block.text)\n }\n return parts.join('\\n\\n')\n}\n\nfunction joinTextBlocks(blocks: readonly unknown[], label: string): string {\n const parts: string[] = []\n for (const block of blocks) {\n if (!isRecord(block)) throw refuse(`${label} content blocks must be objects`)\n if (block.type === 'text') {\n if (typeof block.text !== 'string') throw refuse(`${label} text blocks require string text`)\n // `cache_control` and `citations` markers on text blocks are dropped;\n // they alter no message content and have no canonical slot.\n parts.push(block.text)\n continue\n }\n throw refuse(`${label} content block type '${String(block.type)}' has no metered translation`)\n }\n return parts.join('\\n\\n')\n}\n\nconst STOP_REASON_BY_FINISH_REASON: Record<string, string> = {\n stop: 'end_turn',\n length: 'max_tokens',\n content_filter: 'refusal',\n // 'tool_calls' is the OpenAI wire echo; 'tool_use' is the canonical\n // normalization the execution owner applies. Both denote the same stop.\n tool_calls: 'tool_use',\n tool_use: 'tool_use',\n}\n\n/**\n * Encode one canonical owner response as an Anthropic message.\n *\n * Usage fields are display-level for the CLI; the ledger receipt reads the\n * same canonical response through the proxy's strict receipt checks. An\n * uncaptured usage renders as zeros here while the receipt keeps the honest\n * unknown-cost maximum. Canonical tool calls become `tool_use` content blocks\n * after the text block, matching Anthropic block ordering.\n */\nexport function encodeAnthropicMessage(\n response: ChatResponse,\n callId: string,\n): Record<string, unknown> {\n const finishReason = response.finishReason ?? 'stop'\n const stopReason = finishReason === null ? 'end_turn' : STOP_REASON_BY_FINISH_REASON[finishReason]\n if (stopReason === undefined) {\n throw new AnthropicRequestRefusal(\n 502,\n 'api_error',\n `optimizer model finish reason '${String(finishReason)}' has no Anthropic translation`,\n )\n }\n const captured = response.usage.captured !== false\n const cachedTokens = response.usage.cachedPromptTokens ?? 0\n const content: Record<string, unknown>[] = []\n if (response.content.length > 0) content.push({ type: 'text', text: response.content })\n for (const call of response.toolCalls ?? []) {\n content.push({ type: 'tool_use', id: call.id, name: call.name, input: parseToolInput(call) })\n }\n return {\n id: `msg_${callId}`,\n type: 'message',\n role: 'assistant',\n model: response.model,\n content,\n stop_reason: stopReason,\n stop_sequence: null,\n usage: captured\n ? {\n input_tokens: response.usage.promptTokens - cachedTokens,\n cache_read_input_tokens: cachedTokens,\n cache_creation_input_tokens: 0,\n output_tokens: response.usage.completionTokens,\n }\n : { input_tokens: 0, output_tokens: 0 },\n }\n}\n\nfunction parseToolInput(call: LlmToolCall): Record<string, unknown> {\n const text = call.argumentsJson.trim()\n if (text === '') return {}\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n throw new AnthropicRequestRefusal(\n 502,\n 'api_error',\n `optimizer model tool call '${call.name}' returned arguments that are not valid JSON`,\n )\n }\n if (!isRecord(parsed)) {\n throw new AnthropicRequestRefusal(\n 502,\n 'api_error',\n `optimizer model tool call '${call.name}' arguments must encode a JSON object`,\n )\n }\n return parsed\n}\n\n/**\n * Render one completed Anthropic message as the SSE stream the CLI expects.\n *\n * The whole stream is synthesized after the owner call completes, so the\n * event burst is exact: usage is final and a cap-violating response is\n * rejected with a real status instead of a half-delivered stream. A\n * `tool_use` block streams as an empty-input `content_block_start` plus one\n * `input_json_delta` carrying the complete arguments JSON.\n */\nexport function renderAnthropicSseStream(message: Record<string, unknown>): string {\n const content = Array.isArray(message.content) ? message.content : []\n const usage = isRecord(message.usage) ? message.usage : { input_tokens: 0, output_tokens: 0 }\n const events: { event: string; data: Record<string, unknown> }[] = [\n {\n event: 'message_start',\n data: {\n type: 'message_start',\n message: { ...message, content: [], stop_reason: null, stop_sequence: null },\n },\n },\n ]\n for (const [index, block] of content.entries()) {\n if (!isRecord(block)) continue\n if (block.type === 'text') {\n events.push(\n {\n event: 'content_block_start',\n data: {\n type: 'content_block_start',\n index,\n content_block: { type: 'text', text: '' },\n },\n },\n {\n event: 'content_block_delta',\n data: {\n type: 'content_block_delta',\n index,\n delta: { type: 'text_delta', text: block.text },\n },\n },\n {\n event: 'content_block_stop',\n data: { type: 'content_block_stop', index },\n },\n )\n continue\n }\n if (block.type === 'tool_use') {\n events.push(\n {\n event: 'content_block_start',\n data: {\n type: 'content_block_start',\n index,\n content_block: { type: 'tool_use', id: block.id, name: block.name, input: {} },\n },\n },\n {\n event: 'content_block_delta',\n data: {\n type: 'content_block_delta',\n index,\n delta: { type: 'input_json_delta', partial_json: JSON.stringify(block.input) },\n },\n },\n {\n event: 'content_block_stop',\n data: { type: 'content_block_stop', index },\n },\n )\n }\n }\n events.push(\n {\n event: 'message_delta',\n data: {\n type: 'message_delta',\n delta: { stop_reason: message.stop_reason, stop_sequence: null },\n usage: { output_tokens: typeof usage.output_tokens === 'number' ? usage.output_tokens : 0 },\n },\n },\n { event: 'message_stop', data: { type: 'message_stop' } },\n )\n return events\n .map((entry) => `event: ${entry.event}\\ndata: ${JSON.stringify(entry.data)}\\n\\n`)\n .join('')\n}\n\nexport function anthropicErrorEnvelope(\n errorType: string,\n message: string,\n): { type: 'error'; error: { type: string; message: string } } {\n return { type: 'error', error: { type: errorType, message } }\n}\n\nexport function anthropicErrorTypeForStatus(status: number): string {\n if (status === 401) return 'authentication_error'\n if (status === 403) return 'permission_error'\n if (status === 404) return 'not_found_error'\n if (status === 413) return 'request_too_large'\n if (status === 429) return 'rate_limit_error'\n if (status >= 500) return 'api_error'\n return 'invalid_request_error'\n}\n\nfunction refuse(message: string): AnthropicRequestRefusal {\n return new AnthropicRequestRefusal(400, 'invalid_request_error', message)\n}\n","import type { Server, ServerResponse } from 'node:http'\n\nexport function listenLocal(server: Server): Promise<number> {\n return new Promise((resolvePromise, reject) => {\n server.once('error', reject)\n server.listen(0, '127.0.0.1', () => {\n server.off('error', reject)\n const address = server.address()\n if (!address || typeof address === 'string') {\n reject(new Error('external optimizer callback did not bind a TCP port'))\n return\n }\n resolvePromise(address.port)\n })\n })\n}\n\nexport function closeServer(server: Server): Promise<void> {\n return new Promise((resolvePromise, reject) => {\n server.close((error) => (error ? reject(error) : resolvePromise()))\n })\n}\n\nexport function sendJson(response: ServerResponse, status: number, body: unknown): void {\n response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })\n response.end(JSON.stringify(body))\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport type { ChatResponse } from '../analyst/chat-client'\nimport type {\n CostChannel,\n CostLedgerHandle,\n CostReceiptInput,\n CustomTokenPricing,\n} from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\nimport {\n assertServedModel,\n assertServedModelPolicy,\n ModelSubstitutionError,\n type ServedModelPolicy,\n} from '../integrity/served-model'\nimport { canonicalJson } from '../verdict-cache'\nimport {\n AnthropicRequestRefusal,\n anthropicErrorEnvelope,\n anthropicErrorTypeForStatus,\n encodeAnthropicMessage,\n renderAnthropicSseStream,\n translateAnthropicMessagesRequest,\n} from './external-optimizer-anthropic'\nimport {\n assertExternalOptimizerModelBudget,\n assertJsonValue,\n type ExternalOptimizerChatRequest,\n type ExternalOptimizerEndpointFormat,\n type ExternalOptimizerModelBudget,\n type ExternalOptimizerModelCall,\n type ExternalOptimizerModelExecutionObservation,\n type ExternalOptimizerModelProxy,\n type ExternalOptimizerWireCounts,\n isRecord,\n} from './external-optimizer-contracts'\nimport { closeServer, listenLocal, sendJson } from './external-optimizer-http'\n\nconst MODEL_PROXY_PATHS = new Set(['/v1/chat/completions', '/v1/responses'])\ntype ModelProxyPath = '/v1/chat/completions' | '/v1/responses' | '/v1/messages'\ntype ModelProxyWire = 'openai' | 'anthropic'\n\ntype UnsequencedExecutionObservation = ExternalOptimizerModelExecutionObservation extends infer T\n ? T extends ExternalOptimizerModelExecutionObservation\n ? Omit<T, 'sequence'>\n : never\n : never\n\ninterface ProviderProxyResponse {\n status: number\n contentType: string\n body: Uint8Array\n receipt: CostReceiptInput\n usageComplete: boolean\n /** A Runtime-owned call failed after returning complete execution evidence. */\n modelCallFailed?: string\n /** Set when the response violated the output or reasoning limit; forces a 502. */\n usageRejected?: string\n}\n\ntype ExternalOptimizerModelProxyArgs = {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n /** Served-model acceptance for every proxied call. Default `'exact'`. */\n servedModelPolicy?: ServedModelPolicy\n costLedger: CostLedgerHandle\n phase: string\n actor: string\n /** Cost-ledger channel. Defaults to `optimizer`. */\n channel?: CostChannel\n tags?: Record<string, string>\n /** Deterministic ledger identity for a single-request proxy. */\n callId?: string\n /**\n * Also serve `POST /v1/messages` (Anthropic Messages API) for `claude` CLI\n * children. The route translates onto the same owner call and receipt\n * pipeline; without the flag it stays 404. Default: false.\n */\n anthropicEndpoint?: boolean\n initialUsage?: {\n requests: number\n /** Known billed subtotal. Omit when prior billed USD is unknown. */\n costUsd?: number\n }\n signal?: AbortSignal\n}\n\n/**\n * Put an OpenAI-compatible optimizer behind the shared cost ledger.\n *\n * The child process receives only a loopback URL and an ephemeral token. The\n * package that owns execution receives a validated immutable request through\n * `call`; Eval receives no provider credential. Every request reserves its\n * conservative byte-count input bound plus the declared output cap before the\n * owner is invoked exactly once.\n */\nexport async function startExternalOptimizerModelProxy(\n args: ExternalOptimizerModelProxyArgs,\n): Promise<ExternalOptimizerModelProxy> {\n assertModelProxyConfig(args)\n args.signal?.throwIfAborted()\n const token = randomLocalToken()\n let requestCount = 0\n let successfulCompletionCount = 0\n const wireCounts: Record<ModelProxyWire, ExternalOptimizerWireCounts> = {\n openai: { requestAttempts: 0, successfulCompletions: 0 },\n anthropic: { requestAttempts: 0, successfulCompletions: 0 },\n }\n let modelCallInvocations = 0\n let executionRecordCount = 0\n let executionSequence = 0\n const failures: Error[] = []\n let totalRequestCount = args.initialUsage?.requests ?? 0\n let committedForBudget = args.initialUsage?.costUsd ?? 0\n let reservedForBudget = 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\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'external optimizer model proxy 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 = handleModelProxyRequest({\n request,\n response,\n controller,\n token,\n args,\n nextReservation: (maximumCostUsd, wire) => {\n if (totalRequestCount >= args.budget.maxRequests) {\n return { accepted: false as const, reason: 'optimizer model request limit reached' }\n }\n if (\n args.budget.maxCostUsd !== undefined &&\n maximumCostUsd !== undefined &&\n committedForBudget + reservedForBudget + maximumCostUsd >\n args.budget.maxCostUsd + Number.EPSILON\n ) {\n return { accepted: false as const, reason: 'optimizer model cost limit reached' }\n }\n requestCount += 1\n wireCounts[wire].requestAttempts += 1\n totalRequestCount += 1\n reservedForBudget += maximumCostUsd ?? 0\n return { accepted: true as const }\n },\n settleReservation: (maximumCostUsd, chargedCostUsd) => {\n reservedForBudget = Math.max(0, reservedForBudget - (maximumCostUsd ?? 0))\n committedForBudget += chargedCostUsd ?? 0\n },\n recordSuccessfulCompletion: (wire) => {\n successfulCompletionCount += 1\n wireCounts[wire].successfulCompletions += 1\n },\n recordExecutionReceipt: (observation) => {\n try {\n args.recordExecution({ ...observation, sequence: executionSequence + 1 })\n } catch (error) {\n throw new ModelExecutionPersistenceError(\n `optimizer model execution evidence was not persisted: ${toErrorMessage(error)}`,\n )\n }\n executionSequence += 1\n executionRecordCount += 1\n },\n recordModelCallInvocation: () => {\n modelCallInvocations += 1\n },\n recordFailure: (error) => {\n failures.push(error)\n },\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 ??= closeModelProxy()\n return closePromise\n }\n const onAbort = (): void => {\n for (const controller of activeControllers) controller.abort(args.signal?.reason)\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n const assertExecutionComplete = (): void => {\n if (executionRecordCount !== modelCallInvocations) {\n throw new Error(\n `external optimizer model callback returned ${executionRecordCount} execution records for ${modelCallInvocations} invoked calls`,\n )\n }\n }\n return {\n baseUrl: `http://127.0.0.1:${port}/v1`,\n apiKey: token,\n requestAttempts: () => requestCount,\n successfulCompletions: () => successfulCompletionCount,\n wireUsage: () => ({\n openai: { ...wireCounts.openai },\n anthropic: { ...wireCounts.anthropic },\n }),\n assertExecutionComplete,\n failures: () => [...failures],\n close,\n }\n\n async function closeModelProxy(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\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 model proxy closed with active request work')\n }\n let executionError: unknown\n try {\n assertExecutionComplete()\n } catch (error) {\n executionError = error\n }\n if (serverResult?.status === 'rejected' && executionError !== undefined) {\n throw new AggregateError(\n [serverResult.reason, executionError],\n 'external optimizer model proxy close and execution evidence both failed',\n )\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n if (executionError !== undefined) throw executionError\n }\n}\n\nasync function handleModelProxyRequest(args: {\n request: IncomingMessage\n response: ServerResponse\n controller: AbortController\n token: string\n args: {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n servedModelPolicy?: ServedModelPolicy\n costLedger: CostLedgerHandle\n phase: string\n actor: string\n channel?: CostChannel\n tags?: Record<string, string>\n callId?: string\n anthropicEndpoint?: boolean\n }\n nextReservation: (\n maximumCostUsd: number | undefined,\n wire: ModelProxyWire,\n ) =>\n | { accepted: true }\n | {\n accepted: false\n reason: 'optimizer model request limit reached' | 'optimizer model cost limit reached'\n }\n settleReservation: (\n maximumCostUsd: number | undefined,\n chargedCostUsd: number | undefined,\n ) => void\n recordSuccessfulCompletion: (wire: ModelProxyWire) => void\n recordExecutionReceipt: (observation: UnsequencedExecutionObservation) => void\n recordModelCallInvocation: () => void\n recordFailure: (error: Error) => void\n}): Promise<void> {\n const { controller, request, response } = args\n let wire: ModelProxyWire = 'openai'\n // The `claude` CLI retries only 408/409/429/5xx. A budget or ledger refusal\n // must therefore surface as 402 on the Anthropic wire: retrying an exhausted\n // budget burns wall clock with no possible recovery.\n const respondError = (status: number, message: string, errorType?: string): void => {\n if (wire === 'anthropic') {\n const mapped = status === 429 ? 402 : status\n sendJsonIfOpen(\n response,\n mapped,\n anthropicErrorEnvelope(errorType ?? anthropicErrorTypeForStatus(mapped), message),\n )\n return\n }\n sendJsonIfOpen(response, status, { error: message })\n }\n try {\n const path = request.url ? new URL(request.url, 'http://127.0.0.1').pathname : ''\n const anthropicPath = path === '/v1/messages' && args.args.anthropicEndpoint === true\n if (request.method !== 'POST' || !(MODEL_PROXY_PATHS.has(path) || anthropicPath)) {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (anthropicPath) wire = 'anthropic'\n const modelPath = path as ModelProxyPath\n const bearerAuthorized = request.headers.authorization === `Bearer ${args.token}`\n // The Anthropic SDK spells ANTHROPIC_AUTH_TOKEN as a bearer and\n // ANTHROPIC_API_KEY as x-api-key; both carry the same ephemeral token.\n const authorized =\n bearerAuthorized || (wire === 'anthropic' && request.headers['x-api-key'] === args.token)\n if (!authorized) {\n respondError(401, 'unauthorized')\n return\n }\n\n const body = await readBody(request, args.args.budget.maxRequestBytes)\n const parsed = parseModelProxyRequest(body, modelPath, args.args.model, args.args.budget)\n const maximumUsage = conservativeMaximumUsage(\n body.byteLength,\n parsed.maxOutputTokens + (args.args.budget.maxReasoningTokensPerRequest ?? 0),\n args.args.budget.pricing,\n )\n const maximumCostUsd = args.args.budget.pricing\n ? costForTokenPricing(args.args.budget.pricing, maximumUsage)\n : undefined\n const reservation = args.nextReservation(maximumCostUsd, wire)\n if (!reservation.accepted) {\n respondError(429, reservation.reason)\n return\n }\n\n const timeout = setTimeout(\n () => controller.abort(),\n args.args.budget.requestTimeoutMs ?? 300_000,\n )\n let chargedForBudget = maximumCostUsd\n try {\n // `strippedFields` discloses the Anthropic control fields the shim\n // removed before metering, so accounting shows the exact served request.\n const requestTags =\n wire === 'anthropic'\n ? {\n ...(args.args.tags ?? {}),\n wire: 'anthropic',\n ...(parsed.strippedFields === undefined\n ? {}\n : { strippedFields: parsed.strippedFields.join(',') }),\n }\n : args.args.tags\n const paid = await args.args.costLedger.runPaidCall<ProviderProxyResponse>({\n ...(args.args.callId ? { callId: args.args.callId } : {}),\n channel: args.args.channel ?? 'optimizer',\n phase: args.args.phase,\n actor: args.args.actor,\n ...(requestTags ? { tags: requestTags } : {}),\n model: args.args.model,\n ...(args.args.budget.pricing\n ? {\n maximumCharge: {\n customTokenPricing: args.args.budget.pricing,\n ...maximumUsage,\n },\n }\n : {}),\n signal: controller.signal,\n execute: async (paidCallSignal, paidCallId) =>\n forwardModelProxyRequest({\n call: args.args.call,\n callId: paidCallId,\n callRef: args.args.callRef,\n recordExecutionReceipt: args.recordExecutionReceipt,\n recordModelCallInvocation: args.recordModelCallInvocation,\n path: modelPath,\n request: parsed.request,\n ...(parsed.stream === undefined ? {} : { anthropicStream: parsed.stream }),\n model: args.args.model,\n allowWithinFamily: args.args.servedModelPolicy === 'allow-within-family',\n maxOutputTokens: parsed.maxOutputTokens,\n ...(args.args.budget.maxReasoningTokensPerRequest === undefined\n ? {}\n : { maxReasoningTokens: args.args.budget.maxReasoningTokensPerRequest }),\n maxResponseBytes: args.args.budget.maxResponseBytes,\n signal: paidCallSignal,\n }),\n receipt: (result) => result.receipt,\n receiptFromError: () => ({\n model: args.args.model,\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n usageUnknown: true,\n }),\n })\n if (!paid.succeeded) {\n args.recordFailure(paid.error)\n chargedForBudget = paid.receipt\n ? paid.receipt.usageUnknown || paid.receipt.costUnknown\n ? maximumCostUsd\n : paid.receipt.costUsd\n : undefined\n respondError(\n isAbortError(paid.error)\n ? 504\n : paid.error instanceof AnthropicRequestRefusal\n ? paid.error.status\n : paid.error instanceof ProviderResponseTooLargeError ||\n paid.error instanceof MissingModelExecutionError ||\n paid.error instanceof ModelExecutionPersistenceError ||\n paid.error instanceof OwnerModelContractError ||\n paid.error instanceof ModelSubstitutionError\n ? 502\n : 429,\n paid.error.message,\n paid.error instanceof AnthropicRequestRefusal ? paid.error.errorType : undefined,\n )\n return\n }\n if (paid.value.modelCallFailed) {\n respondError(502, paid.value.modelCallFailed)\n return\n }\n chargedForBudget = paid.value.usageComplete ? paid.receipt.costUsd : maximumCostUsd\n // A response that violated the output or reasoning limit is rejected. A\n // response the provider merely under-reported is forwarded with its cost\n // charged at the reservation maximum, so the analysis keeps its usable\n // completion and the ledger holds an honest upper-bound charge.\n if (paid.value.usageRejected) {\n respondError(502, paid.value.usageRejected)\n return\n }\n if (paid.value.status >= 200 && paid.value.status < 300) {\n args.recordSuccessfulCompletion(wire)\n }\n if (response.destroyed || response.writableEnded) return\n response.writeHead(paid.value.status, {\n 'content-type': paid.value.contentType,\n 'content-length': String(paid.value.body.byteLength),\n })\n response.end(paid.value.body)\n } finally {\n clearTimeout(timeout)\n args.settleReservation(maximumCostUsd, chargedForBudget)\n }\n } catch (error) {\n const status =\n error instanceof AnthropicRequestRefusal\n ? error.status\n : error instanceof RequestBodyTooLargeError\n ? 413\n : error instanceof Error && isAbortError(error)\n ? 503\n : 400\n respondError(\n status,\n toErrorMessage(error),\n error instanceof AnthropicRequestRefusal ? error.errorType : undefined,\n )\n }\n}\n\nasync function waitForActiveHandlers(activeHandlers: Set<Promise<void>>): Promise<void> {\n while (activeHandlers.size > 0) {\n await Promise.allSettled([...activeHandlers])\n }\n}\n\nfunction sendJsonIfOpen(response: ServerResponse, status: number, body: unknown): void {\n if (response.destroyed || response.writableEnded) return\n sendJson(response, status, body)\n}\n\nasync function forwardModelProxyRequest(args: {\n call: ExternalOptimizerModelCall\n callId: string\n callRef: string\n recordExecutionReceipt: (observation: UnsequencedExecutionObservation) => void\n recordModelCallInvocation: () => void\n path: ModelProxyPath\n request: ExternalOptimizerChatRequest\n /** Anthropic-wire SSE request; the stream is synthesized after completion. */\n anthropicStream?: boolean\n model: string\n /** True when the proxy's servedModelPolicy is 'allow-within-family'. */\n allowWithinFamily: boolean\n maxOutputTokens: number\n /** Enforced only when the caller declared a thinking budget. */\n maxReasoningTokens?: number\n maxResponseBytes: number\n signal: AbortSignal\n}): Promise<ProviderProxyResponse> {\n args.recordModelCallInvocation()\n let called: Awaited<ReturnType<ExternalOptimizerModelCall>>\n try {\n called = await args.call({\n callId: args.callId,\n request: freezeJsonSnapshot(\n args.request,\n 'optimizer model canonical request',\n ) as ExternalOptimizerChatRequest,\n endpointFormat: endpointFormat(args.path),\n signal: args.signal,\n })\n } catch (error) {\n throw new MissingModelExecutionError(\n `optimizer model callback rejected without execution evidence: ${toErrorMessage(error)}`,\n )\n }\n if (!called || typeof called !== 'object' || typeof called.succeeded !== 'boolean') {\n throw new MissingModelExecutionError(\n 'optimizer model callback returned no typed success/failure outcome',\n )\n }\n let execution: unknown\n try {\n execution = freezeJsonSnapshot(called.execution, 'optimizer model callback execution evidence')\n } catch (error) {\n throw new MissingModelExecutionError(\n `optimizer model callback returned invalid execution evidence: ${toErrorMessage(error)}`,\n )\n }\n if (called.succeeded) {\n let authoritativeReceipt: CostReceiptInput\n let canonicalResponse: ChatResponse\n try {\n authoritativeReceipt = snapshotModelReceipt(\n called.receipt,\n args.model,\n args.allowWithinFamily,\n )\n canonicalResponse = snapshotChatResponse(called.response, args.model, args.allowWithinFamily)\n assertResponseUsageMatchesReceipt(canonicalResponse, authoritativeReceipt)\n } catch (error) {\n args.recordExecutionReceipt({\n callId: args.callId,\n callRef: args.callRef,\n path: args.path,\n model: args.model,\n succeeded: false,\n error: toErrorMessage(error),\n execution,\n })\n throw error\n }\n args.recordExecutionReceipt({\n callId: args.callId,\n callRef: args.callRef,\n path: args.path,\n model: args.model,\n succeeded: true,\n responseStatus: 200,\n execution,\n })\n // Output tokens include the reasoning subset. The child's requested\n // completion limit governs visible completion tokens, while the separately\n // declared reasoning budget governs thinking tokens.\n const usageKnown = canonicalResponse.usage.captured !== false\n const reasoningTokens = canonicalResponse.usage.reasoningTokens ?? 0\n const completionTokens = canonicalResponse.usage.completionTokens - reasoningTokens\n const usageRejected =\n usageKnown && completionTokens > args.maxOutputTokens\n ? `optimizer model execution reported ${completionTokens} completion tokens, exceeding requested limit ${args.maxOutputTokens}`\n : usageKnown &&\n args.maxReasoningTokens !== undefined &&\n reasoningTokens > args.maxReasoningTokens\n ? `optimizer model execution reported ${reasoningTokens} reasoning tokens, exceeding the declared budget ${args.maxReasoningTokens}`\n : undefined\n const encoded =\n args.path === '/v1/messages'\n ? encodeAnthropicResponseBody({\n callId: args.callId,\n response: canonicalResponse,\n stream: args.anthropicStream === true,\n maxBytes: args.maxResponseBytes,\n })\n : {\n contentType: 'application/json',\n body: encodeCanonicalModelResponse({\n path: args.path,\n callId: args.callId,\n response: canonicalResponse,\n receipt: authoritativeReceipt,\n maxBytes: args.maxResponseBytes,\n }),\n }\n return {\n status: 200,\n contentType: encoded.contentType,\n body: encoded.body,\n receipt: authoritativeReceipt,\n usageComplete: authoritativeReceipt.usageUnknown !== true,\n ...(usageRejected ? { usageRejected } : {}),\n }\n } else {\n if (typeof called.error !== 'string' || !called.error.trim()) {\n throw new MissingModelExecutionError(\n 'optimizer model callback failure did not return a public error',\n )\n }\n args.recordExecutionReceipt({\n callId: args.callId,\n callRef: args.callRef,\n path: args.path,\n model: args.model,\n succeeded: false,\n error: called.error,\n execution,\n })\n const failedReceipt = snapshotModelReceipt(called.receipt, args.model, args.allowWithinFamily)\n return {\n status: 502,\n contentType: 'application/json',\n body: new TextEncoder().encode(JSON.stringify({ error: called.error })),\n receipt: failedReceipt,\n usageComplete: failedReceipt.usageUnknown !== true,\n modelCallFailed: called.error,\n }\n }\n}\n\nfunction snapshotModelReceipt(\n value: CostReceiptInput,\n expectedModel: string,\n allowWithinFamily: boolean,\n): CostReceiptInput {\n let snapshot: CostReceiptInput\n try {\n assertJsonValue(value, 'optimizer model callback receipt')\n snapshot = JSON.parse(canonicalJson(value)) as CostReceiptInput\n } catch (error) {\n throw new OwnerModelContractError(\n `optimizer model callback returned an invalid receipt: ${toErrorMessage(error)}`,\n )\n }\n assertServedModel(expectedModel, snapshot.model, {\n context: 'optimizer model callback receipt',\n allowWithinFamily,\n })\n return snapshot\n}\n\nfunction freezeJsonSnapshot(value: unknown, label: string): unknown {\n assertJsonValue(value, label)\n return deepFreezeJson(JSON.parse(canonicalJson(value)))\n}\n\nfunction deepFreezeJson(value: unknown): unknown {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) deepFreezeJson(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction assertResponseUsageMatchesReceipt(\n response: ChatResponse,\n receipt: CostReceiptInput,\n): void {\n if (response.model !== receipt.model) {\n throw new OwnerModelContractError(\n 'optimizer model response and execution receipt disagree about the served model',\n )\n }\n if (response.usage.captured === false || receipt.usageUnknown === true) {\n if (response.usage.captured !== false || receipt.usageUnknown !== true) {\n throw new OwnerModelContractError(\n 'optimizer model response and execution receipt disagree about whether usage was captured',\n )\n }\n } else {\n const cachedTokens = response.usage.cachedPromptTokens ?? 0\n if (receipt.inputTokens + (receipt.cachedTokens ?? 0) !== response.usage.promptTokens) {\n throw new OwnerModelContractError(\n 'optimizer model response promptTokens must equal receipt inputTokens plus cachedTokens',\n )\n }\n if (cachedTokens !== (receipt.cachedTokens ?? 0)) {\n throw new OwnerModelContractError(\n 'optimizer model response cachedPromptTokens disagrees with the execution receipt',\n )\n }\n if (response.usage.completionTokens !== receipt.outputTokens) {\n throw new OwnerModelContractError(\n 'optimizer model response completionTokens disagrees with the execution receipt',\n )\n }\n if ((response.usage.reasoningTokens ?? 0) !== (receipt.reasoningTokens ?? 0)) {\n throw new OwnerModelContractError(\n 'optimizer model response reasoningTokens disagrees with the execution receipt',\n )\n }\n }\n const receiptCostUsd =\n receipt.actualCostUsd ??\n receipt.estimatedCostUsd ??\n (receipt.customTokenPricing && receipt.usageUnknown !== true\n ? costForTokenPricing(receipt.customTokenPricing, receipt)\n : null)\n if (response.costUsd !== receiptCostUsd) {\n throw new OwnerModelContractError(\n 'optimizer model response billed cost disagrees with the execution receipt',\n )\n }\n}\n\nfunction parseModelProxyRequest(\n body: Uint8Array,\n path: ModelProxyPath,\n expectedModel: string,\n budget: ExternalOptimizerModelBudget,\n): {\n maxOutputTokens: number\n request: ExternalOptimizerChatRequest\n stream?: boolean\n /** Anthropic control fields the translation dropped, disclosed in ledger tags. */\n strippedFields?: readonly string[]\n} {\n if (path === '/v1/messages') {\n const translated = translateAnthropicMessagesRequest(\n body,\n expectedModel,\n budget.maxOutputTokensPerRequest,\n )\n return {\n maxOutputTokens: translated.maxOutputTokens,\n stream: translated.stream,\n ...(translated.strippedFields.length > 0\n ? { strippedFields: translated.strippedFields }\n : {}),\n request: freezeJsonSnapshot(\n translated.request,\n 'optimizer model canonical request',\n ) as ExternalOptimizerChatRequest,\n }\n }\n let value: unknown\n try {\n value = JSON.parse(Buffer.from(body).toString('utf8'))\n } catch {\n throw new Error('optimizer model request must be valid JSON')\n }\n if (!isRecord(value)) throw new Error('optimizer model request must be a JSON object')\n if (value.model !== expectedModel) {\n throw new Error(`optimizer model request must use configured model '${expectedModel}'`)\n }\n if (value.stream !== undefined && value.stream !== false) {\n throw new Error('streaming optimizer model requests are not supported')\n }\n for (const field of ['n', 'best_of', 'candidate_count', 'num_candidates'] as const) {\n if (value[field] !== undefined && value[field] !== 1) {\n throw new Error(`optimizer model request ${field} must be 1 when supplied`)\n }\n }\n if (value.reasoning !== undefined || value.reasoning_effort !== undefined) {\n throw new Error('optimizer model reasoning settings belong to the execution AgentProfile')\n }\n const maxOutputTokens = parseOutputMaximum(\n value,\n path === '/v1/responses'\n ? ['max_output_tokens']\n : ['max_tokens', 'max_completion_tokens', 'max_output_tokens'],\n )\n if (maxOutputTokens > budget.maxOutputTokensPerRequest) {\n throw new Error('optimizer model request exceeds maxOutputTokensPerRequest')\n }\n const request =\n path === '/v1/chat/completions'\n ? parseChatCompletionsRequest(value, expectedModel, maxOutputTokens)\n : parseResponsesRequest(value, expectedModel, maxOutputTokens)\n return {\n maxOutputTokens,\n request: freezeJsonSnapshot(\n request,\n 'optimizer model canonical request',\n ) as ExternalOptimizerChatRequest,\n }\n}\n\nfunction parseChatCompletionsRequest(\n body: Record<string, unknown>,\n model: string,\n maxTokens: number,\n): Omit<ExternalOptimizerChatRequest, never> {\n assertAllowedKeys(body, [\n 'model',\n 'messages',\n 'max_tokens',\n 'max_completion_tokens',\n 'max_output_tokens',\n 'temperature',\n 'thinking',\n 'response_format',\n 'stream',\n 'n',\n 'best_of',\n 'candidate_count',\n 'num_candidates',\n ])\n return {\n model,\n messages: parseChatMessages(body.messages),\n maxTokens,\n ...parseTemperature(body.temperature),\n ...parseThinking(body.thinking),\n ...parseChatResponseFormat(body.response_format),\n }\n}\n\nfunction parseResponsesRequest(\n body: Record<string, unknown>,\n model: string,\n maxTokens: number,\n): Omit<ExternalOptimizerChatRequest, never> {\n assertAllowedKeys(body, [\n 'model',\n 'input',\n 'instructions',\n 'max_output_tokens',\n 'temperature',\n 'thinking',\n 'text',\n 'stream',\n 'n',\n 'best_of',\n 'candidate_count',\n 'num_candidates',\n ])\n const instructions = body.instructions\n if (instructions !== undefined && typeof instructions !== 'string') {\n throw new Error('optimizer Responses instructions must be a string')\n }\n return {\n model,\n messages: [\n ...(instructions === undefined ? [] : [{ role: 'system' as const, content: instructions }]),\n ...parseResponsesInput(body.input),\n ],\n maxTokens,\n ...parseTemperature(body.temperature),\n ...parseThinking(body.thinking),\n ...parseResponsesTextFormat(body.text),\n }\n}\n\nfunction parseOutputMaximum(body: Record<string, unknown>, fields: readonly string[]): number {\n const supplied = fields.flatMap((field) =>\n body[field] === undefined ? [] : [{ field, value: body[field] }],\n )\n if (\n supplied.length === 0 ||\n supplied.some(({ value }) => !Number.isSafeInteger(value) || (value as number) <= 0)\n ) {\n throw new Error('optimizer model request requires a positive output-token limit')\n }\n const values = new Set(supplied.map(({ value }) => value as number))\n if (values.size !== 1) {\n throw new Error('optimizer model request supplied conflicting output-token limits')\n }\n return supplied[0]!.value as number\n}\n\nfunction parseTemperature(value: unknown): { temperature?: number } {\n if (value === undefined) return {}\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error('optimizer model request temperature must be finite')\n }\n return { temperature: value }\n}\n\nfunction parseThinking(value: unknown): { thinking?: 'enabled' | 'disabled' } {\n if (value === undefined) return {}\n if (!isRecord(value)) {\n throw new Error('optimizer model request thinking must be an object')\n }\n assertAllowedKeys(value, ['type'], 'optimizer model request thinking')\n if (value.type !== 'enabled' && value.type !== 'disabled') {\n throw new Error('optimizer model request thinking.type must be enabled or disabled')\n }\n return { thinking: value.type }\n}\n\nfunction parseChatMessages(value: unknown): ExternalOptimizerChatRequest['messages'] {\n if (!Array.isArray(value)) throw new Error('optimizer chat request messages must be an array')\n return value.map((message, index) => parseMessage(message, `optimizer chat message ${index}`))\n}\n\nfunction parseResponsesInput(value: unknown): ExternalOptimizerChatRequest['messages'] {\n if (typeof value === 'string') return [{ role: 'user', content: value }]\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error('optimizer Responses request requires non-empty input')\n }\n return value.map((message, index) => {\n if (!isRecord(message)) {\n throw new Error(`optimizer Responses input ${index} must be a message object`)\n }\n assertAllowedKeys(message, ['type', 'role', 'content'], `optimizer Responses input ${index}`)\n if (message.type !== undefined && message.type !== 'message') {\n throw new Error(`optimizer Responses input ${index} type must be message`)\n }\n return parseMessage(message, `optimizer Responses input ${index}`, true)\n })\n}\n\nfunction parseMessage(\n value: unknown,\n label: string,\n responsesContent = false,\n): ExternalOptimizerChatRequest['messages'][number] {\n if (!isRecord(value)) throw new Error(`${label} must be an object`)\n assertAllowedKeys(\n value,\n responsesContent ? ['type', 'role', 'content'] : ['role', 'content'],\n label,\n )\n if (value.role !== 'system' && value.role !== 'user' && value.role !== 'assistant') {\n throw new Error(`${label} role must be system, user, or assistant`)\n }\n return {\n role: value.role,\n content: parseMessageContent(value.content, label, responsesContent),\n }\n}\n\nfunction parseMessageContent(\n value: unknown,\n label: string,\n responsesContent: boolean,\n): ExternalOptimizerChatRequest['messages'][number]['content'] {\n if (typeof value === 'string') return value\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error(`${label} content must be text or a non-empty content array`)\n }\n return value.map((part, partIndex) => {\n if (!isRecord(part)) throw new Error(`${label} content ${partIndex} must be an object`)\n const partLabel = `${label} content ${partIndex}`\n if (part.type === 'text' || (responsesContent && part.type === 'input_text')) {\n assertAllowedKeys(part, ['type', 'text'], partLabel)\n if (typeof part.text !== 'string') throw new Error(`${partLabel} text must be a string`)\n return { type: 'text' as const, text: part.text }\n }\n if (responsesContent && part.type === 'output_text') {\n assertAllowedKeys(part, ['type', 'text'], partLabel)\n if (typeof part.text !== 'string') throw new Error(`${partLabel} text must be a string`)\n return { type: 'text' as const, text: part.text }\n }\n if (part.type === 'image_url') {\n assertAllowedKeys(part, ['type', 'image_url'], partLabel)\n if (!isRecord(part.image_url) || typeof part.image_url.url !== 'string') {\n throw new Error(`${partLabel} image_url must contain a URL string`)\n }\n assertAllowedKeys(part.image_url, ['url', 'detail'], `${partLabel} image_url`)\n const detail = parseImageDetail(part.image_url.detail, partLabel)\n return { type: 'image_url' as const, image_url: { url: part.image_url.url, ...detail } }\n }\n if (responsesContent && part.type === 'input_image') {\n assertAllowedKeys(part, ['type', 'image_url', 'detail'], partLabel)\n if (typeof part.image_url !== 'string') {\n throw new Error(`${partLabel} image_url must be a URL string`)\n }\n const detail = parseImageDetail(part.detail, partLabel)\n return { type: 'image_url' as const, image_url: { url: part.image_url, ...detail } }\n }\n throw new Error(`${partLabel} uses an unsupported content type`)\n })\n}\n\nfunction parseImageDetail(value: unknown, label: string): { detail?: 'auto' | 'low' | 'high' } {\n if (value === undefined) return {}\n if (value !== 'auto' && value !== 'low' && value !== 'high') {\n throw new Error(`${label} image detail must be auto, low, or high`)\n }\n return { detail: value }\n}\n\nfunction parseChatResponseFormat(\n value: unknown,\n): Pick<ExternalOptimizerChatRequest, 'jsonMode' | 'jsonSchema'> {\n if (value === undefined) return {}\n if (!isRecord(value) || typeof value.type !== 'string') {\n throw new Error('optimizer chat response_format must be an object with a type')\n }\n if (value.type === 'text') {\n assertAllowedKeys(value, ['type'], 'optimizer chat response_format')\n return {}\n }\n if (value.type === 'json_object') {\n assertAllowedKeys(value, ['type'], 'optimizer chat response_format')\n return { jsonMode: true }\n }\n if (value.type !== 'json_schema') {\n throw new Error('optimizer chat response_format type is unsupported')\n }\n assertAllowedKeys(value, ['type', 'json_schema'], 'optimizer chat response_format')\n return { jsonSchema: parseJsonSchema(value.json_schema, 'optimizer chat response_format') }\n}\n\nfunction parseResponsesTextFormat(\n value: unknown,\n): Pick<ExternalOptimizerChatRequest, 'jsonMode' | 'jsonSchema'> {\n if (value === undefined) return {}\n if (!isRecord(value)) throw new Error('optimizer Responses text must be an object')\n assertAllowedKeys(value, ['format'], 'optimizer Responses text')\n if (value.format === undefined) return {}\n if (!isRecord(value.format) || typeof value.format.type !== 'string') {\n throw new Error('optimizer Responses text.format must be an object with a type')\n }\n const format = value.format\n if (format.type === 'text') {\n assertAllowedKeys(format, ['type'], 'optimizer Responses text.format')\n return {}\n }\n if (format.type === 'json_object') {\n assertAllowedKeys(format, ['type'], 'optimizer Responses text.format')\n return { jsonMode: true }\n }\n if (format.type !== 'json_schema') {\n throw new Error('optimizer Responses text.format type is unsupported')\n }\n return { jsonSchema: parseJsonSchema(format, 'optimizer Responses text.format', true) }\n}\n\nfunction parseJsonSchema(\n value: unknown,\n label: string,\n flat = false,\n): { name: string; schema: Record<string, unknown> } {\n if (!isRecord(value)) throw new Error(`${label} JSON schema must be an object`)\n assertAllowedKeys(value, ['name', 'schema', 'strict', ...(flat ? ['type'] : [])], label)\n if (typeof value.name !== 'string' || !value.name.trim()) {\n throw new Error(`${label} JSON schema name must be non-empty`)\n }\n if (!isRecord(value.schema)) throw new Error(`${label} JSON schema body must be an object`)\n if (value.strict !== undefined && value.strict !== true) {\n throw new Error(`${label} JSON schema strict must be true when supplied`)\n }\n return {\n name: value.name,\n schema: freezeJsonSnapshot(value.schema, `${label} schema`) as Record<string, unknown>,\n }\n}\n\nfunction assertAllowedKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n label = 'optimizer model request',\n): void {\n const allowedSet = new Set(allowed)\n const unknown = Object.keys(value).filter((key) => !allowedSet.has(key))\n if (unknown.length > 0)\n throw new Error(`${label} contains unsupported fields: ${unknown.join(', ')}`)\n}\n\nfunction snapshotChatResponse(\n value: unknown,\n expectedModel: string,\n allowWithinFamily: boolean,\n): ChatResponse {\n if (!isRecord(value)) {\n throw new OwnerModelContractError('optimizer model callback response must be an object')\n }\n if (typeof value.content !== 'string') {\n throw new OwnerModelContractError('optimizer model callback response content must be a string')\n }\n assertServedModel(expectedModel, typeof value.model === 'string' ? value.model : null, {\n context: 'optimizer model callback response',\n allowWithinFamily,\n })\n if (!isNonnegativeFiniteNumber(value.durationMs)) {\n throw new OwnerModelContractError(\n 'optimizer model callback response durationMs must be finite and non-negative',\n )\n }\n if (value.costUsd !== null && !isNonnegativeFiniteNumber(value.costUsd)) {\n throw new OwnerModelContractError(\n 'optimizer model callback response costUsd must be null or finite and non-negative',\n )\n }\n if (\n value.finishReason !== undefined &&\n value.finishReason !== null &&\n typeof value.finishReason !== 'string'\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response finishReason must be a string or null',\n )\n }\n const toolCalls = snapshotResponseToolCalls(value.toolCalls)\n if (\n value.contentEmpty !== undefined &&\n (typeof value.contentEmpty !== 'boolean' ||\n value.contentEmpty !== (value.content.trim().length === 0))\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response contentEmpty must match content',\n )\n }\n if (!isRecord(value.raw)) {\n throw new OwnerModelContractError('optimizer model callback response raw must be an object')\n }\n if (!isRecord(value.usage)) {\n throw new OwnerModelContractError('optimizer model callback response usage must be an object')\n }\n const usage = value.usage\n for (const field of ['promptTokens', 'completionTokens', 'totalTokens'] as const) {\n if (!isNonnegativeSafeInteger(usage[field])) {\n throw new OwnerModelContractError(\n `optimizer model callback response usage.${field} must be a non-negative safe integer`,\n )\n }\n }\n const promptTokens = usage.promptTokens as number\n const completionTokens = usage.completionTokens as number\n const totalTokens = usage.totalTokens as number\n if (totalTokens !== promptTokens + completionTokens) {\n throw new OwnerModelContractError(\n 'optimizer model callback response totalTokens must equal promptTokens plus completionTokens',\n )\n }\n if (usage.captured !== undefined && typeof usage.captured !== 'boolean') {\n throw new OwnerModelContractError(\n 'optimizer model callback response usage.captured must be a boolean',\n )\n }\n if (\n usage.cachedPromptTokens !== undefined &&\n (!isNonnegativeSafeInteger(usage.cachedPromptTokens) || usage.cachedPromptTokens > promptTokens)\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response cachedPromptTokens must be a subset of promptTokens',\n )\n }\n if (\n usage.reasoningTokens !== undefined &&\n (!isNonnegativeSafeInteger(usage.reasoningTokens) || usage.reasoningTokens > completionTokens)\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response reasoningTokens must be a subset of completionTokens',\n )\n }\n let raw: Record<string, unknown>\n try {\n raw = freezeJsonSnapshot(\n value.raw,\n 'optimizer model callback canonical response.raw',\n ) as Record<string, unknown>\n } catch (error) {\n throw new OwnerModelContractError(\n `optimizer model callback returned invalid raw response evidence: ${toErrorMessage(error)}`,\n )\n }\n return deepFreezeJson({\n content: value.content,\n ...(toolCalls === undefined ? {} : { toolCalls }),\n usage: {\n promptTokens,\n completionTokens,\n totalTokens,\n ...(usage.captured === undefined ? {} : { captured: usage.captured }),\n ...(usage.reasoningTokens === undefined ? {} : { reasoningTokens: usage.reasoningTokens }),\n ...(usage.cachedPromptTokens === undefined\n ? {}\n : { cachedPromptTokens: usage.cachedPromptTokens }),\n },\n costUsd: value.costUsd,\n model: value.model,\n durationMs: value.durationMs,\n ...(value.finishReason === undefined ? {} : { finishReason: value.finishReason }),\n ...(value.contentEmpty === undefined ? {} : { contentEmpty: value.contentEmpty }),\n raw,\n }) as ChatResponse\n}\n\n/** Snapshot the owner's canonical tool calls onto the allowlisted response. */\nfunction snapshotResponseToolCalls(\n value: unknown,\n): Array<{ id: string; name: string; argumentsJson: string }> | undefined {\n if (value === undefined) return undefined\n if (!Array.isArray(value) || value.length === 0) {\n throw new OwnerModelContractError(\n 'optimizer model callback response toolCalls must be a non-empty array when present',\n )\n }\n return value.map((entry) => {\n if (\n !isRecord(entry) ||\n typeof entry.id !== 'string' ||\n !entry.id ||\n typeof entry.name !== 'string' ||\n !entry.name ||\n typeof entry.argumentsJson !== 'string'\n ) {\n throw new OwnerModelContractError(\n 'optimizer model callback response toolCalls entries require string id, name, and argumentsJson',\n )\n }\n return { id: entry.id, name: entry.name, argumentsJson: entry.argumentsJson }\n })\n}\n\nfunction encodeAnthropicResponseBody(args: {\n callId: string\n response: ChatResponse\n stream: boolean\n maxBytes: number\n}): { contentType: string; body: Uint8Array } {\n const message = encodeAnthropicMessage(args.response, args.callId)\n const body = new TextEncoder().encode(\n args.stream ? renderAnthropicSseStream(message) : JSON.stringify(message),\n )\n if (body.byteLength > args.maxBytes) throw new ProviderResponseTooLargeError()\n return {\n contentType: args.stream ? 'text/event-stream; charset=utf-8' : 'application/json',\n body,\n }\n}\n\nfunction encodeCanonicalModelResponse(args: {\n path: '/v1/chat/completions' | '/v1/responses'\n callId: string\n response: ChatResponse\n receipt: CostReceiptInput\n maxBytes: number\n}): Uint8Array {\n const usage = encodeProtocolUsage(args.path, args.response, args.receipt)\n const finishReason =\n args.response.finishReason === undefined ? 'stop' : args.response.finishReason\n const body =\n args.path === '/v1/chat/completions'\n ? {\n id: `chatcmpl-${args.callId}`,\n object: 'chat.completion',\n created: 0,\n model: args.response.model,\n choices: [\n {\n index: 0,\n message: { role: 'assistant', content: args.response.content },\n finish_reason: finishReason,\n },\n ],\n ...(usage ? { usage } : {}),\n }\n : {\n id: `resp-${args.callId}`,\n object: 'response',\n created_at: 0,\n model: args.response.model,\n status: finishReason === 'length' ? 'incomplete' : 'completed',\n error: null,\n incomplete_details: finishReason === 'length' ? { reason: 'max_output_tokens' } : null,\n output: [\n {\n id: `msg-${args.callId}`,\n type: 'message',\n status: finishReason === 'length' ? 'incomplete' : 'completed',\n role: 'assistant',\n content: [\n {\n type: 'output_text',\n text: args.response.content,\n annotations: [],\n },\n ],\n },\n ],\n output_text: args.response.content,\n ...(usage ? { usage } : {}),\n }\n const encoded = new TextEncoder().encode(JSON.stringify(body))\n if (encoded.byteLength > args.maxBytes) throw new ProviderResponseTooLargeError()\n return encoded\n}\n\nfunction endpointFormat(path: ModelProxyPath): ExternalOptimizerEndpointFormat {\n if (path === '/v1/messages') return 'anthropic-messages'\n return path === '/v1/responses' ? 'responses' : 'chat-completions'\n}\n\nfunction encodeProtocolUsage(\n path: '/v1/chat/completions' | '/v1/responses',\n response: ChatResponse,\n receipt: CostReceiptInput,\n): Record<string, unknown> | undefined {\n if (response.usage.captured === false) return undefined\n const inputDetails = {\n ...(receipt.cachedTokens === undefined ? {} : { cached_tokens: receipt.cachedTokens }),\n ...(receipt.cacheWriteTokens === undefined\n ? {}\n : path === '/v1/chat/completions'\n ? { cache_creation_tokens: receipt.cacheWriteTokens }\n : { cache_write_tokens: receipt.cacheWriteTokens }),\n }\n const outputDetails = {\n ...(receipt.reasoningTokens === undefined ? {} : { reasoning_tokens: receipt.reasoningTokens }),\n }\n return path === '/v1/chat/completions'\n ? {\n prompt_tokens: response.usage.promptTokens,\n completion_tokens: response.usage.completionTokens,\n total_tokens: response.usage.totalTokens,\n ...(Object.keys(inputDetails).length > 0 ? { prompt_tokens_details: inputDetails } : {}),\n ...(Object.keys(outputDetails).length > 0\n ? { completion_tokens_details: outputDetails }\n : {}),\n ...(receipt.actualCostUsd === undefined ? {} : { cost: receipt.actualCostUsd }),\n }\n : {\n input_tokens: response.usage.promptTokens,\n output_tokens: response.usage.completionTokens,\n total_tokens: response.usage.totalTokens,\n ...(Object.keys(inputDetails).length > 0 ? { input_tokens_details: inputDetails } : {}),\n ...(Object.keys(outputDetails).length > 0 ? { output_tokens_details: outputDetails } : {}),\n ...(receipt.actualCostUsd === undefined ? {} : { cost: receipt.actualCostUsd }),\n }\n}\n\nfunction isNonnegativeFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\nfunction isNonnegativeSafeInteger(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0\n}\n\nfunction conservativeMaximumUsage(\n inputTokenUpperBound: number,\n outputTokenUpperBound: number,\n pricing?: CustomTokenPricing,\n): Pick<CostReceiptInput, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'> {\n if (pricing === undefined) {\n return { inputTokens: inputTokenUpperBound, outputTokens: outputTokenUpperBound }\n }\n const inputRates = [\n pricing.inputUsdPerMillion,\n pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion,\n ]\n const mostExpensiveInputClass = inputRates.indexOf(Math.max(...inputRates))\n return {\n inputTokens: mostExpensiveInputClass === 0 ? inputTokenUpperBound : 0,\n ...(mostExpensiveInputClass === 1 ? { cachedTokens: inputTokenUpperBound } : {}),\n // Cache creation is a separately billed class in CostReceipt. Reserve a\n // full request-sized write in addition to the most expensive prompt class;\n // selecting only one class would understate a call that both reads and writes.\n cacheWriteTokens: inputTokenUpperBound,\n outputTokens: outputTokenUpperBound,\n }\n}\n\nfunction assertModelProxyConfig(args: {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n servedModelPolicy?: ServedModelPolicy\n phase: string\n actor: string\n tags?: Record<string, string>\n callId?: string\n initialUsage?: {\n requests: number\n costUsd?: number\n }\n}): void {\n assertServedModelPolicy(\n args.servedModelPolicy,\n 'external optimizer model proxy: servedModelPolicy',\n )\n for (const [label, value] of [\n ['model', args.model],\n ['phase', args.phase],\n ['actor', args.actor],\n ] as const) {\n if (typeof value !== 'string' || !value.trim() || value.trim() !== value) {\n throw new Error(`external optimizer model proxy: ${label} must be trimmed and non-empty`)\n }\n }\n if (typeof args.call !== 'function') {\n throw new Error('external optimizer model proxy: call must be a function')\n }\n if (\n typeof args.callRef !== 'string' ||\n !args.callRef.trim() ||\n args.callRef.trim() !== args.callRef\n ) {\n throw new Error('external optimizer model proxy: callRef must be trimmed and non-empty')\n }\n if (typeof args.recordExecution !== 'function') {\n throw new Error('external optimizer model proxy: recordExecution must be a function')\n }\n if (args.callId !== undefined) {\n if (\n typeof args.callId !== 'string' ||\n !args.callId.trim() ||\n args.callId !== args.callId.trim()\n ) {\n throw new Error('external optimizer model proxy: callId must be trimmed and non-empty')\n }\n if (args.budget.maxRequests !== 1) {\n throw new Error('external optimizer model proxy: callId requires budget.maxRequests to be 1')\n }\n }\n assertExternalOptimizerModelBudget(args.budget, 'external optimizer model proxy: budget')\n if (args.tags !== undefined) {\n for (const [key, value] of Object.entries(args.tags)) {\n if (!key.trim() || key.trim() !== key || !value.trim() || value.trim() !== value) {\n throw new Error('external optimizer model proxy: tags must be trimmed and non-empty')\n }\n }\n }\n if (args.initialUsage !== undefined) {\n if (\n !Number.isSafeInteger(args.initialUsage.requests) ||\n args.initialUsage.requests < 0 ||\n (args.initialUsage.costUsd !== undefined &&\n (!Number.isFinite(args.initialUsage.costUsd) || args.initialUsage.costUsd < 0))\n ) {\n throw new Error(\n 'external optimizer model proxy: initialUsage must contain non-negative requests and cost',\n )\n }\n if (\n args.initialUsage.requests > args.budget.maxRequests ||\n (args.budget.maxCostUsd !== undefined &&\n args.initialUsage.costUsd !== undefined &&\n args.initialUsage.costUsd > args.budget.maxCostUsd + Number.EPSILON)\n ) {\n throw new Error('external optimizer model proxy: initialUsage exceeds the configured budget')\n }\n }\n}\n\nclass RequestBodyTooLargeError extends Error {}\n\nclass ProviderResponseTooLargeError extends Error {\n constructor() {\n super('optimizer model response exceeds maxResponseBytes')\n }\n}\n\nclass MissingModelExecutionError extends Error {}\nclass ModelExecutionPersistenceError extends Error {}\nclass OwnerModelContractError extends Error {}\n\nfunction readBody(request: IncomingMessage, maximumBytes: number): Promise<Uint8Array> {\n return new Promise((resolvePromise, reject) => {\n let size = 0\n let tooLarge = false\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n if (tooLarge) return\n size += chunk.byteLength\n if (size > maximumBytes) {\n tooLarge = true\n chunks.length = 0\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n if (tooLarge) {\n reject(new RequestBodyTooLargeError('optimizer model request body too large'))\n return\n }\n resolvePromise(new Uint8Array(Buffer.concat(chunks)))\n })\n })\n}\n\nfunction randomLocalToken(): string {\n return randomBytes(32).toString('hex')\n}\n\nfunction isAbortError(error: Error): boolean {\n return error.name === 'AbortError' || error.message.toLowerCase().includes('abort')\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import type {\n ExternalOptimizerCallback,\n ExternalOptimizerModelProxy,\n} from './external-optimizer-contracts'\n\nexport async function runWithCleanup<T>(args: {\n label: string\n run: () => Promise<T>\n cleanup: () => Promise<void>\n}): Promise<T> {\n let value: T | undefined\n let operationError: Error | undefined\n try {\n value = await args.run()\n } catch (cause) {\n operationError = toError(cause)\n }\n\n let cleanupError: Error | undefined\n try {\n await args.cleanup()\n } catch (cause) {\n cleanupError = toError(cause)\n }\n\n if (operationError && cleanupError) {\n throw new AggregateError(\n [operationError, cleanupError],\n `${operationError.message}; ${args.label} cleanup failed: ${cleanupError.message}`,\n )\n }\n if (operationError) throw operationError\n if (cleanupError) {\n throw new Error(`${args.label} cleanup failed: ${cleanupError.message}`, {\n cause: cleanupError,\n })\n }\n return value as T\n}\n\nexport async function closeExternalOptimizerResources(args: {\n label: string\n callback: ExternalOptimizerCallback\n modelProxy?: ExternalOptimizerModelProxy\n}): Promise<void> {\n const results = await Promise.allSettled([\n ...(args.modelProxy ? [args.modelProxy.close()] : []),\n args.callback.close(),\n ])\n const errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []))\n if (errors.length > 0) {\n throw new AggregateError(errors, `${args.label}: failed to close optimizer resources`)\n }\n}\n\nfunction toError(cause: unknown): Error {\n return cause instanceof Error ? cause : new Error(String(cause))\n}\n","import { type ChildProcess, spawn } from 'node:child_process'\nimport { lstat, mkdtemp, open, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport {\n type ExternalOptimizerRunnerCommand,\n isRecord,\n resolveExternalOptimizerProcessLimits,\n} from './external-optimizer-contracts'\nimport { runWithCleanup } from './external-optimizer-resources'\n\nconst PROCESS_TERMINATION_GRACE_MS = 5_000\nconst PROCESS_TERMINATION_POLL_MS = 25\nconst PROCESS_KILL_WAIT_MS = 1_000\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\ninterface ProcessOutputCapture {\n full: string | undefined\n head: string\n tail: string\n totalChars: number\n}\n\nexport async function runExternalOptimizerProcess<TOutput>(args: {\n label: string\n tempPrefix: string\n module: string\n input: unknown\n runner?: ExternalOptimizerRunnerCommand\n /** Additional bridge arguments inserted before --input/--output. */\n additionalArgs?: readonly string[]\n timeoutMs: number\n signal?: AbortSignal\n}): Promise<TOutput> {\n if (\n !Number.isSafeInteger(args.timeoutMs) ||\n args.timeoutMs <= 0 ||\n args.timeoutMs > MAX_TIMER_DELAY_MS\n ) {\n throw new Error(`${args.label} timeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n const limits = resolveExternalOptimizerProcessLimits(args.runner?.limits)\n if (process.platform === 'win32') {\n throw new Error(\n `${args.label} requires POSIX process-group cleanup; run the optimizer through WSL or Linux`,\n )\n }\n throwIfAborted(args.signal, args.label)\n const dir = await mkdtemp(join(tmpdir(), args.tempPrefix))\n const inputPath = join(dir, 'input.json')\n const outputPath = join(dir, 'output.json')\n return runWithCleanup({\n label: `${args.label} temporary directory`,\n run: async () => {\n const serializedInput = JSON.stringify(args.input)\n if (serializedInput === undefined) {\n throw new Error(`${args.label} input must be JSON-serializable`)\n }\n const inputJson = `${serializedInput}\\n`\n const inputBytes = Buffer.byteLength(inputJson)\n if (inputBytes > limits.maxInputBytes) {\n throw new Error(`${args.label} input exceeds ${limits.maxInputBytes} bytes (${inputBytes})`)\n }\n await writeFile(inputPath, inputJson)\n const command = resolveRunnerCommand(args.runner?.command ?? 'python')\n const commandArgs = [\n ...(args.runner?.args ?? ['-m', args.module]),\n ...(args.additionalArgs ?? []),\n '--input',\n inputPath,\n '--output',\n outputPath,\n ]\n await runProcess({\n label: args.label,\n command,\n args: commandArgs,\n cwd: dir,\n env: args.runner?.env,\n timeoutMs: args.timeoutMs,\n maxOutputChars: limits.maxOutputChars,\n signal: args.signal,\n })\n throwIfAborted(args.signal, args.label)\n const raw = JSON.parse(\n await readBoundedTextFile(outputPath, limits.maxResultBytes, `${args.label} output`),\n ) as unknown\n throwIfAborted(args.signal, args.label)\n if (!isRecord(raw)) throw new Error(`${args.label} output must be a JSON object`)\n return raw as TOutput\n },\n cleanup: () => rm(dir, { recursive: true, force: true }),\n })\n}\n\nfunction resolveRunnerCommand(command: string): string {\n if (isAbsolute(command) || (!command.includes('/') && !command.includes('\\\\'))) return command\n return resolve(command)\n}\n\nasync function readBoundedTextFile(path: string, maxBytes: number, label: string): Promise<string> {\n const entry = await lstat(path)\n if (!entry.isFile()) throw new Error(`${label} must be a regular file`)\n const file = await open(path, 'r')\n try {\n const buffer = Buffer.allocUnsafe(maxBytes + 1)\n let bytesRead = 0\n while (bytesRead < buffer.byteLength) {\n const chunk = await file.read(buffer, bytesRead, buffer.byteLength - bytesRead, bytesRead)\n if (chunk.bytesRead === 0) break\n bytesRead += chunk.bytesRead\n }\n if (bytesRead > maxBytes) {\n throw new Error(`${label} exceeds ${maxBytes} bytes`)\n }\n return buffer.subarray(0, bytesRead).toString('utf8')\n } finally {\n await file.close()\n }\n}\n\nfunction runProcess(args: {\n label: string\n command: string\n args: string[]\n cwd: string | undefined\n env: NodeJS.ProcessEnv | undefined\n timeoutMs: number\n maxOutputChars: number\n signal: AbortSignal | undefined\n}): Promise<void> {\n throwIfAborted(args.signal, args.label)\n return new Promise((resolvePromise, reject) => {\n const child = spawn(args.command, args.args, {\n cwd: args.cwd,\n env: { ...safeProcessEnvironment(), ...args.env },\n stdio: ['ignore', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n const stdout = createProcessOutputCapture()\n const stderr = createProcessOutputCapture()\n let settled = false\n let timeout: NodeJS.Timeout | undefined\n const onAbort = () => finish(abortReason(args.signal!, args.label))\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n if (timeout) clearTimeout(timeout)\n args.signal?.removeEventListener('abort', onAbort)\n void terminateProcessTree(child).then(\n () => {\n if (error) reject(error)\n else resolvePromise()\n },\n (cleanupError: unknown) => {\n if (error) {\n const cleanup =\n cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError))\n reject(\n new AggregateError(\n [error, cleanup],\n `${error.message}; ${args.label} process cleanup failed: ${cleanup.message}`,\n ),\n )\n return\n }\n reject(\n new Error(\n `${args.label} process cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,\n ),\n )\n },\n )\n }\n timeout = setTimeout(() => {\n finish(new Error(`${args.label} exceeded ${args.timeoutMs}ms`))\n }, args.timeoutMs)\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n child.stdout.on('data', (chunk: Buffer) => {\n appendProcessOutput(stdout, chunk, args.maxOutputChars)\n })\n child.stderr.on('data', (chunk: Buffer) => {\n appendProcessOutput(stderr, chunk, args.maxOutputChars)\n })\n child.on('error', (error) => {\n finish(new Error(`${args.label} could not start: ${error.message}`))\n })\n child.on('close', (code) => {\n if (code === 0) {\n finish()\n return\n }\n finish(\n new Error(\n `${args.label} exited ${String(code)}. stderr=${summarizeProcessOutput(stderr)} stdout=${summarizeProcessOutput(stdout)}`,\n ),\n )\n })\n })\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined, label: string): void {\n if (signal?.aborted) throw abortReason(signal, label)\n}\n\nfunction abortReason(signal: AbortSignal, label: string): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new Error(`${label} aborted`, { cause: signal.reason })\n}\n\nfunction safeProcessEnvironment(): NodeJS.ProcessEnv {\n const allowed = [\n 'PATH',\n 'HOME',\n 'USER',\n 'LOGNAME',\n 'SHELL',\n 'TMPDIR',\n 'TMP',\n 'TEMP',\n 'LANG',\n 'LANGUAGE',\n 'LC_ALL',\n 'VIRTUAL_ENV',\n 'PYTHONPATH',\n 'SYSTEMROOT',\n 'COMSPEC',\n 'PATHEXT',\n 'WINDIR',\n ] as const\n return Object.fromEntries(\n allowed.flatMap((name) => {\n const value = process.env[name]\n return value === undefined ? [] : [[name, value]]\n }),\n )\n}\n\nasync function terminateProcessTree(child: ChildProcess): Promise<void> {\n const pid = child.pid\n if (!pid) return\n if (process.platform === 'win32') {\n throw new Error('native Windows process-tree cleanup is unsupported')\n }\n\n if (!signalProcessGroup(pid, 'SIGTERM')) return\n if (await waitForProcessGroupExit(pid, PROCESS_TERMINATION_GRACE_MS)) return\n if (!signalProcessGroup(pid, 'SIGKILL')) return\n if (await waitForProcessGroupExit(pid, PROCESS_KILL_WAIT_MS)) return\n throw new Error(`process group ${pid} remained alive after SIGKILL`)\n}\n\nfunction signalProcessGroup(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(-pid, signal)\n return true\n } catch (error) {\n if (isMissingProcessError(error)) return false\n throw error\n }\n}\n\nasync function waitForProcessGroupExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n while (processGroupExists(pid)) {\n const remainingMs = deadline - Date.now()\n if (remainingMs <= 0) return false\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(PROCESS_TERMINATION_POLL_MS, remainingMs)),\n )\n }\n return true\n}\n\nfunction processGroupExists(pid: number): boolean {\n try {\n process.kill(-pid, 0)\n return true\n } catch (error) {\n if (isMissingProcessError(error)) return false\n throw error\n }\n}\n\nfunction isMissingProcessError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ESRCH'\n )\n}\n\nfunction createProcessOutputCapture(): ProcessOutputCapture {\n return { full: '', head: '', tail: '', totalChars: 0 }\n}\n\nfunction appendProcessOutput(\n capture: ProcessOutputCapture,\n chunk: Buffer,\n maxOutputChars: number,\n): void {\n const text = chunk.toString()\n capture.totalChars += text.length\n const headChars = Math.floor(maxOutputChars / 2)\n const tailChars = maxOutputChars - headChars\n if (capture.full !== undefined) {\n const combined = `${capture.full}${text}`\n if (combined.length <= maxOutputChars) {\n capture.full = combined\n return\n }\n capture.head = combined.slice(0, headChars)\n capture.tail = combined.slice(-tailChars)\n capture.full = undefined\n return\n }\n capture.tail = `${capture.tail}${text}`.slice(-tailChars)\n}\n\nfunction summarizeProcessOutput(capture: ProcessOutputCapture, max = 4_000): string {\n const raw =\n capture.full ??\n `${capture.head}\\n...[${capture.totalChars - capture.head.length - capture.tail.length} chars omitted]...\\n${capture.tail}`\n const compact = raw.trim().replace(/\\s+/g, ' ')\n if (compact.length <= max) return compact\n const headChars = Math.floor(max / 3)\n const tailChars = max - headChars\n return `${compact.slice(0, headChars)}...[${compact.length - max} chars omitted]...${compact.slice(-tailChars)}`\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGA,IAAa,oBAAb,cAAuC,gBAAgB,CAAC;;AAGxD,IAAa,6BAAb,cAAgD,kBAAkB,CAAC;;AAGnE,IAAa,4BAAb,cAA+C,kBAAkB,CAAC;;;;ACElE,MAAa,6BAAgD;CAC3D,SAAS;CACT,iBAAiB,SAAS,YAAY,IAAI,2BAA2B,SAAS,OAAO;AACvF;AAEA,SAAgB,uBAAuB,MAAc,MAAoB;CACvE,iBAAiB,MAAM,MAAM,0BAA0B;AACzD;AAQA,SAAgB,4BACd,YACA,KACmB;CACnB,OAAO,sBAAsB,YAAY,4BAA4B,GAAG;AAC1E;;;;;;;;;;ACUA,SAAgB,oBAAqC;CAEnD,MAAM,EAAE,YAAY,WAAW,cAAc,UAAU,kBADnC,cAAc,OAAO,KAAK,GACqC,CAAC,CAClF,SACF;CACA,OAAO;EACL,UAAU,KAAK;GACb,IAAI,CAAC,WAAW,GAAG,GAAG,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;EAC1D;EACA,OAAO,MAAM;GACX,OAAO,WAAW,IAAI;EACxB;EACA,KAAK,MAAM;GACT,IAAI;IACF,OAAO,aAAa,MAAM,MAAM;GAClC,QAAQ;IACN;GACF;EACF;EACA,MAAM,MAAM,SAAS;GACnB,cAAc,MAAM,OAAqB;EAC3C;EACA,OAAO,MAAM,SAAS,eAAe;GACnC,MAAM,SAAS,4BAA4B,YAAY;IACrD,IAAI,cAAc;IAClB,IAAI;KACF,cAAc,SAAS,IAAI,CAAC,CAAC;IAC/B,SAAS,OAAO;KACd,IAAK,MAAgC,SAAS,UAAU,MAAM;IAChE;IACA,IAAI,gBAAgB,eAAe,OAAO,KAAA;IAC1C,uBAAuB,MAAM,OAAO;IACpC,OAAO,gBAAgB,OAAO,WAAW,OAAO;GAClD,CAAC;GACD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/run-score.ts","../src/semantic-concept-judge.ts","../src/analyst/trace-tool-callback.ts","../src/analyst/dspy-rlm-engine.ts","../src/analyst/finding-subject.ts","../src/analyst/findings-store.ts","../src/analyst/kinds/control-integrity.ts","../src/analyst/kinds/failure-mode.ts","../src/analyst/kinds/improvement.ts","../src/analyst/kinds/knowledge-gap.ts","../src/analyst/kinds/knowledge-poisoning.ts","../src/analyst/kinds/index.ts"],"mappings":";;;;;;;;;;UAAiB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAiBc,kBAAkB,OAAO,UAAU,UAAS,QAAQ;iBAiBpD,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;KCLZ;UAEK;EACf;;EAEA;;EAEA;;EAEA,aAAa;;UAGE;EACf;EACA;;EAEA;EACA;EACA,UAAU;;UAGK;;EAEf;;EAEA;;EAEA,aAAa;IAAQ;IAAc;;;EAEnC,kBAAkB;;EAElB;EACA;;UAGe;EACf;EACA;;EAEA;EACA;EACA;EACA,UAAU;EACV;EACA;EACA;;EAEA;EACA;;;;;;;;KASU;UAQK;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,MAAM;;EAEN,UAAU;EACV,aAAa;EACb;EACA,WAAW;EACX,SAAS;;;;;;EAMT,iBAAiB;;EAEjB,oBAAoB,QAAQ,OAAO;;cAKxB;;;;;;iBAkGS,wBACpB,OAAO,2BACP,SAAS,8BACR,QAAQ;;;KC9OC,0BAA0B;;;UCoBrB;;EAEf,MAAM;;EAEN;;EAEA,kBAAkB,aAAa;EAC/B;;EAEA,UAAU;;EAEV;;EAEA;;;;;;EAMA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,kBAAkB,QAAQ;;EAE1B;;;;;;;;;;EAUA;;EAEA,SAAS;;EAET;;;iBAIc,yBAAyB,SAAS,4BAA4B;;;;;;;;;;;;;;;;;;;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CPzB,+BAA+B;;;;;;;;;;;;cCP/B,sCAAsC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-D-V8gCs_.d.ts","names":[],"sources":["../src/campaign/analyst-surface.ts","../src/campaign/cross-surface-types.ts","../src/campaign/cross-surface-interaction.ts","../src/campaign/search-ledger-errors.ts","../src/campaign/fixtures.ts","../src/campaign/gates/neutralization-gate.ts","../src/campaign/grounded-reflection.ts","../src/campaign/labeled-store/fs-adapter.ts","../src/campaign/neutralize.ts","../src/campaign/presets/run-profile-matrix.ts","../src/campaign/presets/playback.ts","../src/campaign/presets/segmented-profile-matrix.ts","../src/campaign/run-dir.ts","../src/campaign/scenario-selection.ts","../src/campaign/score-utils.ts","../src/campaign/single-run-lock.ts","../src/campaign/surface-identity.ts","../src/campaign/upstream-evaluators.ts","../src/campaign/worktree/index.ts"],"mappings":";;;;;;;;;;;;;;;;UAWiB,6BAA6B;EAC5C;EACA,YAAY;EACZ,YAAY;EACZ,yBAAyB;EACzB,kBAAkB;;UAGH;EACf,mBAAmB;EACnB,QAAQ;EACR,MAAM;;UAGS;EACf,QAAQ;IACN;IACA,YAAY;IACZ;IACA,QAAQ;MACN,QAAQ;;iBAGE,iCACd,SAAS,2CAET,SAAS,gBACT,UAAU,sBACV,SAAS,oBACN,QAAQ;iBAgBG,4BAA4B,YAC1C,sBACA;;;;KCtDU;;UAGK;EACf;EACA;;EAEA;;;UAIe;EACf;EACA;EACA;EACA;;;UAIe;EACf;;EAEA;;EAEA;;;;;;;UAQe;EACf;EACA;;EAEA;EACA,cAAc;EACd;EACA;;;;;;EAMA,MAAM;EACN,mBAAmB;;EAEnB;;UAGe;EACf;EACA;EACA;;;UAIe;EACf;EACA;EACA;EACA;;EAEA,kCAAkC;;EAElC;;UAGe,qCACf,aAAa,sBAAsB;EAEnC,qBAAqB;EACrB,qBAAqB;EACrB,eAAe;EACf;;EAEA;;EAEA;;EAEA;;EAEA;EACA,WAAW;EACX,WAAW;;UAGI;EACf;EACA;EACA;E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