@tangle-network/agent-eval 2.0.7 → 2.0.10

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 (314) hide show
  1. package/CHANGELOG.md +80 -16
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-CRdalpZv.d.ts → agent-profile-_JzxgLDM.d.ts} +11 -5
  4. package/dist/{agent-profile-CRdalpZv.d.ts.map → agent-profile-_JzxgLDM.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +14 -13
  6. package/dist/analyst/index.d.ts.map +1 -1
  7. package/dist/analyst/index.js +34 -13
  8. package/dist/analyst/index.js.map +1 -1
  9. package/dist/analyze-runs-Izz_ZeWg.d.ts +65 -0
  10. package/dist/analyze-runs-Izz_ZeWg.d.ts.map +1 -0
  11. package/dist/{analyze-runs-C_9cXPZn.js → analyze-runs-xhH2Qxoc.js} +6 -5
  12. package/dist/{analyze-runs-C_9cXPZn.js.map → analyze-runs-xhH2Qxoc.js.map} +1 -1
  13. package/dist/app-grade/index.d.ts +4 -4
  14. package/dist/app-grade/index.js +1 -1
  15. package/dist/{benchmark-command-DkBMUDwy.js → benchmark-command-CGQXNFj7.js} +12 -8
  16. package/dist/benchmark-command-CGQXNFj7.js.map +1 -0
  17. package/dist/benchmarks/index.d.ts +4 -4
  18. package/dist/benchmarks/index.js +4 -4
  19. package/dist/builder-eval/index.js +2 -2
  20. package/dist/calibration-CrORXMWx.d.ts +128 -0
  21. package/dist/calibration-CrORXMWx.d.ts.map +1 -0
  22. package/dist/{calibration-Cfoup0xz.js → calibration-Dz8mQb5P.js} +2 -2
  23. package/dist/{calibration-Cfoup0xz.js.map → calibration-Dz8mQb5P.js.map} +1 -1
  24. package/dist/campaign/index.d.ts +8 -8
  25. package/dist/campaign/index.js +13 -12
  26. package/dist/{campaign-DfSWSreo.js → campaign-eus7YRs2.js} +1590 -15
  27. package/dist/campaign-eus7YRs2.js.map +1 -0
  28. package/dist/{campaign-evidence-BojANgU7.d.ts → campaign-evidence-BOcX4w0r.d.ts} +5 -5
  29. package/dist/{campaign-evidence-BojANgU7.d.ts.map → campaign-evidence-BOcX4w0r.d.ts.map} +1 -1
  30. package/dist/{campaign-evidence-D_oBFfLc.js → campaign-evidence-KM5GTsHG.js} +5 -5
  31. package/dist/{campaign-evidence-D_oBFfLc.js.map → campaign-evidence-KM5GTsHG.js.map} +1 -1
  32. package/dist/{cluster-Bj90LK-1.d.ts → chat-client-BlTooBDA.d.ts} +9 -241
  33. package/dist/chat-client-BlTooBDA.d.ts.map +1 -0
  34. package/dist/{chat-client-CvyDOQBv.js → chat-client-Oyot5tyo.js} +2 -2
  35. package/dist/{chat-client-CvyDOQBv.js.map → chat-client-Oyot5tyo.js.map} +1 -1
  36. package/dist/{chat-json-call-DMrwmB-k.js → chat-json-call-DTmv2uNY.js} +2 -2
  37. package/dist/{chat-json-call-DMrwmB-k.js.map → chat-json-call-DTmv2uNY.js.map} +1 -1
  38. package/dist/cli.js +7 -7
  39. package/dist/cluster-BJ0nW3P7.d.ts +241 -0
  40. package/dist/cluster-BJ0nW3P7.d.ts.map +1 -0
  41. package/dist/{cluster-bootstrap-DPzVy3_K.js → cluster-bootstrap-CTC8Dd30.js} +3 -2
  42. package/dist/{cluster-bootstrap-DPzVy3_K.js.map → cluster-bootstrap-CTC8Dd30.js.map} +1 -1
  43. package/dist/{completion-verifier-DsotH2l3.js → completion-verifier-CCPG2Yc0.js} +3 -3
  44. package/dist/{completion-verifier-DsotH2l3.js.map → completion-verifier-CCPG2Yc0.js.map} +1 -1
  45. package/dist/{completion-verifier-Cy38EpGE.d.ts → completion-verifier-CQOC3_bm.d.ts} +2 -2
  46. package/dist/{completion-verifier-Cy38EpGE.d.ts.map → completion-verifier-CQOC3_bm.d.ts.map} +1 -1
  47. package/dist/contract/index.d.ts +14 -12
  48. package/dist/contract/index.js +14 -12
  49. package/dist/contract/index.js.map +1 -1
  50. package/dist/{decision-point-C46p-p9v.js → decision-point-CfqtnGop.js} +3 -3
  51. package/dist/{decision-point-C46p-p9v.js.map → decision-point-CfqtnGop.js.map} +1 -1
  52. package/dist/{default-registry-BWFPtmuI.js → default-registry-Rs5uzlfJ.js} +4 -4
  53. package/dist/{default-registry-BWFPtmuI.js.map → default-registry-Rs5uzlfJ.js.map} +1 -1
  54. package/dist/{default-registry-xoX0PMCb.d.ts → default-registry-X8McMoUV.d.ts} +6 -6
  55. package/dist/{default-registry-xoX0PMCb.d.ts.map → default-registry-X8McMoUV.d.ts.map} +1 -1
  56. package/dist/define-agent-eval-D8ntOXqV.js +96 -0
  57. package/dist/define-agent-eval-D8ntOXqV.js.map +1 -0
  58. package/dist/define-agent-eval-DH5-xi-F.d.ts +52 -0
  59. package/dist/define-agent-eval-DH5-xi-F.d.ts.map +1 -0
  60. package/dist/diagnosis/index.d.ts +3 -3
  61. package/dist/diagnosis/index.js +1 -1
  62. package/dist/{dspy-rlm-engine-r7YpKLhS.js → dspy-rlm-engine-ChE1PUM5.js} +3 -3
  63. package/dist/{dspy-rlm-engine-r7YpKLhS.js.map → dspy-rlm-engine-ChE1PUM5.js.map} +1 -1
  64. package/dist/{emitter-BjW3NnX-.js → emitter-xN9wGTVw.js} +9 -2
  65. package/dist/{emitter-BjW3NnX-.js.map → emitter-xN9wGTVw.js.map} +1 -1
  66. package/dist/{eval-campaign-Cyk-tkLh.js → eval-campaign-BciGnrGy.js} +3 -3
  67. package/dist/{eval-campaign-Cyk-tkLh.js.map → eval-campaign-BciGnrGy.js.map} +1 -1
  68. package/dist/{evaluation-X5E22NQK.d.ts → evaluation-CjZH6gW0.d.ts} +4 -4
  69. package/dist/{evaluation-X5E22NQK.d.ts.map → evaluation-CjZH6gW0.d.ts.map} +1 -1
  70. package/dist/evaluation.d.ts +1 -1
  71. package/dist/{exact-types-DjuabhUV.d.ts → exact-types-BIHqYBYf.d.ts} +2 -2
  72. package/dist/{exact-types-DjuabhUV.d.ts.map → exact-types-BIHqYBYf.d.ts.map} +1 -1
  73. package/dist/{execution-insight-CE20Bxq0.d.ts → execution-insight-YihQrSqd.d.ts} +2 -2
  74. package/dist/{execution-insight-CE20Bxq0.d.ts.map → execution-insight-YihQrSqd.d.ts.map} +1 -1
  75. package/dist/experiment/index.d.ts +5 -5
  76. package/dist/experiment/index.js +10 -184
  77. package/dist/experiment/index.js.map +1 -1
  78. package/dist/{external-optimizer-contracts-ZDBfbZ_s.js → external-optimizer-contracts-BFV8lnhl.js} +7 -2
  79. package/dist/{external-optimizer-contracts-ZDBfbZ_s.js.map → external-optimizer-contracts-BFV8lnhl.js.map} +1 -1
  80. package/dist/{external-optimizer-process-4QdcF7Kd.js → external-optimizer-process-B6emPodQ.js} +3 -3
  81. package/dist/{external-optimizer-process-4QdcF7Kd.js.map → external-optimizer-process-B6emPodQ.js.map} +1 -1
  82. package/dist/{external-optimizer-subprocess-BW0ZWUUr.js → external-optimizer-subprocess-_O06eDVA.js} +35 -376
  83. package/dist/external-optimizer-subprocess-_O06eDVA.js.map +1 -0
  84. package/dist/{feedback-trajectory-BMkJezPc.d.ts → feedback-trajectory-CoQPmSJV.d.ts} +3 -3
  85. package/dist/{feedback-trajectory-BMkJezPc.d.ts.map → feedback-trajectory-CoQPmSJV.d.ts.map} +1 -1
  86. package/dist/finding-scope-B_As3F_v.js +359 -0
  87. package/dist/finding-scope-B_As3F_v.js.map +1 -0
  88. package/dist/{findings-store-DV8WA5nD.js → findings-store-CvYUzQBR.js} +4 -4
  89. package/dist/{findings-store-DV8WA5nD.js.map → findings-store-CvYUzQBR.js.map} +1 -1
  90. package/dist/fuzz.js +1 -1
  91. package/dist/{index-C6TG1LwA.d.ts → index-BSb3fJyZ.d.ts} +318 -131
  92. package/dist/index-BSb3fJyZ.d.ts.map +1 -0
  93. package/dist/{index-CKjqN9_U.d.ts → index-Bk1XEkP7.d.ts} +99 -3
  94. package/dist/index-Bk1XEkP7.d.ts.map +1 -0
  95. package/dist/{index-DAFZRMlF.d.ts → index-BmWw8zN6.d.ts} +10 -8
  96. package/dist/index-BmWw8zN6.d.ts.map +1 -0
  97. package/dist/{index-DKpMyD_Z.d.ts → index-CCOaNmh2.d.ts} +7 -7
  98. package/dist/{index-DKpMyD_Z.d.ts.map → index-CCOaNmh2.d.ts.map} +1 -1
  99. package/dist/{index-xEM_SoCl.d.ts → index-ZffK_5sD.d.ts} +22 -20
  100. package/dist/index-ZffK_5sD.d.ts.map +1 -0
  101. package/dist/{index-BqAPIToS.d.ts → index-aRalB_Ma.d.ts} +3 -3
  102. package/dist/{index-BqAPIToS.d.ts.map → index-aRalB_Ma.d.ts.map} +1 -1
  103. package/dist/index.d.ts +33 -29
  104. package/dist/index.js +28 -25
  105. package/dist/index.js.map +1 -1
  106. package/dist/{analyze-runs-xjKBBqIB.d.ts → insight-report-DYofCMLx.d.ts} +4 -64
  107. package/dist/insight-report-DYofCMLx.d.ts.map +1 -0
  108. package/dist/{integrity-BF0tJK21.js → integrity-DacT3oJ1.js} +2 -2
  109. package/dist/{integrity-BF0tJK21.js.map → integrity-DacT3oJ1.js.map} +1 -1
  110. package/dist/{integrity-B9320cw1.d.ts → integrity-DotDLWtj.d.ts} +2 -2
  111. package/dist/{integrity-B9320cw1.d.ts.map → integrity-DotDLWtj.d.ts.map} +1 -1
  112. package/dist/{judge-gate-DqlzOBOm.js → judge-gate-CpD3wmcf.js} +3 -3
  113. package/dist/{judge-gate-DqlzOBOm.js.map → judge-gate-CpD3wmcf.js.map} +1 -1
  114. package/dist/{llm-client-Dw4x6EdE.js → llm-client-Dk8lBnMh.js} +15 -2
  115. package/dist/{llm-client-Dw4x6EdE.js.map → llm-client-Dk8lBnMh.js.map} +1 -1
  116. package/dist/llm-judge-DYmEdo3M.js +476 -0
  117. package/dist/llm-judge-DYmEdo3M.js.map +1 -0
  118. package/dist/{matrix-CqZSpwgN.d.ts → matrix-BDl7hoBr.d.ts} +6 -2
  119. package/dist/matrix-BDl7hoBr.d.ts.map +1 -0
  120. package/dist/measure-validity-plan-BReXzcVh.d.ts +201 -0
  121. package/dist/measure-validity-plan-BReXzcVh.d.ts.map +1 -0
  122. package/dist/measure-validity-plan-CJkBNzX_.js +154 -0
  123. package/dist/measure-validity-plan-CJkBNzX_.js.map +1 -0
  124. package/dist/meta-eval/index.d.ts +5 -3
  125. package/dist/meta-eval/index.js +808 -15
  126. package/dist/meta-eval/index.js.map +1 -1
  127. package/dist/multishot/golden/index.d.ts +1 -1
  128. package/dist/multishot/index.d.ts +497 -4
  129. package/dist/multishot/index.d.ts.map +1 -1
  130. package/dist/multishot/index.js +1000 -48
  131. package/dist/multishot/index.js.map +1 -1
  132. package/dist/node-transport-DJno8V46.js +62 -0
  133. package/dist/node-transport-DJno8V46.js.map +1 -0
  134. package/dist/openapi.json +1 -1
  135. package/dist/{llm-judge-DQJTQx01.js → optimization-method-4JlbMxd2.js} +38 -513
  136. package/dist/optimization-method-4JlbMxd2.js.map +1 -0
  137. package/dist/{outcome-observations-DL3CC8w1.js → outcome-observations-DEh8_V_P.js} +31 -6
  138. package/dist/outcome-observations-DEh8_V_P.js.map +1 -0
  139. package/dist/outcome-store-CHtuvstd.d.ts +56 -0
  140. package/dist/outcome-store-CHtuvstd.d.ts.map +1 -0
  141. package/dist/{paired-arms-DZhH3FGu.js → paired-arms-CJH5Q0wx.js} +3 -2
  142. package/dist/{paired-arms-DZhH3FGu.js.map → paired-arms-CJH5Q0wx.js.map} +1 -1
  143. package/dist/{paired-promotion-decision-Dn3-jaq4.js → paired-promotion-decision-BtfVwEAk.js} +3 -2
  144. package/dist/{paired-promotion-decision-Dn3-jaq4.js.map → paired-promotion-decision-BtfVwEAk.js.map} +1 -1
  145. package/dist/{paired-promotion-decision-ChHBuuHV.d.ts → paired-promotion-decision-DJlI4z_k.d.ts} +2 -2
  146. package/dist/{paired-promotion-decision-ChHBuuHV.d.ts.map → paired-promotion-decision-DJlI4z_k.d.ts.map} +1 -1
  147. package/dist/{paired-promotion-power-BlzXdgMD.js → paired-promotion-power-DG1avBKf.js} +3 -3
  148. package/dist/{paired-promotion-power-BlzXdgMD.js.map → paired-promotion-power-DG1avBKf.js.map} +1 -1
  149. package/dist/paired-tests-CXcD_B80.js +688 -0
  150. package/dist/paired-tests-CXcD_B80.js.map +1 -0
  151. package/dist/pareto-DIVE5D0T.js +81 -0
  152. package/dist/pareto-DIVE5D0T.js.map +1 -0
  153. package/dist/pipelines/index.d.ts +2 -1
  154. package/dist/pipelines/index.d.ts.map +1 -1
  155. package/dist/pipelines/index.js +1 -1
  156. package/dist/{sequential-BphITa5b.js → power-COie_o6E.js} +181 -4
  157. package/dist/power-COie_o6E.js.map +1 -0
  158. package/dist/{prime-protocol-Cv6_47rh.d.ts → prime-protocol-BRMk6dGI.d.ts} +2 -2
  159. package/dist/{prime-protocol-Cv6_47rh.d.ts.map → prime-protocol-BRMk6dGI.d.ts.map} +1 -1
  160. package/dist/{promotion-gate-CGkxh36r.d.ts → promotion-gate-B0VTBoXg.d.ts} +2 -2
  161. package/dist/{promotion-gate-CGkxh36r.d.ts.map → promotion-gate-B0VTBoXg.d.ts.map} +1 -1
  162. package/dist/{promotion-policy-CxDIh-9p.js → promotion-policy-BgI7PsQn.js} +4 -4
  163. package/dist/{promotion-policy-CxDIh-9p.js.map → promotion-policy-BgI7PsQn.js.map} +1 -1
  164. package/dist/{proposal-findings-DedMih-u.js → proposal-findings-CfRFCFXS.js} +2 -2
  165. package/dist/{proposal-findings-DedMih-u.js.map → proposal-findings-CfRFCFXS.js.map} +1 -1
  166. package/dist/{registry-CIjC6SdV.d.ts → registry-BeInzotS.d.ts} +4 -4
  167. package/dist/{registry-CIjC6SdV.d.ts.map → registry-BeInzotS.d.ts.map} +1 -1
  168. package/dist/{release-confidence-BLHOMK5Q.js → release-confidence-Cndq1hwi.js} +2 -2
  169. package/dist/{release-confidence-BLHOMK5Q.js.map → release-confidence-Cndq1hwi.js.map} +1 -1
  170. package/dist/reporting.d.ts +5 -5
  171. package/dist/reporting.js +6 -5
  172. package/dist/reporting.js.map +1 -1
  173. package/dist/{research-report-D6XIK0eK.d.ts → research-report-CL5_UqCX.d.ts} +2 -2
  174. package/dist/{research-report-D6XIK0eK.d.ts.map → research-report-CL5_UqCX.d.ts.map} +1 -1
  175. package/dist/{researcher---DhHG4J.d.ts → researcher-BOpZP_Ja.d.ts} +4 -4
  176. package/dist/{researcher---DhHG4J.d.ts.map → researcher-BOpZP_Ja.d.ts.map} +1 -1
  177. package/dist/{reward-hacking-DKAflk2c.js → reward-hacking-DMTm1OBd.js} +2 -2
  178. package/dist/{reward-hacking-DKAflk2c.js.map → reward-hacking-DMTm1OBd.js.map} +1 -1
  179. package/dist/rl.d.ts +9 -8
  180. package/dist/rl.d.ts.map +1 -1
  181. package/dist/rl.js +11 -10
  182. package/dist/rl.js.map +1 -1
  183. package/dist/rollout/index.d.ts +2 -2
  184. package/dist/rollout/index.js +1 -1
  185. package/dist/{rollout-B_lrpd9a.js → rollout--rSr43Pd.js} +2 -2
  186. package/dist/{rollout-B_lrpd9a.js.map → rollout--rSr43Pd.js.map} +1 -1
  187. package/dist/{rollout-nodes-Vas6OSxX.js → rollout-nodes-DFxKpIr2.js} +39 -10
  188. package/dist/rollout-nodes-DFxKpIr2.js.map +1 -0
  189. package/dist/{rubric-predictive-validity--6z0q8s6.js → rubric-predictive-validity-BXJ92Jp_.js} +3 -9
  190. package/dist/rubric-predictive-validity-BXJ92Jp_.js.map +1 -0
  191. package/dist/{rubric-predictive-validity-C9wc7f_D.d.ts → rubric-predictive-validity-DH94_0Q1.d.ts} +3 -56
  192. package/dist/rubric-predictive-validity-DH94_0Q1.d.ts.map +1 -0
  193. package/dist/{run-improvement-loop-BfwOUudy.d.ts → run-improvement-loop-BeHu5D9Z.d.ts} +396 -11
  194. package/dist/run-improvement-loop-BeHu5D9Z.d.ts.map +1 -0
  195. package/dist/{run-record-Bqg0NZ_e.js → run-record-CuO8ErrI.js} +3 -2
  196. package/dist/run-record-CuO8ErrI.js.map +1 -0
  197. package/dist/{runtime-rollouts-drQynu3t.js → runtime-rollouts-CE0MbQPq.js} +55 -8
  198. package/dist/runtime-rollouts-CE0MbQPq.js.map +1 -0
  199. package/dist/search/index.d.ts +2 -2
  200. package/dist/search/index.js +2 -2
  201. package/dist/{search-kernel-DJq9bUDU.d.ts → search-kernel-CJZ-ZSV1.d.ts} +3 -3
  202. package/dist/{search-kernel-DJq9bUDU.d.ts.map → search-kernel-CJZ-ZSV1.d.ts.map} +1 -1
  203. package/dist/{pareto-Bg75Gajo.js → search-kernel-mZc79S6N.js} +6 -88
  204. package/dist/search-kernel-mZc79S6N.js.map +1 -0
  205. package/dist/{search-summary-B1x1Vmzh.js → search-summary-CCgP2qXz.js} +4 -4
  206. package/dist/{search-summary-B1x1Vmzh.js.map → search-summary-CCgP2qXz.js.map} +1 -1
  207. package/dist/{define-agent-eval-Cjc0wWnO.d.ts → self-improve-B1fsNejr.d.ts} +8 -54
  208. package/dist/self-improve-B1fsNejr.d.ts.map +1 -0
  209. package/dist/{define-agent-eval-B6uE3gNu.js → self-improve-C_Bcdmv8.js} +9 -97
  210. package/dist/self-improve-C_Bcdmv8.js.map +1 -0
  211. package/dist/{sequential-BhbTSxpt.d.ts → sequential-CHplorpC.d.ts} +2 -2
  212. package/dist/{sequential-BhbTSxpt.d.ts.map → sequential-CHplorpC.d.ts.map} +1 -1
  213. package/dist/{sequential-ux_XrjBf.js → sequential-DR-pnYQ7.js} +3 -3
  214. package/dist/{sequential-ux_XrjBf.js.map → sequential-DR-pnYQ7.js.map} +1 -1
  215. package/dist/{server-1fzBCxMh.js → server-aZFmRucn.js} +3 -3
  216. package/dist/{server-1fzBCxMh.js.map → server-aZFmRucn.js.map} +1 -1
  217. package/dist/{skillopt-optimization-method-D_swD0Cy.js → skillopt-optimization-method-DHk1K757.js} +95 -40
  218. package/dist/skillopt-optimization-method-DHk1K757.js.map +1 -0
  219. package/dist/{statistical-heldout-CaS4T-43.js → statistical-heldout-CL_7mI5C.js} +3 -3
  220. package/dist/{statistical-heldout-CaS4T-43.js.map → statistical-heldout-CL_7mI5C.js.map} +1 -1
  221. package/dist/{statistics-DSidA5I2.js → statistics-AKnVFnK-.js} +233 -700
  222. package/dist/statistics-AKnVFnK-.js.map +1 -0
  223. package/dist/statistics.d.ts +3 -3
  224. package/dist/statistics.js +3 -2
  225. package/dist/{store-tool-spans-DniaFwjM.d.ts → store-tool-spans-M3WxeRrG.d.ts} +4 -4
  226. package/dist/{store-tool-spans-DniaFwjM.d.ts.map → store-tool-spans-M3WxeRrG.d.ts.map} +1 -1
  227. package/dist/{summary-report-CI4J6gxU.js → summary-report-DyBkOC6V.js} +15 -7
  228. package/dist/summary-report-DyBkOC6V.js.map +1 -0
  229. package/dist/summary-report-figures-CJHygLgw.d.ts.map +1 -1
  230. package/dist/supervisor-run/index.d.ts +12 -2
  231. package/dist/supervisor-run/index.d.ts.map +1 -1
  232. package/dist/supervisor-run/index.js +3 -3
  233. package/dist/{systemone-DzY-2Zri.d.ts → systemone-4PadCE4C.d.ts} +8 -7
  234. package/dist/systemone-4PadCE4C.d.ts.map +1 -0
  235. package/dist/{systemone-review-CXecR_m-.d.ts → systemone-review-DpAXWDkL.d.ts} +2 -2
  236. package/dist/{systemone-review-CXecR_m-.d.ts.map → systemone-review-DpAXWDkL.d.ts.map} +1 -1
  237. package/dist/systemone.d.ts +3 -3
  238. package/dist/systemone.js +1 -1
  239. package/dist/{tool-groups-DF6OqhoG.d.ts → tool-groups-SlnoQNyT.d.ts} +2 -2
  240. package/dist/tool-groups-SlnoQNyT.d.ts.map +1 -0
  241. package/dist/tool-waste-B01AMpID.d.ts +121 -0
  242. package/dist/tool-waste-B01AMpID.d.ts.map +1 -0
  243. package/dist/{tool-waste-u7JJ_BlE.js → tool-waste-BZnYSa6J.js} +3 -2
  244. package/dist/{tool-waste-u7JJ_BlE.js.map → tool-waste-BZnYSa6J.js.map} +1 -1
  245. package/dist/{trace-questions-DO8y3J-E.d.ts → trace-questions-ybyF0B6N.d.ts} +2 -2
  246. package/dist/{trace-questions-DO8y3J-E.d.ts.map → trace-questions-ybyF0B6N.d.ts.map} +1 -1
  247. package/dist/trace-repair/index.d.ts +1 -1
  248. package/dist/trace-repair/index.js +1 -1
  249. package/dist/traces.d.ts +4 -4
  250. package/dist/traces.js +1 -1
  251. package/dist/trajectory-B3o6Ald_.d.ts +100 -0
  252. package/dist/trajectory-B3o6Ald_.d.ts.map +1 -0
  253. package/dist/trajectory-replay/index.js +1 -1
  254. package/dist/{tree-DQMlcNFI.js → tree-CiIe-f3f.js} +6 -4
  255. package/dist/{tree-DQMlcNFI.js.map → tree-CiIe-f3f.js.map} +1 -1
  256. package/dist/{types-fuOwNq1C.d.ts → types-B1W3v8dT.d.ts} +3 -2
  257. package/dist/types-B1W3v8dT.d.ts.map +1 -0
  258. package/dist/{types-BMSDkS8l.d.ts → types-D5XtEH9Q.d.ts} +11 -4
  259. package/dist/{types-BMSDkS8l.d.ts.map → types-D5XtEH9Q.d.ts.map} +1 -1
  260. package/dist/types-DK4vNv5q.js.map +1 -1
  261. package/dist/{types-D_PfKC59.d.ts → types-an-CUndX.d.ts} +2 -2
  262. package/dist/{types-D_PfKC59.d.ts.map → types-an-CUndX.d.ts.map} +1 -1
  263. package/dist/{types-BLv2Ngla.d.ts → types-xVtEOBhO.d.ts} +31 -8
  264. package/dist/types-xVtEOBhO.d.ts.map +1 -0
  265. package/dist/wire/index.d.ts +2 -2
  266. package/dist/wire/index.js +1 -1
  267. package/dist/world/index.d.ts +529 -0
  268. package/dist/world/index.d.ts.map +1 -0
  269. package/dist/world/index.js +1356 -0
  270. package/dist/world/index.js.map +1 -0
  271. package/docs/campaign-proposers.md +7 -0
  272. package/docs/concepts.md +2 -0
  273. package/docs/design/statistics-decisions.md +48 -0
  274. package/docs/eval-surface-map.md +5 -2
  275. package/docs/feature-guide.md +3 -1
  276. package/docs/multi-turn-optimization.md +84 -0
  277. package/docs/outcome-validity.md +108 -0
  278. package/docs/public-api.md +89 -34
  279. package/docs/{multi-shot-optimization.md → trajectory-optimization.md} +1 -1
  280. package/docs/world.md +104 -0
  281. package/package.json +6 -1
  282. package/dist/analyze-runs-xjKBBqIB.d.ts.map +0 -1
  283. package/dist/benchmark-command-DkBMUDwy.js.map +0 -1
  284. package/dist/campaign-DfSWSreo.js.map +0 -1
  285. package/dist/cluster-Bj90LK-1.d.ts.map +0 -1
  286. package/dist/define-agent-eval-B6uE3gNu.js.map +0 -1
  287. package/dist/define-agent-eval-Cjc0wWnO.d.ts.map +0 -1
  288. package/dist/external-optimizer-subprocess-BW0ZWUUr.js.map +0 -1
  289. package/dist/index-C6TG1LwA.d.ts.map +0 -1
  290. package/dist/index-CKjqN9_U.d.ts.map +0 -1
  291. package/dist/index-DAFZRMlF.d.ts.map +0 -1
  292. package/dist/index-xEM_SoCl.d.ts.map +0 -1
  293. package/dist/interval-CWyxqDpE.d.ts +0 -43
  294. package/dist/interval-CWyxqDpE.d.ts.map +0 -1
  295. package/dist/llm-judge-DQJTQx01.js.map +0 -1
  296. package/dist/matrix-CqZSpwgN.d.ts.map +0 -1
  297. package/dist/outcome-observations-DL3CC8w1.js.map +0 -1
  298. package/dist/pareto-Bg75Gajo.js.map +0 -1
  299. package/dist/rollout-nodes-Vas6OSxX.js.map +0 -1
  300. package/dist/rubric-predictive-validity--6z0q8s6.js.map +0 -1
  301. package/dist/rubric-predictive-validity-C9wc7f_D.d.ts.map +0 -1
  302. package/dist/run-improvement-loop-BfwOUudy.d.ts.map +0 -1
  303. package/dist/run-record-Bqg0NZ_e.js.map +0 -1
  304. package/dist/runtime-rollouts-drQynu3t.js.map +0 -1
  305. package/dist/sequential-BphITa5b.js.map +0 -1
  306. package/dist/skillopt-optimization-method-D_swD0Cy.js.map +0 -1
  307. package/dist/statistics-DSidA5I2.js.map +0 -1
  308. package/dist/summary-report-CI4J6gxU.js.map +0 -1
  309. package/dist/systemone-DzY-2Zri.d.ts.map +0 -1
  310. package/dist/tool-groups-DF6OqhoG.d.ts.map +0 -1
  311. package/dist/tool-waste-CIhtU1ad.d.ts +0 -217
  312. package/dist/tool-waste-CIhtU1ad.d.ts.map +0 -1
  313. package/dist/types-BLv2Ngla.d.ts.map +0 -1
  314. package/dist/types-fuOwNq1C.d.ts.map +0 -1
@@ -1,10 +1,205 @@
1
+ import { a as hashCanonical, o as jsonDocument } from "../canonical-DKgL_Wby.js";
2
+ import { S as makeRng } from "../paired-tests-CXcD_B80.js";
3
+ import { Q as runCampaign, R as defaultProductionGate } from "../optimization-method-4JlbMxd2.js";
1
4
  import { d as estimateCost, p as isModelPriced } from "../cost-ledger-C5CCidPm.js";
2
- import { t as DEFAULT_JUDGE_MODEL } from "../chat-client-CvyDOQBv.js";
5
+ import { _ as EMITTED_EVIDENCE_MAX_CHARS, y as excerptEvidence } from "../campaign-evidence-KM5GTsHG.js";
6
+ import { m as inMemoryCampaignStorage, p as fsCampaignStorage } from "../finding-scope-B_As3F_v.js";
7
+ import { n as selfImprove } from "../self-improve-C_Bcdmv8.js";
8
+ import { n as runTaskId } from "../emitter-xN9wGTVw.js";
9
+ import { t as DEFAULT_JUDGE_MODEL } from "../chat-client-Oyot5tyo.js";
10
+ import { i as decisionQuestionDigest, r as decisionPoint } from "../decision-point-CfqtnGop.js";
11
+ import { t as clusterBootstrapMean } from "../cluster-bootstrap-CTC8Dd30.js";
3
12
  import { n as withCellSpend } from "../cell-spend-zxmzg4GH.js";
4
13
  import { t as runAgentMatrix } from "../matrix-CgpX8wdm.js";
5
14
  import { n as MultishotFatalToolError, r as assertMultishotShotResult, t as MultishotDriverEmptyError } from "../types-DK4vNv5q.js";
6
15
  import { mkdirSync, writeFileSync } from "node:fs";
7
16
  import { join } from "node:path";
17
+ // src/multishot/conversation-conditions.ts
18
+ /** Paired conversations did not meet the same simulated user on the same seed. */
19
+ var SimulatedUserMismatchError = class extends Error {
20
+ mismatches;
21
+ constructor(mismatches) {
22
+ const shown = listSome(mismatches.map((row) => `${row.cellId}: ${row.detail}`), "; ");
23
+ super(`${mismatches.length} paired conversation(s) did not meet the same simulated user on the same seed, so the comparison is refused (${shown})`);
24
+ this.name = "SimulatedUserMismatchError";
25
+ this.mismatches = mismatches;
26
+ }
27
+ };
28
+ /** A score on the agent's success was asked to read a conversation whose
29
+ * user side was the candidate. Optimizing the user to raise the agent's
30
+ * success would teach it to be easy; the user side's objective is the
31
+ * agent's failure rate, through `improveAdversarialUser` only. */
32
+ var UserSideObjectiveError = class extends Error {
33
+ constructor(message) {
34
+ super(message);
35
+ this.name = "UserSideObjectiveError";
36
+ }
37
+ };
38
+ /** A scenario an adversarial-user search emitted reached a held-out split. */
39
+ var AdversarialScenarioInHeldOutError = class extends Error {
40
+ scenarioIds;
41
+ constructor(scenarioIds) {
42
+ super(`held-out split contains ${scenarioIds.length} scenario(s) an adversarial-user search emitted (${listSome(scenarioIds)}); they train the agent side and never measure it`);
43
+ this.name = "AdversarialScenarioInHeldOutError";
44
+ this.scenarioIds = scenarioIds;
45
+ }
46
+ };
47
+ /**
48
+ * Refuse a comparison whose paired conversations (same cell id) met different
49
+ * simulated users or ran on different seeds, or carry no identity to show it.
50
+ * Returns the number of pairs compared.
51
+ */
52
+ function assertSameSimulatedUser(baseline, candidate) {
53
+ const mismatches = [];
54
+ let pairs = 0;
55
+ for (const [cellId, other] of candidate) {
56
+ const base = baseline.get(cellId);
57
+ if (base === void 0) continue;
58
+ pairs += 1;
59
+ const missing = ["baseline", "candidate"].filter((arm) => !hasIdentity(arm === "baseline" ? base : other));
60
+ if (missing.length > 0) mismatches.push({
61
+ cellId,
62
+ reason: "missing",
63
+ detail: `${missing.join(" and ")} carries no simulated-user identity`
64
+ });
65
+ else if (base.simulatedUser.digest !== other.simulatedUser.digest) mismatches.push({
66
+ cellId,
67
+ reason: "simulated-user",
68
+ detail: `baseline user ${base.simulatedUser.digest} (${base.simulatedUser.model}), candidate user ${other.simulatedUser.digest} (${other.simulatedUser.model})`
69
+ });
70
+ else if (base.seed !== other.seed) mismatches.push({
71
+ cellId,
72
+ reason: "seed",
73
+ detail: `baseline seed ${base.seed}, candidate seed ${other.seed}`
74
+ });
75
+ }
76
+ if (mismatches.length > 0) throw new SimulatedUserMismatchError(mismatches);
77
+ return pairs;
78
+ }
79
+ /** The first three items, and an ellipsis when there are more. Package-internal. */
80
+ function listSome(items, separator = ", ") {
81
+ return [...items.slice(0, 3), ...items.length > 3 ? ["…"] : []].join(separator);
82
+ }
83
+ function hasIdentity(artifact) {
84
+ return typeof artifact?.simulatedUser?.digest === "string" && artifact.simulatedUser.digest.length > 0 && Number.isFinite(artifact.seed);
85
+ }
86
+ /** Refuse a held-out split that contains an adversarial-user scenario.
87
+ * `conversationGate` runs it before the held-out run starts; run it on the
88
+ * test cases of any comparison that does not go through that gate. */
89
+ function assertHeldOutExcludesAdversarial(scenarios) {
90
+ const emitted = scenarios.filter((scenario) => scenario.origin?.kind === "adversarial-user");
91
+ if (emitted.length > 0) throw new AdversarialScenarioInHeldOutError(emitted.map((scenario) => scenario.id));
92
+ }
93
+ /**
94
+ * Score the agent side of a conversation: 0 when the code-checked outcome
95
+ * failed, else 1, or the semantic judge's composite when one is given. The
96
+ * `outcome` dimension is always the code check. Refuses a conversation whose
97
+ * user side was the candidate.
98
+ */
99
+ function conversationJudge(opts = {}) {
100
+ const semantic = opts.semantic;
101
+ return {
102
+ name: "conversation-outcome",
103
+ judgeVersion: `agent-eval:conversation-outcome:v1${semantic ? `+${semantic.name}:${semantic.judgeVersion ?? "unversioned"}` : ""}`,
104
+ dimensions: [{
105
+ key: "outcome",
106
+ description: "1 when the code-checked outcome passed, else 0"
107
+ }, ...(semantic?.dimensions ?? []).filter((dimension) => dimension.key !== "outcome")],
108
+ score(input) {
109
+ if (input.artifact.optimizedRole !== "agent") throw new UserSideObjectiveError(`conversation '${input.scenario.id}' optimized the user side; the agent-success score reads agent-side conversations only, and improveAdversarialUser scores the user side on the agent's failure rate`);
110
+ const { passed, detail } = input.artifact.outcome;
111
+ if (!passed || !semantic) return {
112
+ dimensions: { outcome: passed ? 1 : 0 },
113
+ composite: passed ? 1 : 0,
114
+ notes: detail
115
+ };
116
+ return Promise.resolve(semantic.score(input)).then((score) => ({
117
+ ...score,
118
+ dimensions: {
119
+ ...score.dimensions,
120
+ outcome: 1
121
+ },
122
+ notes: `${detail}\n${score.notes}`
123
+ }));
124
+ }
125
+ };
126
+ }
127
+ /**
128
+ * The promotion gate for conversations: refuses a held-out split containing
129
+ * adversarial-user scenarios and any comparison whose arms met different
130
+ * simulated users or seeds, then decides with `inner`.
131
+ */
132
+ function conversationGate(opts = {}) {
133
+ return {
134
+ name: "conversation",
135
+ admitHeldOut: assertHeldOutExcludesAdversarial,
136
+ async decide(ctx) {
137
+ assertHeldOutExcludesAdversarial(ctx.scenarios);
138
+ if (ctx.baselineArtifacts === void 0) throw new SimulatedUserMismatchError([{
139
+ cellId: "*",
140
+ reason: "missing",
141
+ detail: "the baseline arm carries no simulated-user identity: no baseline artifacts"
142
+ }]);
143
+ const pairedConversations = assertSameSimulatedUser(ctx.baselineArtifacts, ctx.candidateArtifacts);
144
+ if (ctx.neutralizedArtifacts) assertSameSimulatedUser(ctx.baselineArtifacts, ctx.neutralizedArtifacts);
145
+ const result = await (opts.inner ?? defaultProductionGate({
146
+ holdoutScenarios: ctx.scenarios,
147
+ deltaThreshold: opts.deltaThreshold ?? .05,
148
+ ...opts.independentUnitByScenarioId ? { independentUnitByScenarioId: opts.independentUnitByScenarioId } : {}
149
+ })).decide(ctx);
150
+ return {
151
+ ...result,
152
+ contributingGates: [{
153
+ name: "simulated-user-identity",
154
+ status: "pass",
155
+ detail: { pairedConversations }
156
+ }, ...result.contributingGates]
157
+ };
158
+ }
159
+ };
160
+ }
161
+ // src/multishot/conversation-evidence.ts
162
+ const DETAIL_MAX_CHARS = 400;
163
+ const TOOL_RESULT_MAX_CHARS = 300;
164
+ /** The evidence a reflection reads for one conversation. */
165
+ function describeConversation(artifact) {
166
+ const base = {
167
+ outcome: {
168
+ passed: artifact.outcome.passed,
169
+ detail: excerptEvidence(artifact.outcome.detail, DETAIL_MAX_CHARS)
170
+ },
171
+ ending: {
172
+ kind: artifact.ending.kind,
173
+ turn: artifact.ending.turn
174
+ },
175
+ agentTurns: artifact.agentTurns,
176
+ firstPushbackTurn: artifact.pushback.determined ? artifact.pushback.firstTurn : "undetermined",
177
+ transcript: ""
178
+ };
179
+ const full = renderTranscript(artifact.transcript);
180
+ let budget = EMITTED_EVIDENCE_MAX_CHARS - JSON.stringify(base).length;
181
+ let evidence = {
182
+ ...base,
183
+ transcript: excerptEvidence(full, Math.max(0, budget))
184
+ };
185
+ for (let length = JSON.stringify(evidence).length; length > 2e3 && budget > 0; length = JSON.stringify(evidence).length) {
186
+ budget -= length - EMITTED_EVIDENCE_MAX_CHARS;
187
+ evidence = {
188
+ ...base,
189
+ transcript: excerptEvidence(full, Math.max(0, budget))
190
+ };
191
+ }
192
+ return evidence;
193
+ }
194
+ function renderTranscript(transcript) {
195
+ return transcript.map((message) => {
196
+ if (message.role === "tool") return `tool: ${excerptEvidence(message.content, TOOL_RESULT_MAX_CHARS)}`;
197
+ if (message.role === "user") return `user: ${message.content}`;
198
+ const calls = message.toolCalls?.map((call) => call.name) ?? [];
199
+ const called = calls.length > 0 ? ` [called ${calls.join(", ")}]` : "";
200
+ return `agent: ${message.content}${called}`;
201
+ }).join("\n");
202
+ }
8
203
  // src/multishot/cost.ts
9
204
  /**
10
205
  * Rough per-model cost estimate from token counts. Underestimates Anthropic,
@@ -354,57 +549,37 @@ function openConversation(opts, meter) {
354
549
  }
355
550
  async function driverTurn(turn) {
356
551
  const usdBefore = meter.costUsd;
357
- const driverMessages = [{
358
- role: "system",
359
- content: driverSystemPrompt
360
- }];
361
- for (const msg of transcript) {
362
- if (msg.role === "tool") continue;
363
- const content = driverVisibleContent(msg);
364
- if (!content) continue;
365
- if (msg.role === "assistant") driverMessages.push({
366
- role: "user",
367
- content
368
- });
369
- else if (msg.role === "user") driverMessages.push({
370
- role: "assistant",
371
- content
372
- });
373
- }
374
552
  const tokens = {
375
553
  input: 0,
376
554
  output: 0
377
555
  };
378
- for (const model of driverModels) for (let attempt = 0; attempt < 2; attempt++) {
379
- const { message, usage, costUsd } = await driverTransport({
380
- model,
381
- messages: driverMessages,
382
- temperature: .9,
383
- maxTokens: driverMaxTokens,
384
- signal: opts.signal
385
- });
386
- meter.costUsd += costUsd ?? estimateMultishotCost(model, usage);
387
- if (costUsd === void 0 && usage === void 0) meter.uncaptured = true;
388
- tokens.input += usage?.prompt_tokens ?? 0;
389
- tokens.output += usage?.completion_tokens ?? 0;
390
- const content = (message.content ?? "").trim();
391
- if (content.length > 0) {
392
- agentMessages.push({
393
- role: "user",
394
- content
395
- });
396
- transcript.push({
397
- role: "user",
398
- content
399
- });
400
- return {
401
- content,
402
- tokens,
403
- usd: meter.costUsd - usdBefore
404
- };
556
+ const content = await requestUserReply({
557
+ models: driverModels,
558
+ messages: driverViewMessages(driverSystemPrompt, transcript),
559
+ transport: driverTransport,
560
+ maxTokens: driverMaxTokens,
561
+ signal: opts.signal,
562
+ turn,
563
+ onResponse: (model, { usage, costUsd }) => {
564
+ meter.costUsd += costUsd ?? estimateMultishotCost(model, usage);
565
+ if (costUsd === void 0 && usage === void 0) meter.uncaptured = true;
566
+ tokens.input += usage?.prompt_tokens ?? 0;
567
+ tokens.output += usage?.completion_tokens ?? 0;
405
568
  }
406
- }
407
- throw new MultishotDriverEmptyError(turn);
569
+ });
570
+ agentMessages.push({
571
+ role: "user",
572
+ content
573
+ });
574
+ transcript.push({
575
+ role: "user",
576
+ content
577
+ });
578
+ return {
579
+ content,
580
+ tokens,
581
+ usd: meter.costUsd - usdBefore
582
+ };
408
583
  }
409
584
  return {
410
585
  conversation: {
@@ -421,6 +596,54 @@ function openConversation(opts, meter) {
421
596
  toolCalls: () => toolCalls
422
597
  };
423
598
  }
599
+ /** The simulated user's next message. The driver must never go silent: an
600
+ * empty reply is retried once per model, the models are tried in order, and
601
+ * then `MultishotDriverEmptyError` is thrown. Every response, empty ones
602
+ * included, reaches `onResponse`, because every attempt was billed. The
603
+ * conversation loop and the realism measure both ask the simulated user
604
+ * through here, so a driver measured against recorded turns is sampled the
605
+ * way a rollout samples it. */
606
+ async function requestUserReply(input) {
607
+ for (const model of input.models) for (let attempt = 0; attempt < 2; attempt++) {
608
+ const response = await input.transport({
609
+ model,
610
+ messages: input.messages,
611
+ temperature: .9,
612
+ maxTokens: input.maxTokens,
613
+ signal: input.signal
614
+ });
615
+ input.onResponse?.(model, response);
616
+ const content = (response.message.content ?? "").trim();
617
+ if (content.length > 0) return content;
618
+ }
619
+ throw new MultishotDriverEmptyError(input.turn);
620
+ }
621
+ /** The simulated user's view of a transcript, as the driver request's
622
+ * messages. The agent's `assistant` messages become `user` (the agent talking
623
+ * TO the driver); the driver's prior `user` messages become `assistant` (its
624
+ * own earlier replies). Tool messages are hidden. The conversation loop and
625
+ * the realism measure both build the driver's request here, so a driver
626
+ * measured against recorded turns sees exactly what it sees in a rollout. */
627
+ function driverViewMessages(driverSystemPrompt, transcript) {
628
+ const driverMessages = [{
629
+ role: "system",
630
+ content: driverSystemPrompt
631
+ }];
632
+ for (const msg of transcript) {
633
+ if (msg.role === "tool") continue;
634
+ const content = driverVisibleContent(msg);
635
+ if (!content) continue;
636
+ if (msg.role === "assistant") driverMessages.push({
637
+ role: "user",
638
+ content
639
+ });
640
+ else if (msg.role === "user") driverMessages.push({
641
+ role: "assistant",
642
+ content
643
+ });
644
+ }
645
+ return driverMessages;
646
+ }
424
647
  /** Silent tool-calling agent turns surface to the driver as
425
648
  * "Agent called tools: …" so the simulated user can react to them. */
426
649
  function driverVisibleContent(msg) {
@@ -431,6 +654,735 @@ function driverVisibleContent(msg) {
431
654
  if (toolNames.length === 0) return "Agent called tools.";
432
655
  return `Agent called ${toolNames.length === 1 ? "tool" : "tools"}: ${toolNames.join(", ")}.`;
433
656
  }
657
+ // src/multishot/rollout.ts
658
+ const SIGNED_OFF = "[[signed-off]]";
659
+ const GAVE_UP = "[[gave-up]]";
660
+ /** Ends on `[[signed-off]]` when the user's problem is resolved and on
661
+ * `[[gave-up]]` when the user would stop using the service. */
662
+ const DEFAULT_USER_ENDING = {
663
+ ref: "agent-eval:user-ending-markers:v1",
664
+ instructions: [
665
+ `When your problem is resolved to your standard, end your message with ${SIGNED_OFF}.`,
666
+ `If you would stop using this service now because the agent is not getting anywhere, end your message with ${GAVE_UP}.`,
667
+ "Otherwise use neither marker."
668
+ ].join("\n"),
669
+ classify(message) {
670
+ for (const [marker, kind] of [[SIGNED_OFF, "signed-off"], [GAVE_UP, "gave-up"]]) if (message.includes(marker)) return {
671
+ kind,
672
+ message: message.split(marker).join("").trim()
673
+ };
674
+ return { kind: "continue" };
675
+ }
676
+ };
677
+ /** How each rigor level asks the simulated user to push back, as
678
+ * `PersonaRigor` defines them. */
679
+ const RIGOR_STANCE = {
680
+ cooperative: "Your stance: a forgiving early adopter. Accept a reasonable answer and move on; push back only when the agent is clearly wrong or stuck.",
681
+ demanding: "Your stance: an experienced professional. Reject vague or hedged answers and ask for specifics before you accept anything.",
682
+ relentless: "Your stance: you are reviewing this for someone who will hold you to it. Interrogate every claim and accept nothing the agent has not defended."
683
+ };
684
+ /** Builds the simulated user from its options alone. The rollout and the
685
+ * realism measure both build it here, so a measured driver is the driver a
686
+ * rollout runs. */
687
+ function simulatedUserSetup(user, persona, plan) {
688
+ if (user.shape !== void 0 && !user.shapeRef) throw new TypeError("simulated user: a custom shape needs a shapeRef naming its callbacks");
689
+ const rigor = user.rigor ?? "demanding";
690
+ const ending = user.ending ?? DEFAULT_USER_ENDING;
691
+ const shape = defaultShapeFromProfile({
692
+ name: "agent",
693
+ description: user.agentDescription ?? "an AI agent"
694
+ }, user.shape);
695
+ const opener = shape.buildOpener(persona);
696
+ const driverSystemPrompt = [
697
+ shape.buildDriverSystemPrompt(persona),
698
+ RIGOR_STANCE[rigor],
699
+ ending.instructions,
700
+ plan ? `Your plan for this conversation:\n${plan}` : ""
701
+ ].filter((block) => block.length > 0).join("\n\n");
702
+ const fields = {
703
+ model: user.model,
704
+ fallbackModels: [...user.fallbackModels ?? []],
705
+ rigor,
706
+ personaId: persona.id,
707
+ personaDigest: hashCanonical(jsonDocument(persona)),
708
+ promptDigest: hashCanonical(driverSystemPrompt),
709
+ openerDigest: hashCanonical(opener),
710
+ endingRef: ending.ref,
711
+ shapeRef: user.shapeRef ?? "agent-eval:default-shape",
712
+ maxTokens: user.maxTokens ?? 600
713
+ };
714
+ return {
715
+ opener,
716
+ driverSystemPrompt,
717
+ identity: {
718
+ digest: hashCanonical(jsonDocument(fields)),
719
+ ...fields
720
+ }
721
+ };
722
+ }
723
+ /**
724
+ * Run a multishot conversation as the `agent(surface, scenario, ctx)` dispatch
725
+ * of `selfImprove` and `compareOptimizationMethods`. Pass `dispatchRef` along
726
+ * with `agent`, score with `conversationJudge`, gate with `conversationGate`
727
+ * and show the optimizer `describeConversation`.
728
+ */
729
+ function multishotRollout(opts) {
730
+ const profileOf = opts.profile ?? textSurfaceProfile;
731
+ return {
732
+ agent: async (surface, scenario, ctx) => converse(opts, profileOf(surface, scenario), scenario, scenario.userPlan, "agent", ctx),
733
+ dispatchRef: rolloutDispatchRef(opts, "agent"),
734
+ simulatedUser: (scenario) => simulatedUserSetup(opts.user, scenario.persona, scenario.userPlan).identity
735
+ };
736
+ }
737
+ /** The user side of the same conversation: the agent profile is fixed and the
738
+ * candidate surface is the simulated user's plan. Package-internal; the only
739
+ * public way to optimize it is `improveAdversarialUser`, whose objective is
740
+ * fixed to the agent's failure rate. */
741
+ function userSideRollout(opts, agentProfile) {
742
+ return {
743
+ agent: async (surface, scenario, ctx) => {
744
+ if (typeof surface !== "string") throw new TypeError("adversarial user: the plan surface must be text");
745
+ return converse(opts, agentProfile, scenario, [scenario.userPlan, surface].filter(Boolean).join("\n\n"), "user", ctx);
746
+ },
747
+ dispatchRef: rolloutDispatchRef({
748
+ ...opts,
749
+ profileDigest: hashCanonical(jsonDocument(agentProfile))
750
+ }, "user")
751
+ };
752
+ }
753
+ function textSurfaceProfile(surface) {
754
+ if (typeof surface !== "string") throw new TypeError("multishotRollout: a non-text surface needs a `profile` mapping it to an AgentProfile");
755
+ return {
756
+ name: "agent",
757
+ prompt: { systemPrompt: surface }
758
+ };
759
+ }
760
+ function rolloutDispatchRef(opts, role) {
761
+ const ending = opts.user.ending ?? DEFAULT_USER_ENDING;
762
+ return `multishot-rollout:${hashCanonical(jsonDocument({
763
+ role,
764
+ maxTurns: opts.maxTurns,
765
+ revision: opts.revision,
766
+ profileDigest: opts.profileDigest,
767
+ agent: {
768
+ model: opts.agent.model,
769
+ tools: opts.agent.tools ?? [],
770
+ maxTokens: opts.agent.maxTokens,
771
+ toolFollowupMaxTokens: opts.agent.toolFollowupMaxTokens,
772
+ maxToolDispatches: opts.agent.maxToolDispatches
773
+ },
774
+ user: {
775
+ model: opts.user.model,
776
+ fallbackModels: opts.user.fallbackModels ?? [],
777
+ rigor: opts.user.rigor ?? "demanding",
778
+ agentDescription: opts.user.agentDescription ?? "an AI agent",
779
+ shapeRef: opts.user.shapeRef ?? "agent-eval:default-shape",
780
+ maxTokens: opts.user.maxTokens ?? 600,
781
+ endingRef: ending.ref,
782
+ endingInstructions: ending.instructions
783
+ }
784
+ }))}`;
785
+ }
786
+ async function converse(opts, profile, scenario, plan, optimizedRole, ctx) {
787
+ if (!Number.isSafeInteger(opts.maxTurns) || opts.maxTurns < 1) throw new RangeError(`multishotRollout: maxTurns must be a positive integer, got ${opts.maxTurns}`);
788
+ if (opts.agent.tools === void 0 !== (opts.agent.toolExecutors === void 0)) throw new TypeError("multishotRollout: agent tools and toolExecutors go together");
789
+ const user = simulatedUserSetup(opts.user, scenario.persona, plan);
790
+ const ending = opts.user.ending ?? DEFAULT_USER_ENDING;
791
+ const metered = (leg, channel, actor, transport) => {
792
+ return async (req) => {
793
+ const { tools, signal, ...rest } = req;
794
+ const request = {
795
+ ...rest,
796
+ ...tools && tools.length > 0 ? { tools } : {},
797
+ seed: ctx.seed
798
+ };
799
+ const maximumCharge = opts.maximumCharge?.(leg, request);
800
+ const result = await ctx.cost.runPaidCall({
801
+ channel,
802
+ actor,
803
+ model: request.model,
804
+ signal: signal ?? ctx.signal,
805
+ ...maximumCharge === void 0 ? {} : { maximumCharge },
806
+ execute: (callSignal) => transport({
807
+ ...request,
808
+ signal: callSignal
809
+ }),
810
+ receipt: (response) => legReceipt(request.model, response)
811
+ });
812
+ if (!result.succeeded) throw result.error;
813
+ return result.value;
814
+ };
815
+ };
816
+ const close = {};
817
+ const result = await runMultishotConversation({
818
+ profile,
819
+ persona: scenario.persona,
820
+ shape: {
821
+ buildOpener: () => user.opener,
822
+ buildDriverSystemPrompt: () => user.driverSystemPrompt
823
+ },
824
+ tools: opts.agent.tools ?? [],
825
+ toolExecutors: opts.agent.toolExecutors ?? {},
826
+ artifactTypeFor: opts.agent.artifactTypeFor,
827
+ maxTurns: opts.maxTurns,
828
+ agentModel: opts.agent.model,
829
+ driverModel: opts.user.model,
830
+ driverFallbackModels: opts.user.fallbackModels,
831
+ agentMaxTokens: opts.agent.maxTokens,
832
+ toolFollowupMaxTokens: opts.agent.toolFollowupMaxTokens,
833
+ driverMaxTokens: user.identity.maxTokens,
834
+ maxToolDispatches: opts.agent.maxToolDispatches,
835
+ agentTransport: metered("agent", "agent", "agent", opts.agent.transport),
836
+ driverTransport: metered("user", "driver", "simulated-user", opts.user.transport),
837
+ toolTransport: metered("tool", "agent", "tool", opts.agent.toolTransport ?? opts.agent.transport),
838
+ signal: ctx.signal
839
+ }, async (conversation) => {
840
+ for (let turn = 0; turn < conversation.maxTurns; turn++) {
841
+ await conversation.agentTurn(turn);
842
+ if (turn === conversation.maxTurns - 1) {
843
+ close.ending = {
844
+ kind: "turn-cap",
845
+ turn
846
+ };
847
+ return;
848
+ }
849
+ const { content } = await conversation.driverTurn(turn);
850
+ const classified = ending.classify(content);
851
+ if (classified.kind !== "continue") {
852
+ close.ending = {
853
+ kind: classified.kind,
854
+ turn
855
+ };
856
+ close.message = classified.message;
857
+ return;
858
+ }
859
+ }
860
+ });
861
+ const ended = close.ending;
862
+ if (ended === void 0) throw new Error("multishotRollout: the conversation never ended");
863
+ const transcript = result.transcript.map((message) => ({ ...message }));
864
+ if (close.message !== void 0) transcript[transcript.length - 1].content = close.message;
865
+ const userMessages = transcript.filter((message) => message.role === "user").slice(1);
866
+ const firstPushback = opts.user.pushback ? userMessages.findIndex((message) => opts.user.pushback(message.content)) : void 0;
867
+ const record = {
868
+ transcript,
869
+ artifacts: result.artifacts,
870
+ ending: ended
871
+ };
872
+ const outcome = opts.outcome(record, scenario);
873
+ if (typeof outcome?.passed !== "boolean" || typeof outcome.detail !== "string") throw new TypeError("multishotRollout: outcome must return { passed: boolean, detail: string }");
874
+ return {
875
+ transcript,
876
+ artifacts: result.artifacts,
877
+ toolCalls: result.toolCalls,
878
+ agentTurns: ended.turn + 1,
879
+ ending: ended,
880
+ outcome: {
881
+ passed: outcome.passed,
882
+ detail: outcome.detail
883
+ },
884
+ pushback: firstPushback === void 0 ? { determined: false } : {
885
+ determined: true,
886
+ firstTurn: firstPushback < 0 ? null : firstPushback
887
+ },
888
+ simulatedUser: user.identity,
889
+ seed: ctx.seed,
890
+ optimizedRole
891
+ };
892
+ }
893
+ function legReceipt(requested, response) {
894
+ const usage = response.usage;
895
+ return {
896
+ model: response.model ?? requested,
897
+ inputTokens: usage?.prompt_tokens ?? 0,
898
+ outputTokens: usage?.completion_tokens ?? 0,
899
+ ...usage === void 0 ? { usageUnknown: true } : {},
900
+ ...response.costUsd === void 0 ? {} : { actualCostUsd: response.costUsd }
901
+ };
902
+ }
903
+ // src/multishot/realism.ts
904
+ /** The shared-context identity of a user turn: its task and visible context. */
905
+ function userTurnContextDigest(input) {
906
+ return hashCanonical(jsonDocument({
907
+ taskId: input.taskId,
908
+ context: input.context
909
+ }));
910
+ }
911
+ /**
912
+ * The real user turns of one recorded conversation, from its trajectory: each
913
+ * model call whose input ends in a user message that answers an agent message
914
+ * is one turn. System and tool messages are not part of what the user saw. A
915
+ * run without a task identity yields rows without a context digest.
916
+ */
917
+ function recordedUserTurns(trajectory, run) {
918
+ const taskId = runTaskId(run);
919
+ const turns = [];
920
+ const seen = /* @__PURE__ */ new Set();
921
+ for (const step of trajectory.steps) {
922
+ const span = step.span;
923
+ if (span.kind !== "llm") continue;
924
+ const last = span.messages.at(-1);
925
+ if (last?.role !== "user" || last.content.trim().length === 0) continue;
926
+ const context = span.messages.slice(0, -1).filter((message) => (message.role === "user" || message.role === "assistant") && message.content.trim().length > 0).map((message) => ({
927
+ role: message.role,
928
+ content: message.content
929
+ }));
930
+ if (context.at(-1)?.role !== "assistant") continue;
931
+ const turn = context.filter((message) => message.role === "user").length;
932
+ if (seen.has(turn)) continue;
933
+ seen.add(turn);
934
+ turns.push({
935
+ conversationId: trajectory.runId,
936
+ ...taskId === void 0 ? {} : {
937
+ taskId,
938
+ contextDigest: userTurnContextDigest({
939
+ taskId,
940
+ context
941
+ })
942
+ },
943
+ turn,
944
+ context,
945
+ realMessage: last.content,
946
+ evidenceRefs: [{
947
+ kind: "span",
948
+ uri: span.spanId
949
+ }]
950
+ });
951
+ }
952
+ return turns;
953
+ }
954
+ /** A recorded turn carries no proof of a shared context, or a proof its
955
+ * context does not match. */
956
+ var SharedContextIdentityError = class extends Error {
957
+ conversationId;
958
+ turn;
959
+ constructor(row, reason) {
960
+ super(`recorded user turn ${row.conversationId}#${row.turn} ${reason}; a realism comparison needs the identity that proves the driver saw the real user's context`);
961
+ this.name = "SharedContextIdentityError";
962
+ this.conversationId = row.conversationId;
963
+ this.turn = row.turn;
964
+ }
965
+ };
966
+ function assertSharedContext(row) {
967
+ if (!row.taskId || !row.contextDigest) throw new SharedContextIdentityError(row, "has no task identity and context digest");
968
+ if (userTurnContextDigest({
969
+ taskId: row.taskId,
970
+ context: row.context
971
+ }) !== row.contextDigest) throw new SharedContextIdentityError(row, "has a context digest its context does not match");
972
+ }
973
+ /**
974
+ * The simulated user a rollout runs, as a realism driver: the same prompt,
975
+ * the same driver point of view on the recorded context, the same model
976
+ * rotation. An ending marker is removed, as a rollout removes it.
977
+ */
978
+ function simulatedUserDriver(opts) {
979
+ const ending = opts.user.ending ?? DEFAULT_USER_ENDING;
980
+ const models = [opts.user.model, ...opts.user.fallbackModels ?? []];
981
+ return {
982
+ identity: `simulated-user:${hashCanonical(jsonDocument({
983
+ models,
984
+ rigor: opts.user.rigor ?? "demanding",
985
+ agentDescription: opts.user.agentDescription ?? "an AI agent",
986
+ shapeRef: opts.user.shapeRef ?? "agent-eval:default-shape",
987
+ maxTokens: opts.user.maxTokens ?? 600,
988
+ endingRef: ending.ref,
989
+ endingInstructions: ending.instructions,
990
+ plan: opts.plan
991
+ }))}`,
992
+ async next({ turn, signal, costLedger }) {
993
+ const setup = simulatedUserSetup(opts.user, opts.persona(turn), opts.plan);
994
+ const messages = driverViewMessages(setup.driverSystemPrompt, turn.context);
995
+ const transport = costLedger ? async (req) => {
996
+ const result = await costLedger.runPaidCall({
997
+ channel: "driver",
998
+ phase: "realism.driver",
999
+ actor: "simulated-user",
1000
+ model: req.model,
1001
+ signal: req.signal,
1002
+ execute: (callSignal) => opts.user.transport({
1003
+ ...req,
1004
+ signal: callSignal
1005
+ }),
1006
+ receipt: (response) => ({
1007
+ model: response.model ?? req.model,
1008
+ inputTokens: response.usage?.prompt_tokens ?? 0,
1009
+ outputTokens: response.usage?.completion_tokens ?? 0,
1010
+ ...response.usage === void 0 ? { usageUnknown: true } : {},
1011
+ ...response.costUsd === void 0 ? {} : { actualCostUsd: response.costUsd }
1012
+ })
1013
+ });
1014
+ if (!result.succeeded) throw result.error;
1015
+ return result.value;
1016
+ } : opts.user.transport;
1017
+ const content = await requestUserReply({
1018
+ models,
1019
+ messages,
1020
+ transport,
1021
+ maxTokens: setup.identity.maxTokens,
1022
+ signal,
1023
+ turn: turn.turn
1024
+ });
1025
+ const classified = ending.classify(content);
1026
+ return classified.kind === "continue" ? content : classified.message;
1027
+ }
1028
+ };
1029
+ }
1030
+ /** The realism question: which of two messages did the real user write. */
1031
+ const SIMULATOR_REALISM_QUESTIONS = { real: {
1032
+ type: "choice",
1033
+ instructions: "The state holds a conversation between a user and an AI agent up to the user's next message, and two candidate next messages, a and b. A real user wrote one; a simulator wrote the other. Choose the one the real user wrote. Judge voice, length, specificity, what the user would know, and how a person reacts to the agent's last message. Neither position is more likely.",
1034
+ criteria: {
1035
+ a: "The real user wrote message a.",
1036
+ b: "The real user wrote message b."
1037
+ }
1038
+ } };
1039
+ /** The realism judge as a System One decision point at the turn layer. */
1040
+ function simulatorRealismJudge(opts) {
1041
+ const questionDigest = decisionQuestionDigest({
1042
+ id: opts.id,
1043
+ version: opts.version,
1044
+ model: opts.model,
1045
+ servedModel: opts.calibration?.servedModel ?? opts.model,
1046
+ name: "real",
1047
+ question: SIMULATOR_REALISM_QUESTIONS.real
1048
+ });
1049
+ const point = decisionPoint({
1050
+ id: opts.id,
1051
+ version: opts.version,
1052
+ layers: ["turn"],
1053
+ model: opts.model,
1054
+ questions: SIMULATOR_REALISM_QUESTIONS,
1055
+ policy: { real: {
1056
+ minimumProbability: opts.minimumProbability ?? .6,
1057
+ minimumMargin: opts.minimumMargin ?? .2,
1058
+ options: {
1059
+ a: { action: "record" },
1060
+ b: { action: "record" }
1061
+ },
1062
+ ...opts.calibration ? { calibration: opts.calibration } : {}
1063
+ } },
1064
+ ledger: opts.ledger,
1065
+ evaluator: opts.evaluator
1066
+ });
1067
+ return {
1068
+ id: point.id,
1069
+ definitionDigest: point.definitionDigest,
1070
+ questionDigest,
1071
+ calibrated: opts.calibration !== void 0 && opts.calibration.kappa >= .77 && opts.calibration.questionDigest === questionDigest,
1072
+ decide: point.decide
1073
+ };
1074
+ }
1075
+ /** Measure how often a judge tells the driver's message from the real user's. */
1076
+ async function measureSimulatorRealism(opts) {
1077
+ if (opts.turns.length === 0) throw new RangeError("measureSimulatorRealism: no recorded turns");
1078
+ for (const row of opts.turns) assertSharedContext(row);
1079
+ const at = opts.at ?? (/* @__PURE__ */ new Date()).toISOString();
1080
+ const turns = sampleTurns(opts.turns, opts.sample, opts.seed);
1081
+ const correctByConversation = /* @__PURE__ */ new Map();
1082
+ const reasons = {};
1083
+ const probabilitiesOnReal = [];
1084
+ let failedJudgments = 0;
1085
+ let unbalancedTurns = 0;
1086
+ for (const row of turns) {
1087
+ const simulated = await opts.driver.next({
1088
+ turn: row,
1089
+ ...opts.signal ? { signal: opts.signal } : {},
1090
+ ...opts.costLedger ? { costLedger: opts.costLedger } : {}
1091
+ });
1092
+ const unit = `${row.conversationId}:${row.turn}`;
1093
+ const answers = [];
1094
+ for (const order of ["real-first", "real-second"]) {
1095
+ const judged = await opts.judge.decide({
1096
+ runId: opts.runId,
1097
+ invocationId: `${unit}:${order}`,
1098
+ layer: "turn",
1099
+ consumer: "simulator-realism",
1100
+ state: {
1101
+ context: row.context,
1102
+ a: order === "real-first" ? row.realMessage : simulated,
1103
+ b: order === "real-first" ? simulated : row.realMessage
1104
+ },
1105
+ scope: {
1106
+ population: [unit],
1107
+ n: 1,
1108
+ window: {
1109
+ from: at,
1110
+ to: at
1111
+ }
1112
+ },
1113
+ at,
1114
+ evidenceRefs: row.evidenceRefs?.length ? row.evidenceRefs : [{
1115
+ kind: "event",
1116
+ uri: `user-turn:${unit}`
1117
+ }]
1118
+ }, {
1119
+ ...opts.signal ? { signal: opts.signal } : {},
1120
+ ...opts.costLedger ? { costLedger: opts.costLedger } : {},
1121
+ channel: "judge",
1122
+ actor: "simulator-realism-judge",
1123
+ costPhase: "realism.judge"
1124
+ });
1125
+ answers.push(judgedAnswer(judged));
1126
+ }
1127
+ const failed = answers.filter((answer) => !answer).length;
1128
+ failedJudgments += failed;
1129
+ if (failed > 0) {
1130
+ if (failed < answers.length) unbalancedTurns += 1;
1131
+ continue;
1132
+ }
1133
+ for (const [index, answer] of answers.entries()) {
1134
+ if (!answer) continue;
1135
+ const realOption = index === 0 ? "a" : "b";
1136
+ reasons[answer.reason] = (reasons[answer.reason] ?? 0) + 1;
1137
+ probabilitiesOnReal.push(answer.probabilities[realOption] ?? 0);
1138
+ const list = correctByConversation.get(row.conversationId) ?? [];
1139
+ list.push(answer.choice === realOption ? 1 : 0);
1140
+ correctByConversation.set(row.conversationId, list);
1141
+ }
1142
+ }
1143
+ if (correctByConversation.size === 0) throw new Error("measureSimulatorRealism: no presentation was judged");
1144
+ const interval = clusterBootstrapMean([...correctByConversation].map(([conversationId, list]) => ({
1145
+ cluster: conversationId,
1146
+ value: list.reduce((sum, value) => sum + value, 0) / list.length
1147
+ })), {
1148
+ ...opts.confidence === void 0 ? {} : { confidence: opts.confidence },
1149
+ ...opts.resamples === void 0 ? {} : { resamples: opts.resamples },
1150
+ ...opts.seed === void 0 ? {} : { seed: opts.seed }
1151
+ });
1152
+ const onCalibratedModel = Object.keys(reasons).every((reason) => reason === "threshold" || reason === "uncertain");
1153
+ return {
1154
+ driver: opts.driver.identity,
1155
+ judge: {
1156
+ id: opts.judge.id,
1157
+ definitionDigest: opts.judge.definitionDigest,
1158
+ calibrated: opts.judge.calibrated && onCalibratedModel,
1159
+ reasons
1160
+ },
1161
+ conversations: correctByConversation.size,
1162
+ turns: turns.length,
1163
+ presentations: probabilitiesOnReal.length,
1164
+ failedJudgments,
1165
+ unbalancedTurns,
1166
+ accuracy: {
1167
+ mean: interval.mean,
1168
+ low: interval.low,
1169
+ high: interval.high,
1170
+ confidence: interval.confidence,
1171
+ resamples: interval.resamples
1172
+ },
1173
+ meanProbabilityOnReal: probabilitiesOnReal.reduce((sum, value) => sum + value, 0) / probabilitiesOnReal.length,
1174
+ indistinguishable: interval.low <= .5 && interval.high >= .5
1175
+ };
1176
+ }
1177
+ function judgedAnswer(judged) {
1178
+ if (!judged.succeeded) return void 0;
1179
+ const record = judged.value.record;
1180
+ if (!record || record.error) return void 0;
1181
+ return record.answers.real;
1182
+ }
1183
+ function sampleTurns(turns, sample, seed) {
1184
+ if (sample === void 0 || sample >= turns.length) return [...turns];
1185
+ if (!Number.isSafeInteger(sample) || sample < 1) throw new RangeError(`measureSimulatorRealism: sample must be a positive integer, got ${sample}`);
1186
+ const random = makeRng(seed ?? 0);
1187
+ const order = turns.map((_, index) => index);
1188
+ for (let index = order.length - 1; index > 0; index--) {
1189
+ const swap = Math.floor(random() * (index + 1));
1190
+ [order[index], order[swap]] = [order[swap], order[index]];
1191
+ }
1192
+ return order.slice(0, sample).sort((left, right) => left - right).map((index) => turns[index]);
1193
+ }
1194
+ // src/multishot/adversarial-user.ts
1195
+ /** Scenarios for the user-side search would reach the agent's held-out split. */
1196
+ var AdversarialSplitError = class extends Error {
1197
+ scenarioIds;
1198
+ constructor(scenarioIds) {
1199
+ super(`adversarial user search would use ${scenarioIds.length} scenario(s) that share an id or persona with the agent's held-out split (${listSome(scenarioIds)})`);
1200
+ this.name = "AdversarialSplitError";
1201
+ this.scenarioIds = scenarioIds;
1202
+ }
1203
+ };
1204
+ /**
1205
+ * Search for a simulated-user plan that makes a fixed agent fail, admit it
1206
+ * only above a realism floor, and emit what it breaks as agent train scenarios.
1207
+ */
1208
+ async function improveAdversarialUser(opts) {
1209
+ if ("judge" in opts || "gate" in opts) throw new UserSideObjectiveError("improveAdversarialUser: the user side's objective is the agent's failure rate; it accepts no judge or gate");
1210
+ if (!(opts.realism.maxJudgeAccuracy >= .5 && opts.realism.maxJudgeAccuracy <= 1)) throw new RangeError("improveAdversarialUser: realism.maxJudgeAccuracy must be in [0.5, 1]");
1211
+ const repeats = opts.solvability?.repeats ?? 3;
1212
+ if (!Number.isSafeInteger(repeats) || repeats < 1) throw new RangeError("improveAdversarialUser: solvability.repeats must be a positive integer");
1213
+ assertDisjointFromHeldOut([...opts.scenarios, ...opts.selectionScenarios ?? []], opts.agentHeldOut);
1214
+ const rollout = userSideRollout(opts.rollout, opts.agentProfile);
1215
+ const shared = {
1216
+ agent: rollout.agent,
1217
+ dispatchRef: rollout.dispatchRef,
1218
+ scenarios: opts.scenarios,
1219
+ judge: agentFailureJudge(),
1220
+ describeArtifact: describeConversation,
1221
+ baselineSurface: opts.baselinePlan,
1222
+ ...opts.selectionScenarios ? { selectionScenarios: opts.selectionScenarios } : {},
1223
+ ...opts.budget ? { budget: opts.budget } : {},
1224
+ ...opts.runDir ? { runDir: opts.runDir } : {},
1225
+ ...opts.storage ? { storage: opts.storage } : {},
1226
+ ...opts.expectUsage ? { expectUsage: opts.expectUsage } : {},
1227
+ ...opts.model ? { model: opts.model } : {}
1228
+ };
1229
+ const improvement = opts.method ? await selfImprove({
1230
+ ...shared,
1231
+ method: opts.method
1232
+ }) : await selfImprove({
1233
+ ...shared,
1234
+ ...opts.proposer ? { proposer: opts.proposer } : {}
1235
+ });
1236
+ const plan = String(improvement.winner.surface);
1237
+ if (improvement.gateDecision !== "ship") return {
1238
+ improvement,
1239
+ plan,
1240
+ realism: null,
1241
+ admitted: false,
1242
+ reasons: [`the user-side search did not ship (${improvement.gateDecision})`],
1243
+ trainScenarios: [],
1244
+ unsolvableScenarios: []
1245
+ };
1246
+ const realism = await measureSimulatorRealism({
1247
+ turns: opts.realism.turns,
1248
+ driver: simulatedUserDriver({
1249
+ user: opts.rollout.user,
1250
+ persona: opts.realism.persona,
1251
+ plan
1252
+ }),
1253
+ judge: opts.realism.judge,
1254
+ runId: opts.realism.runId,
1255
+ ...pick(opts.realism, [
1256
+ "at",
1257
+ "sample",
1258
+ "confidence",
1259
+ "resamples",
1260
+ "seed",
1261
+ "costLedger"
1262
+ ])
1263
+ });
1264
+ const reasons = [];
1265
+ if (!realism.judge.calibrated) reasons.push("realism judge is not calibrated on this question and served model; a plan is admitted only by a calibrated judge");
1266
+ if (realism.accuracy.high > opts.realism.maxJudgeAccuracy) reasons.push(`realism: judge accuracy reaches ${realism.accuracy.high.toFixed(3)} at the interval's upper end, above the floor ${opts.realism.maxJudgeAccuracy}`);
1267
+ const admitted = reasons.length === 0;
1268
+ return {
1269
+ improvement,
1270
+ plan,
1271
+ realism,
1272
+ admitted,
1273
+ reasons,
1274
+ ...await sortBySolvability(opts, admitted ? failedScenarios(improvement, opts.scenarios, plan) : [], repeats)
1275
+ };
1276
+ }
1277
+ /** Run each candidate under its plan; one pass makes it a train scenario. */
1278
+ async function sortBySolvability(opts, candidates, repeats) {
1279
+ if (candidates.length === 0) return {
1280
+ trainScenarios: [],
1281
+ unsolvableScenarios: []
1282
+ };
1283
+ const reference = opts.solvability?.referenceProfile;
1284
+ const profile = reference ?? opts.agentProfile;
1285
+ const solver = userSideRollout(opts.rollout, profile);
1286
+ const campaign = await runCampaign({
1287
+ scenarios: candidates,
1288
+ dispatch: (scenario, ctx) => solver.agent("", scenario, ctx),
1289
+ dispatchRef: `adversarial-solvability:${solver.dispatchRef}`,
1290
+ reps: repeats,
1291
+ seed: opts.solvability?.seed ?? 42,
1292
+ runDir: opts.runDir ? `${opts.runDir}/solvability` : `mem://adversarial-solvability`,
1293
+ storage: opts.storage ?? (opts.runDir ? fsCampaignStorage() : inMemoryCampaignStorage()),
1294
+ expectUsage: opts.expectUsage ?? "assert"
1295
+ });
1296
+ const agent = reference ? "reference" : "same";
1297
+ const profileDigest = hashCanonical(jsonDocument(profile));
1298
+ const trainScenarios = [];
1299
+ const unsolvableScenarios = [];
1300
+ for (const scenario of candidates) {
1301
+ const cells = campaign.cells.filter((cell) => cell.scenarioId === scenario.id);
1302
+ const passed = cells.find((cell) => cell.error === void 0 && cell.artifact.outcome.passed);
1303
+ if (passed) {
1304
+ const solvedBy = {
1305
+ agent,
1306
+ profileDigest,
1307
+ seed: passed.artifact.seed,
1308
+ detail: passed.artifact.outcome.detail
1309
+ };
1310
+ trainScenarios.push({
1311
+ ...scenario,
1312
+ origin: {
1313
+ ...scenario.origin,
1314
+ solvedBy
1315
+ }
1316
+ });
1317
+ continue;
1318
+ }
1319
+ const last = cells.at(-1);
1320
+ unsolvableScenarios.push({
1321
+ scenario,
1322
+ reason: `the ${agent} agent passed none of ${cells.length} conversation(s) under the plan (${last?.error ?? last?.artifact.outcome.detail ?? "no conversation ran"})`,
1323
+ attempts: cells.length
1324
+ });
1325
+ }
1326
+ return {
1327
+ trainScenarios,
1328
+ unsolvableScenarios
1329
+ };
1330
+ }
1331
+ /** Score of the user side: 1 when the agent failed the outcome check. */
1332
+ function agentFailureJudge() {
1333
+ return {
1334
+ name: "agent-failure",
1335
+ judgeVersion: "agent-eval:agent-failure:v1",
1336
+ dimensions: [{
1337
+ key: "agent_failure",
1338
+ description: "1 when the agent failed the code-checked outcome"
1339
+ }],
1340
+ score({ artifact }) {
1341
+ if (artifact.optimizedRole !== "user") throw new UserSideObjectiveError("agent-failure scores user-side conversations only");
1342
+ const failed = artifact.outcome.passed ? 0 : 1;
1343
+ return {
1344
+ dimensions: { agent_failure: failed },
1345
+ composite: failed,
1346
+ notes: artifact.outcome.detail
1347
+ };
1348
+ }
1349
+ };
1350
+ }
1351
+ function assertDisjointFromHeldOut(scenarios, heldOut) {
1352
+ const ids = new Set(heldOut.map((scenario) => scenario.id));
1353
+ const personas = new Set(heldOut.map((scenario) => personaDigest(scenario)));
1354
+ const overlap = scenarios.filter((scenario) => ids.has(scenario.id) || personas.has(personaDigest(scenario))).map((scenario) => scenario.id);
1355
+ if (overlap.length > 0) throw new AdversarialSplitError([...new Set(overlap)]);
1356
+ }
1357
+ function personaDigest(scenario) {
1358
+ return hashCanonical(jsonDocument(scenario.persona));
1359
+ }
1360
+ function failedScenarios(improvement, scenarios, plan) {
1361
+ const planDigest = hashCanonical(plan);
1362
+ const emitted = /* @__PURE__ */ new Map();
1363
+ for (const cell of improvement.raw.winnerOnHoldout.cells) {
1364
+ if (cell.error !== void 0 || cell.artifact.outcome.passed) continue;
1365
+ if (emitted.has(cell.scenarioId)) continue;
1366
+ const source = scenarios.find((scenario) => scenario.id === cell.scenarioId);
1367
+ if (!source) continue;
1368
+ emitted.set(cell.scenarioId, {
1369
+ ...structuredClone(source),
1370
+ id: `${source.id}~adversarial-${planDigest.slice(7, 19)}`,
1371
+ userPlan: [source.userPlan, plan].filter(Boolean).join("\n\n"),
1372
+ origin: {
1373
+ kind: "adversarial-user",
1374
+ sourceScenarioId: source.id,
1375
+ planDigest
1376
+ }
1377
+ });
1378
+ }
1379
+ return [...emitted.values()];
1380
+ }
1381
+ function pick(value, keys) {
1382
+ const picked = {};
1383
+ for (const key of keys) if (value[key] !== void 0) picked[key] = value[key];
1384
+ return picked;
1385
+ }
434
1386
  // src/multishot/judges.ts
435
1387
  async function runJudge(judge, input) {
436
1388
  const model = judge.model ?? "zai/glm-5.3";
@@ -824,6 +1776,6 @@ function withJudgeMaxTokens(judge, maxTokens) {
824
1776
  maxTokens
825
1777
  };
826
1778
  }
827
- export { DEFAULT_CODER_MODEL, DEFAULT_JUDGE_MODEL, MultishotDriverEmptyError, MultishotFatalToolError, assertMultishotShotResult, computeCellComposite, defaultDelegationTools, defaultShapeFromProfile, estimateMultishotCost, renderDimensions, renderJsonFooter, runJudge, runMultishot, runMultishotConversation, runMultishotMatrix };
1779
+ export { AdversarialScenarioInHeldOutError, AdversarialSplitError, DEFAULT_CODER_MODEL, DEFAULT_JUDGE_MODEL, DEFAULT_USER_ENDING, MultishotDriverEmptyError, MultishotFatalToolError, SIMULATOR_REALISM_QUESTIONS, SharedContextIdentityError, SimulatedUserMismatchError, UserSideObjectiveError, assertHeldOutExcludesAdversarial, assertMultishotShotResult, assertSameSimulatedUser, computeCellComposite, conversationGate, conversationJudge, defaultDelegationTools, defaultShapeFromProfile, describeConversation, estimateMultishotCost, improveAdversarialUser, measureSimulatorRealism, multishotRollout, recordedUserTurns, renderDimensions, renderJsonFooter, runJudge, runMultishot, runMultishotConversation, runMultishotMatrix, simulatedUserDriver, simulatorRealismJudge, userTurnContextDigest };
828
1780
 
829
1781
  //# sourceMappingURL=index.js.map