reeval 0.27.2 → 0.28.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 (433) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +15 -15
  3. package/dist/{adapter-BuisZmtg.js → adapter-mMrKaF9C.js} +4 -4
  4. package/dist/{adapter-BuisZmtg.js.map → adapter-mMrKaF9C.js.map} +1 -1
  5. package/dist/agent-BMHM86Qy.js +271 -0
  6. package/dist/agent-BMHM86Qy.js.map +1 -0
  7. package/dist/agents-BP6F1c6y.d.ts +3 -0
  8. package/dist/agents-DgfyOMRm.js +400 -0
  9. package/dist/agents-DgfyOMRm.js.map +1 -0
  10. package/dist/{api-C8ZbQG7s.js → api-DIzSkDXZ.js} +2 -2
  11. package/dist/{api-C8ZbQG7s.js.map → api-DIzSkDXZ.js.map} +1 -1
  12. package/dist/assemble-Dsl_C0gf.js +1 -0
  13. package/dist/{assemble-Co4noZvq.js → assemble-DxVRcaLC.js} +17 -17
  14. package/dist/{assemble-Co4noZvq.js.map → assemble-DxVRcaLC.js.map} +1 -1
  15. package/dist/{attach-DP3wc3A7.js → attach-CB-ESG7D.js} +5 -5
  16. package/dist/{attach-DP3wc3A7.js.map → attach-CB-ESG7D.js.map} +1 -1
  17. package/dist/{attempt-host-Bo8mbyuQ.js → attempt-host-B3zsORzT.js} +5 -5
  18. package/dist/{attempt-host-Bo8mbyuQ.js.map → attempt-host-B3zsORzT.js.map} +1 -1
  19. package/dist/{boat-BgdwW3_Q.js → boat-B2B3XO9B.js} +8 -8
  20. package/dist/{boat-BgdwW3_Q.js.map → boat-B2B3XO9B.js.map} +1 -1
  21. package/dist/{boat-obBLVWWQ.js → boat-CANaudKC.js} +1 -1
  22. package/dist/{boat-images-CetjuF_c.js → boat-images-sSz82GXk.js} +8 -8
  23. package/dist/{boat-images-CetjuF_c.js.map → boat-images-sSz82GXk.js.map} +1 -1
  24. package/dist/{bundle-dK2eveab.js → bundle-CJsMYTJw.js} +15 -13
  25. package/dist/bundle-CJsMYTJw.js.map +1 -0
  26. package/dist/capture-5WMKZZRx.js +1 -0
  27. package/dist/{capture-B8_Kx5R-.js → capture-DTHe_BcS.js} +13 -13
  28. package/dist/{capture-B8_Kx5R-.js.map → capture-DTHe_BcS.js.map} +1 -1
  29. package/dist/{cases-C6vnV-gn.js → cases-B_a7flE8.js} +3 -3
  30. package/dist/{cases-C6vnV-gn.js.map → cases-B_a7flE8.js.map} +1 -1
  31. package/dist/cases-D0-dA8q1.js +1 -0
  32. package/dist/{classify-BIJQ2Xqo.js → classify-gLl11KS8.js} +3 -3
  33. package/dist/{classify-BIJQ2Xqo.js.map → classify-gLl11KS8.js.map} +1 -1
  34. package/dist/{cli-eakKMZFR.js → cli-EopIiwBJ.js} +113 -112
  35. package/dist/cli-EopIiwBJ.js.map +1 -0
  36. package/dist/{cli-spec-DO-RQP-t.js → cli-spec-CYh8vLTE.js} +31 -9
  37. package/dist/cli-spec-CYh8vLTE.js.map +1 -0
  38. package/dist/cli.js +4 -2
  39. package/dist/cli.js.map +1 -1
  40. package/dist/{cloud-BQbD0pT8.js → cloud-CsofVdxN.js} +4 -4
  41. package/dist/{cloud-BQbD0pT8.js.map → cloud-CsofVdxN.js.map} +1 -1
  42. package/dist/{cloud-files-DFLNNUdK.js → cloud-files-BpWbKpxg.js} +9 -9
  43. package/dist/{cloud-files-DFLNNUdK.js.map → cloud-files-BpWbKpxg.js.map} +1 -1
  44. package/dist/{cloud-project-D-5mk4oh.js → cloud-project-CN1f7p5a.js} +2 -2
  45. package/dist/{cloud-project-D-5mk4oh.js.map → cloud-project-CN1f7p5a.js.map} +1 -1
  46. package/dist/{cloud-project-CV3-AVEe.js → cloud-project-DLn9l5X6.js} +1 -1
  47. package/dist/{cloud-push-bZL0TUQm.js → cloud-push-CLIcWVa6.js} +11 -11
  48. package/dist/{cloud-push-bZL0TUQm.js.map → cloud-push-CLIcWVa6.js.map} +1 -1
  49. package/dist/{cloud-push-CjBRaPak.js → cloud-push-CPLWxn8b.js} +1 -1
  50. package/dist/{cloud-run-CKcBID4J.js → cloud-run-ChdOr6zu.js} +18 -14
  51. package/dist/cloud-run-ChdOr6zu.js.map +1 -0
  52. package/dist/{cloud-run-BYvtsyiN.js → cloud-run-DIAXbsWd.js} +1 -1
  53. package/dist/{cloud-secrets-OuKaQUlX.js → cloud-secrets-DAuRwjTP.js} +75 -57
  54. package/dist/cloud-secrets-DAuRwjTP.js.map +1 -0
  55. package/dist/cloud-secrets-a1B2IsjU.js +1 -0
  56. package/dist/{command-C6nA8Fwo.js → command-6UkOgqge.js} +22 -22
  57. package/dist/{command-C6nA8Fwo.js.map → command-6UkOgqge.js.map} +1 -1
  58. package/dist/{command-BC_zVYDg.js → command-CQS2gjNM.js} +17 -17
  59. package/dist/{command-BC_zVYDg.js.map → command-CQS2gjNM.js.map} +1 -1
  60. package/dist/{command-CPJuVTme.js → command-CUBXsFfz.js} +7 -7
  61. package/dist/{command-CPJuVTme.js.map → command-CUBXsFfz.js.map} +1 -1
  62. package/dist/{command-CU-A_HL3.js → command-Dq-mFirh.js} +2 -2
  63. package/dist/{command-CU-A_HL3.js.map → command-Dq-mFirh.js.map} +1 -1
  64. package/dist/{command-CcWqLUbc.js → command-I8E1FgG5.js} +12 -12
  65. package/dist/{command-CcWqLUbc.js.map → command-I8E1FgG5.js.map} +1 -1
  66. package/dist/{commands-DzRyz-v9.js → commands-BeLE4oN4.js} +18 -18
  67. package/dist/{commands-DzRyz-v9.js.map → commands-BeLE4oN4.js.map} +1 -1
  68. package/dist/{commands-CBbpjvzR.js → commands-wkSzuPgF.js} +1 -1
  69. package/dist/{config-Ozz1O7Dl.js → config-CfZWILTy.js} +22 -25
  70. package/dist/config-CfZWILTy.js.map +1 -0
  71. package/dist/{provenance-Cylt_YxT.d.ts → core-C2d0URWs.d.ts} +2 -2
  72. package/dist/{core-B3Qg8zwG.js → core-tpzE5NhW.js} +8 -8
  73. package/dist/{core-B3Qg8zwG.js.map → core-tpzE5NhW.js.map} +1 -1
  74. package/dist/{cost-DQ0ayy6h.js → cost-CSfMv_sp.js} +5 -2
  75. package/dist/cost-CSfMv_sp.js.map +1 -0
  76. package/dist/{cost-a_rUSdsf.js → cost-_uinO5Yg.js} +1 -1
  77. package/dist/{cost-Dp-xFGJ1.js → cost-rRhvzqJo.js} +2 -2
  78. package/dist/{cost-Dp-xFGJ1.js.map → cost-rRhvzqJo.js.map} +1 -1
  79. package/dist/{cursor-catalog-pRZm3jCP.js → cursor-catalog-Cw3kv68u.js} +15 -5
  80. package/dist/cursor-catalog-Cw3kv68u.js.map +1 -0
  81. package/dist/{daytona-Bg62QEsJ.js → daytona-fLoFUu2I.js} +10 -10
  82. package/dist/{daytona-Bg62QEsJ.js.map → daytona-fLoFUu2I.js.map} +1 -1
  83. package/dist/{daytona-image-DFsZlHaL.js → daytona-image-BRBFQA9c.js} +4 -4
  84. package/dist/{daytona-image-DFsZlHaL.js.map → daytona-image-BRBFQA9c.js.map} +1 -1
  85. package/dist/daytona-image-DuZpq9Qw.js +1 -0
  86. package/dist/db-BPumcvp8.js +1 -0
  87. package/dist/{db-BQb7-_SX.js → db-t2g-ANto.js} +10 -10
  88. package/dist/{db-BQb7-_SX.js.map → db-t2g-ANto.js.map} +1 -1
  89. package/dist/{default-effort-DXPtXTsk.js → default-effort-ByvTDqX7.js} +3 -2
  90. package/dist/default-effort-ByvTDqX7.js.map +1 -0
  91. package/dist/{default-effort-C1Y0LOHo.js → default-effort-C9He6KVv.js} +1 -1
  92. package/dist/{docker-BNZw-uhT.js → docker-BKA4ELbB.js} +1 -1
  93. package/dist/{docker-DzSu1y_e.js → docker-h8mYtGWF.js} +2 -2
  94. package/dist/{docker-DzSu1y_e.js.map → docker-h8mYtGWF.js.map} +1 -1
  95. package/dist/{doctor-TkGfyasW.js → doctor-CPXSQ4s-.js} +27 -26
  96. package/dist/doctor-CPXSQ4s-.js.map +1 -0
  97. package/dist/{env-8x1O8I1M.js → env-ARmqWMQ5.js} +3 -1
  98. package/dist/env-ARmqWMQ5.js.map +1 -0
  99. package/dist/{environment-C2i5ggoS.js → environment-B_ht7Lbp.js} +4 -3
  100. package/dist/environment-B_ht7Lbp.js.map +1 -0
  101. package/dist/{errors-xUi3AkBi.js → errors-BQxdlRgT.js} +2 -2
  102. package/dist/{errors-xUi3AkBi.js.map → errors-BQxdlRgT.js.map} +1 -1
  103. package/dist/{eval-source-CVx2dMCC.js → eval-source-Byy9CDjg.js} +5 -5
  104. package/dist/{eval-source-CVx2dMCC.js.map → eval-source-Byy9CDjg.js.map} +1 -1
  105. package/dist/{evaluate-Nnh0iPuo.d.ts → evaluate-Bhdj1cv0.d.ts} +1 -1
  106. package/dist/{evaluate-D9hHc00J.js → evaluate-DoObbRZ2.js} +70 -55
  107. package/dist/evaluate-DoObbRZ2.js.map +1 -0
  108. package/dist/events-D7kBBdzl.js +1 -0
  109. package/dist/{events-CQJ9VK-x.js → events-Da6Pl5_b.js} +3 -3
  110. package/dist/{events-CQJ9VK-x.js.map → events-Da6Pl5_b.js.map} +1 -1
  111. package/dist/{files-DxMU7Qa3.js → files-CLNAE1rM.js} +6 -6
  112. package/dist/{files-DxMU7Qa3.js.map → files-CLNAE1rM.js.map} +1 -1
  113. package/dist/files-CjabTKaR.js +1 -0
  114. package/dist/{files-C0k5nNUu.js → files-CmLgOH3w.js} +3 -3
  115. package/dist/{files-C0k5nNUu.js.map → files-CmLgOH3w.js.map} +1 -1
  116. package/dist/{files-CGzUGcN2.js → files-CsJWxr6c.js} +2 -2
  117. package/dist/{files-CGzUGcN2.js.map → files-CsJWxr6c.js.map} +1 -1
  118. package/dist/{files-FLbqNavk.js → files-DV9Tfusu.js} +7 -7
  119. package/dist/{files-FLbqNavk.js.map → files-DV9Tfusu.js.map} +1 -1
  120. package/dist/{files--mW-Ym3B.js → files-Dc2xVqx1.js} +1 -1
  121. package/dist/{files-lwByH3UH.js → files-DgRaHy0k.js} +5 -5
  122. package/dist/{files-lwByH3UH.js.map → files-DgRaHy0k.js.map} +1 -1
  123. package/dist/files-DrXNXtQR.js +1 -0
  124. package/dist/files-Ds_hi5Bh.js +1 -0
  125. package/dist/{files-f7mRGOM3.js → files-uFFwVJZG.js} +4 -4
  126. package/dist/{files-f7mRGOM3.js.map → files-uFFwVJZG.js.map} +1 -1
  127. package/dist/gateway.d.ts +1 -1
  128. package/dist/harness-Dcd3ffkY.js.map +1 -1
  129. package/dist/{harness-install-CTAsIRk9.js → harness-install-CmD1eQsL.js} +7 -5
  130. package/dist/harness-install-CmD1eQsL.js.map +1 -0
  131. package/dist/harness.d.ts +1 -1
  132. package/dist/{ids-D9QbaaVk.js → ids-cqB_4aeP.js} +3 -3
  133. package/dist/{ids-D9QbaaVk.js.map → ids-cqB_4aeP.js.map} +1 -1
  134. package/dist/{images-D-MMgo1d.js → images-CWT6Ye03.js} +13 -13
  135. package/dist/{images-D-MMgo1d.js.map → images-CWT6Ye03.js.map} +1 -1
  136. package/dist/index.d.ts +4 -4
  137. package/dist/index.js +4 -4
  138. package/dist/{init-DJXSbI19.js → init-BESRsV7F.js} +5 -5
  139. package/dist/{init-DJXSbI19.js.map → init-BESRsV7F.js.map} +1 -1
  140. package/dist/init-CSfZF3uV.js +1 -0
  141. package/dist/{ink-list-BsPpwXuw.js → ink-list-Cu48wlm7.js} +2 -2
  142. package/dist/{ink-list-BsPpwXuw.js.map → ink-list-Cu48wlm7.js.map} +1 -1
  143. package/dist/{inputs-CTlr7diQ.js → inputs-BoQrNOoN.js} +6 -6
  144. package/dist/{inputs-CTlr7diQ.js.map → inputs-BoQrNOoN.js.map} +1 -1
  145. package/dist/internal/vm.d.ts +2 -2
  146. package/dist/{invocations-2vDCZ_7f.js → invocations-FUUh2r22.js} +3 -3
  147. package/dist/{invocations-2vDCZ_7f.js.map → invocations-FUUh2r22.js.map} +1 -1
  148. package/dist/{judge-3ABSMDa4.js → judge-CUjB8kYF.js} +71 -24
  149. package/dist/judge-CUjB8kYF.js.map +1 -0
  150. package/dist/judge.d.ts +3 -3
  151. package/dist/judge.js +1 -1
  152. package/dist/{judgments-CVCUWT-g.js → judgments-8zHsGW8o.js} +2 -2
  153. package/dist/{judgments-CVCUWT-g.js.map → judgments-8zHsGW8o.js.map} +1 -1
  154. package/dist/{kinds-DhH1c5u6.js → kinds-C6PeknHN.js} +7 -7
  155. package/dist/{kinds-DhH1c5u6.js.map → kinds-C6PeknHN.js.map} +1 -1
  156. package/dist/{labels-Dtyf5-pd.js → labels-CbwHtEHq.js} +2 -3
  157. package/dist/labels-CbwHtEHq.js.map +1 -0
  158. package/dist/{layout-ChWMCz4x.js → layout-zk3wcJ-D.js} +4 -4
  159. package/dist/{layout-ChWMCz4x.js.map → layout-zk3wcJ-D.js.map} +1 -1
  160. package/dist/{link-TH-DivdC.js → link-C74mznSy.js} +3 -3
  161. package/dist/{link-TH-DivdC.js.map → link-C74mznSy.js.map} +1 -1
  162. package/dist/{list-DSm2TZds.js → list-B_bnCkKF.js} +7 -7
  163. package/dist/{list-DSm2TZds.js.map → list-B_bnCkKF.js.map} +1 -1
  164. package/dist/{live-D3zHauJd.js → live-BXjhPeBS.js} +5 -5
  165. package/dist/{live-D3zHauJd.js.map → live-BXjhPeBS.js.map} +1 -1
  166. package/dist/{live-YXsT5z0d.js → live-CVlGZ5uP.js} +2 -2
  167. package/dist/{live-YXsT5z0d.js.map → live-CVlGZ5uP.js.map} +1 -1
  168. package/dist/{machine-service-DeE4-ueU.js → machine-service-CIPF3GOD.js} +1 -1
  169. package/dist/{machine-service-Bs-09eUN.js → machine-service-WRvLuPyf.js} +3 -3
  170. package/dist/{machine-service-Bs-09eUN.js.map → machine-service-WRvLuPyf.js.map} +1 -1
  171. package/dist/{machines-BxWMvCkU.js → machines-BIhbRJ4m.js} +23 -23
  172. package/dist/{machines-BxWMvCkU.js.map → machines-BIhbRJ4m.js.map} +1 -1
  173. package/dist/{markdown-COts-jxf.js → markdown-aVaKa5tB.js} +2 -2
  174. package/dist/{markdown-COts-jxf.js.map → markdown-aVaKa5tB.js.map} +1 -1
  175. package/dist/{model-BGc_y-K_.js → model-CnuJlONr.js} +1 -1
  176. package/dist/{model-B89uRS9X.js → model-D3sK3a5R.js} +13 -13
  177. package/dist/model-D3sK3a5R.js.map +1 -0
  178. package/dist/{model-WiM6J5cw.js → model-DmPDqMOT.js} +6 -5
  179. package/dist/model-DmPDqMOT.js.map +1 -0
  180. package/dist/{model-U9bZgClN.js → model-EhOuBsho.js} +24 -16
  181. package/dist/{model-U9bZgClN.js.map → model-EhOuBsho.js.map} +1 -1
  182. package/dist/model-Yu4XAseh.js +1 -0
  183. package/dist/{node-eEX-KpkO.js → node-ChfH6UTx.js} +4 -4
  184. package/dist/{node-eEX-KpkO.js.map → node-ChfH6UTx.js.map} +1 -1
  185. package/dist/{openrouter-models-B1sIOTD2.js → openrouter-models-D19R699I.js} +7 -8
  186. package/dist/openrouter-models-D19R699I.js.map +1 -0
  187. package/dist/options-DFSyG3S8.js +1 -0
  188. package/dist/{patch-CudvhNHJ.js → patch-DBQCuZAJ.js} +2 -2
  189. package/dist/{patch-CudvhNHJ.js.map → patch-DBQCuZAJ.js.map} +1 -1
  190. package/dist/pi-providers-C7r3J259.js +1 -0
  191. package/dist/{plan-CqBiH_vR.js → plan-Dj19aa3f.js} +10 -10
  192. package/dist/{plan-CqBiH_vR.js.map → plan-Dj19aa3f.js.map} +1 -1
  193. package/dist/{plugins-4DkJ-SSG.js → plugins-rlmJz7B3.js} +6 -15
  194. package/dist/plugins-rlmJz7B3.js.map +1 -0
  195. package/dist/{preflight-DshE4siP.js → preflight-C919d0x1.js} +9 -9
  196. package/dist/{preflight-DshE4siP.js.map → preflight-C919d0x1.js.map} +1 -1
  197. package/dist/{preflight-VrtpmE-m.js → preflight-CVGDRu2C.js} +1 -1
  198. package/dist/{preflight-DTUzpuHa.js → preflight-CvIY-sKu.js} +4 -4
  199. package/dist/{preflight-DTUzpuHa.js.map → preflight-CvIY-sKu.js.map} +1 -1
  200. package/dist/preflight-DzeTciWY.js +1 -0
  201. package/dist/{prepare-neo93PDB.js → prepare-BAkGolQG.js} +11 -8
  202. package/dist/prepare-BAkGolQG.js.map +1 -0
  203. package/dist/{prepare-B8mcpoSU.js → prepare-D91IAX_H.js} +2 -2
  204. package/dist/{prices-7Av-R8LY.js → prices-DZa1s6oE.js} +2 -2
  205. package/dist/{prices-7Av-R8LY.js.map → prices-DZa1s6oE.js.map} +1 -1
  206. package/dist/prices-DhqfDLI0.js +1 -0
  207. package/dist/{provenance-DH-yi6D5.js → provenance-BKmmc54i.js} +4 -4
  208. package/dist/{provenance-DH-yi6D5.js.map → provenance-BKmmc54i.js.map} +1 -1
  209. package/dist/{provider-Cn7lmECy.js → provider-BNQjWvVI.js} +2 -2
  210. package/dist/{provider-Cn7lmECy.js.map → provider-BNQjWvVI.js.map} +1 -1
  211. package/dist/provider-CVvAjoNS.js +1 -0
  212. package/dist/{providers-CkS7-mTp.js → providers-BJtQ3NwC.js} +1 -1
  213. package/dist/{providers-CjS_fnib.js → providers-zFYsqSGY.js} +26 -26
  214. package/dist/{providers-CjS_fnib.js.map → providers-zFYsqSGY.js.map} +1 -1
  215. package/dist/{query-B9eLoFkA.js → query-Bb9N_XYo.js} +2 -2
  216. package/dist/{query-B9eLoFkA.js.map → query-Bb9N_XYo.js.map} +1 -1
  217. package/dist/query-CIn4l3KN.js +1 -0
  218. package/dist/{questions-OKDjvm6B.js → questions-7ENfOXct.js} +6 -6
  219. package/dist/{questions-OKDjvm6B.js.map → questions-7ENfOXct.js.map} +1 -1
  220. package/dist/{recipe-CRoyNF64.js → recipe-BYfLWBQt.js} +3 -3
  221. package/dist/{recipe-CRoyNF64.js.map → recipe-BYfLWBQt.js.map} +1 -1
  222. package/dist/{record-BWy9s9CV.js → record-CB1A6v0V.js} +2 -2
  223. package/dist/{record-BWy9s9CV.js.map → record-CB1A6v0V.js.map} +1 -1
  224. package/dist/{remarks-UZpf9-8r.js → remarks-Cf6sylYA.js} +10 -10
  225. package/dist/{remarks-UZpf9-8r.js.map → remarks-Cf6sylYA.js.map} +1 -1
  226. package/dist/{remarks-BbMdB_8I.js → remarks-vofg7p1p.js} +3 -3
  227. package/dist/{remarks-BbMdB_8I.js.map → remarks-vofg7p1p.js.map} +1 -1
  228. package/dist/{remote-Dr1gXMTr.js → remote-3htNQd1k.js} +8 -7
  229. package/dist/remote-3htNQd1k.js.map +1 -0
  230. package/dist/renderer/ascii.d.ts +1 -1
  231. package/dist/renderer/markdown.d.ts +1 -1
  232. package/dist/renderer/markdown.js +1 -1
  233. package/dist/{report-B-kavICs.js → report-BQTwKMyw.js} +3 -3
  234. package/dist/{report-B-kavICs.js.map → report-BQTwKMyw.js.map} +1 -1
  235. package/dist/{report-inputs-UUAME7ww.js → report-inputs-CfN15NUr.js} +6 -6
  236. package/dist/{report-inputs-UUAME7ww.js.map → report-inputs-CfN15NUr.js.map} +1 -1
  237. package/dist/{resolve-ihtFbkZH.js → resolve-BithWafe.js} +27 -17
  238. package/dist/resolve-BithWafe.js.map +1 -0
  239. package/dist/{resolve-C_UGu3ls.js → resolve-Cb2dNF75.js} +2 -2
  240. package/dist/{resolve-C_UGu3ls.js.map → resolve-Cb2dNF75.js.map} +1 -1
  241. package/dist/resolve-D8NaRPmt.js +1 -0
  242. package/dist/{results-yZWhaeav.js → results-BSrEuS2x.js} +6 -6
  243. package/dist/{results-yZWhaeav.js.map → results-BSrEuS2x.js.map} +1 -1
  244. package/dist/{resume-Ds4K9mQc.js → resume-VlM095b2.js} +6 -6
  245. package/dist/{resume-Ds4K9mQc.js.map → resume-VlM095b2.js.map} +1 -1
  246. package/dist/{retry-Cjf40USW.js → retry-DI6qS8FY.js} +5 -5
  247. package/dist/{retry-Cjf40USW.js.map → retry-DI6qS8FY.js.map} +1 -1
  248. package/dist/routes-D1tgwWoe.js +629 -0
  249. package/dist/routes-D1tgwWoe.js.map +1 -0
  250. package/dist/{run-C_kA5Jzh.js → run-DwLQh41-.js} +3 -3
  251. package/dist/{run-C_kA5Jzh.js.map → run-DwLQh41-.js.map} +1 -1
  252. package/dist/{runtime-D1gU5fAJ.js → runtime-CXxeCKoX.js} +6 -6
  253. package/dist/{runtime-D1gU5fAJ.js.map → runtime-CXxeCKoX.js.map} +1 -1
  254. package/dist/sandbox/boat.d.ts +2 -2
  255. package/dist/sandbox/boat.js +1 -1
  256. package/dist/sandbox/daytona.d.ts +2 -2
  257. package/dist/sandbox/daytona.js +1 -1
  258. package/dist/{sandbox-Br9klmXq.js → sandbox-D1vDKYqU.js} +2 -2
  259. package/dist/{sandbox-Br9klmXq.js.map → sandbox-D1vDKYqU.js.map} +1 -1
  260. package/dist/sandbox.d.ts +3 -3
  261. package/dist/sandbox.js +1 -1
  262. package/dist/secrets-file-BFJSaPHI.js +169 -0
  263. package/dist/secrets-file-BFJSaPHI.js.map +1 -0
  264. package/dist/{server-2cICWjvT.js → server-BrBZ0_xA.js} +6 -6
  265. package/dist/{server-2cICWjvT.js.map → server-BrBZ0_xA.js.map} +1 -1
  266. package/dist/server-CzilMQ_m.js +1 -0
  267. package/dist/shared-7f8bQJP4.d.ts +2 -0
  268. package/dist/{skill-dirs-B7o83G5I.js → skill-dirs-DaHQ463p.js} +2 -2
  269. package/dist/skill-dirs-DaHQ463p.js.map +1 -0
  270. package/dist/{source-CFimUGjU.js → source-CfeQ4DL4.js} +2 -2
  271. package/dist/{source-CFimUGjU.js.map → source-CfeQ4DL4.js.map} +1 -1
  272. package/dist/source-DqFPDDZU.js +1 -0
  273. package/dist/{spans-BshoUrAD.js → spans-DUexyi3E.js} +2 -2
  274. package/dist/spans-DUexyi3E.js.map +1 -0
  275. package/dist/{src-CRZg669b.js → src-1TaLS8AT.js} +1 -1
  276. package/dist/{src-CEValY4l.js → src-B3sBDfG2.js} +157 -114
  277. package/dist/src-B3sBDfG2.js.map +1 -0
  278. package/dist/{src-ZaP7-0pi.js → src-BWb__auU.js} +1 -1
  279. package/dist/{src-kjTrRKQJ.js → src-CU4tXeik.js} +1 -1
  280. package/dist/src-CfDk0uu4.js +3068 -0
  281. package/dist/src-CfDk0uu4.js.map +1 -0
  282. package/dist/src-DR_j9K3o.js +2 -0
  283. package/dist/{src-B8t-GsRm.js → src-DV-o1jAX.js} +1 -1
  284. package/dist/{src-DP-gPQ5B.js → src-RygE9XhU.js} +1 -1
  285. package/dist/{src-7kshnPZC.js → src-V6cCl3Ak.js} +1 -1
  286. package/dist/src-hPuCF6xC.js +1 -0
  287. package/dist/{src-B5r1d23Y.js → src-o0VTS7Rt.js} +5 -2
  288. package/dist/{src-B5r1d23Y.js.map → src-o0VTS7Rt.js.map} +1 -1
  289. package/dist/src-og0zwqOf.js +4 -0
  290. package/dist/ssh-pool-BWXdYQl0.js +1 -0
  291. package/dist/{ssh-pool-CANmGvdx.js → ssh-pool-DqFdHcz0.js} +7 -7
  292. package/dist/{ssh-pool-CANmGvdx.js.map → ssh-pool-DqFdHcz0.js.map} +1 -1
  293. package/dist/{start-D-xFuv0f.js → start-BSBWBxQb.js} +13 -6
  294. package/dist/start-BSBWBxQb.js.map +1 -0
  295. package/dist/startup-YENEnSa_.js +16 -0
  296. package/dist/startup-YENEnSa_.js.map +1 -0
  297. package/dist/state-7TAiol30.js +1 -0
  298. package/dist/{state-DcuHVqLB.js → state-BhSANU74.js} +5 -5
  299. package/dist/{state-DcuHVqLB.js.map → state-BhSANU74.js.map} +1 -1
  300. package/dist/store/local.d.ts +1 -1
  301. package/dist/store/s3.d.ts +1 -1
  302. package/dist/{studio-share-qopKtSPe.js → studio-share-58-7lF42.js} +6 -6
  303. package/dist/{studio-share-qopKtSPe.js.map → studio-share-58-7lF42.js.map} +1 -1
  304. package/dist/suite-BvIl9-41.js +2 -0
  305. package/dist/{suite-DBbQs15H.js → suite-Bz0uCwd3.js} +4 -4
  306. package/dist/{suite-DBbQs15H.js.map → suite-Bz0uCwd3.js.map} +1 -1
  307. package/dist/{summary-CtTtjh3v.js → summary-Bx1qyFwL.js} +8 -8
  308. package/dist/{summary-CtTtjh3v.js.map → summary-Bx1qyFwL.js.map} +1 -1
  309. package/dist/{sync-DcFcjYLX.js → sync-BeiDYfR6.js} +6 -6
  310. package/dist/{sync-DcFcjYLX.js.map → sync-BeiDYfR6.js.map} +1 -1
  311. package/dist/{tart-CgW8e9RN.d.ts → tart-Brv7Huzv.d.ts} +2 -2
  312. package/dist/{tart-D4VLu2qF.js → tart-CcdnLmyl.js} +7 -7
  313. package/dist/{tart-D4VLu2qF.js.map → tart-CcdnLmyl.js.map} +1 -1
  314. package/dist/{tart-bake-BksL4gS9.js → tart-bake-BRfCI3R9.js} +1 -1
  315. package/dist/{tart-bake-BEzKMVWv.js → tart-bake-CRrij4Ct.js} +7 -7
  316. package/dist/{tart-bake-BEzKMVWv.js.map → tart-bake-CRrij4Ct.js.map} +1 -1
  317. package/dist/{tart-cli-C05FdPQV.js → tart-cli-B1qZ4EPU.js} +2 -2
  318. package/dist/{tart-cli-C05FdPQV.js.map → tart-cli-B1qZ4EPU.js.map} +1 -1
  319. package/dist/{tart-cli-DVI2SWz4.js → tart-cli-B7YKODI8.js} +1 -1
  320. package/dist/{tart-hosts-DESXVcNv.js → tart-hosts-CNUiaq7k.js} +1 -1
  321. package/dist/{tart-hosts-GDk-lRnT.js → tart-hosts-CifzR5Lp.js} +4 -4
  322. package/dist/{tart-hosts-GDk-lRnT.js.map → tart-hosts-CifzR5Lp.js.map} +1 -1
  323. package/dist/{tart-images-CLpWt7Mm.js → tart-images-DOboVDfH.js} +2 -2
  324. package/dist/{tart-images-CLpWt7Mm.js.map → tart-images-DOboVDfH.js.map} +1 -1
  325. package/dist/testing.d.ts +3 -3
  326. package/dist/testing.js +4 -4
  327. package/dist/{tool-class-CB-m4PiF.js → tool-class-DzpZJJWK.js} +2 -2
  328. package/dist/{tool-class-CB-m4PiF.js.map → tool-class-DzpZJJWK.js.map} +1 -1
  329. package/dist/{trace-CJQLlAbB.js → trace-BY_rkR5K.js} +2 -2
  330. package/dist/{trace-CJQLlAbB.js.map → trace-BY_rkR5K.js.map} +1 -1
  331. package/dist/{types-Buut5yGe.js → types-BRXqpxJ1.js} +3 -8
  332. package/dist/types-BRXqpxJ1.js.map +1 -0
  333. package/dist/{types-CYz4dqAd.d.ts → types-CseRWbr7.d.ts} +1 -1
  334. package/dist/{types-BZaItiui.d.ts → types-DtRJb-jv.d.ts} +203 -199
  335. package/dist/{ui-Df1vnh7L.js → ui-CNYSCEFR.js} +5 -5
  336. package/dist/{ui-Df1vnh7L.js.map → ui-CNYSCEFR.js.map} +1 -1
  337. package/dist/{usage-CwIRPPZ9.js → usage-Dg_IyU0o.js} +3 -5
  338. package/dist/usage-Dg_IyU0o.js.map +1 -0
  339. package/dist/vercel-models-DZxE5QJe.js +14 -0
  340. package/dist/vercel-models-DZxE5QJe.js.map +1 -0
  341. package/dist/{vertex-DQQGhUn7.js → vertex-BS-i5_z3.js} +20 -91
  342. package/dist/vertex-BS-i5_z3.js.map +1 -0
  343. package/dist/vertex-DWCgbhK1.js +2 -0
  344. package/dist/view/index.d.ts +3 -3
  345. package/dist/view/index.js +12 -12
  346. package/dist/view/report/index.d.ts +3 -3
  347. package/dist/view/report/index.js +3 -3
  348. package/dist/{views-BP8ck_JR.js → views-CLF_vJ6q.js} +6 -6
  349. package/dist/{views-BP8ck_JR.js.map → views-CLF_vJ6q.js.map} +1 -1
  350. package/dist/views-ZX-NomRg.js +2 -0
  351. package/dist/{vm-container-Bx3bIlDn.js → vm-container-BHRWzfKZ.js} +6 -6
  352. package/dist/{vm-container-Bx3bIlDn.js.map → vm-container-BHRWzfKZ.js.map} +1 -1
  353. package/dist/{vm-images-CimgmVk6.js → vm-images-CZitoP8K.js} +13 -13
  354. package/dist/{vm-images-CimgmVk6.js.map → vm-images-CZitoP8K.js.map} +1 -1
  355. package/dist/{worker-entry-CY_GX-KW.js → worker-entry-DTrgQNo6.js} +3 -3
  356. package/dist/{worker-entry-CY_GX-KW.js.map → worker-entry-DTrgQNo6.js.map} +1 -1
  357. package/dist/{workspace-2wz0BP-V.js → workspace-CgkcWyX1.js} +6 -6
  358. package/dist/{workspace-2wz0BP-V.js.map → workspace-CgkcWyX1.js.map} +1 -1
  359. package/dist/workspace-DbRCjXfa.js +1 -0
  360. package/package.json +1 -1
  361. package/dist/agent-ofh_n1XS.js +0 -987
  362. package/dist/agent-ofh_n1XS.js.map +0 -1
  363. package/dist/agents-D4H9bKHD.d.ts +0 -2
  364. package/dist/agents-DGr0kCFD.js +0 -1408
  365. package/dist/agents-DGr0kCFD.js.map +0 -1
  366. package/dist/assemble-HOUMVnjQ.js +0 -1
  367. package/dist/bundle-dK2eveab.js.map +0 -1
  368. package/dist/capture-BEGBn9e9.js +0 -1
  369. package/dist/cases-Bsp-G-ZL.js +0 -1
  370. package/dist/cli-eakKMZFR.js.map +0 -1
  371. package/dist/cli-spec-DO-RQP-t.js.map +0 -1
  372. package/dist/cloud-run-CKcBID4J.js.map +0 -1
  373. package/dist/cloud-secrets-D_IiyGgA.js +0 -1
  374. package/dist/cloud-secrets-OuKaQUlX.js.map +0 -1
  375. package/dist/config-Ozz1O7Dl.js.map +0 -1
  376. package/dist/cost-DQ0ayy6h.js.map +0 -1
  377. package/dist/cursor-catalog-pRZm3jCP.js.map +0 -1
  378. package/dist/daytona-image-D8TFfSxM.js +0 -1
  379. package/dist/db-Djz9zixD.js +0 -1
  380. package/dist/default-effort-DXPtXTsk.js.map +0 -1
  381. package/dist/doctor-TkGfyasW.js.map +0 -1
  382. package/dist/env-8x1O8I1M.js.map +0 -1
  383. package/dist/environment-C2i5ggoS.js.map +0 -1
  384. package/dist/evaluate-D9hHc00J.js.map +0 -1
  385. package/dist/events-CwWpBkkc.js +0 -1
  386. package/dist/files-1PVfWWXB.js +0 -1
  387. package/dist/files-CsPOd60N.js +0 -1
  388. package/dist/files-DOz7Qr5r.js +0 -1
  389. package/dist/harness-install-CTAsIRk9.js.map +0 -1
  390. package/dist/init-DkTAnHaf.js +0 -1
  391. package/dist/judge-3ABSMDa4.js.map +0 -1
  392. package/dist/labels-Dtyf5-pd.js.map +0 -1
  393. package/dist/model-B89uRS9X.js.map +0 -1
  394. package/dist/model-Doy9vFnq.js +0 -1
  395. package/dist/model-WiM6J5cw.js.map +0 -1
  396. package/dist/openrouter-models-B1sIOTD2.js.map +0 -1
  397. package/dist/options-BK7nMvou.js +0 -1
  398. package/dist/plugins-4DkJ-SSG.js.map +0 -1
  399. package/dist/preflight-CjR6YpXu.js +0 -1
  400. package/dist/prepare-neo93PDB.js.map +0 -1
  401. package/dist/prices-CZWSNosm.js +0 -1
  402. package/dist/provider-B24hZX95.js +0 -1
  403. package/dist/provider-stop-DjBMfZW5.js +0 -69
  404. package/dist/provider-stop-DjBMfZW5.js.map +0 -1
  405. package/dist/query-3PjR8hU2.js +0 -1
  406. package/dist/remote-Dr1gXMTr.js.map +0 -1
  407. package/dist/resolve-CKRG9k6Z.js +0 -1
  408. package/dist/resolve-ihtFbkZH.js.map +0 -1
  409. package/dist/routes-Cp4gAjBZ.js +0 -427
  410. package/dist/routes-Cp4gAjBZ.js.map +0 -1
  411. package/dist/secrets-file-B1Yj1WjD.js +0 -100
  412. package/dist/secrets-file-B1Yj1WjD.js.map +0 -1
  413. package/dist/server-CzTVzKWG.js +0 -1
  414. package/dist/shared-B3iLKAiu.d.ts +0 -1
  415. package/dist/skill-dirs-B7o83G5I.js.map +0 -1
  416. package/dist/source-CydZOoBv.js +0 -1
  417. package/dist/spans-BshoUrAD.js.map +0 -1
  418. package/dist/src-2MDgX3cP.js +0 -3
  419. package/dist/src-CEValY4l.js.map +0 -1
  420. package/dist/src-CH8ZNcTe.js +0 -1
  421. package/dist/src-Con14kZF.js +0 -2
  422. package/dist/ssh-pool-Du_BZWR1.js +0 -1
  423. package/dist/start-D-xFuv0f.js.map +0 -1
  424. package/dist/state-C007zNcM.js +0 -1
  425. package/dist/suite-BQNoCyRE.js +0 -2
  426. package/dist/types-Buut5yGe.js.map +0 -1
  427. package/dist/usage-CwIRPPZ9.js.map +0 -1
  428. package/dist/vercel-models-Ci33llXz.js +0 -21
  429. package/dist/vercel-models-Ci33llXz.js.map +0 -1
  430. package/dist/vertex-DQQGhUn7.js.map +0 -1
  431. package/dist/vertex-DtWe0Xf6.js +0 -1
  432. package/dist/views-_yc6K-9E.js +0 -2
  433. package/dist/workspace-CQxNEvkp.js +0 -1
@@ -0,0 +1,3068 @@
1
+ import { r as SKILL_LAYOUTS } from "./skill-dirs-DaHQ463p.js";
2
+ import { i as tokenUsage, t as addUsage } from "./usage-Dg_IyU0o.js";
3
+ import { constants } from "node:os";
4
+ import { join, posix, resolve } from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ import { HarnessAgent, createHarnessSandboxTemplate } from "@ai-sdk/harness/agent";
7
+ import { appendFile, mkdir, rename, writeFile } from "node:fs/promises";
8
+ // ../agents/src/spec.ts
9
+ const PLUGIN_PARTS = [
10
+ "skills",
11
+ "agents",
12
+ "commands",
13
+ "hooks",
14
+ "mcp",
15
+ "rules"
16
+ ];
17
+ /** Where the session copies each plugin, under the sandbox's home. */
18
+ const PLUGIN_DIR = "~/.reeval/plugins";
19
+ // ../agents/src/catalog/plugins.ts
20
+ /** Claude Code's hook events as Cursor names them, as the Cursor SDK converts Claude Code's own. */
21
+ const CURSOR_HOOK_EVENTS = {
22
+ SessionStart: "sessionStart",
23
+ SessionEnd: "sessionEnd",
24
+ UserPromptSubmit: "beforeSubmitPrompt",
25
+ PreToolUse: "preToolUse",
26
+ PostToolUse: "postToolUse",
27
+ SubagentStop: "subagentStop",
28
+ PreCompact: "preCompact",
29
+ Stop: "stop"
30
+ };
31
+ /** Claude Code's tool names as Cursor's hooks match them; null for one Cursor has no tool for. */
32
+ const CURSOR_HOOK_TOOLS = {
33
+ Bash: "Shell",
34
+ Read: "Read",
35
+ Write: "Write",
36
+ Edit: "Write",
37
+ Glob: null,
38
+ Grep: "Grep",
39
+ WebFetch: "WebFetch",
40
+ WebSearch: "WebSearch",
41
+ Task: "Task"
42
+ };
43
+ /**
44
+ * A Claude Code hook group's tool matcher as Cursor's, on the tool events only: each name mapped,
45
+ * `mcp__<server>__<tool>` as `MCP:<tool>`; null when it names only tools Cursor lacks.
46
+ */
47
+ function cursorHookMatcher(event, matcher) {
48
+ if (event !== "PreToolUse" && event !== "PostToolUse") return void 0;
49
+ if (!matcher || matcher === "*") return void 0;
50
+ const out = [];
51
+ for (const raw of matcher.split("|")) {
52
+ const name = raw.trim();
53
+ const parts = name.split("__");
54
+ const tool = name.startsWith("mcp__") && parts.length >= 3 ? `MCP:${parts.slice(2).join("__")}` : CURSOR_HOOK_TOOLS[name] === void 0 ? name : CURSOR_HOOK_TOOLS[name];
55
+ if (tool && !out.includes(tool)) out.push(tool);
56
+ }
57
+ return out.length ? out.join("|") : null;
58
+ }
59
+ /** Where Cursor reads what reeval unpacks from a plugin, in the workspace (settingSources `project`). */
60
+ const CURSOR_PLUGIN_UNPACK = {
61
+ rules: ".cursor/rules",
62
+ agents: ".cursor/agents",
63
+ commands: ".cursor/commands",
64
+ hooks: {
65
+ file: ".cursor/hooks.json",
66
+ events: CURSOR_HOOK_EVENTS,
67
+ matcher: cursorHookMatcher
68
+ }
69
+ };
70
+ /**
71
+ * A plugin subagent's or command's frontmatter as OpenCode 2 takes it: the description, and a
72
+ * subagent's `mode`. OpenCode skips a file whose frontmatter its schema refuses, without saying,
73
+ * and Claude Code's `tools: Read, Grep`, `model: sonnet` and `allowed-tools` are such keys.
74
+ */
75
+ function opencodeFrontmatter(part, front) {
76
+ const d = front.description;
77
+ const description = typeof d === "string" || typeof d === "number" || typeof d === "boolean" ? String(d) : void 0;
78
+ return {
79
+ ...description ? { description } : {},
80
+ ...part === "agents" ? { mode: "subagent" } : {}
81
+ };
82
+ }
83
+ /** Where OpenCode reads plugin subagents and commands, in the workspace's config directory. */
84
+ const OPENCODE_PLUGIN_UNPACK = {
85
+ agents: ".opencode/agents",
86
+ commands: ".opencode/commands",
87
+ frontmatter: opencodeFrontmatter
88
+ };
89
+ /**
90
+ * Where pi reads plugin commands, as prompt templates (`/<name>`), in the workspace, which its
91
+ * `--approve` trusts. Its frontmatter takes `description` and `argument-hint`, and ignores the
92
+ * rest of Claude Code's.
93
+ */
94
+ const PI_PLUGIN_UNPACK = { commands: ".pi/prompts" };
95
+ /**
96
+ * What Claude Code's plugin format bundles, which Grok Build reads too: every part but rules,
97
+ * which neither loads from a plugin.
98
+ */
99
+ const CLAUDE_FORMAT_PARTS = PLUGIN_PARTS.filter((p) => p !== "rules");
100
+ /** The marketplace Claude Code's settings name for the session's plugins. */
101
+ const CLAUDE_PLUGIN_MARKETPLACE = "reeval";
102
+ /**
103
+ * Claude Code's settings for the session's plugins: a `directory` marketplace at the directory
104
+ * they were copied to, listing each, and each enabled as `<plugin>@reeval`. Claude Code installs
105
+ * and loads them as it starts, since the bridge leaves every settings source on.
106
+ */
107
+ function claudePluginFiles(plugins) {
108
+ const [first] = plugins;
109
+ if (!first) return [];
110
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
111
+ const marketplace = {
112
+ name: CLAUDE_PLUGIN_MARKETPLACE,
113
+ owner: { name: "reeval" },
114
+ plugins: plugins.map((p) => ({
115
+ name: p.name,
116
+ source: `./${p.name}`
117
+ }))
118
+ };
119
+ const settings = {
120
+ extraKnownMarketplaces: { [CLAUDE_PLUGIN_MARKETPLACE]: { source: {
121
+ source: "directory",
122
+ path: first.dir.slice(0, first.dir.lastIndexOf("/"))
123
+ } } },
124
+ enabledPlugins: Object.fromEntries(plugins.map((p) => [`${p.name}@${CLAUDE_PLUGIN_MARKETPLACE}`, true]))
125
+ };
126
+ return [{
127
+ path: `${PLUGIN_DIR}/.claude-plugin/marketplace.json`,
128
+ content: json(marketplace)
129
+ }, {
130
+ path: "~/.claude/settings.json",
131
+ content: json(settings),
132
+ merge: true
133
+ }];
134
+ }
135
+ // ../agents/src/catalog/layouts.ts
136
+ /**
137
+ * The MCP servers the agent is given: all of them, less the plugins' own where it takes plugin
138
+ * items namespaced, since it loads those from the plugin and would otherwise start each twice.
139
+ */
140
+ function agentMcp(layout, mcp, plugins) {
141
+ if (layout.pluginPlacement !== "namespaced") return mcp;
142
+ const own = new Set(plugins.flatMap((p) => p.servers));
143
+ return Object.fromEntries(Object.entries(mcp).filter(([name]) => !own.has(name)));
144
+ }
145
+ /** Where each agent with an image reads rules and skills. */
146
+ const LAYOUTS = {
147
+ cursor: {
148
+ rulesFile: "AGENTS.md",
149
+ ...SKILL_LAYOUTS.cursor,
150
+ pluginPlacement: "flat",
151
+ pluginUnpack: CURSOR_PLUGIN_UNPACK,
152
+ pluginHookEvents: Object.keys(CURSOR_HOOK_EVENTS)
153
+ },
154
+ "claude-code": {
155
+ rulesFile: "CLAUDE.md",
156
+ ...SKILL_LAYOUTS["claude-code"],
157
+ pluginPlacement: "namespaced",
158
+ pluginFiles: claudePluginFiles
159
+ },
160
+ antigravity: {
161
+ rulesFile: "AGENTS.md",
162
+ ...SKILL_LAYOUTS.antigravity,
163
+ pluginPlacement: "namespaced",
164
+ pluginHookEvents: [
165
+ "SessionStart",
166
+ "PreToolUse",
167
+ "PostToolUse",
168
+ "Stop"
169
+ ]
170
+ },
171
+ opencode: {
172
+ rulesFile: "AGENTS.md",
173
+ ...SKILL_LAYOUTS.opencode,
174
+ pluginPlacement: "flat",
175
+ pluginUnpack: OPENCODE_PLUGIN_UNPACK
176
+ },
177
+ goose: {
178
+ rulesFile: "AGENTS.md",
179
+ ...SKILL_LAYOUTS.goose,
180
+ pluginPlacement: "flat"
181
+ },
182
+ pi: {
183
+ rulesFile: "AGENTS.md",
184
+ ...SKILL_LAYOUTS.pi,
185
+ pluginPlacement: "flat",
186
+ pluginUnpack: PI_PLUGIN_UNPACK
187
+ },
188
+ codex: {
189
+ rulesFile: "AGENTS.md",
190
+ ...SKILL_LAYOUTS.codex,
191
+ pluginPlacement: "namespaced"
192
+ },
193
+ fx: {
194
+ rulesFile: "AGENTS.md",
195
+ ...SKILL_LAYOUTS.fx,
196
+ pluginPlacement: "flat"
197
+ },
198
+ "grok-build": {
199
+ rulesFile: "AGENTS.md",
200
+ ...SKILL_LAYOUTS["grok-build"],
201
+ pluginPlacement: "namespaced"
202
+ }
203
+ };
204
+ /** The fake agent's own layout. */
205
+ const FAKE_LAYOUT = {
206
+ rulesFile: "AGENTS.md",
207
+ ...SKILL_LAYOUTS.fake,
208
+ pluginPlacement: "flat"
209
+ };
210
+ // ../agents/src/errors.ts
211
+ /** A failure of the harness or of where it runs, rather than of the agent's work. */
212
+ var AgentError = class extends Error {
213
+ name = "AgentError";
214
+ /** Another try may succeed: a 5xx, a network error or a timeout, not a refused key or a bad config. */
215
+ transient;
216
+ constructor(message, options = {}) {
217
+ super(message);
218
+ this.transient = options.transient ?? false;
219
+ }
220
+ };
221
+ // ../agents/src/catalog/mcp.ts
222
+ /** Codex's `config.toml` `[mcp_servers]` shape. */
223
+ function codexMcpServers(servers) {
224
+ return Object.fromEntries(Object.entries(servers).map(([name, s]) => {
225
+ if (s.transport === "sse") throw new AgentError(`Codex has no SSE MCP transport, so it can't use the ${name} server (mcp.sse): use mcp.http or mcp.stdio`);
226
+ return s.transport === "stdio" ? [name, {
227
+ command: s.command,
228
+ args: s.args,
229
+ env: s.env ?? {}
230
+ }] : [name, {
231
+ url: s.url,
232
+ http_headers: s.headers ?? {}
233
+ }];
234
+ }));
235
+ }
236
+ /** The `.mcp.json` shape. */
237
+ function claudeMcpServers(servers) {
238
+ return Object.fromEntries(Object.entries(servers).map(([name, s]) => s.transport === "stdio" ? [name, {
239
+ type: "stdio",
240
+ command: s.command,
241
+ args: s.args,
242
+ env: s.env
243
+ }] : [name, {
244
+ type: s.transport,
245
+ url: s.url,
246
+ headers: s.headers
247
+ }]));
248
+ }
249
+ /** The Antigravity CLI's `mcp_config.json` shape: remote servers take `serverUrl`, not `url`. */
250
+ function antigravityMcpServers(servers) {
251
+ return Object.fromEntries(Object.entries(servers).map(([name, s]) => s.transport === "stdio" ? [name, {
252
+ command: s.command,
253
+ args: s.args,
254
+ env: s.env
255
+ }] : [name, {
256
+ serverUrl: s.url,
257
+ headers: s.headers
258
+ }]));
259
+ }
260
+ /**
261
+ * A `{env:…}` or `{file:…}` OpenCode would substitute. It runs `\{env:[^}]+\}`, then
262
+ * `\{file:[^}]+\}`, over its whole config text with no escape, so a reference left open at the end
263
+ * of a value runs on into the JSON after it, and only `{env:}` and `{file:}` are left alone.
264
+ */
265
+ const OPENCODE_REFERENCE = /\{(?:env|file):(?!\})/;
266
+ const fieldKey = (key) => /^[A-Za-z_$][\w$]*$/.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
267
+ /**
268
+ * The first part of a server OpenCode would substitute, as what the server wouldn't get: its name,
269
+ * a value as `mcp.<name>.<field>`, or an env or header name. Names are in the same config text as
270
+ * values, so they're substituted too; a secret's value is never named.
271
+ */
272
+ function openCodeReference(name, s) {
273
+ if (OPENCODE_REFERENCE.test(name)) return "its name";
274
+ const server = `mcp${fieldKey(name)}`;
275
+ const [map, kind, values] = s.transport === "stdio" ? [
276
+ "env",
277
+ "env",
278
+ s.env ?? {}
279
+ ] : [
280
+ "headers",
281
+ "header",
282
+ s.headers ?? {}
283
+ ];
284
+ return [...s.transport === "stdio" ? [[`${server}.command`, s.command], ...s.args.map((a, i) => [`${server}.args[${i}]`, a])] : [[`${server}.url`, s.url]], ...Object.entries(values).flatMap(([k, v]) => [[`the ${kind} name ${k} in ${server}.${map}`, k], [`${server}.${map}${fieldKey(k)}`, v]])].find(([, text]) => OPENCODE_REFERENCE.test(text))?.[0];
285
+ }
286
+ /**
287
+ * OpenCode's config shape (its `mcp.servers`), which the adapter sets `codemode: false` on.
288
+ * OpenCode has no SSE transport, and refuses a value it would substitute.
289
+ */
290
+ function opencodeMcpServers(servers) {
291
+ return Object.fromEntries(Object.entries(servers).map(([name, s]) => {
292
+ if (s.transport === "sse") throw new AgentError(`OpenCode has no SSE MCP transport, so it can't use the ${name} server (mcp.sse): use mcp.http or mcp.stdio`);
293
+ const field = openCodeReference(name, s);
294
+ if (field) throw new AgentError(`OpenCode substitutes {env:…} and {file:…} anywhere in its config, with no escape, so the ${name} server wouldn't get ${field} as written: take the reference out, or leave OpenCode out of this cell`);
295
+ return s.transport === "stdio" ? [name, {
296
+ type: "local",
297
+ command: [s.command, ...s.args],
298
+ environment: s.env ?? {}
299
+ }] : [name, {
300
+ type: "remote",
301
+ url: s.url,
302
+ headers: s.headers ?? {},
303
+ oauth: false
304
+ }];
305
+ }));
306
+ }
307
+ /**
308
+ * The key Goose keeps an extension by (its `name_to_key`): whitespace dropped, anything but ASCII
309
+ * letters, digits, `_` and `-` made `_`, lower-cased. Of two extensions with one key it keeps one.
310
+ */
311
+ const gooseKey = (name) => name.replace(/\s/g, "").replace(/[^A-Za-z0-9_-]/g, "_").toLowerCase();
312
+ /** Goose's extension shape (its `config.yaml`); it has no SSE transport. */
313
+ function gooseMcpServers(servers) {
314
+ const byKey = /* @__PURE__ */ new Map();
315
+ for (const name of Object.keys(servers)) {
316
+ const key = gooseKey(name);
317
+ const other = byKey.get(key);
318
+ if (other !== void 0) throw new AgentError(`Goose keys the ${other} and ${name} MCP servers both as ${key}, and keeps only one: rename one`);
319
+ byKey.set(key, name);
320
+ }
321
+ return Object.fromEntries(Object.entries(servers).map(([name, s]) => {
322
+ if (s.transport === "sse") throw new AgentError(`Goose has no SSE MCP transport, so it can't use the ${name} server (mcp.sse): use mcp.http or mcp.stdio`);
323
+ return s.transport === "stdio" ? [name, {
324
+ type: "stdio",
325
+ cmd: s.command,
326
+ args: s.args,
327
+ envs: s.env ?? {}
328
+ }] : [name, {
329
+ type: "streamable_http",
330
+ uri: s.url,
331
+ headers: s.headers ?? {}
332
+ }];
333
+ }));
334
+ }
335
+ /**
336
+ * pi's `mcp.json` shape, which the adapter escapes and sets `"exposure": "direct"` on. pi
337
+ * skips a server whose name isn't letters, digits, `_` and `-`, so the plan refuses it instead.
338
+ * A plugin's server, `<plugin>:<server>`, is named `<plugin>_<server>`, so its tools are
339
+ * `mcp__<plugin>_<server>__<tool>`.
340
+ */
341
+ function piMcpServers(servers) {
342
+ const named = /* @__PURE__ */ new Map();
343
+ return Object.fromEntries(Object.entries(servers).map(([key, s]) => {
344
+ const name = /^[a-z0-9-]+:[^:]+$/.test(key) ? key.replace(":", "_") : key;
345
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new AgentError(`pi takes MCP server names of letters, digits, "_" and "-" only, so it can't use the ${key} server: rename it`);
346
+ const other = named.get(name);
347
+ if (other) throw new AgentError(`pi names the ${key} MCP server ${name}, as it does the ${other} server, and keeps only one: rename one`);
348
+ named.set(name, key);
349
+ if (s.transport === "sse") throw new AgentError(`pi has no SSE MCP transport, so it can't use the ${key} server (mcp.sse): use mcp.http or mcp.stdio`);
350
+ return s.transport === "stdio" ? [name, {
351
+ command: s.command,
352
+ args: s.args,
353
+ env: s.env ?? {}
354
+ }] : [name, {
355
+ url: s.url,
356
+ headers: s.headers ?? {}
357
+ }];
358
+ }));
359
+ }
360
+ /**
361
+ * ACP's `McpServer` shape, which fx and Grok Build take on `session/new`: `env` and `headers` as
362
+ * name-value lists.
363
+ */
364
+ function acpMcpServers(servers) {
365
+ const pairs = (values = {}) => Object.entries(values).map(([name, value]) => ({
366
+ name,
367
+ value
368
+ }));
369
+ return Object.fromEntries(Object.entries(servers).map(([name, s]) => s.transport === "stdio" ? [name, s.command.startsWith("/") ? {
370
+ command: s.command,
371
+ args: s.args,
372
+ env: pairs(s.env)
373
+ } : {
374
+ command: "/usr/bin/env",
375
+ args: [s.command, ...s.args],
376
+ env: pairs(s.env)
377
+ }] : [name, {
378
+ type: s.transport,
379
+ url: s.url,
380
+ headers: pairs(s.headers)
381
+ }]));
382
+ }
383
+ /** fx's ACP `session/new` servers: its `initialize` reports `mcpCapabilities.sse: false`. */
384
+ function fxMcpServers(servers) {
385
+ for (const [name, s] of Object.entries(servers)) if (s.transport === "sse") throw new AgentError(`fx has no SSE MCP transport, so it can't use the ${name} server (mcp.sse): use mcp.http or mcp.stdio`);
386
+ return acpMcpServers(servers);
387
+ }
388
+ /** The Cursor SDK's `McpServerConfig` shape. */
389
+ function cursorMcpServers(servers) {
390
+ return Object.fromEntries(Object.entries(servers).map(([name, s]) => s.transport === "stdio" ? [name, {
391
+ type: "stdio",
392
+ command: s.command,
393
+ args: s.args,
394
+ env: s.env
395
+ }] : [name, {
396
+ type: s.transport,
397
+ url: s.url,
398
+ headers: s.headers
399
+ }]));
400
+ }
401
+ // ../agents/src/catalog/antigravity.ts
402
+ const antigravity = {
403
+ ...LAYOUTS.antigravity,
404
+ pluginParts: PLUGIN_PARTS,
405
+ pluginManifestsFirst: [
406
+ "plugin.json",
407
+ ".antigravity-plugin/plugin.json",
408
+ ".gemini-plugin/plugin.json",
409
+ "gemini-extension.json"
410
+ ],
411
+ name: "Antigravity",
412
+ factory: "antigravity",
413
+ keychainTrust: true,
414
+ platforms: ["linux", "darwin"],
415
+ reasoning: "recovered",
416
+ reasoningTokens: true,
417
+ credential: "GEMINI_API_KEY",
418
+ mcpServers: antigravityMcpServers
419
+ };
420
+ // ../agents/src/catalog/reported.ts
421
+ const WEB_EVENTS = {
422
+ webSearch: "web-search",
423
+ webFetch: "web-fetch"
424
+ };
425
+ /** `harnessMetadata.cursorSdk.unreportedTools` as transcript event types. */
426
+ function cursorUnreported(harnessMetadata) {
427
+ const tools = harnessMetadata?.cursorSdk?.unreportedTools;
428
+ return Array.isArray(tools) ? tools.flatMap((t) => WEB_EVENTS[t] ? [WEB_EVENTS[t]] : []) : [];
429
+ }
430
+ const usdIn = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : void 0;
431
+ /** Claude Code's `total_cost_usd`, its session's cost so far, as its bridge reports it. */
432
+ function claudeCodeCost(harnessMetadata) {
433
+ const meta = harnessMetadata?.["claude-code"];
434
+ const usd = usdIn(meta?.costUsd);
435
+ if (usd === void 0) return void 0;
436
+ return {
437
+ usd,
438
+ session: typeof meta?.sessionId === "string" ? meta.sessionId : ""
439
+ };
440
+ }
441
+ /** The sum of the turn's model calls' `cost.total`, priced by pi or billed by OpenRouter. */
442
+ function piCost(harnessMetadata) {
443
+ const usd = usdIn(harnessMetadata?.pi?.costUsd);
444
+ return usd === void 0 ? void 0 : { usd };
445
+ }
446
+ // ../agents/src/catalog/claude-code.ts
447
+ const claudeCode = {
448
+ ...LAYOUTS["claude-code"],
449
+ pluginParts: CLAUDE_FORMAT_PARTS,
450
+ name: "Claude Code",
451
+ factory: "claudeCode",
452
+ bridgePort: true,
453
+ platforms: ["linux", "darwin"],
454
+ reasoning: "streamed",
455
+ reasoningTokens: true,
456
+ subagentCalls: true,
457
+ reportedCost: claudeCodeCost,
458
+ credential: "ANTHROPIC_API_KEY",
459
+ fallbackCredentials: ["CLAUDE_CODE_OAUTH_TOKEN"],
460
+ mcpServers: claudeMcpServers
461
+ };
462
+ // ../agents/src/catalog/codex.ts
463
+ const codex = {
464
+ ...LAYOUTS.codex,
465
+ pluginParts: ["skills", "mcp"],
466
+ pluginApps: "they need a ChatGPT login",
467
+ pluginManifestsFirst: ["plugin.json", ".codex-plugin/plugin.json"],
468
+ pluginRootManifestNeedsSchema: true,
469
+ pluginServersByName: true,
470
+ name: "Codex",
471
+ factory: "codex",
472
+ keychainTrust: true,
473
+ platforms: ["linux", "darwin"],
474
+ reasoning: "whole",
475
+ reasoningTokens: true,
476
+ storedUsage: async () => {
477
+ const m = await import("./src-BWb__auU.js");
478
+ return {
479
+ command: m.codexStoredUsageCommand,
480
+ parse: m.parseCodexStoredUsage
481
+ };
482
+ },
483
+ fullToolOutput: "all",
484
+ credential: "OPENAI_API_KEY",
485
+ mcpServers: codexMcpServers
486
+ };
487
+ // ../agents/src/catalog/cursor.ts
488
+ const cursor = {
489
+ ...LAYOUTS.cursor,
490
+ pluginParts: PLUGIN_PARTS,
491
+ name: "Cursor",
492
+ factory: "cursor",
493
+ platforms: ["linux", "darwin"],
494
+ reasoning: "streamed",
495
+ reasoningTokens: false,
496
+ credential: "CURSOR_API_KEY",
497
+ unreported: cursorUnreported,
498
+ mcpServers: cursorMcpServers
499
+ };
500
+ // ../agents/src/catalog/fx.ts
501
+ const fx = {
502
+ ...LAYOUTS.fx,
503
+ pluginParts: ["skills", "mcp"],
504
+ name: "fx",
505
+ factory: "fx",
506
+ bridgePort: true,
507
+ platforms: ["linux", "darwin"],
508
+ configuredModelOnStart: true,
509
+ reasoning: "streamed",
510
+ reasoningTokens: "provider",
511
+ fullToolOutput: ["bash"],
512
+ mcpServers: fxMcpServers
513
+ };
514
+ // ../agents/src/catalog/provider-model.ts
515
+ /** The `<provider>` a pi or Goose model id, `<provider>/<model>`, names. */
516
+ const providerOf = (model) => model.slice(0, Math.max(model.indexOf("/"), 0));
517
+ /** The model id pi or Goose asks its provider for: the id without its `<provider>/`. */
518
+ const withoutProvider = (model) => model.slice(model.indexOf("/") + 1);
519
+ // ../agents/src/catalog/goose.ts
520
+ const goose = {
521
+ ...LAYOUTS.goose,
522
+ pluginParts: ["skills", "mcp"],
523
+ name: "Goose",
524
+ factory: "goose",
525
+ keychainTrust: true,
526
+ bridgePort: true,
527
+ platforms: ["linux", "darwin"],
528
+ configuredModelOnStart: true,
529
+ reasoning: "streamed",
530
+ reasoningTokens: false,
531
+ storedUsage: async () => {
532
+ const m = await import("./src-DV-o1jAX.js");
533
+ return {
534
+ command: m.gooseStoredUsageCommand,
535
+ parse: m.parseGooseStoredUsage,
536
+ mark: m.gooseUsageMark
537
+ };
538
+ },
539
+ modelId: withoutProvider,
540
+ mcpServers: gooseMcpServers
541
+ };
542
+ // ../agents/src/catalog/grok-build.ts
543
+ const grokBuild = {
544
+ ...LAYOUTS["grok-build"],
545
+ pluginParts: CLAUDE_FORMAT_PARTS,
546
+ pluginServersByName: true,
547
+ name: "Grok Build",
548
+ factory: "grokBuild",
549
+ keychainTrust: true,
550
+ bridgePort: true,
551
+ platforms: ["linux", "darwin"],
552
+ configuredModelOnStart: true,
553
+ reasoning: "streamed",
554
+ reasoningTokens: true,
555
+ storedUsage: async () => {
556
+ const m = await import("./src-RygE9XhU.js");
557
+ return {
558
+ command: m.grokStoredUsageCommand,
559
+ parse: m.parseGrokStoredUsage
560
+ };
561
+ },
562
+ credential: "XAI_API_KEY",
563
+ mcpServers: acpMcpServers
564
+ };
565
+ // ../agents/src/catalog/index.ts
566
+ /** Every real agent's harness, by kind. */
567
+ const HARNESSES = {
568
+ cursor,
569
+ "claude-code": claudeCode,
570
+ antigravity,
571
+ opencode: {
572
+ ...LAYOUTS.opencode,
573
+ pluginParts: [
574
+ "skills",
575
+ "agents",
576
+ "commands",
577
+ "mcp"
578
+ ],
579
+ name: "OpenCode",
580
+ factory: "opencode",
581
+ bridgePort: true,
582
+ platforms: ["linux", "darwin"],
583
+ configuredModelOnStart: true,
584
+ reasoning: "streamed",
585
+ reasoningTokens: "provider",
586
+ storedUsage: async () => {
587
+ const m = await import("./src-og0zwqOf.js");
588
+ return {
589
+ command: m.openCodeStoredUsageCommand,
590
+ parse: m.parseOpenCodeStoredUsage
591
+ };
592
+ },
593
+ mcpServers: opencodeMcpServers
594
+ },
595
+ goose,
596
+ pi: {
597
+ ...LAYOUTS.pi,
598
+ pluginParts: [
599
+ "skills",
600
+ "commands",
601
+ "mcp"
602
+ ],
603
+ name: "pi",
604
+ factory: "pi",
605
+ platforms: ["linux", "darwin"],
606
+ reasoning: "streamed",
607
+ reasoningTokens: true,
608
+ reportedCost: piCost,
609
+ modelId: withoutProvider,
610
+ mcpServers: piMcpServers
611
+ },
612
+ codex,
613
+ fx,
614
+ "grok-build": grokBuild
615
+ };
616
+ // ../agents/src/runner-session.ts
617
+ /** The exit code of the path scripts below when the path doesn't exist. */
618
+ const MISSING = 3;
619
+ /** POSIX `sh`, with GNU or BusyBox `stat -c` and BSD `stat -f` for the size. */
620
+ const STAT = `[ -e "$1" ] || exit ${MISSING}
621
+ if [ -d "$1" ]; then t=directory; elif [ -f "$1" ]; then t=file; else t=other; fi
622
+ s=$(stat -L -c %s -- "$1" 2>/dev/null || stat -L -f %z -- "$1") || exit 1
623
+ printf '%s %s' "$t" "$s"`;
624
+ /**
625
+ * One `<type>\\t<name>` per entry, NUL-separated, since a name can hold a newline. An unreadable
626
+ * directory's glob matches nothing, so it's refused rather than listed as empty.
627
+ */
628
+ const LIST = `[ -e "$1" ] || exit ${MISSING}
629
+ [ -d "$1" ] || { echo "not a directory" >&2; exit 1; }
630
+ ls -a -- "$1" > /dev/null || exit 1
631
+ for f in "$1"/* "$1"/.*; do
632
+ n=\${f##*/}
633
+ [ "$n" = . ] || [ "$n" = .. ] && continue
634
+ [ -e "$f" ] || [ -L "$f" ] || continue
635
+ if [ -L "$f" ]; then t=symlink; elif [ -d "$f" ]; then t=directory; elif [ -f "$f" ]; then t=file; else t=other; fi
636
+ printf '%s\\t%s\\0' "$t" "$n"
637
+ done`;
638
+ const DELETE = `[ -e "$1" ] || [ -L "$1" ] || exit ${MISSING}
639
+ [ -d "$1" ] && [ ! -L "$1" ] && { echo "is a directory" >&2; exit 1; }
640
+ rm -f -- "$1"`;
641
+ async function collect(stream) {
642
+ const chunks = [];
643
+ for await (const chunk of stream) chunks.push(chunk);
644
+ return Buffer.concat(chunks);
645
+ }
646
+ const decode = (bytes, encoding = "utf-8") => new TextDecoder(encoding).decode(bytes);
647
+ function encode(text, encoding = "utf-8") {
648
+ if (!Buffer.isEncoding(encoding)) throw new Error(`can't encode text as ${encoding}`);
649
+ return Buffer.from(text, encoding);
650
+ }
651
+ /** The shell's convention for a process a signal ended: 128 plus the signal's number. */
652
+ function exitCode({ code, signal }) {
653
+ if (code !== null) return code;
654
+ const number = signal ? constants.signals[signal] : void 0;
655
+ return number === void 0 ? 1 : 128 + number;
656
+ }
657
+ function abortError(signal) {
658
+ return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
659
+ }
660
+ /** A {@link Proc} as the AI SDK's sandbox process, `wait()` rejecting when `abortSignal` aborts. */
661
+ function sandboxProcess(proc, stdin, abortSignal) {
662
+ const wait = async () => {
663
+ const exit = await proc.exited;
664
+ if (abortSignal?.aborted) throw abortError(abortSignal);
665
+ return { exitCode: exitCode(exit) };
666
+ };
667
+ const handle = {
668
+ stdout: proc.stdout,
669
+ stderr: proc.stderr,
670
+ wait,
671
+ kill: () => proc.kill("SIGKILL")
672
+ };
673
+ if (!stdin) return handle;
674
+ return {
675
+ ...handle,
676
+ stdin: new WritableStream({
677
+ write: (chunk) => proc.write(chunk),
678
+ close: () => proc.end()
679
+ })
680
+ };
681
+ }
682
+ /**
683
+ * The runner as the network sandbox session the AI SDK harness adapters drive. Files go through
684
+ * its `readFile` and `writeFile`, commands through `spawn` (`stat`, `listDirectory` and
685
+ * `deleteFile` as POSIX `sh` scripts), ports through `forwardPort`, and its `network` passes
686
+ * through untouched. The session doesn't own the runner: `stop` and `destroy` close only the
687
+ * ports it forwarded, and whoever made the runner closes it. It reads the runner's `cwd` once, when
688
+ * it starts.
689
+ */
690
+ async function runnerSession(runner, options = {}) {
691
+ const info = await runner.info();
692
+ const at = (path) => posix.resolve(info.cwd, path);
693
+ const spawn = (o) => {
694
+ if (o.abortSignal?.aborted) return Promise.reject(abortError(o.abortSignal));
695
+ const proc = runner.spawn(o.command, {
696
+ ...o.workingDirectory && { cwd: at(o.workingDirectory) },
697
+ ...o.env && { env: o.env },
698
+ stdin: o.stdin ? "pipe" : "ignore",
699
+ ...o.abortSignal && { signal: o.abortSignal }
700
+ });
701
+ return Promise.resolve(sandboxProcess(proc, o.stdin === true, o.abortSignal));
702
+ };
703
+ const onPath = async (script, o) => {
704
+ const path = at(o.path);
705
+ const proc = runner.spawn([
706
+ "sh",
707
+ "-c",
708
+ script,
709
+ "sh",
710
+ path
711
+ ], { ...o.abortSignal && { signal: o.abortSignal } });
712
+ const [stdout, stderr, exit] = await Promise.all([
713
+ collect(proc.stdout),
714
+ collect(proc.stderr),
715
+ proc.exited
716
+ ]);
717
+ if (o.abortSignal?.aborted) throw abortError(o.abortSignal);
718
+ if (exit.code === MISSING) return null;
719
+ if (exit.code !== 0) throw new Error(`${path}: ${decode(stderr).trim() || `exit ${exitCode(exit)}`}`);
720
+ return decode(stdout);
721
+ };
722
+ const readBinaryFile = (o) => runner.readFile(at(o.path));
723
+ const writeBinaryFile = (o) => runner.writeFile(at(o.path), o.content);
724
+ const bare = {
725
+ description: options.description ?? `Commands start in ${info.cwd}.`,
726
+ readFile: async (o) => {
727
+ const bytes = await readBinaryFile(o);
728
+ if (bytes === null) return null;
729
+ return new ReadableStream({ start(controller) {
730
+ controller.enqueue(bytes);
731
+ controller.close();
732
+ } });
733
+ },
734
+ readBinaryFile,
735
+ readTextFile: async (o) => {
736
+ const bytes = await readBinaryFile(o);
737
+ if (bytes === null) return null;
738
+ const text = decode(bytes, o.encoding);
739
+ if (o.startLine === void 0 && o.endLine === void 0) return text;
740
+ const lines = text.split("\n");
741
+ return lines.slice((o.startLine ?? 1) - 1, o.endLine ?? lines.length).join("\n");
742
+ },
743
+ writeFile: async (o) => writeBinaryFile({
744
+ path: o.path,
745
+ content: await collect(o.content)
746
+ }),
747
+ writeBinaryFile,
748
+ writeTextFile: (o) => writeBinaryFile({
749
+ path: o.path,
750
+ content: encode(o.content, o.encoding)
751
+ }),
752
+ stat: async (o) => {
753
+ const out = await onPath(STAT, o);
754
+ if (out === null) return null;
755
+ const [type, size] = out.trim().split(" ");
756
+ return {
757
+ type,
758
+ size: Number(size)
759
+ };
760
+ },
761
+ listDirectory: async (o) => {
762
+ const out = await onPath(LIST, o);
763
+ if (out === null) return null;
764
+ return out.split("\0").filter(Boolean).map((line) => {
765
+ const tab = line.indexOf(" ");
766
+ return {
767
+ type: line.slice(0, tab),
768
+ name: line.slice(tab + 1)
769
+ };
770
+ });
771
+ },
772
+ deleteFile: async (o) => await onPath(DELETE, o) !== null,
773
+ spawn,
774
+ run: async (o) => {
775
+ const proc = await spawn(o);
776
+ const [stdout, stderr, { exitCode }] = await Promise.all([
777
+ collect(proc.stdout),
778
+ collect(proc.stderr),
779
+ proc.wait()
780
+ ]);
781
+ return {
782
+ exitCode,
783
+ stdout: decode(stdout),
784
+ stderr: decode(stderr)
785
+ };
786
+ }
787
+ };
788
+ const forwarded = /* @__PURE__ */ new Map();
789
+ const getPortEndpoint = async ({ port, protocol = "http" }) => {
790
+ if (!runner.forwardPort) throw new Error(`this runner can't forward port ${port}`);
791
+ let forward = forwarded.get(port);
792
+ if (!forward) {
793
+ forward = runner.forwardPort(port);
794
+ forwarded.set(port, forward);
795
+ }
796
+ const { host, port: hostPort } = await forward;
797
+ return { url: `${protocol}://${host}:${hostPort}` };
798
+ };
799
+ const release = async () => {
800
+ const forwards = [...forwarded.values()];
801
+ forwarded.clear();
802
+ await Promise.all(forwards.map(async (f) => (await f).close()));
803
+ };
804
+ const { network } = runner;
805
+ return {
806
+ ...bare,
807
+ id: options.id ?? crypto.randomUUID(),
808
+ defaultWorkingDirectory: info.cwd,
809
+ ports: options.ports ?? [],
810
+ getPortEndpoint,
811
+ getPortUrl: async (o) => (await getPortEndpoint(o)).url,
812
+ stop: release,
813
+ destroy: release,
814
+ ...network?.setNetworkPolicy && { setNetworkPolicy: network.setNetworkPolicy },
815
+ ...network?.setRequestTransformations && { setRequestTransformations: network.setRequestTransformations },
816
+ ...network?.addRequestTransformations && { addRequestTransformations: network.addRequestTransformations },
817
+ restricted: () => bare
818
+ };
819
+ }
820
+ // ../agents/src/driver/provider-stop.ts
821
+ /**
822
+ * How the model APIs behind the harnesses, and the CLIs that relay them, word a stop that is
823
+ * theirs, not the agent's: Anthropic's low credit (an HTTP 400) and error types, OpenAI's and
824
+ * OpenRouter's quota and credit codes, xAI's spent credits (an HTTP 403 or 429), Google's
825
+ * `RESOURCE_EXHAUSTED` and overloaded model, Codex's quota and capacity errors and Cursor's and
826
+ * Codex's usage limit. Only the providers' own codes and sentences: a bare "rate limit" or
827
+ * "overloaded" can be any tool's output in the CLI's stderr.
828
+ */
829
+ const WORDING = [
830
+ ["credit", /\bcredit balance is too low\b|\binsufficient[_ ]credits?\b|\b402 Payment Required\b|\bused all available credits\b|\breached its monthly spending limit\b/i],
831
+ ["quota", /\binsufficient_quota\b|\bexceeded your current quota\b|\bQuota exceeded\. Check your plan and billing details\b|\bRESOURCE_EXHAUSTED\b|\b(?:hit your|exceeded the) usage limit\b|\busage limit exceeded\b/i],
832
+ ["rate_limit", /\brate_limit_error\b|\brate_limit_exceeded\b|\b429 Too Many Requests\b/i],
833
+ ["overloaded", /\boverloaded_error\b|\bThe model is overloaded\b|\bSelected model is at capacity\b/i]
834
+ ];
835
+ /** The statuses a provider stops a turn with: payment, its rate or quota limit, Anthropic's overload. */
836
+ const STATUS = /* @__PURE__ */ new Map([
837
+ [402, "credit"],
838
+ [429, "rate_limit"],
839
+ [529, "overloaded"]
840
+ ]);
841
+ const CAUSE_TEXT = {
842
+ credit: "out of credit",
843
+ quota: "over its quota",
844
+ rate_limit: "rate limited",
845
+ overloaded: "overloaded"
846
+ };
847
+ /**
848
+ * Whether the model provider, not the agent, ended the turn: it errored, and one of its errors
849
+ * (in the provider's own wording) or the status of the last model call the runner's network
850
+ * saw in it (402, 429, 529) says it was a credit, quota, rate or capacity limit. The wording
851
+ * counts whatever that call's status: a provider that fails a streamed response does it inside
852
+ * an HTTP 200 (Anthropic's and OpenAI's SSE, Cursor's Connect stream). A status alone counts only
853
+ * on the turn's last model call, so a 429 the CLI retried past is the agent's.
854
+ */
855
+ function providerStop(turn) {
856
+ const { errors, status, statuses } = turn;
857
+ if (status !== "error") return void 0;
858
+ const last = statuses.at(-1);
859
+ const failed = last !== void 0 && last >= 400 ? last : void 0;
860
+ const worded = errors.flatMap((message) => {
861
+ const hit = WORDING.find(([, re]) => re.test(message));
862
+ return hit ? [{
863
+ cause: hit[0],
864
+ message
865
+ }] : [];
866
+ })[0];
867
+ const cause = worded?.cause ?? (failed === void 0 ? void 0 : STATUS.get(failed));
868
+ if (!cause) return void 0;
869
+ const error = worded?.message ?? errors.at(-1);
870
+ const http = failed === void 0 ? "" : ` (HTTP ${failed})`;
871
+ return {
872
+ cause,
873
+ status: failed ?? null,
874
+ message: `The model provider stopped the turn, ${CAUSE_TEXT[cause]}${http}${error ? `: ${error.trim()}` : ""}`
875
+ };
876
+ }
877
+ const SHELL_TOOLS = /* @__PURE__ */ new Set([
878
+ "bash",
879
+ "shell",
880
+ "Shell",
881
+ "run_terminal_cmd",
882
+ "execute_command",
883
+ "terminal"
884
+ ]);
885
+ const str = (value) => typeof value === "string" ? value : "";
886
+ /** Wall time until the result part arrived; Cursor can report `completed_at_ms` before the shell returns. */
887
+ function toolDurationMs(start, call, endMs, t) {
888
+ const wall = endMs - start;
889
+ if (t?.end === void 0) return endMs - call.ms;
890
+ if (t.recovered) return t.end - start;
891
+ return Math.max(t.end - start, wall);
892
+ }
893
+ function stallFlags(tool, durationMs) {
894
+ if (durationMs === null || durationMs < 12e4) return {};
895
+ if (SHELL_TOOLS.has(tool) || tool === "edit") return { stalled: true };
896
+ return {};
897
+ }
898
+ const record = (value) => typeof value === "object" && value !== null ? value : {};
899
+ /**
900
+ * A reasoning block recovered after the turn (Antigravity's, from its stored conversation) says
901
+ * in its provider metadata how long before its own part it started, and how long the agent says
902
+ * it took: it's placed there, not where it arrived.
903
+ */
904
+ function recoveredTiming(part) {
905
+ for (const meta of Object.values(record(part.providerMetadata))) {
906
+ const { startedBeforeMs, durationMs } = record(meta);
907
+ if (typeof startedBeforeMs !== "number") continue;
908
+ return {
909
+ startedBeforeMs,
910
+ durationMs: typeof durationMs === "number" ? durationMs : null
911
+ };
912
+ }
913
+ }
914
+ /** The harness's synthetic "fileChange" twin of every edit, which always says "modify". */
915
+ const isFileChangeEcho = (part) => part.toolName === "fileChange" || str(part.toolCallId).startsWith("harness-file-change-");
916
+ function lines(text) {
917
+ if (!text) return [];
918
+ const all = text.split("\n");
919
+ if (all.at(-1) === "") all.pop();
920
+ return all;
921
+ }
922
+ /** Lines only in `before` (removed) and only in `after` (added), as multisets. */
923
+ function lineDelta(before, after) {
924
+ const counts = /* @__PURE__ */ new Map();
925
+ for (const line of lines(before)) counts.set(line, (counts.get(line) ?? 0) + 1);
926
+ let added = 0;
927
+ for (const line of lines(after)) {
928
+ const n = counts.get(line) ?? 0;
929
+ if (n > 0) counts.set(line, n - 1);
930
+ else added++;
931
+ }
932
+ const removed = [...counts.values()].reduce((a, b) => a + b, 0);
933
+ return {
934
+ added,
935
+ removed
936
+ };
937
+ }
938
+ /** Cursor's and OpenCode's edit tools take `path`, Claude Code's `file_path`. */
939
+ const editPath = (input) => str(input.path) || str(input.file_path);
940
+ /**
941
+ * Cursor reports `referenceCount`; Claude Code lists `results`, where each search is
942
+ * `{ content: [{ title, url }] }` and plain strings are commentary.
943
+ */
944
+ function searchReferences(output) {
945
+ const { referenceCount, references, results } = record(output);
946
+ if (typeof referenceCount === "number") return referenceCount;
947
+ if (Array.isArray(references)) return references.length;
948
+ if (!Array.isArray(results)) return null;
949
+ return results.reduce((n, r) => {
950
+ const links = record(r).content;
951
+ return n + (Array.isArray(links) ? links.length : 0);
952
+ }, 0);
953
+ }
954
+ /**
955
+ * Claude Code's bridge sends errors as `{ message }` objects; Cursor's as strings or Errors; ACP
956
+ * harnesses (OpenCode) the tool's `rawOutput`, `{ metadata, error }`. Any other object is kept as JSON.
957
+ */
958
+ const errorText = (error) => str(error) || str(record(error).message) || str(record(error).error) || jsonText(error);
959
+ function jsonText(value) {
960
+ if (typeof value !== "object" || value === null) return String(value);
961
+ try {
962
+ return JSON.stringify(value);
963
+ } catch {
964
+ return String(value);
965
+ }
966
+ }
967
+ /** Lines added and removed across unified-diff hunks, each `{ lines: ['+x', '-y', ' z'] }`. */
968
+ function hunkDelta(hunks) {
969
+ let added = 0;
970
+ let removed = 0;
971
+ for (const hunk of hunks) {
972
+ const lines = record(hunk).lines;
973
+ for (const line of Array.isArray(lines) ? lines : []) if (str(line).startsWith("+")) added++;
974
+ else if (str(line).startsWith("-")) removed++;
975
+ }
976
+ return {
977
+ added,
978
+ removed
979
+ };
980
+ }
981
+ /** Claude Code's Write (`type`, `content`) or Edit (`oldString`, `newString`) result. */
982
+ function claudeEdit(toolCallId, output) {
983
+ const { originalFile, structuredPatch, content, oldString, newString } = output;
984
+ const created = output.type === "create" || output.type === void 0 && originalFile === null;
985
+ const counts = Array.isArray(structuredPatch) && structuredPatch.length > 0 ? hunkDelta(structuredPatch) : created ? {
986
+ added: lines(str(content ?? newString)).length,
987
+ removed: 0
988
+ } : typeof originalFile === "string" && typeof content === "string" ? lineDelta(originalFile, content) : typeof oldString === "string" && typeof newString === "string" ? lineDelta(oldString, newString) : {
989
+ added: null,
990
+ removed: null
991
+ };
992
+ return {
993
+ type: "file-edit",
994
+ toolCallId,
995
+ path: str(output.filePath),
996
+ kind: created ? "create" : "modify",
997
+ ...counts
998
+ };
999
+ }
1000
+ function fileEdits(toolCallId, output, tool, input, inWorkspace) {
1001
+ if (tool === "delete") return [{
1002
+ type: "file-edit",
1003
+ toolCallId,
1004
+ path: editPath(input),
1005
+ kind: "delete",
1006
+ added: 0,
1007
+ removed: null
1008
+ }];
1009
+ const result = record(output);
1010
+ if (typeof result.filePath === "string") return [claudeEdit(toolCallId, result)];
1011
+ const patch = str(record(result.details).patch);
1012
+ if (patch) {
1013
+ const all = lines(patch);
1014
+ const hunks = all.findIndex((l) => l.startsWith("@@"));
1015
+ const body = hunks < 0 ? [] : all.slice(hunks + 1);
1016
+ return [{
1017
+ type: "file-edit",
1018
+ toolCallId,
1019
+ path: editPath(input),
1020
+ kind: "modify",
1021
+ added: body.filter((l) => l.startsWith("+")).length,
1022
+ removed: body.filter((l) => l.startsWith("-")).length
1023
+ }];
1024
+ }
1025
+ const files = record(result.metadata).files;
1026
+ if (Array.isArray(files) && files.length > 0) return files.map((f) => {
1027
+ const file = record(f);
1028
+ return {
1029
+ type: "file-edit",
1030
+ toolCallId,
1031
+ path: inWorkspace(str(file.file) || editPath(input)),
1032
+ kind: file.status === "added" ? "create" : file.status === "deleted" ? "delete" : "modify",
1033
+ added: typeof file.additions === "number" ? file.additions : null,
1034
+ removed: typeof file.deletions === "number" ? file.deletions : null
1035
+ };
1036
+ });
1037
+ const said = str(result.output);
1038
+ if (/^(Created|Wrote) file successfully/.test(said)) {
1039
+ const created = said.startsWith("Created");
1040
+ return [{
1041
+ type: "file-edit",
1042
+ toolCallId,
1043
+ path: inWorkspace(editPath(input)),
1044
+ kind: created ? "create" : "modify",
1045
+ added: created ? lines(str(input.content)).length : null,
1046
+ removed: created ? 0 : null
1047
+ }];
1048
+ }
1049
+ if (result.kind === "add" || result.kind === "update") return [{
1050
+ type: "file-edit",
1051
+ toolCallId,
1052
+ path: editPath(input),
1053
+ kind: result.kind === "add" ? "create" : "modify",
1054
+ added: null,
1055
+ removed: null
1056
+ }];
1057
+ if (typeof result.linesAdded === "number") return [{
1058
+ type: "file-edit",
1059
+ toolCallId,
1060
+ path: editPath(input),
1061
+ kind: str(result.diffString).startsWith("--- /dev/null") ? "create" : "modify",
1062
+ added: result.linesAdded,
1063
+ removed: typeof result.linesRemoved === "number" ? result.linesRemoved : null
1064
+ }];
1065
+ if (tool === "write") return [{
1066
+ type: "file-edit",
1067
+ toolCallId,
1068
+ path: editPath(input),
1069
+ kind: "write",
1070
+ added: typeof input.content === "string" ? lines(input.content).length : null,
1071
+ removed: null
1072
+ }];
1073
+ return [{
1074
+ type: "file-edit",
1075
+ toolCallId,
1076
+ path: editPath(input),
1077
+ kind: "modify",
1078
+ added: null,
1079
+ removed: null
1080
+ }];
1081
+ }
1082
+ /**
1083
+ * The tool's name. Cursor reports an MCP call as `mcp`, with the server and tool in its input;
1084
+ * those are named `mcp__<server>__<tool>`, as Claude Code names its own.
1085
+ */
1086
+ function toolName(part) {
1087
+ const input = record(part.input);
1088
+ if (typeof input.providerIdentifier === "string" && typeof input.toolName === "string") return `mcp__${input.providerIdentifier}__${input.toolName}`;
1089
+ return str(part.toolName);
1090
+ }
1091
+ /** The tool's input: a Cursor MCP call's own `args`, without the wrapper naming its server and tool. */
1092
+ function toolInput(part) {
1093
+ const input = record(part.input);
1094
+ if (typeof input.providerIdentifier === "string" && typeof input.toolName === "string") return input.args ?? {};
1095
+ return part.input;
1096
+ }
1097
+ /** Claude Code's native tool names as its adapter's common ones, for a subagent's calls. */
1098
+ const CLAUDE_COMMON_NAMES = {
1099
+ Read: "read",
1100
+ Write: "write",
1101
+ Edit: "edit",
1102
+ MultiEdit: "edit",
1103
+ Bash: "bash",
1104
+ Glob: "glob",
1105
+ Grep: "grep",
1106
+ WebSearch: "webSearch"
1107
+ };
1108
+ /** A tool result's content as text: Claude's is a string or a list of `{ type: 'text', text }`. */
1109
+ const contentText = (content) => Array.isArray(content) ? content.map((c) => str(record(c).text)).join("") : typeof content === "string" ? content : jsonText(content);
1110
+ /**
1111
+ * A Claude Code subagent's edit as Claude's own Edit or Write result, which `claudeEdit` reads:
1112
+ * the bridge passes a subagent's messages on as raw SDK messages, whose result is only text.
1113
+ */
1114
+ function subagentEditOutput(tool, input, said, inWorkspace) {
1115
+ const filePath = inWorkspace(editPath(input));
1116
+ if (tool === "edit") return {
1117
+ filePath,
1118
+ oldString: input.old_string,
1119
+ newString: input.new_string
1120
+ };
1121
+ return {
1122
+ type: /created successfully/i.test(said) ? "create" : "update",
1123
+ filePath,
1124
+ content: input.content
1125
+ };
1126
+ }
1127
+ /**
1128
+ * The tool calls and results in a Claude Code subagent's SDK message (`parent_tool_use_id` set),
1129
+ * which the bridge passes on only as a `raw` part, as the stream parts its own calls arrive as.
1130
+ */
1131
+ function subagentParts(raw) {
1132
+ const parent = raw.parent_tool_use_id;
1133
+ if (typeof parent !== "string" || raw.type !== "assistant" && raw.type !== "user") return [];
1134
+ const content = record(raw.message).content;
1135
+ if (!Array.isArray(content)) return [];
1136
+ const structured = record(raw.tool_use_result);
1137
+ return content.flatMap((b) => {
1138
+ const block = record(b);
1139
+ if (raw.type === "assistant" && block.type === "tool_use" && typeof block.id === "string") {
1140
+ const name = str(block.name);
1141
+ return [{
1142
+ type: "tool-call",
1143
+ toolCallId: block.id,
1144
+ toolName: CLAUDE_COMMON_NAMES[name] ?? name,
1145
+ input: block.input ?? {},
1146
+ subagent: parent
1147
+ }];
1148
+ }
1149
+ if (raw.type === "user" && block.type === "tool_result") {
1150
+ const said = contentText(block.content);
1151
+ const id = str(block.tool_use_id);
1152
+ return block.is_error === true ? [{
1153
+ type: "tool-error",
1154
+ toolCallId: id,
1155
+ error: said
1156
+ }] : [{
1157
+ type: "tool-result",
1158
+ toolCallId: id,
1159
+ output: said,
1160
+ structured
1161
+ }];
1162
+ }
1163
+ return [];
1164
+ });
1165
+ }
1166
+ const toolOutputOf = (value) => {
1167
+ const said = record(value);
1168
+ if (said.view !== "full") return {};
1169
+ return {
1170
+ view: "full",
1171
+ ...typeof said.bytes === "number" ? { bytes: said.bytes } : {}
1172
+ };
1173
+ };
1174
+ /**
1175
+ * What an adapter says about a tool result's output, as `toolOutput` in the result's
1176
+ * `providerMetadata` under its own key: `view: 'full'` for output it read from where the CLI
1177
+ * saved it (the model got a pointer or nothing), and `bytes`, the saved output's size in UTF-8,
1178
+ * when it kept only part of it. An adapter that finds the saved output only after the result
1179
+ * went out sends a `raw` part whose `toolOutput` also has the `toolCallId` and the `output` that
1180
+ * replaces the result's.
1181
+ */
1182
+ function adapterToolOutput(metadata) {
1183
+ for (const entry of Object.values(record(metadata))) {
1184
+ const said = toolOutputOf(record(entry).toolOutput);
1185
+ if (said.view) return said;
1186
+ }
1187
+ return {};
1188
+ }
1189
+ /**
1190
+ * Turns an AI SDK harness stream into transcript events: text and reasoning blocks joined, each
1191
+ * tool call merged with its result, edits normalized to `file-edit`, web tools given their query
1192
+ * or URL, and the harness's duplicate `fileChange` events dropped. Cursor's tool durations come
1193
+ * from its runner's own `tool_call` events, because tool results are only flushed at the end of
1194
+ * a step. Each tool event's `outputView` is `full` for the tools in `fullToolOutput` and for
1195
+ * output an adapter read from where its CLI saved it, else `model`. An absolute edit path that
1196
+ * `workspace` matches the start of is kept relative to it.
1197
+ */
1198
+ function normalizeStream(parts, startedAt, options = {}) {
1199
+ const { workspace } = options;
1200
+ const inWorkspace = (path) => workspace ? path.replace(workspace, "") : path;
1201
+ const fullByHarness = (tool) => options.fullToolOutput === "all" || options.fullToolOutput?.includes(tool) === true;
1202
+ const timing = /* @__PURE__ */ new Map();
1203
+ const replaced = /* @__PURE__ */ new Map();
1204
+ for (const { ms, part } of parts) {
1205
+ if (part.type !== "raw") continue;
1206
+ const raw = record(part.rawValue);
1207
+ const later = record(raw.toolOutput);
1208
+ if (typeof later.toolCallId === "string" && "output" in later && toolOutputOf(later).view) replaced.set(later.toolCallId, {
1209
+ ...toolOutputOf(later),
1210
+ output: later.output
1211
+ });
1212
+ const event = raw.type === "event" ? record(raw.event) : {};
1213
+ const id = event.type === "tool_call" ? str(event.call_id) : "";
1214
+ if (!id) continue;
1215
+ const t = timing.get(id) ?? {};
1216
+ const started = typeof event.started_at_ms === "number" ? event.started_at_ms - startedAt : void 0;
1217
+ const ended = typeof event.completed_at_ms === "number" ? event.completed_at_ms - startedAt : void 0;
1218
+ if (started !== void 0) t.at = t.start = started;
1219
+ else if (event.status === "running" && t.start === void 0) t.start = ms;
1220
+ if (ended !== void 0) {
1221
+ t.end = ended;
1222
+ if (raw.recovered !== void 0 && t.start !== void 0) t.recovered = true;
1223
+ } else if (event.status === "completed" || event.status === "error") t.end = ms;
1224
+ timing.set(id, t);
1225
+ }
1226
+ const out = [];
1227
+ const stamp = (at) => ({
1228
+ ts: new Date(startedAt + at).toISOString(),
1229
+ atMs: at
1230
+ });
1231
+ const blocks = /* @__PURE__ */ new Map();
1232
+ const pending = /* @__PURE__ */ new Map();
1233
+ const toolDone = (id, reported, end, failed) => {
1234
+ let call = reported;
1235
+ const t = timing.get(id);
1236
+ const durationMs = toolDurationMs(t?.start ?? call.ms, call, end.ms, t);
1237
+ call = t?.at === void 0 ? call : {
1238
+ ...call,
1239
+ ms: t.at
1240
+ };
1241
+ const input = record(call.part.input);
1242
+ const name = toolName(call.part);
1243
+ const replacement = failed ? void 0 : replaced.get(id);
1244
+ const raw = failed ? errorText(end.part.error) : replacement ? replacement.output : end.part.output;
1245
+ const subagent = str(call.part.subagent);
1246
+ const structured = record(end.part.structured);
1247
+ const output = subagent && (name === "edit" || name === "write") && !failed ? typeof structured.filePath === "string" ? {
1248
+ ...structured,
1249
+ filePath: inWorkspace(structured.filePath)
1250
+ } : subagentEditOutput(name, input, str(raw), inWorkspace) : name === "bash" && typeof raw === "string" ? raw.replace(/\r\n/g, "\n") : raw;
1251
+ const base = {
1252
+ ...stamp(call.ms),
1253
+ durationMs,
1254
+ ...stallFlags(name, durationMs),
1255
+ ...subagent ? { subagent } : {}
1256
+ };
1257
+ if ((name === "edit" || name === "write" || name === "delete") && !failed) {
1258
+ for (const edit of fileEdits(id, output, name, input, inWorkspace)) out.push({
1259
+ at: call.ms,
1260
+ event: {
1261
+ ...base,
1262
+ ...edit,
1263
+ ...stallFlags(name, durationMs)
1264
+ }
1265
+ });
1266
+ return;
1267
+ }
1268
+ if (name === "webSearch") {
1269
+ out.push({
1270
+ at: call.ms,
1271
+ event: {
1272
+ ...base,
1273
+ type: "web-search",
1274
+ toolCallId: id,
1275
+ query: str(input.searchTerm) || str(input.query),
1276
+ references: failed ? null : searchReferences(output),
1277
+ ok: !failed
1278
+ }
1279
+ });
1280
+ return;
1281
+ }
1282
+ if (name === "webFetch" || name === "WebFetch") {
1283
+ const result = record(output);
1284
+ const status = typeof result.code === "number" ? result.code : void 0;
1285
+ out.push({
1286
+ at: call.ms,
1287
+ event: {
1288
+ ...base,
1289
+ type: "web-fetch",
1290
+ toolCallId: id,
1291
+ url: str(input.url),
1292
+ ok: !failed && result.success !== false && (status === void 0 || status >= 200 && status < 400)
1293
+ }
1294
+ });
1295
+ return;
1296
+ }
1297
+ const said = replacement ?? adapterToolOutput(end.part.providerMetadata);
1298
+ out.push({
1299
+ at: call.ms,
1300
+ event: {
1301
+ ...base,
1302
+ type: "tool",
1303
+ toolCallId: id,
1304
+ tool: name,
1305
+ input: toolInput(call.part),
1306
+ output,
1307
+ outputView: said.view ?? (fullByHarness(name) ? "full" : "model"),
1308
+ ...said.bytes !== void 0 ? { outputTruncated: { bytes: said.bytes } } : {},
1309
+ ok: !failed
1310
+ }
1311
+ });
1312
+ };
1313
+ for (const stamped of parts) {
1314
+ const { ms, part } = stamped;
1315
+ switch (part.type) {
1316
+ case "raw":
1317
+ for (const sub of subagentParts(record(part.rawValue))) {
1318
+ const id = str(sub.toolCallId);
1319
+ if (sub.type === "tool-call") {
1320
+ pending.set(id, {
1321
+ ms,
1322
+ part: sub
1323
+ });
1324
+ continue;
1325
+ }
1326
+ const call = pending.get(id);
1327
+ if (!call) continue;
1328
+ pending.delete(id);
1329
+ toolDone(id, call, {
1330
+ ms,
1331
+ part: sub
1332
+ }, sub.type === "tool-error");
1333
+ }
1334
+ break;
1335
+ case "text-start":
1336
+ case "reasoning-start": {
1337
+ const recovered = part.type === "reasoning-start" ? recoveredTiming(part) : void 0;
1338
+ blocks.set(str(part.id), {
1339
+ type: part.type === "text-start" ? "text" : "reasoning",
1340
+ ms: recovered ? Math.max(0, ms - recovered.startedBeforeMs) : ms,
1341
+ text: "",
1342
+ ...recovered ? { durationMs: recovered.durationMs } : {}
1343
+ });
1344
+ break;
1345
+ }
1346
+ case "text-delta":
1347
+ case "reasoning-delta": {
1348
+ const block = blocks.get(str(part.id));
1349
+ if (block) block.text += str(part.text ?? part.delta);
1350
+ break;
1351
+ }
1352
+ case "text-end":
1353
+ case "reasoning-end": {
1354
+ const block = blocks.get(str(part.id));
1355
+ blocks.delete(str(part.id));
1356
+ if (block?.text.trim()) out.push({
1357
+ at: block.ms,
1358
+ event: {
1359
+ ...stamp(block.ms),
1360
+ type: block.type,
1361
+ text: block.text,
1362
+ durationMs: block.durationMs !== void 0 ? block.durationMs : ms - block.ms
1363
+ }
1364
+ });
1365
+ break;
1366
+ }
1367
+ case "tool-call":
1368
+ if (!isFileChangeEcho(part)) pending.set(str(part.toolCallId), {
1369
+ ms,
1370
+ part
1371
+ });
1372
+ break;
1373
+ case "tool-result":
1374
+ case "tool-error": {
1375
+ if (isFileChangeEcho(part)) break;
1376
+ const id = str(part.toolCallId);
1377
+ const call = pending.get(id);
1378
+ if (!call) break;
1379
+ pending.delete(id);
1380
+ toolDone(id, call, stamped, part.type === "tool-error");
1381
+ break;
1382
+ }
1383
+ case "error":
1384
+ out.push({
1385
+ at: ms,
1386
+ event: {
1387
+ ...stamp(ms),
1388
+ type: "error",
1389
+ message: errorText(part.error)
1390
+ }
1391
+ });
1392
+ break;
1393
+ case "finish-step": if (part.finishReason === "error") {
1394
+ const message = `A model call failed (${str(part.rawFinishReason) || "error"}), and the agent retried it`;
1395
+ out.push({
1396
+ at: ms,
1397
+ event: {
1398
+ ...stamp(ms),
1399
+ type: "retry",
1400
+ message
1401
+ }
1402
+ });
1403
+ }
1404
+ }
1405
+ }
1406
+ const streamEndMs = parts.at(-1)?.ms;
1407
+ for (const [id, call] of pending) {
1408
+ const name = toolName(call.part);
1409
+ const input = record(call.part.input);
1410
+ const t = timing.get(id);
1411
+ const start = t?.start ?? call.ms;
1412
+ const durationMs = streamEndMs === void 0 ? null : toolDurationMs(start, call, streamEndMs, t);
1413
+ const subagent = str(call.part.subagent);
1414
+ const base = {
1415
+ ...stamp(call.ms),
1416
+ durationMs,
1417
+ ...stallFlags(name, durationMs),
1418
+ ...subagent ? { subagent } : {}
1419
+ };
1420
+ if (name === "webSearch") {
1421
+ out.push({
1422
+ at: call.ms,
1423
+ event: {
1424
+ ...base,
1425
+ type: "web-search",
1426
+ toolCallId: id,
1427
+ query: str(input.searchTerm) || str(input.query),
1428
+ references: null,
1429
+ ok: null
1430
+ }
1431
+ });
1432
+ continue;
1433
+ }
1434
+ if (name === "webFetch" || name === "WebFetch") {
1435
+ out.push({
1436
+ at: call.ms,
1437
+ event: {
1438
+ ...base,
1439
+ type: "web-fetch",
1440
+ toolCallId: id,
1441
+ url: str(input.url),
1442
+ ok: null
1443
+ }
1444
+ });
1445
+ continue;
1446
+ }
1447
+ out.push({
1448
+ at: call.ms,
1449
+ event: {
1450
+ ...base,
1451
+ type: "tool",
1452
+ toolCallId: id,
1453
+ tool: name,
1454
+ input: toolInput(call.part),
1455
+ output: null,
1456
+ ok: null
1457
+ }
1458
+ });
1459
+ }
1460
+ for (const [, block] of blocks) if (block.text.trim()) out.push({
1461
+ at: block.ms,
1462
+ event: {
1463
+ ...stamp(block.ms),
1464
+ type: block.type,
1465
+ text: block.text,
1466
+ durationMs: null
1467
+ }
1468
+ });
1469
+ return out.sort((a, b) => a.at - b.at).map((e) => e.event);
1470
+ }
1471
+ /** Whether a harness's reasoning blocks carry their time: streamed, or recovered with it. */
1472
+ const timesReasoning = (delivery) => delivery === "streamed" || delivery === "recovered";
1473
+ /**
1474
+ * A turn's reasoning time, from the reasoning blocks the harness streamed; null when it can't be
1475
+ * known. A harness whose reasoning arrives whole (`whole`) or not at all (`none`) can't time it.
1476
+ * A streamed or recovered turn with no reasoning block has spent none only when its usage says it
1477
+ * used no reasoning tokens; otherwise the model may have reasoned without the harness showing it.
1478
+ */
1479
+ function reasoningTime(delivery, events, usage) {
1480
+ if (!timesReasoning(delivery)) return null;
1481
+ const blocks = events.flatMap((e) => e.type === "reasoning" ? [e.durationMs] : []);
1482
+ if (blocks.length === 0) return usage?.reasoning === 0 ? 0 : null;
1483
+ if (blocks.some((ms) => ms === null)) return null;
1484
+ return blocks.reduce((n, ms) => n + (ms ?? 0), 0);
1485
+ }
1486
+ // ../agents/src/driver/agent.ts
1487
+ /** A stream part into the attempt's trace, and each tool call as a `-v` line as it happens. */
1488
+ function traceStreamPart(log, part, ms, tools) {
1489
+ const p = part;
1490
+ log.trace("harness", "stream", {
1491
+ ms,
1492
+ part
1493
+ }, p.type.endsWith("-delta") ? false : `stream ${p.type}`);
1494
+ if (p.type === "tool-call" && p.toolCallId) {
1495
+ const name = p.toolName ?? "tool";
1496
+ tools.set(p.toolCallId, {
1497
+ name,
1498
+ at: ms
1499
+ });
1500
+ log.log("harness", `tool ${name} called (${p.toolCallId})`);
1501
+ } else if ((p.type === "tool-result" || p.type === "tool-error") && p.toolCallId) {
1502
+ const call = tools.get(p.toolCallId);
1503
+ const took = call ? ` in ${ms - call.at}ms` : "";
1504
+ const how = p.type === "tool-error" ? `failed: ${errorText(p.error)}` : "returned";
1505
+ log.log("harness", `tool ${call?.name ?? p.toolName ?? "tool"} ${how}${took} (${p.toolCallId})`);
1506
+ } else if (p.type === "error") log.log("harness", `stream error: ${errorText(p.error)}`);
1507
+ }
1508
+ /**
1509
+ * Each turn's cost from what the harness reports on its finish: a session's running total, as
1510
+ * Claude Code's is, less what its earlier turns reported. A total that fell, or a session other
1511
+ * than the attempt's first, can't be split into turns, so that turn has no reported cost; nor
1512
+ * has one the harness put at $0, which it says for a model its own prices don't list.
1513
+ */
1514
+ function turnCosts(reported, source) {
1515
+ let session;
1516
+ let before = 0;
1517
+ return (harnessMetadata) => {
1518
+ const said = reported?.(harnessMetadata);
1519
+ if (!said) return void 0;
1520
+ let usd = said.usd;
1521
+ if (said.session !== void 0) {
1522
+ const same = session === void 0 || session === said.session;
1523
+ const fell = said.usd < before;
1524
+ session ??= said.session;
1525
+ if (!same) return void 0;
1526
+ usd = Math.round((said.usd - before) * 1e9) / 1e9;
1527
+ before = said.usd;
1528
+ if (fell) return void 0;
1529
+ }
1530
+ return usd > 0 ? {
1531
+ usd,
1532
+ basis: "reported",
1533
+ source
1534
+ } : void 0;
1535
+ };
1536
+ }
1537
+ /** How long reading a CLI's stored usage gets, past which the turn keeps none. */
1538
+ const STORED_USAGE_MS = 5e3;
1539
+ /** An adapter's usage, in the AI SDK's provider shape, as a transcript's; null when it counts nothing. */
1540
+ function harnessUsage(usage) {
1541
+ const { inputTokens: input, outputTokens: output } = usage;
1542
+ if (input.total === void 0 && output.total === void 0) return null;
1543
+ const cacheRead = input.cacheRead ?? 0;
1544
+ const cacheWrite = input.cacheWrite ?? 0;
1545
+ return {
1546
+ input: input.noCache ?? Math.max((input.total ?? 0) - cacheRead - cacheWrite, 0),
1547
+ output: output.total ?? 0,
1548
+ cacheRead,
1549
+ cacheWrite,
1550
+ reasoning: output.reasoning ?? null
1551
+ };
1552
+ }
1553
+ /**
1554
+ * The adapter, with every part its sessions emit also passed to `onPart`. `HarnessAgent` keeps
1555
+ * the `stream-start` part's `modelId` (the model the runtime resolved) to itself.
1556
+ */
1557
+ function observed(adapter, onPart) {
1558
+ const session = (s) => new Proxy(s, { get(target, key, receiver) {
1559
+ const value = Reflect.get(target, key, receiver);
1560
+ if (key !== "doPromptTurn" && key !== "doContinueTurn") return value;
1561
+ return (turn) => value.call(target, {
1562
+ ...turn,
1563
+ emit: (part) => {
1564
+ onPart(part);
1565
+ turn.emit(part);
1566
+ }
1567
+ });
1568
+ } });
1569
+ return new Proxy(adapter, { get(target, key, receiver) {
1570
+ const value = Reflect.get(target, key, receiver);
1571
+ if (key !== "doStart") return value;
1572
+ return async (...args) => session(await value.apply(target, args));
1573
+ } });
1574
+ }
1575
+ /**
1576
+ * The built-in tools that wait on a person, which an unattended agent has none of. Claude Code's
1577
+ * `AskUserQuestion` ends the turn on a tool call only the host answers, and the session takes no
1578
+ * new prompt until it gets one, so the agent is never offered it and asks in its reply instead.
1579
+ */
1580
+ const INTERACTIVE_TOOLS = ["askUserQuestions"];
1581
+ /** The adapter's built-in tools the driver turns off: those of {@link INTERACTIVE_TOOLS} it offers. */
1582
+ function interactiveTools(adapter) {
1583
+ return INTERACTIVE_TOOLS.filter((name) => Object.hasOwn(adapter.builtinTools, name));
1584
+ }
1585
+ /**
1586
+ * The turn's error when every model call the runner's network saw in it got an HTTP error,
1587
+ * naming the statuses; undefined when one succeeded or it saw none.
1588
+ */
1589
+ function everyCallFailed(name, statuses) {
1590
+ if (statuses.length === 0 || statuses.some((s) => s < 400)) return void 0;
1591
+ return `every ${name} model call in the turn failed (HTTP ${[...new Set(statuses)].join(", ")})`;
1592
+ }
1593
+ /**
1594
+ * How the APIs behind the harnesses say they refused a key: an HTTP 401, Anthropic's and OpenAI's
1595
+ * wording, Google's (which answers 400), and OpenCode's for any provider's 401 or 403. A bare 403
1596
+ * isn't here: proxies and MCP servers send those for reasons that have nothing to do with the
1597
+ * harness's key. Grok Build checks its key as it starts and, when xAI refuses it (a 400 or 401,
1598
+ * not an outage), offers no `xai.api_key` sign-in, which is all `@ai-sdk/harness-acp` reports.
1599
+ */
1600
+ const REFUSED_KEY = /\bHTTP 401\b|\b401\b.{0,40}\bunauthori[sz]ed\b|\bunauthori[sz]ed\b.{0,40}\b401\b|\b(?:invalid|incorrect) (?:x-)?api[ _-]?key\b|\bapi key not valid\b|\bAPI_KEY_INVALID\b|\bauthentication_error\b|\bprovider authentication required\b|\bauthentication method "xai\.api_key" is not advertised\b/i;
1601
+ /**
1602
+ * The turn's refused-key error (`hinted`, the first error `authHint` named the key in) when the API
1603
+ * rejected the harness's key for the whole turn: the turn errored, or every model call failed,
1604
+ * and no call the runner's network saw succeeded. A key that served one call isn't rejected,
1605
+ * whatever the turn's error says: a 401 the CLI retried past, or refused-key wording that came
1606
+ * from elsewhere (a tool's or MCP server's output in the CLI's stderr).
1607
+ */
1608
+ function rejectedKey(turn) {
1609
+ const { hinted, status, statuses } = turn;
1610
+ if (!hinted || status === "aborted" || statuses.some((s) => s < 400)) return void 0;
1611
+ return status === "error" || statuses.length > 0 ? hinted : void 0;
1612
+ }
1613
+ /**
1614
+ * Starts a real agent's session on `runner` through its AI SDK harness adapter. Each `send` is a
1615
+ * turn, whose result is its normalized transcript, usage, served model and cost, and whether the
1616
+ * key was refused or the provider stopped it. Failing to start throws an {@link AgentError}.
1617
+ */
1618
+ async function startAgent(options) {
1619
+ const { kind, entry, adapter, model, runner, signal, log, traffic, authHint } = options;
1620
+ const close = options.onClose ?? (() => {});
1621
+ let servedModel = null;
1622
+ let finishMetadata;
1623
+ const turnCost = turnCosts(entry.reportedCost, kind);
1624
+ const off = interactiveTools(adapter);
1625
+ const agent = new HarnessAgent({
1626
+ harness: observed(adapter, (part) => {
1627
+ if (part.type === "stream-start" && part.modelId && !entry.configuredModelOnStart) servedModel = part.modelId;
1628
+ if (part.type === "finish") finishMetadata = part.harnessMetadata;
1629
+ }),
1630
+ model,
1631
+ permissionMode: "allow-all",
1632
+ ...off.length ? { inactiveTools: off } : {},
1633
+ sandboxConfig: { workDir: options.workDir },
1634
+ ...options.skills?.length ? { skills: options.skills } : {}
1635
+ });
1636
+ const statuses = () => traffic?.statuses() ?? [];
1637
+ let network;
1638
+ const release = () => Promise.resolve(network?.destroy()).catch(() => {});
1639
+ let session;
1640
+ try {
1641
+ network = await runnerSession(runner, options.session);
1642
+ session = await agent.createSession({
1643
+ sandboxSession: network,
1644
+ abortSignal: signal
1645
+ });
1646
+ } catch (error) {
1647
+ close();
1648
+ await release();
1649
+ if (signal.aborted) throw error;
1650
+ const message = error.message;
1651
+ const hint = authHint?.(message, statuses().includes(401));
1652
+ throw new AgentError(`${hint ? `${hint}. ` : ""}${entry.name} harness failed to start: ${message}`, { transient: !hint && error.transient === true });
1653
+ }
1654
+ const started = network;
1655
+ let usageMark;
1656
+ const storedUsage = async (since) => {
1657
+ const store = await entry.storedUsage?.();
1658
+ if (!store) return null;
1659
+ const command = store.command({
1660
+ since,
1661
+ ...usageMark ? { mark: usageMark } : {}
1662
+ });
1663
+ const read = await Promise.resolve(started.run({
1664
+ command,
1665
+ abortSignal: AbortSignal.timeout(STORED_USAGE_MS)
1666
+ })).then(({ exitCode, stdout, stderr }) => {
1667
+ if (exitCode !== 0) throw new Error(`exit ${exitCode}: ${stderr.trim().slice(-300)}`);
1668
+ return store.parse(stdout);
1669
+ }).catch((error) => {
1670
+ log.log("harness", `reading ${entry.name}'s stored usage failed: ${errorText(error)}`);
1671
+ });
1672
+ if (!read) {
1673
+ log.log("harness", `no usage in ${entry.name}'s store since the turn began`);
1674
+ return null;
1675
+ }
1676
+ if (read.mark) usageMark = read.mark;
1677
+ const usage = harnessUsage(read.usage);
1678
+ const calls = `${read.calls} model call${read.calls === 1 ? "" : "s"}`;
1679
+ log.log("harness", `usage read back from ${entry.name}'s store: ${calls}${usage ? ` · ${usage.input} in · ${usage.output} out` : ""}`);
1680
+ return usage;
1681
+ };
1682
+ let running;
1683
+ let turn;
1684
+ return {
1685
+ async send(prompt, turnSignal) {
1686
+ const startedAt = Date.now();
1687
+ const current = { startedAt };
1688
+ turn = current;
1689
+ const parts = [];
1690
+ const servedBefore = traffic?.servedModels().length ?? 0;
1691
+ const seenBefore = statuses().length;
1692
+ servedModel = null;
1693
+ finishMetadata = void 0;
1694
+ let stepUsage = null;
1695
+ const steps = [];
1696
+ const finish = async (text, status, extra = [], reported = stepUsage) => {
1697
+ const usage = reported ?? await (current.salvaged ?? storedUsage(startedAt));
1698
+ const seen = statuses().slice(seenBefore);
1699
+ const refused = seen.includes(401);
1700
+ const events = [...normalizeStream(parts, startedAt, {
1701
+ ...entry.fullToolOutput ? { fullToolOutput: entry.fullToolOutput } : {},
1702
+ ...options.workspace ? { workspace: options.workspace } : {}
1703
+ }), ...extra].map((e) => e.type === "reasoning" && !timesReasoning(entry.reasoning) ? {
1704
+ ...e,
1705
+ durationMs: null
1706
+ } : e);
1707
+ const failed = everyCallFailed(entry.name, seen);
1708
+ if (status === "completed" && failed && !events.some((e) => e.type === "error")) {
1709
+ const at = Date.now() - startedAt;
1710
+ status = "error";
1711
+ events.push({
1712
+ type: "error",
1713
+ message: failed,
1714
+ ts: new Date(startedAt + at).toISOString(),
1715
+ atMs: at
1716
+ });
1717
+ }
1718
+ let hinted;
1719
+ const transcript = events.map((e) => {
1720
+ if (e.type !== "error") return e;
1721
+ const hint = authHint?.(e.message, refused);
1722
+ if (!hint) return e;
1723
+ const message = `${hint}. ${e.message}`;
1724
+ hinted ??= message;
1725
+ return {
1726
+ ...e,
1727
+ message
1728
+ };
1729
+ });
1730
+ const rejected = rejectedKey({
1731
+ hinted,
1732
+ status,
1733
+ statuses: seen
1734
+ });
1735
+ const stopped = rejected ? void 0 : providerStop({
1736
+ errors: transcript.flatMap((e) => e.type === "error" ? [e.message] : []),
1737
+ status,
1738
+ statuses: seen
1739
+ });
1740
+ const cost = turnCost(finishMetadata);
1741
+ return {
1742
+ text,
1743
+ status,
1744
+ usage,
1745
+ ...cost ? { cost } : {},
1746
+ model: servedModel ?? traffic?.servedModels().slice(servedBefore).at(-1) ?? null,
1747
+ unreported: entry.unreported?.(finishMetadata) ?? [],
1748
+ steps,
1749
+ reasoningMs: reasoningTime(entry.reasoning, transcript, usage),
1750
+ startedAt: new Date(startedAt).toISOString(),
1751
+ durationMs: Date.now() - startedAt,
1752
+ transcript,
1753
+ ...rejected ? { rejectedKey: rejected } : {},
1754
+ ...stopped ? { providerStop: stopped } : {},
1755
+ ...options.raw ? { raw: parts } : {}
1756
+ };
1757
+ };
1758
+ running = (note) => finish("", "aborted", [note]);
1759
+ try {
1760
+ const result = await agent.stream({
1761
+ session,
1762
+ prompt,
1763
+ abortSignal: turnSignal
1764
+ });
1765
+ const tools = /* @__PURE__ */ new Map();
1766
+ for await (const part of result.fullStream) {
1767
+ const ms = Date.now() - startedAt;
1768
+ const stamped = {
1769
+ ms,
1770
+ part
1771
+ };
1772
+ parts.push(stamped);
1773
+ options.onPart?.(stamped);
1774
+ traceStreamPart(log, stamped.part, ms, tools);
1775
+ if (part.type === "finish-step") {
1776
+ const step = tokenUsage(part.usage);
1777
+ if (step) steps.push(step);
1778
+ stepUsage = addUsage(stepUsage, step);
1779
+ }
1780
+ }
1781
+ const reported = await result.totalUsage;
1782
+ const total = tokenUsage(reported);
1783
+ const mark = (await entry.storedUsage?.())?.mark?.(reported.raw);
1784
+ if (mark) usageMark = mark;
1785
+ const status = turnSignal.aborted ? "aborted" : "completed";
1786
+ return finish(await result.text, status, [], total ?? stepUsage);
1787
+ } catch (error) {
1788
+ const message = errorText(error);
1789
+ const at = Date.now() - startedAt;
1790
+ const reported = parts.some(({ part }) => part.type === "error" && errorText(part.error) === message);
1791
+ return finish("", turnSignal.aborted ? "aborted" : "error", reported ? [] : [{
1792
+ type: "error",
1793
+ message,
1794
+ ts: new Date(startedAt + at).toISOString(),
1795
+ atMs: at
1796
+ }]);
1797
+ } finally {
1798
+ if (turn === current) turn = void 0;
1799
+ }
1800
+ },
1801
+ stopped: (note) => running ? running(note) : Promise.reject(/* @__PURE__ */ new Error("No turn is running")),
1802
+ salvage: async () => {
1803
+ if (!turn) return;
1804
+ turn.salvaged ??= storedUsage(turn.startedAt);
1805
+ await turn.salvaged;
1806
+ },
1807
+ close: async () => {
1808
+ close();
1809
+ await session.destroy().catch(() => {});
1810
+ await release();
1811
+ }
1812
+ };
1813
+ }
1814
+ // ../agents/src/routes/api.ts
1815
+ /** The host `api`'s key is brokered on. */
1816
+ const apiHost = (api) => new URL(api.origin).hostname;
1817
+ const under$2 = (base, endpoint) => `${new URL(base).pathname.replace(/\/$/, "")}${endpoint}`;
1818
+ /** The path of `endpoint` (`/chat/completions`) on `api`'s OpenAI-compatible API. */
1819
+ const openaiPath = (api, endpoint) => under$2(api.openai, endpoint);
1820
+ /** The path of `endpoint` (`/v1/messages`) on `api`'s Anthropic Messages API. */
1821
+ const anthropicPath = (api, endpoint) => under$2(api.anthropic, endpoint);
1822
+ // ../agents/src/routes/effort.ts
1823
+ /** Every model: no run has checked the harness's effort reaches any of them there. */
1824
+ const everyModel = () => true;
1825
+ /** Any but a Gemini model (`gemini-3.8-flash`, `google/gemini-3.8-flash`). */
1826
+ const notGemini = (model) => !/^(?:google\/)?gemini-/.test(model);
1827
+ /** Vercel's own API, where `vercel()` goes unless `AI_GATEWAY_BASE_URL` names another. */
1828
+ const VERCEL_API = apiAt("https://ai-gateway.vercel.sh");
1829
+ const VERCEL_HOST = apiHost(VERCEL_API);
1830
+ /**
1831
+ * The host variable naming another gateway with Vercel's API, such as a proxy in front of it:
1832
+ * the origin, with any path its API is under, that stands for `https://ai-gateway.vercel.sh`.
1833
+ * The variable the AI SDK's harness adapters read for it, too.
1834
+ */
1835
+ const VERCEL_BASE_URL = "AI_GATEWAY_BASE_URL";
1836
+ /** What the adapters take Vercel's key as, whichever host variable it came from. */
1837
+ const VERCEL_KEY = "AI_GATEWAY_API_KEY";
1838
+ /** A Vercel project's short-lived token (`vercel env pull`), used when there's no key. */
1839
+ const VERCEL_OIDC = "VERCEL_OIDC_TOKEN";
1840
+ function apiAt(base) {
1841
+ const origin = base.replace(/\/+$/, "");
1842
+ return {
1843
+ origin,
1844
+ openai: `${origin}/v1`,
1845
+ anthropic: origin
1846
+ };
1847
+ }
1848
+ /** `value` as the URL reeval calls: the parsed origin and path, with no trailing slash. */
1849
+ const parsedBase = (value) => {
1850
+ const url = URL.parse(value);
1851
+ return url && `${url.origin}${url.pathname}`.replace(/\/+$/, "");
1852
+ };
1853
+ /** Where `vercel()`'s calls go: `AI_GATEWAY_BASE_URL`'s gateway, else Vercel's own API. */
1854
+ const vercelApi = (env = process.env) => {
1855
+ const value = env[VERCEL_BASE_URL];
1856
+ return value ? apiAt(parsedBase(value) ?? value) : VERCEL_API;
1857
+ };
1858
+ /** `AI_GATEWAY_BASE_URL` as the URL reeval calls, or undefined when it's unset. */
1859
+ const vercelBaseUrl = (env = process.env) => env["AI_GATEWAY_BASE_URL"] ? vercelApi(env).origin : void 0;
1860
+ /**
1861
+ * Why `AI_GATEWAY_BASE_URL` can't be a gateway's URL, or undefined when it's unset or can: the
1862
+ * egress gateway swaps the key in over HTTPS only, a query, a fragment or a user would be lost on
1863
+ * the paths the agents add to it, and a value the URL parser rewrites (spaces, line breaks,
1864
+ * `https:host`) isn't the URL every agent would read from it.
1865
+ */
1866
+ function vercelBaseUrlProblem(env = process.env) {
1867
+ const value = env[VERCEL_BASE_URL];
1868
+ if (!value) return void 0;
1869
+ const url = URL.parse(value);
1870
+ const fix = `Set ${VERCEL_BASE_URL} to an https:// URL such as https://gateway.example.com, or unset it to call Vercel AI Gateway.`;
1871
+ if (!url) return `${VERCEL_BASE_URL} (${JSON.stringify(value)}) isn't a URL. ${fix}`;
1872
+ if (url.protocol !== "https:") return `${VERCEL_BASE_URL} (${JSON.stringify(value)}) isn't https://, and reeval sends the key only over HTTPS. ${fix}`;
1873
+ if (url.search || url.hash || url.username || url.password) return `${VERCEL_BASE_URL} (${JSON.stringify(value)}) has a query, a fragment or a user, which the paths the agents add to it would lose. ${fix}`;
1874
+ const base = parsedBase(value);
1875
+ if (value.replace(/\/+$/, "") !== base) return `${VERCEL_BASE_URL} (${JSON.stringify(value)}) reads as ${base}, and reeval sends the key only to a URL written as it reads. ${fix}`;
1876
+ }
1877
+ /** The host variable the key comes from: `AI_GATEWAY_API_KEY`, else `VERCEL_OIDC_TOKEN`. */
1878
+ const vercelCredential = (env = process.env) => !env["AI_GATEWAY_API_KEY"] && env["VERCEL_OIDC_TOKEN"] ? VERCEL_OIDC : VERCEL_KEY;
1879
+ /** When a JWT's `exp` says it expires, or undefined when it isn't one or doesn't say. */
1880
+ function jwtExpiry(token) {
1881
+ const [, payload] = token.split(".");
1882
+ if (!payload) return void 0;
1883
+ try {
1884
+ const binary = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
1885
+ const json = new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
1886
+ const { exp } = JSON.parse(json);
1887
+ return typeof exp === "number" ? /* @__PURE__ */ new Date(exp * 1e3) : void 0;
1888
+ } catch {
1889
+ return;
1890
+ }
1891
+ }
1892
+ /**
1893
+ * Why the run can't use Vercel's key, or undefined when it can: `VERCEL_OIDC_TOKEN` lasts about
1894
+ * 12 hours, and a run that starts on an expired one fails every attempt.
1895
+ */
1896
+ function vercelCredentialProblem(env = process.env, now = /* @__PURE__ */ new Date()) {
1897
+ if (vercelCredential(env) !== "VERCEL_OIDC_TOKEN") return void 0;
1898
+ const expiry = jwtExpiry(env["VERCEL_OIDC_TOKEN"] ?? "");
1899
+ if (!expiry || expiry > now) return void 0;
1900
+ return `${VERCEL_OIDC} expired at ${expiry.toISOString()}, so vercel() can't authenticate. Run vercel env pull for a new one, or set ${VERCEL_KEY}.`;
1901
+ }
1902
+ /** A harness on Vercel's key, with the model id Vercel serves for its own, if not as written. */
1903
+ const keyed$1 = (modelId) => (env) => ({
1904
+ credential: vercelCredential(env),
1905
+ ...modelId ? { modelId } : {}
1906
+ });
1907
+ /** A gateway id as written, else the id under `provider`. */
1908
+ const under$1 = (provider) => (model) => model.includes("/") ? model : `${provider}/${model}`;
1909
+ /** Why a harness can't follow `AI_GATEWAY_BASE_URL`, as `why` says: its calls stay on Vercel's host. */
1910
+ const fixedUrl = (why) => (env) => env["AI_GATEWAY_BASE_URL"] ? `${why}, so reeval can't send its calls to ${VERCEL_BASE_URL} (${vercelApi(env).origin})` : void 0;
1911
+ /** Vercel AI Gateway: the harnesses reeval runs there, and why it doesn't run the rest. */
1912
+ const VERCEL_ROUTE = {
1913
+ name: "Vercel AI Gateway",
1914
+ api: vercelApi,
1915
+ routes: {
1916
+ "claude-code": keyed$1(),
1917
+ codex: keyed$1(under$1("openai")),
1918
+ goose: keyed$1((model) => model),
1919
+ opencode: keyed$1((model) => `vercel/${model}`),
1920
+ fx: keyed$1(under$1("openai")),
1921
+ "grok-build": keyed$1(under$1("xai")),
1922
+ pi: keyed$1((model) => model)
1923
+ },
1924
+ refusals: {
1925
+ cursor: "Cursor's agent only calls Cursor's own API",
1926
+ antigravity: "Antigravity's CLI only calls Google's API, with a Gemini key"
1927
+ },
1928
+ refusedAt: {
1929
+ goose: fixedUrl(`Goose's vercel_ai_gateway provider has ${VERCEL_HOST} built in`),
1930
+ opencode: fixedUrl(`reeval runs OpenCode's vercel provider only on the hosts its provider table probed, ${VERCEL_HOST}`)
1931
+ },
1932
+ unprovenEffort: {
1933
+ goose: everyModel,
1934
+ opencode: notGemini,
1935
+ pi: notGemini
1936
+ }
1937
+ };
1938
+ // ../agents/src/routes/vertex.ts
1939
+ /** The host variable `vertex()` takes its project from when it names none. */
1940
+ const VERTEX_PROJECT_ENV = "GOOGLE_CLOUD_PROJECT";
1941
+ /** The region a publisher's models are called in: its own, else the entry's location. */
1942
+ const vertexRegion = (settings, publisher) => settings.regions[publisher] ?? settings.location;
1943
+ /** Vertex AI's API host for a region: `global` has no prefix. */
1944
+ const vertexHost = (region) => region === "global" ? "aiplatform.googleapis.com" : `${region}-aiplatform.googleapis.com`;
1945
+ /**
1946
+ * Vertex's id for a Claude model: an `anthropic/` prefix dropped, and the Anthropic API's dated
1947
+ * id (`claude-haiku-4-5-20251001`) written as Vertex's (`claude-haiku-4-5@20251001`), so one
1948
+ * model string works on both `vertex()` and `direct()`.
1949
+ */
1950
+ const vertexClaudeId = (model) => model.replace(/^anthropic\//, "").replace(/-(\d{8})$/, "@$1");
1951
+ /** Vertex's id for an xAI model on its Chat Completions API: `xai/<model>`, unless it names a publisher. */
1952
+ const vertexXaiId = (model) => model.includes("/") ? model : `xai/${model}`;
1953
+ /** OpenCode's id for a Gemini model on Vertex: `google-vertex/<model>`. */
1954
+ const openCodeVertexId = (model) => `google-vertex/${model.replace(/^(?:google|google-vertex)\//, "")}`;
1955
+ /** fx's id for a Gemini model on Vertex AI's Chat Completions endpoint: `google/<model>`. */
1956
+ const fxVertexId = (model) => `google/${model.replace(/^google\//, "")}`;
1957
+ const GOOGLE_CLOUD = "Google Cloud credentials";
1958
+ const geminiId = (model) => model.replace(/^google\//, "");
1959
+ /** The harnesses reeval runs on Vertex: each one's credential and the model id it names there. */
1960
+ const VERTEX_ROUTES = {
1961
+ "claude-code": {
1962
+ credential: GOOGLE_CLOUD,
1963
+ modelId: vertexClaudeId
1964
+ },
1965
+ antigravity: {
1966
+ credential: GOOGLE_CLOUD,
1967
+ modelId: (model) => model
1968
+ },
1969
+ goose: {
1970
+ credential: GOOGLE_CLOUD,
1971
+ modelId: geminiId
1972
+ },
1973
+ pi: {
1974
+ credential: GOOGLE_CLOUD,
1975
+ modelId: geminiId
1976
+ },
1977
+ opencode: {
1978
+ credential: GOOGLE_CLOUD,
1979
+ modelId: openCodeVertexId
1980
+ },
1981
+ "grok-build": {
1982
+ credential: GOOGLE_CLOUD,
1983
+ modelId: vertexXaiId
1984
+ },
1985
+ fx: {
1986
+ credential: GOOGLE_CLOUD,
1987
+ modelId: fxVertexId
1988
+ }
1989
+ };
1990
+ /**
1991
+ * The publisher whose models each harness on Vertex calls, as `reeval doctor` probes them. Grok
1992
+ * Build's xAI models have no free token count to probe with, so it isn't here.
1993
+ */
1994
+ const VERTEX_HARNESS_PUBLISHERS = {
1995
+ "claude-code": "anthropic",
1996
+ antigravity: "google",
1997
+ goose: "google",
1998
+ pi: "google",
1999
+ opencode: "google",
2000
+ fx: "google"
2001
+ };
2002
+ /**
2003
+ * The model a harness on Vertex calls, as `publisher/id`, or undefined for one `reeval doctor`
2004
+ * doesn't probe there. Antigravity's `-low`/`-medium`/`-high` ids name an effort the CLI sends beside the
2005
+ * model, so the id it calls has none.
2006
+ */
2007
+ function vertexHarnessModel(kind, model) {
2008
+ const publisher = VERTEX_HARNESS_PUBLISHERS[kind];
2009
+ if (!publisher) return void 0;
2010
+ const id = model.replace(/^(?:google|google-vertex|anthropic)\//, "");
2011
+ return `${publisher}/${kind === "antigravity" ? id.replace(/-(?:low|medium|high)$/, "") : id}`;
2012
+ }
2013
+ /** The model providers (`google` in `google/gemini-3.8-flash`) a harness runs on Vertex AI, and why no other. */
2014
+ const VERTEX_AGENT_PROVIDERS = {
2015
+ opencode: {
2016
+ providers: ["google", "google-vertex"],
2017
+ only: "OpenCode reaches Vertex AI only on its google-vertex provider, which serves Google's models"
2018
+ },
2019
+ pi: {
2020
+ providers: ["google"],
2021
+ only: "pi reaches Vertex AI only on its google-vertex provider, whose catalog has Google's models only"
2022
+ },
2023
+ goose: {
2024
+ providers: ["google"],
2025
+ only: "Goose's gcp_vertex_ai provider calls a claude-* model on Anthropic's API on Vertex AI, which reeval doesn't route for Goose yet, so it runs Google's models only there"
2026
+ }
2027
+ };
2028
+ /** Why Vertex AI can't serve an agent, beyond the ones reeval doesn't route there yet. */
2029
+ const VERTEX_REFUSALS = {
2030
+ cursor: "Cursor's agent only calls Cursor's own API",
2031
+ codex: "Codex only calls OpenAI's Responses API, which Vertex AI doesn't serve"
2032
+ };
2033
+ // ../agents/src/harnesses.ts
2034
+ /** `each`'s entry for the routing gateway `route` names; undefined on direct and Vertex AI. */
2035
+ const onGateway = (route, each) => route.kind === "vercel" || route.kind === "openrouter" ? each[route.kind] : void 0;
2036
+ const settingsOf = (route) => ({
2037
+ project: route.project,
2038
+ location: route.location,
2039
+ regions: route.regions ?? {}
2040
+ });
2041
+ /** The project, Gemini's region and the service account, for a CLI on Application Default Credentials. */
2042
+ function adcOf(route, name) {
2043
+ if (route.kind !== "vertex") return void 0;
2044
+ if (!route.credentialsFile) throw new AgentError(`${name} on Vertex AI reads a service account: set the route's credentialsFile to one in the runner`);
2045
+ return {
2046
+ project: route.project,
2047
+ location: vertexRegion(settingsOf(route), "google"),
2048
+ credentialsFile: route.credentialsFile
2049
+ };
2050
+ }
2051
+ /** Claude Code's variables that point it at the route's project and Anthropic's region. */
2052
+ const claudeCodeVertexEnv = (route) => ({
2053
+ CLAUDE_CODE_USE_VERTEX: "1",
2054
+ CLAUDE_CODE_SKIP_VERTEX_AUTH: "1",
2055
+ ANTHROPIC_VERTEX_PROJECT_ID: route.project,
2056
+ CLOUD_ML_REGION: vertexRegion(settingsOf(route), "anthropic")
2057
+ });
2058
+ /** Where fx's configured provider calls Vertex's Chat Completions API: Gemini's region. */
2059
+ const fxVertex = (route) => ({
2060
+ project: route.project,
2061
+ location: vertexRegion(settingsOf(route), "google")
2062
+ });
2063
+ /** Where Grok Build calls Vertex's Chat Completions API: xAI's region. */
2064
+ const grokVertexChat = (route) => ({
2065
+ project: route.project,
2066
+ region: vertexRegion(settingsOf(route), "xai")
2067
+ });
2068
+ const servers = (mcpServers) => mcpServers ? { mcpServers } : {};
2069
+ const effortOf = (effort) => effort ? { effort } : {};
2070
+ const pluginDirs = (plugins) => plugins.length ? { plugins: plugins.map(({ name, dir }) => ({
2071
+ name,
2072
+ dir
2073
+ })) } : {};
2074
+ /** The harness's AI SDK adapter, configured for its route; it never reads the host's own auth. */
2075
+ async function catalogAdapter(c) {
2076
+ const { auth, model, effort, mcpServers, harness, route, plugins, env } = c;
2077
+ switch (harness.kind) {
2078
+ case "cursor": return (await import("./src-DR_j9K3o.js")).createCursorSdk({
2079
+ auth,
2080
+ ...mcpServers ? { mcpServers } : {},
2081
+ ...harness.params ? { modelParams: harness.params } : {},
2082
+ ...effortOf(effort),
2083
+ ...c.fetch ? { fetch: c.fetch } : {},
2084
+ requireCredentialBrokering: true
2085
+ });
2086
+ case "claude-code": {
2087
+ const vertex = route.kind === "vertex" ? claudeCodeVertexEnv(route) : {};
2088
+ return (await import("./dist-DCG7vZGQ.js")).createClaudeCode({
2089
+ auth,
2090
+ ...mcpServers ? { mcpServers } : {},
2091
+ ...harness.effort ? { effort: harness.effort } : {},
2092
+ env: {
2093
+ IS_SANDBOX: "1",
2094
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
2095
+ ...vertex
2096
+ }
2097
+ });
2098
+ }
2099
+ case "antigravity": {
2100
+ const vertex = adcOf(route, "Antigravity");
2101
+ return (await import("./src-CU4tXeik.js")).createAntigravity({
2102
+ auth,
2103
+ ...vertex ? { vertex } : {},
2104
+ ...mcpServers ? { mcpServers } : {},
2105
+ ...pluginDirs(plugins),
2106
+ ...effortOf(effort),
2107
+ requireCredentialBrokering: true
2108
+ });
2109
+ }
2110
+ case "opencode": {
2111
+ const opencode = await import("./src-og0zwqOf.js");
2112
+ const vertex = adcOf(route, "OpenCode");
2113
+ let vars;
2114
+ if (!vertex) {
2115
+ const resolved = opencode.resolveOpenCodeProvider(model, env);
2116
+ if ("error" in resolved) throw new AgentError(`opencode(): ${resolved.error}`);
2117
+ vars = resolved.vars;
2118
+ }
2119
+ return opencode.createOpenCode({
2120
+ auth,
2121
+ model,
2122
+ ...vertex ? { vertex } : { vars },
2123
+ ...effortOf(effort),
2124
+ ...servers(mcpServers),
2125
+ requireCredentialBrokering: true
2126
+ });
2127
+ }
2128
+ case "goose": {
2129
+ const goose = await import("./src-DV-o1jAX.js");
2130
+ const direct = {
2131
+ google: goose.GEMINI_PROVIDER,
2132
+ anthropic: goose.ANTHROPIC_PROVIDER,
2133
+ openai: goose.OPENAI_PROVIDER,
2134
+ xai: goose.XAI_PROVIDER
2135
+ };
2136
+ const vertex = adcOf(route, "Goose");
2137
+ const provider = onGateway(route, {
2138
+ vercel: goose.AI_GATEWAY_PROVIDER,
2139
+ openrouter: goose.OPENROUTER_PROVIDER
2140
+ }) ?? direct[providerOf(harness.model)];
2141
+ return goose.createGoose({
2142
+ ...vertex ? { vertex } : provider ? { provider } : {},
2143
+ auth,
2144
+ model,
2145
+ ...effortOf(effort),
2146
+ ...servers(mcpServers),
2147
+ requireCredentialBrokering: true
2148
+ });
2149
+ }
2150
+ case "pi": {
2151
+ const pi = await import("./src-1TaLS8AT.js");
2152
+ const api = vercelApi(env);
2153
+ const gateway = onGateway(route, {
2154
+ vercel: {
2155
+ ...pi.PI_AI_GATEWAY,
2156
+ openai: api.openai,
2157
+ anthropic: api.anthropic
2158
+ },
2159
+ openrouter: pi.PI_OPENROUTER
2160
+ });
2161
+ const modelInfo = gateway && model && !pi.piGatewayDescribes(gateway, model) ? await c.describeModel?.(model) : void 0;
2162
+ let source;
2163
+ if (gateway) source = {
2164
+ gateway,
2165
+ ...modelInfo ? { modelInfo } : {}
2166
+ };
2167
+ else if (route.kind === "vertex") source = { vertex: adcOf(route, "pi") };
2168
+ else {
2169
+ const provider = (await import("./pi-providers-C7r3J259.js")).piProvider(providerOf(harness.model));
2170
+ if ("refused" in provider) throw new AgentError(`pi(): ${provider.refused}`);
2171
+ source = { provider };
2172
+ }
2173
+ return pi.createPi({
2174
+ auth,
2175
+ ...source,
2176
+ ...effortOf(effort),
2177
+ ...servers(mcpServers),
2178
+ requireCredentialBrokering: true
2179
+ });
2180
+ }
2181
+ case "codex": {
2182
+ const codex = await import("./src-BWb__auU.js");
2183
+ const provider = onGateway(route, {
2184
+ vercel: {
2185
+ ...codex.AI_GATEWAY_PROVIDER,
2186
+ baseUrl: vercelApi(env).openai
2187
+ },
2188
+ openrouter: codex.OPENROUTER_PROVIDER
2189
+ });
2190
+ return codex.createCodex({
2191
+ auth,
2192
+ ...provider ? { provider } : {},
2193
+ ...effortOf(effort),
2194
+ ...servers(mcpServers),
2195
+ ...pluginDirs(plugins),
2196
+ requireCredentialBrokering: true
2197
+ });
2198
+ }
2199
+ case "fx": return (await import("./src-V6cCl3Ak.js")).createFx({
2200
+ auth,
2201
+ model,
2202
+ ...onGateway(route, {
2203
+ vercel: { gatewayUrl: vercelApi(env).origin },
2204
+ openrouter: { provider: "openrouter" }
2205
+ }),
2206
+ ...route.kind === "vertex" ? { vertex: fxVertex(route) } : {},
2207
+ ...effortOf(effort),
2208
+ ...servers(mcpServers),
2209
+ requireCredentialBrokering: true
2210
+ });
2211
+ case "grok-build": {
2212
+ const grok = await import("./src-RygE9XhU.js");
2213
+ let access;
2214
+ if (route.kind === "vertex") {
2215
+ if (!route.accessToken) throw new AgentError("Grok Build on Vertex AI sends a bearer of its own: set the route's accessToken");
2216
+ const { project, region } = grokVertexChat(route);
2217
+ access = {
2218
+ auth: { [grok.VERTEX_TOKEN_ENV]: route.accessToken },
2219
+ provider: grok.vertexProvider(project, region)
2220
+ };
2221
+ } else access = {
2222
+ auth,
2223
+ ...onGateway(route, {
2224
+ vercel: { provider: {
2225
+ ...grok.AI_GATEWAY_PROVIDER,
2226
+ baseUrl: vercelApi(env).openai
2227
+ } },
2228
+ openrouter: { provider: grok.OPENROUTER_PROVIDER }
2229
+ })
2230
+ };
2231
+ return grok.createGrokBuild({
2232
+ ...access,
2233
+ model,
2234
+ ...plugins.length ? {
2235
+ pluginDirs: plugins.map((p) => p.dir),
2236
+ pluginMcpServers: plugins.flatMap((p) => p.servers.map((s) => s.slice(p.name.length + 1)))
2237
+ } : {},
2238
+ ...effortOf(effort),
2239
+ ...servers(mcpServers),
2240
+ requireCredentialBrokering: true
2241
+ });
2242
+ }
2243
+ }
2244
+ }
2245
+ const HEAD = 98304;
2246
+ const TAIL = 16384;
2247
+ /** Longest first, so a secret that starts another can't leave the longer one's rest behind. */
2248
+ const longestFirst = (secrets) => [...new Set(secrets.filter((s) => s.length > 0))].sort((a, b) => b.length - a.length);
2249
+ /** `text` with each secret value replaced, as it is and as it reads inside a JSON string. */
2250
+ function masked(text, secrets) {
2251
+ let out = text;
2252
+ for (const secret of longestFirst(secrets)) for (const form of /* @__PURE__ */ new Set([secret, JSON.stringify(secret).slice(1, -1)])) out = out.replaceAll(form, "[masked]");
2253
+ return out;
2254
+ }
2255
+ function capped(text) {
2256
+ if (text.length <= 131072) return text;
2257
+ const omitted = text.length - HEAD - TAIL;
2258
+ const sha = createHash("sha256").update(text).digest("hex");
2259
+ return `${text.slice(0, HEAD)}\n[truncated ${omitted} of ${text.length} characters, sha256 ${sha}]\n${text.slice(-16384)}`;
2260
+ }
2261
+ /** Where each secret is in `text`, longest first, as non-overlapping `[start, end)` ranges by start. */
2262
+ function secretRanges(text, secrets) {
2263
+ const ranges = [];
2264
+ for (const secret of secrets) for (let at = text.indexOf(secret); at !== -1; at = text.indexOf(secret, at + 1)) {
2265
+ const end = at + secret.length;
2266
+ if (!ranges.some(([s, e]) => at < e && s < end)) ranges.push([at, end]);
2267
+ }
2268
+ return ranges.sort((a, b) => a[0] - b[0]);
2269
+ }
2270
+ /**
2271
+ * `text`, the stream's characters from `start`, without those in a secret's range: `[masked]`
2272
+ * stands where a range starts, and where `text` starts inside one when `open`.
2273
+ */
2274
+ function maskSpan(text, start, ranges, open) {
2275
+ let next = "";
2276
+ let r = 0;
2277
+ for (let i = 0; i < text.length; i++) {
2278
+ const at = start + i;
2279
+ let range = ranges[r];
2280
+ while (range && range[1] <= at) range = ranges[++r];
2281
+ if (!range || at < range[0]) next += text[i];
2282
+ else if (range[0] === at || open && i === 0) next += "[masked]";
2283
+ }
2284
+ return next;
2285
+ }
2286
+ /** `text` laid over `d`'s stream with `d`'s own text at `at`, masked, if it reads as the stream there. */
2287
+ function aligned(text, d, at) {
2288
+ const start = d.offset - at;
2289
+ if (start < 0 || d.stream.slice(start, start + text.length) !== text) return void 0;
2290
+ return maskSpan(text, start, d.ranges, true);
2291
+ }
2292
+ /** Of `deltas`, sorted by `at`, the one nearest to the part at `at`. */
2293
+ function nearest(deltas, at) {
2294
+ let lo = 0;
2295
+ let hi = deltas.length - 1;
2296
+ while (lo < hi) {
2297
+ const mid = lo + hi >> 1;
2298
+ if (deltas[mid].at < at) lo = mid + 1;
2299
+ else hi = mid;
2300
+ }
2301
+ const after = deltas[lo];
2302
+ const before = deltas[lo - 1];
2303
+ return before && at - before.at < after.at - at ? before : after;
2304
+ }
2305
+ /**
2306
+ * `value` with each string that repeats stream text masked, where the string, laid over the
2307
+ * stream so a delta's text is where the stream has it, reads as the stream. A string that is a
2308
+ * delta's text exactly is laid over the nearest such delta in the turn, before or after the
2309
+ * `raw` part: an adapter may hold deltas back past the native event they came from. A string
2310
+ * that holds a delta, such as the text so far, is matched against the deltas since the previous
2311
+ * `raw` part. Object keys, numbers and `type` discriminators are left alone.
2312
+ */
2313
+ function maskLeaves(value, leaves, key) {
2314
+ if (typeof value === "string") {
2315
+ if (key === "type") return value;
2316
+ const same = leaves.byText.get(value);
2317
+ if (same) return aligned(value, nearest(same, leaves.at), 0) ?? value;
2318
+ for (const d of leaves.since) for (let at = value.indexOf(d.text); at !== -1; at = value.indexOf(d.text, at + 1)) {
2319
+ const masked = aligned(value, d, at);
2320
+ if (masked !== void 0) return masked;
2321
+ }
2322
+ return value;
2323
+ }
2324
+ if (Array.isArray(value)) return value.map((v) => maskLeaves(v, leaves));
2325
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, maskLeaves(v, leaves, k)]));
2326
+ return value;
2327
+ }
2328
+ /**
2329
+ * The parts with each secret masked in the text their deltas make together: a model's text splits
2330
+ * a key over several deltas, none of which holds the whole of it. The first delta a match starts
2331
+ * in gets `[masked]`, and every delta loses the match's characters it held. Each `raw` part's
2332
+ * strings are masked where they repeat that text (`maskLeaves`).
2333
+ */
2334
+ function maskedDeltas(parts, secrets) {
2335
+ const out = parts.map((p) => ({
2336
+ ...p,
2337
+ part: { ...p.part }
2338
+ }));
2339
+ const streams = /* @__PURE__ */ new Map();
2340
+ out.forEach(({ part }, at) => {
2341
+ const type = String(part.type);
2342
+ if (!type.endsWith("-delta")) return;
2343
+ const field = typeof part.text === "string" ? "text" : typeof part.delta === "string" ? "delta" : "";
2344
+ if (!field) return;
2345
+ const key = `${type}\0${String(part.id)}`;
2346
+ const deltas = streams.get(key);
2347
+ if (deltas) deltas.push({
2348
+ part,
2349
+ field,
2350
+ at
2351
+ });
2352
+ else streams.set(key, [{
2353
+ part,
2354
+ field,
2355
+ at
2356
+ }]);
2357
+ });
2358
+ const ordered = longestFirst(secrets);
2359
+ const texts = /* @__PURE__ */ new Map();
2360
+ const byText = /* @__PURE__ */ new Map();
2361
+ for (const deltas of streams.values()) {
2362
+ const stream = deltas.map((d) => d.part[d.field]).join("");
2363
+ const ranges = secretRanges(stream, ordered);
2364
+ if (!ranges.length) continue;
2365
+ let offset = 0;
2366
+ for (const d of deltas) {
2367
+ const text = d.part[d.field];
2368
+ if (text) texts.set(d.part, {
2369
+ text,
2370
+ offset,
2371
+ stream,
2372
+ ranges,
2373
+ at: d.at
2374
+ });
2375
+ d.part[d.field] = maskSpan(text, offset, ranges, false);
2376
+ offset += text.length;
2377
+ }
2378
+ }
2379
+ if (!texts.size) return out;
2380
+ for (const d of [...texts.values()].sort((a, b) => a.at - b.at)) {
2381
+ const same = byText.get(d.text);
2382
+ if (same) same.push(d);
2383
+ else byText.set(d.text, [d]);
2384
+ }
2385
+ let since = [];
2386
+ out.forEach(({ part }, at) => {
2387
+ const text = texts.get(part);
2388
+ if (text) since.push(text);
2389
+ if (part.type !== "raw") return;
2390
+ part.rawValue = maskLeaves(part.rawValue, {
2391
+ byText,
2392
+ since,
2393
+ at
2394
+ });
2395
+ since = [];
2396
+ });
2397
+ return out;
2398
+ }
2399
+ /** The transcript event as `transcript.jsonl` has it: a tool's long output cut to its ends. */
2400
+ function line(turn, event, secrets) {
2401
+ if (event.type !== "tool") return {
2402
+ turn,
2403
+ ...event
2404
+ };
2405
+ const raw = typeof event.output === "string" ? event.output : JSON.stringify(event.output, null, 2);
2406
+ if (raw === void 0 || raw.length <= 131072) return {
2407
+ turn,
2408
+ ...event
2409
+ };
2410
+ const text = masked(raw, secrets);
2411
+ const bytes = Math.max(event.outputTruncated?.bytes ?? 0, Buffer.byteLength(text));
2412
+ return {
2413
+ turn,
2414
+ ...event,
2415
+ output: capped(text),
2416
+ outputTruncated: { bytes }
2417
+ };
2418
+ }
2419
+ /**
2420
+ * Writes a session's `out` directory: `session.json`, then a line of `turns.jsonl` and the turn's
2421
+ * lines of `transcript.jsonl` as each turn ends, so a directory a crash left behind still reads.
2422
+ * Every file has the secrets masked. Writes run in order, one at a time.
2423
+ */
2424
+ var OutWriter = class OutWriter {
2425
+ dir;
2426
+ #options;
2427
+ #secrets;
2428
+ #parts = /* @__PURE__ */ new Map();
2429
+ #queue = Promise.resolve();
2430
+ constructor(options, secrets) {
2431
+ this.dir = resolve(options.dir);
2432
+ this.#options = options;
2433
+ this.#secrets = longestFirst(secrets);
2434
+ }
2435
+ static async open(options, secrets) {
2436
+ const out = new OutWriter(options, secrets);
2437
+ await mkdir(options.raw ? join(out.dir, "raw") : out.dir, { recursive: true });
2438
+ for (const file of ["turns.jsonl", "transcript.jsonl"]) await writeFile(join(out.dir, file), "");
2439
+ if (options.raw) await writeFile(join(out.dir, "raw", "parts.jsonl"), "");
2440
+ if (options.debug) await writeFile(join(out.dir, "debug.log"), "");
2441
+ return out;
2442
+ }
2443
+ #then(write) {
2444
+ const next = this.#queue.then(write);
2445
+ this.#queue = next.catch(() => {});
2446
+ return next;
2447
+ }
2448
+ #append(file, lines) {
2449
+ const text = lines.map((l) => `${JSON.stringify(l)}\n`).join("");
2450
+ return this.#then(() => appendFile(join(this.dir, file), masked(text, this.#secrets)));
2451
+ }
2452
+ session(doc) {
2453
+ const file = join(this.dir, "session.json");
2454
+ const text = masked(`${JSON.stringify(doc, null, 2)}\n`, this.#secrets);
2455
+ return this.#then(async () => {
2456
+ await writeFile(`${file}.tmp`, text);
2457
+ await rename(`${file}.tmp`, file);
2458
+ });
2459
+ }
2460
+ async turn(turn, prompt, result) {
2461
+ const { transcript, raw: _raw, steps: _steps, ...rest } = result;
2462
+ const record = {
2463
+ turn,
2464
+ prompt,
2465
+ ...rest
2466
+ };
2467
+ await this.#append("transcript.jsonl", transcript.map((e) => line(turn, e, this.#secrets)));
2468
+ await this.#append("turns.jsonl", [record]);
2469
+ }
2470
+ /** Holds a turn's stream part for {@link parts}, which masks a secret split across deltas. */
2471
+ part(turn, part) {
2472
+ if (!this.#options.raw) return;
2473
+ const parts = this.#parts.get(turn);
2474
+ if (parts) parts.push(part);
2475
+ else this.#parts.set(turn, [part]);
2476
+ }
2477
+ /** Writes the turn's held parts to `raw/parts.jsonl`, once. */
2478
+ parts(turn) {
2479
+ const parts = this.#parts.get(turn);
2480
+ if (!parts) return Promise.resolve();
2481
+ this.#parts.delete(turn);
2482
+ const lines = maskedDeltas(parts, this.#secrets).map((p) => ({
2483
+ turn,
2484
+ ...p
2485
+ }));
2486
+ return this.#append("raw/parts.jsonl", lines);
2487
+ }
2488
+ log(text) {
2489
+ if (!this.#options.debug) return Promise.resolve();
2490
+ const entry = `${(/* @__PURE__ */ new Date()).toISOString()} ${text}\n`;
2491
+ return this.#then(() => appendFile(join(this.dir, "debug.log"), masked(entry, this.#secrets)));
2492
+ }
2493
+ /** Waits for every write so far. */
2494
+ flush() {
2495
+ return this.#queue;
2496
+ }
2497
+ };
2498
+ // ../agents/src/routes/openrouter.ts
2499
+ const OPENROUTER_API = {
2500
+ origin: "https://openrouter.ai",
2501
+ openai: "https://openrouter.ai/api/v1",
2502
+ anthropic: "https://openrouter.ai/api"
2503
+ };
2504
+ const OPENROUTER_HOST = apiHost(OPENROUTER_API);
2505
+ const OPENROUTER_KEY = "OPENROUTER_API_KEY";
2506
+ /** An id as OpenRouter names it: as written when it names a provider, else under `provider`. */
2507
+ const under = (provider) => (model) => model.includes("/") ? model : `${provider}/${model}`;
2508
+ /**
2509
+ * An Anthropic id as OpenRouter names it, with the version dotted (`anthropic/claude-haiku-4.5`
2510
+ * for `claude-haiku-4-5`), unless the id names a provider.
2511
+ */
2512
+ const anthropicOnOpenRouter = (model) => model.includes("/") ? model : `anthropic/${model.replace(/-(\d{1,2})-(\d{1,2})$/, "-$1.$2")}`;
2513
+ /** A harness on OpenRouter's key, under its own name, with the model id OpenRouter serves. */
2514
+ const keyed = (modelId) => () => ({
2515
+ credential: OPENROUTER_KEY,
2516
+ modelId
2517
+ });
2518
+ /** OpenRouter: the harnesses reeval runs there, and why it doesn't run the rest. */
2519
+ const OPENROUTER_ROUTE = {
2520
+ name: "OpenRouter",
2521
+ api: () => OPENROUTER_API,
2522
+ routes: {
2523
+ "claude-code": keyed(anthropicOnOpenRouter),
2524
+ codex: keyed(under("openai")),
2525
+ goose: keyed((model) => model),
2526
+ opencode: keyed((model) => `openrouter/${model}`),
2527
+ fx: keyed(under("openai")),
2528
+ "grok-build": keyed(under("x-ai")),
2529
+ pi: keyed((model) => model)
2530
+ },
2531
+ refusals: {
2532
+ cursor: "Cursor's agent only calls Cursor's own API",
2533
+ antigravity: "Antigravity's CLI only calls Google's API, with a Gemini key, and OpenRouter has no Gemini API"
2534
+ },
2535
+ unprovenEffort: {
2536
+ "claude-code": everyModel,
2537
+ goose: notGemini,
2538
+ opencode: notGemini,
2539
+ pi: notGemini
2540
+ }
2541
+ };
2542
+ // ../agents/src/routes/index.ts
2543
+ /** Every route that serves harnesses on one key, by name. */
2544
+ const ROUTES = {
2545
+ vercel: VERCEL_ROUTE,
2546
+ openrouter: OPENROUTER_ROUTE
2547
+ };
2548
+ /** OpenCode's id for `model` on `route`, as that route writes it. */
2549
+ function openCodeModelOn(model, route) {
2550
+ if (route === "vertex") return openCodeVertexId(model);
2551
+ return Object.hasOwn(ROUTES, route) ? `${route}/${model}` : model;
2552
+ }
2553
+ // ../agents/src/setup.ts
2554
+ const INSTALLS = {
2555
+ cursor: {
2556
+ cli: "@cursor/sdk",
2557
+ probe: `node -p "'@cursor/sdk ' + require(process.env.HOME + '/.ai-sdk-harness/.harness-bootstrap/cursor-sdk/node_modules/@cursor/sdk/package.json').version"`,
2558
+ adapter: async () => (await import("./src-DR_j9K3o.js")).createCursorSdk()
2559
+ },
2560
+ "claude-code": {
2561
+ cli: "claude",
2562
+ adapter: async () => (await import("./dist-DCG7vZGQ.js")).createClaudeCode()
2563
+ },
2564
+ antigravity: {
2565
+ cli: "agy",
2566
+ adapter: async () => (await import("./src-CU4tXeik.js")).createAntigravity()
2567
+ },
2568
+ opencode: {
2569
+ cli: "opencode",
2570
+ adapter: async () => (await import("./src-og0zwqOf.js")).createOpenCode({
2571
+ auth: { GOOGLE_GENERATIVE_AI_API_KEY: "unused" },
2572
+ model: "google/unused"
2573
+ })
2574
+ },
2575
+ goose: {
2576
+ cli: "goose",
2577
+ adapter: async () => {
2578
+ const goose = await import("./src-DV-o1jAX.js");
2579
+ return goose.createGoose({
2580
+ auth: { GOOGLE_API_KEY: "unused" },
2581
+ provider: goose.GEMINI_PROVIDER,
2582
+ model: "unused"
2583
+ });
2584
+ }
2585
+ },
2586
+ pi: {
2587
+ cli: "pi",
2588
+ adapter: async () => {
2589
+ const pi = await import("./src-1TaLS8AT.js");
2590
+ const provider = pi.piProvider("google");
2591
+ if ("refused" in provider) throw new Error(provider.refused);
2592
+ return pi.createPi({
2593
+ auth: { GEMINI_API_KEY: "unused" },
2594
+ provider
2595
+ });
2596
+ }
2597
+ },
2598
+ codex: {
2599
+ cli: "codex",
2600
+ adapter: async () => (await import("./src-BWb__auU.js")).createCodex({ auth: { OPENAI_API_KEY: "unused" } })
2601
+ },
2602
+ fx: {
2603
+ cli: "fx",
2604
+ adapter: async () => (await import("./src-V6cCl3Ak.js")).createFx({
2605
+ auth: { AI_GATEWAY_API_KEY: "unused" },
2606
+ model: "unused/unused"
2607
+ })
2608
+ },
2609
+ "grok-build": {
2610
+ cli: "grok",
2611
+ adapter: async () => (await import("./src-RygE9XhU.js")).createGrokBuild({
2612
+ auth: { XAI_API_KEY: "unused" },
2613
+ model: "unused"
2614
+ })
2615
+ }
2616
+ };
2617
+ /** How `kind`'s CLI is installed, which an image or a machine bakes ahead of a session. */
2618
+ function setupOf(kind) {
2619
+ const entry = HARNESSES[kind];
2620
+ const install = INSTALLS[kind];
2621
+ return {
2622
+ name: entry.name,
2623
+ ...install,
2624
+ recipe: async () => (await install.adapter()).getBootstrap?.({}),
2625
+ credentials: [...entry.credential ? [entry.credential] : [], ...entry.fallbackCredentials ?? []],
2626
+ platforms: entry.platforms
2627
+ };
2628
+ }
2629
+ /** The AI SDK's bootstrap state directory, under `home`. */
2630
+ const stateDirectory = (home) => posix.join(home, ".ai-sdk-harness");
2631
+ /** The identity the AI SDK gives `recipe`, which names the marker it writes once it ran. */
2632
+ async function recipeIdentity(recipe) {
2633
+ const strings = [
2634
+ stateDirectory("$HOME"),
2635
+ recipe.harnessId,
2636
+ recipe.bootstrapDir,
2637
+ ...[...recipe.files].sort((a, b) => a.path.localeCompare(b.path)).flatMap((f) => [f.path, f.content]),
2638
+ JSON.stringify(recipe.commands),
2639
+ "1"
2640
+ ];
2641
+ const bytes = new TextEncoder().encode(strings.map((s) => `${s}\0`).join(""));
2642
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
2643
+ return Array.from(digest.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
2644
+ }
2645
+ /** Where the AI SDK marks `recipe` installed, for a user whose home is `home`. */
2646
+ async function recipeMarker(recipe, home) {
2647
+ const dir = posix.resolve(stateDirectory(home), recipe.bootstrapDir);
2648
+ return posix.join(dir, `.bootstrap-${await recipeIdentity(recipe)}.ok`);
2649
+ }
2650
+ /**
2651
+ * Installs `adapter`'s CLI on `runner` as `mode` says, before its session starts; the session
2652
+ * would otherwise install it as it starts, untimed. False when there was nothing to install.
2653
+ */
2654
+ async function installHarness(o) {
2655
+ const recipe = await o.adapter.getBootstrap?.({});
2656
+ if (!recipe) return false;
2657
+ const marker = await recipeMarker(recipe, o.home);
2658
+ if (o.mode === "skip") {
2659
+ if (await o.runner.readFile(marker) === null) throw new AgentError(`The runner doesn't have this build of the ${o.name} CLI installed, and install is 'skip': install it there, or use install: 'auto'`);
2660
+ return false;
2661
+ }
2662
+ if (o.mode === "always") {
2663
+ if ((await o.runner.spawn([
2664
+ "rm",
2665
+ "-f",
2666
+ "--",
2667
+ marker
2668
+ ]).exited).code !== 0) throw new AgentError(`Couldn't remove ${marker} to install again`);
2669
+ }
2670
+ await (await createHarnessSandboxTemplate({
2671
+ harnesses: [o.adapter],
2672
+ sandboxConfig: { workDir: o.workDir }
2673
+ }))?.prepare({
2674
+ session: await runnerSession(o.runner, { id: "install" }),
2675
+ ...o.signal ? { abortSignal: o.signal } : {}
2676
+ });
2677
+ return true;
2678
+ }
2679
+ // ../agents/src/version.ts
2680
+ /** This package's version, which `test/out.test.ts` holds to package.json. */
2681
+ const AGENTS_VERSION = "0.1.0";
2682
+ // ../agents/src/session.ts
2683
+ /** The route's configuration for the harness; undefined on its provider's own API. */
2684
+ function routeConfig(harness, route, entry, env) {
2685
+ if (route.kind === "direct") return void 0;
2686
+ const config = route.kind === "vertex" ? VERTEX_ROUTES[harness.kind] : ROUTES[route.kind].routes[harness.kind]?.(env);
2687
+ if (!config) {
2688
+ const name = route.kind === "vertex" ? "Vertex AI" : ROUTES[route.kind].name;
2689
+ throw new AgentError(`The ${entry.name} harness doesn't run on ${name}`);
2690
+ }
2691
+ return config;
2692
+ }
2693
+ /** Events pushed in one place and read with `for await` in another, ending on `end()`. */
2694
+ function channel() {
2695
+ const buffered = [];
2696
+ let waiting;
2697
+ let ended = false;
2698
+ return {
2699
+ push(value) {
2700
+ if (waiting) {
2701
+ waiting({
2702
+ value,
2703
+ done: false
2704
+ });
2705
+ waiting = void 0;
2706
+ } else buffered.push(value);
2707
+ },
2708
+ end() {
2709
+ ended = true;
2710
+ waiting?.({
2711
+ value: void 0,
2712
+ done: true
2713
+ });
2714
+ waiting = void 0;
2715
+ },
2716
+ iterable: { [Symbol.asyncIterator]: () => ({ next: () => {
2717
+ const value = buffered.shift();
2718
+ if (value !== void 0) return Promise.resolve({
2719
+ value,
2720
+ done: false
2721
+ });
2722
+ if (ended) return Promise.resolve({
2723
+ value: void 0,
2724
+ done: true
2725
+ });
2726
+ return new Promise((resolve) => {
2727
+ waiting = resolve;
2728
+ });
2729
+ } }) }
2730
+ };
2731
+ }
2732
+ const skillMd = (skill) => `---\nname: ${skill.name}\ndescription: ${JSON.stringify(skill.description)}\n---\n${skill.content}`;
2733
+ /** One path segment of at most 128 characters, not ending in `.`: a skill's directory name. */
2734
+ const SKILL_NAME = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,126}[A-Za-z0-9_-])?$/;
2735
+ /** Refuses a skill whose name or files would land outside its own directory. */
2736
+ function checkSkills(skills) {
2737
+ for (const skill of skills) {
2738
+ if (!SKILL_NAME.test(skill.name)) throw new AgentError(`The skill name ${JSON.stringify(skill.name)} isn't one path segment of at most 128 letters, digits, '.', '_' or '-', ending in no '.'`);
2739
+ for (const f of skill.files ?? []) {
2740
+ const segments = f.path.split("/");
2741
+ if (/[\\\0]/.test(f.path) || f.path.startsWith("/") || segments.some((s) => s === "" || s === ".." || s.endsWith(".") || s.length > 255)) throw new AgentError(`The skill ${skill.name}'s file ${JSON.stringify(f.path)} isn't a relative path inside it, with no '\\', NUL, empty segment or segment ending in '.'`);
2742
+ }
2743
+ }
2744
+ }
2745
+ /** How long `close()` waits on each step of a turn or session that doesn't stop, by default. */
2746
+ const CLOSE_TIMEOUT_MS = 1e4;
2747
+ /** The longest `setTimeout` takes; past it, Node fires at once. */
2748
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
2749
+ const closeTimeoutOf = (ms) => ms === void 0 || Number.isNaN(ms) ? CLOSE_TIMEOUT_MS : Math.min(Math.max(ms, 0), MAX_TIMEOUT_MS);
2750
+ /** A write that fails on the path it was given (too long, a NUL) as the skill's fault. */
2751
+ async function placing(skill, write) {
2752
+ try {
2753
+ await write();
2754
+ } catch (error) {
2755
+ const code = error.code;
2756
+ if (code === "ENAMETOOLONG" || code === "ERR_INVALID_ARG_VALUE" || code === "ERR_INVALID_ARG_TYPE") throw new AgentError(`Couldn't place the skill ${skill}: ${errorText(error)}`);
2757
+ throw error;
2758
+ }
2759
+ }
2760
+ /** `promise`'s value, or undefined once `ms` have passed without it settling. */
2761
+ async function within(promise, ms) {
2762
+ let late = () => {};
2763
+ const lateness = new Promise((resolve) => {
2764
+ late = resolve;
2765
+ });
2766
+ const timer = setTimeout(() => late(void 0), ms);
2767
+ try {
2768
+ return await Promise.race([Promise.resolve(promise).then((value) => ({ value })), lateness]);
2769
+ } finally {
2770
+ clearTimeout(timer);
2771
+ }
2772
+ }
2773
+ /**
2774
+ * A coding agent on a runner. `start()` asks the runner where it is, places the rules and skills,
2775
+ * builds the adapter and starts the harness's session; each `send` is a turn.
2776
+ */
2777
+ function agent(options) {
2778
+ const { harness } = options;
2779
+ const entry = HARNESSES[harness.kind];
2780
+ const layout = LAYOUTS[harness.kind];
2781
+ const workDir = options.workDir ?? ".";
2782
+ const outOptions = typeof options.out === "string" ? { dir: options.out } : options.out;
2783
+ const route = options.route ?? { kind: "direct" };
2784
+ const env = options.env ?? process.env;
2785
+ const plugins = options.plugins ?? [];
2786
+ const closeTimeout = closeTimeoutOf(options.closeTimeoutMs);
2787
+ const emit = (event) => {
2788
+ try {
2789
+ options.onEvent?.(event);
2790
+ } catch {}
2791
+ };
2792
+ async function start() {
2793
+ const owned = typeof options.runner === "function";
2794
+ const signal = options.signal ?? new AbortController().signal;
2795
+ let out;
2796
+ const warn = (message) => emit({
2797
+ type: "warning",
2798
+ message
2799
+ });
2800
+ const writing = (write) => write?.catch((error) => warn(`writing ${out?.dir}: ${errorText(error)}`));
2801
+ const log = {
2802
+ log: (phase, text) => {
2803
+ options.log?.log(phase, text);
2804
+ writing(out?.log(`[${phase}] ${text}`));
2805
+ },
2806
+ trace: (phase, kind, data, show) => options.log?.trace(phase, kind, data, show)
2807
+ };
2808
+ const doc = {
2809
+ schemaVersion: 1,
2810
+ agentsVersion: AGENTS_VERSION,
2811
+ harness: {
2812
+ kind: harness.kind,
2813
+ model: harness.model,
2814
+ ...harness.effort ? { effort: harness.effort } : {}
2815
+ },
2816
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2817
+ phases: {},
2818
+ status: "running"
2819
+ };
2820
+ const phase = (name, since) => {
2821
+ const ms = Date.now() - since;
2822
+ if (name !== "ready" && name !== "closed") doc.phases[name] = ms;
2823
+ emit({
2824
+ type: "phase",
2825
+ phase: name,
2826
+ ms
2827
+ });
2828
+ };
2829
+ let credentials = {};
2830
+ let runner;
2831
+ let session;
2832
+ let onPart;
2833
+ const begun = Date.now();
2834
+ try {
2835
+ const skills = options.skills ?? [];
2836
+ checkSkills(skills);
2837
+ credentials = typeof options.credentials === "function" ? await options.credentials() : options.credentials ?? {};
2838
+ if (outOptions) out = await OutWriter.open(outOptions, Object.values(credentials));
2839
+ runner = typeof options.runner === "function" ? await options.runner() : options.runner;
2840
+ const box = runner;
2841
+ const names = Object.keys(credentials);
2842
+ const variable = names.length ? names.join(" or ") : entry.credential ?? "its credential";
2843
+ const authHint = options.authHint ?? ((message, refused) => refused || REFUSED_KEY.test(message) ? `The API rejected ${variable} for the ${entry.name} harness` : void 0);
2844
+ const starting = async (step) => {
2845
+ try {
2846
+ return await step();
2847
+ } catch (error) {
2848
+ if (error instanceof AgentError || signal.aborted) throw error;
2849
+ const message = errorText(error);
2850
+ const hint = authHint(message, options.traffic?.statuses().includes(401) ?? false);
2851
+ throw new AgentError(`${hint ? `${hint}. ` : ""}${entry.name} harness failed to start: ${message}`, { transient: !hint && error.transient === true });
2852
+ }
2853
+ };
2854
+ let since = Date.now();
2855
+ const info = await starting(() => box.info());
2856
+ doc.runner = info;
2857
+ phase("runner", since);
2858
+ await writing(out?.session(doc));
2859
+ since = Date.now();
2860
+ if (options.rules !== void 0) await box.writeFile(posix.join(workDir, layout.rulesFile), options.rules);
2861
+ for (const skill of skills.filter((s) => s.placement === "workspace")) {
2862
+ const dir = posix.join(workDir, layout.workspaceSkillDir, skill.name);
2863
+ await placing(skill.name, () => box.writeFile(`${dir}/SKILL.md`, skillMd(skill)));
2864
+ for (const f of skill.files ?? []) await placing(skill.name, () => box.writeFile(`${dir}/${f.path}`, f.content));
2865
+ }
2866
+ phase("place", since);
2867
+ since = Date.now();
2868
+ const model = (routeConfig(harness, route, entry, env)?.modelId ?? entry.modelId)?.(harness.model) ?? harness.model;
2869
+ const mcp = agentMcp(layout, options.mcp ?? {}, plugins);
2870
+ const input = {
2871
+ auth: credentials,
2872
+ model,
2873
+ ...harness.effort ? { effort: harness.effort } : {},
2874
+ ...Object.keys(mcp).length ? { mcpServers: entry.mcpServers(mcp) } : {}
2875
+ };
2876
+ const adapter = options.adapter ? await options.adapter(input) : await catalogAdapter({
2877
+ ...input,
2878
+ harness,
2879
+ route,
2880
+ plugins,
2881
+ env,
2882
+ ...options.describeModel ? { describeModel: options.describeModel } : {},
2883
+ ...options.fetch ? { fetch: options.fetch } : {}
2884
+ });
2885
+ doc.adapter = { name: adapter.harnessId };
2886
+ if (await starting(() => installHarness({
2887
+ runner: box,
2888
+ home: info.home,
2889
+ adapter,
2890
+ name: entry.name,
2891
+ mode: options.install ?? "auto",
2892
+ workDir,
2893
+ signal
2894
+ }))) {
2895
+ phase("install", since);
2896
+ since = Date.now();
2897
+ }
2898
+ session = await startAgent({
2899
+ kind: harness.kind,
2900
+ entry,
2901
+ adapter,
2902
+ model,
2903
+ runner: box,
2904
+ ...options.session ? { session: options.session } : {},
2905
+ workDir,
2906
+ skills: skills.filter((s) => s.placement !== "workspace").map((s) => ({
2907
+ name: s.name,
2908
+ description: s.description,
2909
+ content: s.content,
2910
+ files: s.files ?? []
2911
+ })),
2912
+ signal,
2913
+ log,
2914
+ ...options.traffic ? { traffic: options.traffic } : {},
2915
+ authHint,
2916
+ ...options.workspace ? { workspace: options.workspace } : {},
2917
+ ...options.raw || outOptions?.raw ? { raw: true } : {},
2918
+ onPart: (part) => onPart?.(part)
2919
+ });
2920
+ phase("bootstrap", since);
2921
+ } catch (error) {
2922
+ if (outOptions && !out) out = await OutWriter.open(outOptions, Object.values(credentials)).catch(() => void 0);
2923
+ doc.status = "failed";
2924
+ doc.error = errorText(error);
2925
+ doc.endedAt = (/* @__PURE__ */ new Date()).toISOString();
2926
+ await writing(out?.session(doc));
2927
+ await writing(out?.flush());
2928
+ if (owned) await runner?.close().catch(() => {});
2929
+ throw error;
2930
+ }
2931
+ const box = runner;
2932
+ await writing(out?.session(doc));
2933
+ emit({
2934
+ type: "phase",
2935
+ phase: "ready",
2936
+ ms: Date.now() - begun
2937
+ });
2938
+ const closed = new AbortController();
2939
+ let turns = 0;
2940
+ let running;
2941
+ let closing;
2942
+ return {
2943
+ send(prompt, sendOptions = {}) {
2944
+ if (closing) throw new AgentError("The session is closed");
2945
+ if (running) throw new AgentError("A turn is already running in this session");
2946
+ const turn = turns++;
2947
+ const events = channel();
2948
+ const report = (event) => {
2949
+ events.push(event);
2950
+ emit(event);
2951
+ };
2952
+ const turnSignal = AbortSignal.any([
2953
+ signal,
2954
+ closed.signal,
2955
+ sendOptions.signal
2956
+ ].filter((s) => s !== void 0));
2957
+ onPart = (part) => {
2958
+ out?.part(turn, part);
2959
+ if (options.parts) report({
2960
+ type: "part",
2961
+ turn,
2962
+ part
2963
+ });
2964
+ };
2965
+ let force = () => {};
2966
+ const forced = new Promise((resolve) => {
2967
+ force = resolve;
2968
+ });
2969
+ report({
2970
+ type: "turn-start",
2971
+ turn,
2972
+ prompt
2973
+ });
2974
+ const result = (async () => {
2975
+ try {
2976
+ const result = await Promise.race([session.send(prompt, turnSignal), forced]);
2977
+ for (const event of result.transcript) report({
2978
+ type: "transcript",
2979
+ turn,
2980
+ event
2981
+ });
2982
+ await writing(out?.parts(turn));
2983
+ await writing(out?.turn(turn, prompt, result));
2984
+ report({
2985
+ type: "turn-end",
2986
+ turn,
2987
+ result
2988
+ });
2989
+ return result;
2990
+ } finally {
2991
+ await writing(out?.parts(turn));
2992
+ onPart = void 0;
2993
+ running = void 0;
2994
+ events.end();
2995
+ }
2996
+ })();
2997
+ running = {
2998
+ done: result.catch(() => {}),
2999
+ force,
3000
+ startedAt: Date.now()
3001
+ };
3002
+ return {
3003
+ events: events.iterable,
3004
+ result
3005
+ };
3006
+ },
3007
+ async stopped(note) {
3008
+ const turn = running;
3009
+ if (!turn || !session.stopped) throw new AgentError("No turn is running");
3010
+ const result = await session.stopped(note);
3011
+ turn.force(result);
3012
+ await turn.done;
3013
+ return result;
3014
+ },
3015
+ salvage: () => session.salvage?.() ?? Promise.resolve(),
3016
+ close() {
3017
+ closing ??= (async () => {
3018
+ const since = Date.now();
3019
+ closed.abort();
3020
+ const turn = running;
3021
+ if (turn && !await within(turn.done, closeTimeout)) {
3022
+ const atMs = Date.now() - turn.startedAt;
3023
+ const message = `The turn didn't stop within ${closeTimeout}ms of the session closing`;
3024
+ warn(message);
3025
+ turn.force({
3026
+ text: "",
3027
+ status: "aborted",
3028
+ startedAt: new Date(turn.startedAt).toISOString(),
3029
+ durationMs: atMs,
3030
+ transcript: [{
3031
+ type: "error",
3032
+ message,
3033
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
3034
+ atMs
3035
+ }],
3036
+ usage: null,
3037
+ model: null,
3038
+ unreported: []
3039
+ });
3040
+ await turn.done;
3041
+ }
3042
+ if (!await within(session.close(), closeTimeout)) warn(`The ${entry.name} session didn't close within ${closeTimeout}ms`);
3043
+ if (owned) await box.close().catch(() => {});
3044
+ doc.status = "closed";
3045
+ doc.endedAt = (/* @__PURE__ */ new Date()).toISOString();
3046
+ await writing(out?.session(doc));
3047
+ await writing(out?.flush());
3048
+ phase("closed", since);
3049
+ })();
3050
+ return closing;
3051
+ }
3052
+ };
3053
+ }
3054
+ return {
3055
+ start,
3056
+ async exec(prompt, execOptions) {
3057
+ const session = await start();
3058
+ try {
3059
+ return await session.send(prompt, execOptions).result;
3060
+ } finally {
3061
+ await session.close();
3062
+ }
3063
+ }
3064
+ };
3065
+ }
3066
+ export { errorText as A, PLUGIN_PARTS as B, vercelBaseUrl as C, apiHost as D, anthropicPath as E, AgentError as F, FAKE_LAYOUT as I, LAYOUTS as L, HARNESSES as M, providerOf as N, openaiPath as O, claudeMcpServers as P, agentMcp as R, vercelApi as S, vercelCredentialProblem as T, VERCEL_BASE_URL as _, OPENROUTER_HOST as a, VERCEL_OIDC as b, VERTEX_AGENT_PROVIDERS as c, VERTEX_ROUTES as d, vertexClaudeId as f, VERCEL_API as g, vertexRegion as h, OPENROUTER_API as i, providerStop as j, REFUSED_KEY as k, VERTEX_PROJECT_ENV as l, vertexHost as m, setupOf as n, OPENROUTER_KEY as o, vertexHarnessModel as p, openCodeModelOn as r, OPENROUTER_ROUTE as s, agent as t, VERTEX_REFUSALS as u, VERCEL_HOST as v, vercelBaseUrlProblem as w, VERCEL_ROUTE as x, VERCEL_KEY as y, PLUGIN_DIR as z };
3067
+
3068
+ //# sourceMappingURL=src-CfDk0uu4.js.map