nolo-cli 0.259.0-alpha.1 → 0.261.0-alpha.1

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 (320) hide show
  1. package/README.md +1 -1
  2. package/{_executeModel-MTM4BJK3.js → _executeModel-PODMRXJJ.js} +97 -83
  3. package/accountResolver-NGICIMEE.js +1 -1
  4. package/{action-C6IQAKN4.js → action-NJTYNXXR.js} +12 -10
  5. package/{addContentAction-53364YDW.js → addContentAction-RUPXLROG.js} +14 -13
  6. package/{addDialogAgentAction-U5DD5EN5.js → addDialogAgentAction-57EJ2UBC.js} +20 -24
  7. package/{agentDeleteCommand-53NN3VSK.js → agentDeleteCommand-DRFCOTYP.js} +185 -147
  8. package/{agentEmailCommands-KOGGIT6I.js → agentEmailCommands-FHENHUBF.js} +143 -127
  9. package/{agentGrantCommands-L6O2HVJI.js → agentGrantCommands-BMVKNYIY.js} +9 -6
  10. package/{agentListCommands-62UYUQDI.js → agentListCommands-W66W5K3V.js} +88 -69
  11. package/{agentMachineCommands-W6TNJXEA.js → agentMachineCommands-C3BUBCXU.js} +69 -60
  12. package/{agentProviderCommands-QLTABYR7.js → agentProviderCommands-VIWKP7DM.js} +11 -8
  13. package/{agentPullCommand-2EYJ5ENC.js → agentPullCommand-5SNSXOY7.js} +10 -7
  14. package/agentRecordCommands-DYMHWTID.js +210 -0
  15. package/agentRun-QVFG3CI4.js +250 -0
  16. package/agentRunCommand-YV4V5HSL.js +248 -0
  17. package/{agentRunControl-LXMADX3N.js → agentRunControl-RGBHKPKJ.js} +19 -12
  18. package/{agentRuntimeLocal-YGNJMQW3.js → agentRuntimeLocal-LVEMOYS2.js} +62 -49
  19. package/{agentSlice-3HHYUQLM.js → agentSlice-OJCM7OUX.js} +15 -18
  20. package/appConfigCommands-ZUXQLE7L.js +417 -0
  21. package/{appDeleteCommands-5COJ6CSG.js → appDeleteCommands-L5UKUMXY.js} +68 -58
  22. package/{appDeployCommands-3JPAT3XO.js → appDeployCommands-KX2BRQUW.js} +74 -59
  23. package/{appDeployStatusCommands-RHZKF3G4.js → appDeployStatusCommands-7LHRSWW7.js} +68 -58
  24. package/{appGetCommands-73DXOAQW.js → appGetCommands-F7SDFCUK.js} +74 -58
  25. package/{appListCommands-HD5LOQ3G.js → appListCommands-U4NJKSMZ.js} +74 -58
  26. package/appMigrateCommands-JAPOLYSW.js +230 -0
  27. package/appSourceCommands-TLXPWXUH.js +279 -0
  28. package/authCommand-AU3GZBZ2.js +65 -0
  29. package/{authCommands-T5FODCEG.js → authCommands-JKBWMUQ4.js} +20 -17
  30. package/{builtinSkillRegistry-EDHD2UHU.js → builtinSkillRegistry-6XUWMAV5.js} +8 -6
  31. package/{chromeOpsCommands-3SSTDFRF.js → chromeOpsCommands-F47WYQWF.js} +68 -18
  32. package/{chunk-5YS6QHGT.js → chunk-2FGFY72B.js} +9 -9
  33. package/{chunk-MJBLXJMP.js → chunk-2I4R6ZRV.js} +12 -9
  34. package/{chunk-FXEPZKNJ.js → chunk-2MIZHEND.js} +506 -64
  35. package/{chunk-TLE77UJ5.js → chunk-2OROOEOQ.js} +0 -1
  36. package/{chunk-6RSNVJGO.js → chunk-2ZBPWX7N.js} +4 -4
  37. package/chunk-35JIFLIG.js +30 -0
  38. package/{chunk-7OVOZRZF.js → chunk-3B7OTHDW.js} +23 -379
  39. package/{chunk-DNNPARJK.js → chunk-3QMN3T6L.js} +50 -37
  40. package/{chunk-DMPZMYH4.js → chunk-3R4AYHJR.js} +13 -1
  41. package/{chunk-XNNBXUEM.js → chunk-3TII7WCF.js} +5 -5
  42. package/{chunk-223KZUJ6.js → chunk-4HZCBA4Q.js} +18 -15
  43. package/{chunk-C5A54QS7.js → chunk-4INJGWE3.js} +18 -5
  44. package/chunk-4IVMDQBA.js +261 -0
  45. package/chunk-4Y6CZ2N4.js +82 -0
  46. package/{chunk-KZ4A7EIV.js → chunk-56OAS5RZ.js} +1 -1
  47. package/{chunk-KQHEGELM.js → chunk-63G7JWEA.js} +16 -6
  48. package/{chunk-4EACJPZI.js → chunk-6BBXJGIQ.js} +51 -42
  49. package/chunk-72VWN4VK.js +51 -0
  50. package/chunk-7LR2IFUH.js +100 -0
  51. package/{chunk-S73EPYNC.js → chunk-7LS5ATRP.js} +20 -6
  52. package/{chunk-XPETQ4MR.js → chunk-7X4BFUJV.js} +24 -10
  53. package/{chunk-KHYSFS3W.js → chunk-A454UXB6.js} +148 -73
  54. package/chunk-A4O76A6V.js +432 -0
  55. package/chunk-AMNZPQCY.js +635 -0
  56. package/{chunk-4MXYCQBS.js → chunk-AQNWWJLH.js} +2 -56
  57. package/{chunk-LHCGKAFO.js → chunk-BKP325XS.js} +184 -112
  58. package/{chunk-PENRYZ4D.js → chunk-BPB3T5EU.js} +4 -7
  59. package/{chunk-U6QNVOR5.js → chunk-BUGLH2A7.js} +130 -6
  60. package/{chunk-2JHGUL5K.js → chunk-BVYHE6QD.js} +2 -2
  61. package/{chunk-KXOPLLFP.js → chunk-CA7LGAHV.js} +69 -9
  62. package/{chunk-2FZVXOFX.js → chunk-CEIWXKHP.js} +112 -200
  63. package/{chunk-Y2TCTNUD.js → chunk-CK2LMTYO.js} +4 -4
  64. package/{chunk-AIFQKNPP.js → chunk-CL33RFD7.js} +1 -1
  65. package/{chunk-57V4PADY.js → chunk-CNYPQYXT.js} +781 -449
  66. package/{chunk-P4R5KXU7.js → chunk-CW6LRDSF.js} +5 -5
  67. package/chunk-D3ONA3FP.js +762 -0
  68. package/{chunk-PIVTQRX6.js → chunk-DDKA6V6X.js} +111 -12
  69. package/chunk-DLXL4NSL.js +1179 -0
  70. package/{chunk-EJQE5HB7.js → chunk-DSBRIUX5.js} +4 -2
  71. package/{chunk-XRGBJHZX.js → chunk-E36V7MPY.js} +9 -5
  72. package/{chunk-4YPH5KRA.js → chunk-EDKMRDET.js} +1 -1
  73. package/{chunk-DBJODIZ6.js → chunk-EQOWWSNQ.js} +19 -27
  74. package/chunk-ER6NTALN.js +34 -0
  75. package/{chunk-L4XST72F.js → chunk-ERCSHBUD.js} +16027 -17392
  76. package/chunk-EUHMI5KG.js +101 -0
  77. package/{chunk-YQLAFJRQ.js → chunk-FBNVJ2TO.js} +1 -1
  78. package/{chunk-Q2EERN52.js → chunk-FF5ZRKW7.js} +12 -7
  79. package/{chunk-6XIE5ZGI.js → chunk-FGFJUFPS.js} +5 -6
  80. package/chunk-FI4DPLR7.js +902 -0
  81. package/{chunk-HDKMVYNJ.js → chunk-FNLT7NKG.js} +7 -11
  82. package/{chunk-JCQ3WCQ3.js → chunk-FOC4TORM.js} +69 -3
  83. package/chunk-FP46RAJQ.js +58 -0
  84. package/{chunk-JPXACKSW.js → chunk-G22P2J7O.js} +30 -81
  85. package/{chunk-7WHCIA5V.js → chunk-G5IAIGGD.js} +3 -8
  86. package/{chunk-FZENZCIA.js → chunk-GEC4CHS2.js} +19 -12
  87. package/chunk-GF4LYNNZ.js +25 -0
  88. package/{chunk-IYLUK67R.js → chunk-GH6SS2DZ.js} +25 -8
  89. package/chunk-HAZ6UVH4.js +368 -0
  90. package/{chunk-OKAXQFON.js → chunk-HB4J5HA6.js} +4 -4
  91. package/{chunk-324FWHUA.js → chunk-HHXF57CL.js} +12 -3
  92. package/chunk-HJTI7RZV.js +94 -0
  93. package/{chunk-HQUGB2HM.js → chunk-HMFKYZKP.js} +62 -50
  94. package/{chunk-Q2MPKE4B.js → chunk-HVRG27HI.js} +76 -26
  95. package/{chunk-46FETNLF.js → chunk-IN4B6Z2D.js} +7 -6
  96. package/chunk-IV6VUVLJ.js +88 -0
  97. package/{chunk-LLUBUHNT.js → chunk-IWWJSSST.js} +5 -9
  98. package/{chunk-7BIJFGKS.js → chunk-J22PFCQN.js} +106 -52
  99. package/chunk-J42X32PV.js +472 -0
  100. package/{chunk-LCBAMY2M.js → chunk-JKVOKKMQ.js} +0 -7
  101. package/{chunk-KT7S7ANZ.js → chunk-JPYOHIHX.js} +9 -9
  102. package/{chunk-R7XWZDOH.js → chunk-JUMQJSQF.js} +1423 -282
  103. package/{chunk-KVMLM5VD.js → chunk-KAHYBAEN.js} +211 -472
  104. package/{chunk-KLMBM6P6.js → chunk-KALCFXQO.js} +2454 -1115
  105. package/chunk-KDDXC2IH.js +148 -0
  106. package/chunk-KGKTN2NX.js +25 -0
  107. package/chunk-KGWE224L.js +246 -0
  108. package/{chunk-OYUMJMC5.js → chunk-KSV6T4AH.js} +6 -1
  109. package/{chunk-P27E22MA.js → chunk-L43DGEPZ.js} +1 -1
  110. package/{chunk-5BIDJVNX.js → chunk-L45P4JTE.js} +180 -31
  111. package/chunk-LHCIIUCX.js +222 -0
  112. package/{chunk-CBIGMWMI.js → chunk-LHJB4BXJ.js} +1 -1
  113. package/{chunk-TRRXYFTR.js → chunk-LOFRSJX2.js} +1 -0
  114. package/{chunk-SQL7YNED.js → chunk-LPXBBC32.js} +71 -5
  115. package/{chunk-BIDSIRTS.js → chunk-LTCZOOAM.js} +11 -17
  116. package/chunk-LUTSMSIL.js +425 -0
  117. package/chunk-LXP53WGF.js +168 -0
  118. package/{chunk-2CT2J3O6.js → chunk-M7VNNPVX.js} +2493 -4055
  119. package/chunk-MDAYRIP7.js +1889 -0
  120. package/{chunk-6B2OBX5B.js → chunk-MMXHIHJZ.js} +15 -47
  121. package/{chunk-HPDLPEUG.js → chunk-MPWQI36J.js} +267 -234
  122. package/chunk-MRACVEPZ.js +7 -0
  123. package/{chunk-ZYPXOQS2.js → chunk-MSFKHPA6.js} +1 -1
  124. package/chunk-NHLLXINQ.js +8 -0
  125. package/{chunk-QXTEEEIN.js → chunk-NJCTPWJU.js} +8 -8
  126. package/chunk-NLS7F5DW.js +1697 -0
  127. package/{chunk-FP37ELBT.js → chunk-NTBTVKKB.js} +17 -25
  128. package/{chunk-JLZJL3WC.js → chunk-O77F26YB.js} +370 -39
  129. package/{chunk-LVZVSLKO.js → chunk-O7ZY6SUK.js} +5 -22
  130. package/{chunk-YN23INFZ.js → chunk-OIOMBPCA.js} +23 -2
  131. package/{chunk-CJOOF4L5.js → chunk-OSZNERNW.js} +17 -14
  132. package/{chunk-JZO7KUF3.js → chunk-P4I55ASV.js} +313 -275
  133. package/{chunk-2C5VN7NH.js → chunk-P4XAHM4B.js} +1 -1
  134. package/chunk-PL5RKESU.js +40 -0
  135. package/chunk-Q5FJJ6XI.js +103 -0
  136. package/{chunk-WS36XPJD.js → chunk-Q5IXZF3S.js} +82 -6
  137. package/{createAgentAutomationAction-GRZ6XY7Q.js → chunk-QKM55LP2.js} +3 -160
  138. package/{chunk-WSLL7VV4.js → chunk-QXWXRBOL.js} +9 -9
  139. package/{chunk-MXA54TQM.js → chunk-QZYQ3Y3G.js} +1 -1
  140. package/{chunk-FE7G6DSP.js → chunk-R72QWIFO.js} +14 -4
  141. package/{chunk-5RGU3J7P.js → chunk-REAE2SZK.js} +0 -1
  142. package/chunk-RF576RYE.js +117 -0
  143. package/chunk-RI7SXDJW.js +1317 -0
  144. package/{chunk-FEIVARWR.js → chunk-RIOAPUGV.js} +238 -25
  145. package/{chunk-BZLGPM5B.js → chunk-RNLKWUVY.js} +7 -12
  146. package/{chunk-J7JRCOIW.js → chunk-RWXHGPWJ.js} +1 -1
  147. package/{chunk-J55F3IEZ.js → chunk-SARJZIGR.js} +1 -1
  148. package/chunk-SJFL32RD.js +356 -0
  149. package/{chunk-6SOWMEAY.js → chunk-SR57FDTX.js} +2 -258
  150. package/{chunk-MPGR4ZNR.js → chunk-SRVLHMES.js} +46 -42
  151. package/{chunk-CEKRIR22.js → chunk-SU4NCTW4.js} +1 -1
  152. package/{chunk-RD3QLZQV.js → chunk-SWJRX4M5.js} +324 -2
  153. package/{chunk-R3TUHCSJ.js → chunk-T3Y2NA4H.js} +8 -3
  154. package/{chunk-53W5BXLN.js → chunk-TCOHWKDM.js} +54 -55
  155. package/{chunk-KWNVPY6M.js → chunk-TJXO66M2.js} +8 -5
  156. package/{chunk-QIGQFON2.js → chunk-TXMFSGRY.js} +1 -1
  157. package/{chunk-ADYWV732.js → chunk-U5PSCTMR.js} +264 -177
  158. package/{chunk-UUCYUN6Y.js → chunk-UB7NV7NN.js} +1 -1
  159. package/{chunk-QGFLVQ6E.js → chunk-UBOTXA3Z.js} +4 -14
  160. package/{chunk-6YX2RAQN.js → chunk-UEZL3RBG.js} +89 -164
  161. package/{chunk-NCFKHYDM.js → chunk-UJL23HBL.js} +774 -119
  162. package/chunk-ULPU4C43.js +1710 -0
  163. package/{chunk-UA3QTA2S.js → chunk-VC3MAT33.js} +4442 -2570
  164. package/{chunk-VNHZJEQN.js → chunk-VCESLFF4.js} +3 -3
  165. package/chunk-VOO3YQQP.js +17157 -0
  166. package/{chunk-Y2GWUBNS.js → chunk-VZDSNDUD.js} +279 -149
  167. package/{chunk-6BMTKYAO.js → chunk-W2Z5E2R7.js} +126 -698
  168. package/{chunk-4ZCTKB27.js → chunk-W5GKF5ZW.js} +1 -0
  169. package/chunk-WEEB2JKA.js +443 -0
  170. package/{chunk-NUHQO3RB.js → chunk-WIVVNJUS.js} +1 -1
  171. package/chunk-WMBJDXMY.js +408 -0
  172. package/chunk-WSQLCWLQ.js +201 -0
  173. package/{chunk-OOVOAG4Q.js → chunk-WY6DMHMG.js} +1 -1
  174. package/{chunk-6K32PBRY.js → chunk-XJW6SLBZ.js} +3 -3
  175. package/{chunk-MNFUKRRU.js → chunk-XKNDVHF5.js} +7 -7
  176. package/{chunk-MHKPUGPD.js → chunk-XREMPMNK.js} +20 -4
  177. package/chunk-XT6C2QZW.js +46 -0
  178. package/chunk-XUDXQT7R.js +790 -0
  179. package/{chunk-ZEZC7IIM.js → chunk-YFSM2366.js} +35 -35
  180. package/{chunk-RIWKZT7E.js → chunk-YRPIUIEQ.js} +11 -9
  181. package/{chunk-U35UUM5K.js → chunk-YVOUSIIA.js} +1 -1
  182. package/{chunk-6VEO7Z3Y.js → chunk-Z27AH6A5.js} +6 -6
  183. package/chunk-Z3KTXWWB.js +76 -0
  184. package/{chunk-UWWOWTW2.js → chunk-Z7EP5HDL.js} +1 -1
  185. package/{chunk-YFEK7ACQ.js → chunk-ZB2E724W.js} +4 -4
  186. package/{chunk-YLAHYLDQ.js → chunk-ZC3CMUKU.js} +2 -89
  187. package/{chunk-5P3PPQVP.js → chunk-ZQAADXSF.js} +1 -1
  188. package/{cliAgentConfigHelpers-BXHQ3PXP.js → cliAgentConfigHelpers-BJJEXHSZ.js} +20 -14
  189. package/{cliAuthorityBrokerClient-TFNXJLXL.js → cliAuthorityBrokerClient-3SKOA7OZ.js} +3 -1
  190. package/cliAuthorityBrokerProcess-VIJEKQSX.js +34 -0
  191. package/{cliEnvHelpers-CNMP3RDX.js → cliEnvHelpers-NDMKN4X2.js} +6 -3
  192. package/{cliExecutor-K6FDZTQ2.js → cliExecutor-Z62UBJ5S.js} +12 -6
  193. package/cliLocalAgentRecordReader-KCZS2MZU.js +113 -0
  194. package/cloudAutomationCommands-2WQUGQSW.js +310 -0
  195. package/{commandRegistry-IFYQLPGM.js → commandRegistry-C64JBZJ3.js} +288 -121
  196. package/{contentThunks-QCFCD2X3.js → contentThunks-G3HEIRXC.js} +45 -43
  197. package/{cooldownCommands-WDOI5VD7.js → cooldownCommands-FPAFS7XG.js} +1 -1
  198. package/createAgentAutomationAction-DSBL3X3A.js +172 -0
  199. package/createDialogAction-OHFUHC53.js +86 -0
  200. package/{createPageAction-QCVBMP4C.js → createPageAction-E6JZSZLU.js} +49 -45
  201. package/{db-VR74ADGC.js → db-KTQ3LL2Q.js} +3 -3
  202. package/{dbSlice-RWPSVHBC.js → dbSlice-U3GPLEL3.js} +21 -16
  203. package/deleteDbKey-DRXKWJX5.js +86 -0
  204. package/{dialogCommands-4IEQUALS.js → dialogCommands-4EX2OTIC.js} +80 -66
  205. package/{dialogMessageRecord-OAV77LT7.js → dialogMessageRecord-2HJTEXQX.js} +1 -1
  206. package/dialogNotifyCommand-4SCE2Z2R.js +44 -0
  207. package/dialogPortabilityCommands-ZSFFHRX4.js +3036 -0
  208. package/{dialogSlice-XFYID6KE.js → dialogSlice-PRZCIJCH.js} +43 -42
  209. package/{dialogTraceCommand-Y67NRFCV.js → dialogTraceCommand-RKB76OVX.js} +84 -70
  210. package/{dialogUsageCommand-WJ3U6KZU.js → dialogUsageCommand-BP7HMRYP.js} +7 -4
  211. package/{docCreateCommands-QLRIWRQE.js → docCreateCommands-JGPNGIZ7.js} +68 -59
  212. package/{docDeleteCommands-XPRYA532.js → docDeleteCommands-XRJTNRDH.js} +68 -59
  213. package/{docReadCommands-EXQI7ETH.js → docReadCommands-6GFO4ARS.js} +67 -58
  214. package/{docStore-MWFUKZL2.js → docStore-QRLIWFTU.js} +16 -17
  215. package/{docUpdateCommands-EFBFQV77.js → docUpdateCommands-W2GXMUXW.js} +68 -59
  216. package/{ebookDownloaderAgentCommand-DYSKF5ZY.js → ebookDownloaderAgentCommand-2DHPGEOQ.js} +14 -17
  217. package/{fetchMessages-TQEUZD7H.js → fetchMessages-RGPIYEPZ.js} +2 -2
  218. package/{getPricing-5BLZRPTM.js → getPricing-BK6CUBAE.js} +8 -4
  219. package/{handleSendMessageAction-GG3TR62X.js → handleSendMessageAction-DHGWURJZ.js} +265 -119
  220. package/{hostCredentialCreate-26S6DDJ5.js → hostCredentialCreate-FPUZ7RMI.js} +138 -122
  221. package/index.js +36 -22
  222. package/{keys-RWF7UCB4.js → keys-FXEGMKSG.js} +2 -2
  223. package/localAutomationCommands-ZMU22RQJ.js +198 -0
  224. package/localAutomationRuntime-MU5FGJ3V.js +60 -0
  225. package/{localDialogRead-BJJT3TF5.js → localDialogRead-W2EVXISA.js} +2 -2
  226. package/{localRuntimeAdapter-VREWZWPC.js → localRuntimeAdapter-YBXQBV4G.js} +136 -119
  227. package/localRuntimeAuthority-LDXMEDO5.js +44 -0
  228. package/{localRuntimeDb-ZJFGNHML.js → localRuntimeDb-6TQZDLNU.js} +1 -1
  229. package/{machineCommands-CL5XK5UC.js → machineCommands-57RTUYRV.js} +251 -357
  230. package/{machineInfo-LWHTEBHJ.js → machineInfo-BJIU3WQ5.js} +4 -2
  231. package/machineWsRunDispatch-VBKV3FFE.js +227 -0
  232. package/{mcpLocalAuthorizeCommand-RBXJDE6J.js → mcpLocalAuthorizeCommand-J76SOJVZ.js} +40 -22
  233. package/mcpLocalManageCommands-USETIMHB.js +212 -0
  234. package/{memberThunks-43B7UYC5.js → memberThunks-7UERUEMI.js} +102 -22
  235. package/{memoryCommands-BC6REPQB.js → memoryCommands-N7NHEE55.js} +25 -34
  236. package/{models-ZX2BYIMB.js → models-TOXYINNM.js} +3 -2
  237. package/{offlineMarxistsAgentCommand-XVXUE6G5.js → offlineMarxistsAgentCommand-WZBJBCPZ.js} +16 -22
  238. package/package.json +3 -3
  239. package/parityCommands-LYDLWSLK.js +613 -0
  240. package/{projectArchive-OC63TWTD.js → projectArchive-KCNQDVWJ.js} +49 -45
  241. package/{providerPresetApply-NTJUINI6.js → providerPresetApply-IRJ56XIZ.js} +12 -16
  242. package/{providerRegistry-W45SLUV6.js → providerRegistry-26PAUYH2.js} +3 -13
  243. package/{read-KG6INYUT.js → read-SPSQ6NLR.js} +11 -10
  244. package/{readDocTool-N3GA52JR.js → readDocTool-ENUL2GNL.js} +5 -1
  245. package/{readlineWorkspace-2NO6D6IZ.js → readlineWorkspace-MKS7TAEF.js} +927 -573
  246. package/{rememberExplicit-CPAPONSI.js → rememberExplicit-7KX4HXQC.js} +4 -4
  247. package/remove-TNNDO635.js +32 -0
  248. package/{removeDialogAgentAction-EEVSOQOJ.js → removeDialogAgentAction-POPUZ3WU.js} +22 -26
  249. package/{runAgentClientLoop-U7V32UTD.js → runAgentClientLoop-KVILXQNI.js} +117 -82
  250. package/{runtimeDoctorCommands-V3M3JTUV.js → runtimeDoctorCommands-4J2DP4LZ.js} +23 -16
  251. package/{secretCommands-KVVZS7A6.js → secretCommands-CSTQYB6T.js} +2 -2
  252. package/{setDialogExtraReferencesAction-DNO5POHA.js → setDialogExtraReferencesAction-35THMVBP.js} +16 -17
  253. package/{setPrimaryDialogAgentAction-QABBEO4C.js → setPrimaryDialogAgentAction-WLXBNIG7.js} +23 -27
  254. package/{settingThunks-DVKG4X4S.js → settingThunks-6Y5U5M5N.js} +170 -497
  255. package/{skillDiscovery-5GEGWJ6N.js → skillDiscovery-IUEZZG2B.js} +3 -3
  256. package/{spaceCommands-7QKXKBDQ.js → spaceCommands-LXNJBO2U.js} +293 -58
  257. package/spacePruneCommand-2ITUFYBM.js +233 -0
  258. package/{store-Z53ICFL3.js → store-WSAVTR32.js} +3 -1
  259. package/{streamAgentChatTurn-UAGFOXNJ.js → streamAgentChatTurn-EY6MFKCA.js} +225 -137
  260. package/{switchDialogAgentAction-KYWJSGOO.js → switchDialogAgentAction-TG6BQRDA.js} +19 -23
  261. package/{tableCommands-EFA754RE.js → tableCommands-35G34R4B.js} +28 -49
  262. package/{toolApiClient-N5PYW2R3.js → toolApiClient-MPQIFYXP.js} +15 -4
  263. package/{tools-2Q2LBDUC.js → tools-CSLTRRUR.js} +73 -63
  264. package/{tuiRestart-4QDWLHYZ.js → tuiRestart-ALR4Q3JM.js} +20 -13
  265. package/tuiSummaryLlmCaller-3Y3JEXJK.js +52 -0
  266. package/{updateCommands-GJGRS6JK.js → updateCommands-GHQVP6Z5.js} +13 -8
  267. package/{updateDialogTitleAction-GGNTTI5L.js → updateDialogTitleAction-LFAWF5EW.js} +57 -58
  268. package/{usageCommand-WI6SQOPB.js → usageCommand-5VKW6T4C.js} +6 -8
  269. package/{usageRebuildCommand-WQRLLZAT.js → usageRebuildCommand-VUQETFMW.js} +11 -15
  270. package/{windowsSelfUpdate-C7LGVWYX.js → windowsSelfUpdate-SXSVXK4X.js} +2 -2
  271. package/workContext-ZAW6VXT7.js +18 -0
  272. package/workContextQueryProjection-CACY5VFE.js +23 -0
  273. package/{workloadLifecycle-DYX5ZMAT.js → workloadLifecycle-P2SJVV3S.js} +1 -1
  274. package/agentFavoriteCommands-7LOP3HUD.js +0 -186
  275. package/agentRecordCommands-TPE7NSZ6.js +0 -194
  276. package/agentRunCommand-DMVGBPLI.js +0 -232
  277. package/authCommand-V6EOMZX6.js +0 -79
  278. package/chunk-2MBTWINN.js +0 -89
  279. package/chunk-523DITKR.js +0 -32
  280. package/chunk-BUDVRYES.js +0 -2213
  281. package/chunk-BZMDWGQQ.js +0 -47
  282. package/chunk-GAHJLSDO.js +0 -107
  283. package/chunk-GYX6XTAI.js +0 -84
  284. package/chunk-HNUWUO75.js +0 -93
  285. package/chunk-HSBHS6KT.js +0 -33401
  286. package/chunk-KG27JIG4.js +0 -136
  287. package/chunk-OB4FBZXJ.js +0 -364
  288. package/chunk-OKH74FML.js +0 -3746
  289. package/chunk-OLZBQWZU.js +0 -6
  290. package/chunk-OOV5JN25.js +0 -1317
  291. package/chunk-OQFOE4SJ.js +0 -405
  292. package/chunk-PXYBUFDB.js +0 -53
  293. package/chunk-R3FZHW4Q.js +0 -103
  294. package/chunk-R3MV2GII.js +0 -106
  295. package/chunk-SCAC3NM5.js +0 -11751
  296. package/chunk-SR4FE5VD.js +0 -9
  297. package/chunk-SYTHYBMI.js +0 -3558
  298. package/chunk-UKZX3NHN.js +0 -48
  299. package/chunk-UVLYNWIE.js +0 -74
  300. package/chunk-VQX5JJNI.js +0 -861
  301. package/chunk-X4O7FJF5.js +0 -160
  302. package/chunk-YJPK35HB.js +0 -175
  303. package/chunk-YNIYE47Z.js +0 -105
  304. package/chunk-Z4PCXPUE.js +0 -127
  305. package/chunk-ZR5IVL4N.js +0 -862
  306. package/chunk-ZTHAJU3O.js +0 -2537
  307. package/cliAuthorityBrokerProcess-5ZFBTHLB.js +0 -22
  308. package/cliLocalAgentRecordReader-34UKRBLY.js +0 -104
  309. package/createDialogAction-ZAJERW62.js +0 -82
  310. package/deleteFile-ECU6FU5C.js +0 -55
  311. package/dialogNotifyCommand-IASQGEMW.js +0 -36
  312. package/localRuntimeAuthority-UF2DAQ3F.js +0 -28
  313. package/machineWsRunDispatch-TBVOYOAH.js +0 -209
  314. package/markdownToSlate-PXYAIBVL.js +0 -8
  315. package/tuiSummaryLlmCaller-HROLGN4F.js +0 -45
  316. package/webapi-QVV65DQF.js +0 -2487
  317. package/workContext-Y3ADAPZU.js +0 -14
  318. package/{chunk-USGHJSGO.js → chunk-GX2MFKF3.js} +3 -3
  319. package/{chunk-PHREU2KZ.js → chunk-WX266G2C.js} +0 -0
  320. package/{chunk-DXWGFL2Z.js → chunk-YY7IGJMN.js} +3 -3
@@ -1,81 +1,22 @@
1
- import {
2
- buildCliProcessEnv,
3
- resolveLaunchableCodexCommand
4
- } from "./chunk-ZEZC7IIM.js";
5
1
  import {
6
2
  buildCliPrompt
7
3
  } from "./chunk-ATNTHIZI.js";
4
+ import {
5
+ buildCliProcessEnv,
6
+ resolveLaunchableCodexCommand
7
+ } from "./chunk-YFSM2366.js";
8
8
 
9
9
  // packages/ai/agent/cliExecutor.ts
10
- import { execFile, spawn as spawn2 } from "child_process";
10
+ import { spawn as spawn3 } from "child_process";
11
11
  import { randomUUID as randomUUID2 } from "node:crypto";
12
- import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
13
- import { isAbsolute, join, relative, resolve } from "node:path";
12
+ import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, realpathSync as realpathSync2, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
13
+ import { isAbsolute as isAbsolute2, join, relative as relative2, resolve as resolve2 } from "node:path";
14
14
  import { tmpdir } from "node:os";
15
- import { StringDecoder } from "node:string_decoder";
15
+ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
16
16
 
17
17
  // packages/ai/agent/executors/opencodeExecutor.ts
18
18
  import { spawn } from "node:child_process";
19
19
  import { randomUUID } from "node:crypto";
20
- function terminateProcessGroup(proc, signal = "SIGTERM") {
21
- const pid = proc.pid;
22
- if (!pid || pid <= 0) return;
23
- if (process.platform !== "win32") {
24
- try {
25
- process.kill(-pid, signal);
26
- } catch {
27
- }
28
- } else {
29
- try {
30
- const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
31
- stdio: "ignore",
32
- windowsHide: true
33
- });
34
- killer.on("error", () => {
35
- });
36
- killer.unref?.();
37
- } catch {
38
- }
39
- }
40
- try {
41
- proc.kill(signal);
42
- } catch {
43
- }
44
- }
45
- async function killProcessGroupEscalating(proc, graceMs = 1200) {
46
- const pid = proc.pid;
47
- if (!pid || pid <= 0) return;
48
- terminateProcessGroup(proc, "SIGTERM");
49
- const start = Date.now();
50
- while (Date.now() - start < graceMs) {
51
- let alive = false;
52
- if (process.platform !== "win32") {
53
- try {
54
- process.kill(-pid, 0);
55
- alive = true;
56
- } catch {
57
- try {
58
- process.kill(pid, 0);
59
- alive = true;
60
- } catch {
61
- alive = false;
62
- }
63
- }
64
- } else {
65
- try {
66
- process.kill(pid, 0);
67
- alive = true;
68
- } catch {
69
- alive = false;
70
- }
71
- }
72
- if (!alive) {
73
- return;
74
- }
75
- await new Promise((resolve2) => setTimeout(resolve2, 50));
76
- }
77
- terminateProcessGroup(proc, "SIGKILL");
78
- }
79
20
  async function executeOpenCodeStreaming(prompt, options) {
80
21
  if (options.imageInputs && options.imageInputs.length > 0) {
81
22
  throw new Error("OpenCode executor does not support imageInputs (unsupported)");
@@ -149,43 +90,32 @@ async function executeOpenCodeStreaming(prompt, options) {
149
90
  internalAbortController.abort(procErr);
150
91
  }
151
92
  });
152
- const cleanup = async () => {
153
- if (hasCleanedUp) return;
93
+ const cleanup = () => {
154
94
  hasCleanedUp = true;
155
- try {
156
- if (!internalAbortController.signal.aborted) {
157
- internalAbortController.abort();
158
- }
159
- } catch {
160
- }
161
- if (activeSessionId && serverBaseUrl) {
162
- try {
163
- const cleanupAbortController = new AbortController();
164
- const abortTimeout = setTimeout(() => cleanupAbortController.abort(), 800);
95
+ if (!internalAbortController.signal.aborted) internalAbortController.abort();
96
+ return (async () => {
97
+ if (activeSessionId && serverBaseUrl) {
98
+ const timeout = AbortSignal.timeout(800);
165
99
  try {
166
- await fetch(`${serverBaseUrl}/session/${activeSessionId}/abort`, {
167
- method: "POST",
168
- headers: { "Content-Type": "application/json" },
169
- body: "{}",
170
- signal: cleanupAbortController.signal
171
- });
172
- } finally {
173
- clearTimeout(abortTimeout);
100
+ await Promise.race([
101
+ fetch(`${serverBaseUrl}/session/${activeSessionId}/abort`, { method: "POST", signal: timeout }),
102
+ new Promise((resolve3) => timeout.addEventListener("abort", () => resolve3(), { once: true }))
103
+ ]);
104
+ } catch {
174
105
  }
175
- } catch {
176
106
  }
177
- }
178
- await killProcessGroupEscalating(serveProc);
107
+ await terminateCliProcessGroupEscalating(serveProc);
108
+ })();
179
109
  };
180
110
  try {
181
- const portPromise = new Promise((resolve2, reject) => {
111
+ const portPromise = new Promise((resolve3, reject) => {
182
112
  let buffer = "";
183
113
  const checkUrl = (chunk) => {
184
114
  buffer += chunk.toString();
185
115
  const match = buffer.match(/http:\/\/127\.0\.0\.1:(\d+)/);
186
116
  if (match) {
187
117
  cleanupStartup();
188
- resolve2(match[0]);
118
+ resolve3(match[0]);
189
119
  return;
190
120
  }
191
121
  const nonLoopback = buffer.match(/http:\/\/(?!127\.0\.0\.1)[a-zA-Z0-9.-]+:\d+/);
@@ -282,13 +212,13 @@ async function executeOpenCodeStreaming(prompt, options) {
282
212
  const emittedToolCalls = /* @__PURE__ */ new Set();
283
213
  const emittedToolResults = /* @__PURE__ */ new Set();
284
214
  const emittedToolErrors = /* @__PURE__ */ new Set();
285
- const streamPromise = new Promise((resolve2, reject) => {
215
+ const streamPromise = new Promise((resolve3, reject) => {
286
216
  let buffer = "";
287
217
  const reader = sseResponse.body.getReader();
288
218
  const decoder = new TextDecoder("utf-8");
289
219
  const markCompleted = () => {
290
220
  isCompleted = true;
291
- resolve2();
221
+ resolve3();
292
222
  };
293
223
  const handleEventJson = (parsed) => {
294
224
  const type = parsed?.type;
@@ -493,11 +423,9 @@ async function executeOpenCodeStreaming(prompt, options) {
493
423
  }
494
424
  }
495
425
  const elapsed = Date.now() - startTime;
496
- return {
497
- text: fullText,
498
- raw: fullText,
499
- elapsed
500
- };
426
+ return attachExecutionStoppedPromise({ text: fullText, raw: fullText, elapsed }, cleanup());
427
+ } catch (error) {
428
+ throw attachExecutionStoppedPromise(error instanceof Error ? error : new Error(String(error)), cleanup());
501
429
  } finally {
502
430
  if (deadlineTimer) {
503
431
  clearTimeout(deadlineTimer);
@@ -507,10 +435,1081 @@ async function executeOpenCodeStreaming(prompt, options) {
507
435
  options.signal.removeEventListener("abort", onExternalAbort);
508
436
  }
509
437
  serveProc.off("exit", onProcExit);
510
- await cleanup();
511
438
  }
512
439
  }
513
440
 
441
+ // packages/ai/agent/executors/agyAcpClient.ts
442
+ import { spawn as spawn2 } from "node:child_process";
443
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
444
+ import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
445
+ import { StringDecoder } from "node:string_decoder";
446
+ var ACP_PROTOCOL_VERSION = 1;
447
+ var DEFAULT_IDLE_TIMEOUT_MS = 10 * 6e4;
448
+ var DEFAULT_HANDSHAKE_TIMEOUT_MS = 6e4;
449
+ var CANCEL_GRACE_MS = 800;
450
+ var MAX_TERMINAL_OUTPUT_CHARS = 2e5;
451
+ var STDERR_TAIL_CHARS = 4e3;
452
+ function asRecord(value) {
453
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
454
+ }
455
+ function asString(value) {
456
+ return typeof value === "string" ? value : void 0;
457
+ }
458
+ function asNumber(value) {
459
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
460
+ }
461
+ function createAbortError(message = "agy ACP execution aborted") {
462
+ return new DOMException(message, "AbortError");
463
+ }
464
+ function isWithin(root, target) {
465
+ const rel = relative(resolve(root), resolve(target));
466
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
467
+ }
468
+ var AgyAcpRequestTimeoutError = class extends Error {
469
+ constructor(timedOutMethod) {
470
+ super(`agy ACP request timed out: ${timedOutMethod}`);
471
+ this.timedOutMethod = timedOutMethod;
472
+ this.name = "AgyAcpRequestTimeoutError";
473
+ }
474
+ };
475
+ function toRpcError(value) {
476
+ const record = asRecord(value);
477
+ if (!record) return null;
478
+ const code = asNumber(record.code);
479
+ const message = asString(record.message);
480
+ if (code === void 0 && message === void 0) return null;
481
+ return { code: code ?? -32e3, message: message ?? "unknown JSON-RPC error" };
482
+ }
483
+ function normalizeAcpUsage(value) {
484
+ const record = asRecord(value);
485
+ if (!record) return void 0;
486
+ const pick = (...keys) => {
487
+ for (const key of keys) {
488
+ const found = asNumber(record[key]);
489
+ if (found !== void 0) return found;
490
+ }
491
+ return void 0;
492
+ };
493
+ const input = pick("inputTokens", "input_tokens", "prompt_tokens");
494
+ const output = pick("outputTokens", "output_tokens", "completion_tokens");
495
+ const total = pick("totalTokens", "total_tokens");
496
+ const cacheRead = pick("cachedReadTokens", "cache_read_tokens", "cache_read_input_tokens");
497
+ if (input === void 0 && output === void 0 && total === void 0 && cacheRead === void 0) {
498
+ return void 0;
499
+ }
500
+ return {
501
+ ...input !== void 0 ? { input_tokens: input } : {},
502
+ ...output !== void 0 ? { output_tokens: output } : {},
503
+ ...total !== void 0 ? { total_tokens: total } : {},
504
+ ...cacheRead !== void 0 ? { cache_read_input_tokens: cacheRead } : {}
505
+ };
506
+ }
507
+ var AcpRpcPeer = class {
508
+ constructor(writeLine, onRequest, onNotification) {
509
+ this.writeLine = writeLine;
510
+ this.onRequest = onRequest;
511
+ this.onNotification = onNotification;
512
+ }
513
+ buffer = "";
514
+ decoder = new StringDecoder("utf8");
515
+ pending = /* @__PURE__ */ new Map();
516
+ nextId = 1;
517
+ disposed = false;
518
+ /** 消费方(onChunk/onToolEvent)抛错被兜住的次数:交给上层转成 warning,别静默丢帧。 */
519
+ droppedNotifications = 0;
520
+ /** 喂入 stdout 字节流。 */
521
+ feed(chunk) {
522
+ this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
523
+ while (true) {
524
+ const newlineIndex = this.buffer.indexOf("\n");
525
+ if (newlineIndex < 0) return;
526
+ const line = this.buffer.slice(0, newlineIndex).trim();
527
+ this.buffer = this.buffer.slice(newlineIndex + 1);
528
+ if (line) this.handleLine(line);
529
+ }
530
+ }
531
+ handleLine(line) {
532
+ let parsed;
533
+ try {
534
+ parsed = JSON.parse(line);
535
+ } catch {
536
+ return;
537
+ }
538
+ const message = asRecord(parsed);
539
+ if (!message) return;
540
+ const id = asNumber(message.id);
541
+ const method = asString(message.method);
542
+ if (method === void 0) {
543
+ if (id === void 0) return;
544
+ const pending = this.pending.get(id);
545
+ if (!pending) return;
546
+ this.pending.delete(id);
547
+ if (pending.timer) clearTimeout(pending.timer);
548
+ const error = toRpcError(message.error);
549
+ if (error) {
550
+ pending.reject(new Error(`${error.message} (code ${error.code})`));
551
+ return;
552
+ }
553
+ pending.resolve(message.result);
554
+ return;
555
+ }
556
+ if (id === void 0) {
557
+ try {
558
+ this.onNotification(method, message.params);
559
+ } catch {
560
+ this.droppedNotifications += 1;
561
+ }
562
+ return;
563
+ }
564
+ void Promise.resolve().then(() => this.onRequest(method, message.params)).then(
565
+ (result) => this.send({ jsonrpc: "2.0", id, result: result ?? null }),
566
+ (error) => this.send({
567
+ jsonrpc: "2.0",
568
+ id,
569
+ error: {
570
+ code: -32603,
571
+ message: error instanceof Error ? error.message : String(error)
572
+ }
573
+ })
574
+ );
575
+ }
576
+ /** 发请求并等回复;`timeoutMs <= 0` 表示不设超时。 */
577
+ request(method, params, timeoutMs) {
578
+ if (this.disposed) {
579
+ return Promise.reject(new Error(`agy ACP peer is closed (request ${method})`));
580
+ }
581
+ const id = this.nextId++;
582
+ return new Promise((resolvePromise, rejectPromise) => {
583
+ const timer = timeoutMs > 0 ? setTimeout(() => {
584
+ this.pending.delete(id);
585
+ rejectPromise(new AgyAcpRequestTimeoutError(method));
586
+ }, timeoutMs) : null;
587
+ timer?.unref?.();
588
+ this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
589
+ this.send({ jsonrpc: "2.0", id, method, params });
590
+ });
591
+ }
592
+ /** 发通知(无回复)。 */
593
+ notify(method, params) {
594
+ if (this.disposed) return;
595
+ this.send({ jsonrpc: "2.0", method, params });
596
+ }
597
+ /** 取走并清零「被兜住的消费方异常」计数。 */
598
+ takeDroppedNotifications() {
599
+ const dropped = this.droppedNotifications;
600
+ this.droppedNotifications = 0;
601
+ return dropped;
602
+ }
603
+ send(payload) {
604
+ try {
605
+ this.writeLine(`${JSON.stringify(payload)}
606
+ `);
607
+ } catch {
608
+ }
609
+ }
610
+ /** 关闭:所有在途请求立刻失败,避免悬挂的 await。 */
611
+ dispose(reason) {
612
+ if (this.disposed) return;
613
+ this.disposed = true;
614
+ for (const [id, pending] of this.pending) {
615
+ this.pending.delete(id);
616
+ if (pending.timer) clearTimeout(pending.timer);
617
+ pending.reject(reason);
618
+ }
619
+ this.buffer = "";
620
+ }
621
+ };
622
+ function parseModelOptions(raw) {
623
+ if (!Array.isArray(raw)) return [];
624
+ const result = [];
625
+ for (const item of raw) {
626
+ const record = asRecord(item);
627
+ if (!record) continue;
628
+ const value = asString(record.value) ?? asString(record.modelId) ?? asString(record.id);
629
+ if (!value) continue;
630
+ result.push({
631
+ value,
632
+ name: asString(record.name) ?? value,
633
+ ...asString(record.description) ? { description: asString(record.description) } : {}
634
+ });
635
+ }
636
+ return result;
637
+ }
638
+ function parseConfigOptions(result) {
639
+ const record = asRecord(result);
640
+ if (!record) return [];
641
+ const options = [];
642
+ for (const raw of Array.isArray(record.configOptions) ? record.configOptions : []) {
643
+ const item = asRecord(raw);
644
+ if (!item) continue;
645
+ const id = asString(item.id);
646
+ if (!id) continue;
647
+ options.push({
648
+ id,
649
+ name: asString(item.name) ?? id,
650
+ category: asString(item.category) ?? null,
651
+ currentValue: asString(item.currentValue) ?? null,
652
+ options: parseModelOptions(item.options)
653
+ });
654
+ }
655
+ const models = asRecord(record.models);
656
+ if (models && options.every((option) => !isModelOption(option))) {
657
+ const available = parseModelOptions(models.availableModels);
658
+ if (available.length > 0) {
659
+ options.push({
660
+ id: "model",
661
+ name: "Model",
662
+ category: "model",
663
+ currentValue: asString(models.currentModelId) ?? null,
664
+ options: available
665
+ });
666
+ }
667
+ }
668
+ return options;
669
+ }
670
+ function isModelOption(option) {
671
+ const haystack = `${option.id} ${option.name} ${option.category ?? ""}`.toLowerCase();
672
+ return haystack.includes("model");
673
+ }
674
+ function pickModelOption(options) {
675
+ const byCategory = options.find((option) => {
676
+ const category = (option.category ?? "").toLowerCase();
677
+ return category === "model" || category === "model_config";
678
+ });
679
+ if (byCategory) return byCategory;
680
+ return options.find(isModelOption) ?? null;
681
+ }
682
+ var AgyAcpSession = class {
683
+ constructor(key, config) {
684
+ this.key = key;
685
+ this.config = config;
686
+ }
687
+ peer = null;
688
+ proc = null;
689
+ acpSessionId = null;
690
+ configOptions = [];
691
+ appliedModel = null;
692
+ idleTimer = null;
693
+ turnQueue = Promise.resolve();
694
+ history = [];
695
+ stderrTail = "";
696
+ systemPromptSent = false;
697
+ /** 进程被回收/崩溃后置位:下一轮需要把历史作为上下文前导重发。 */
698
+ needsContextReplay = false;
699
+ /**
700
+ * 显式状态:并发门只认 occupied(starting|warm),不能用 isWarm() 充当「是否占槽」——
701
+ * 握手窗口内 acpSessionId 还没回来,用 isWarm() 会让本机同时起两个 agy。
702
+ */
703
+ state = "starting";
704
+ /** 进程组终止(含升级 kill)进行中:这段时间仍算占槽,否则新旧 agy 进程会并存。 */
705
+ terminating = false;
706
+ /**
707
+ * 注册表已关闭:会话不可复生。否则排在 turnQueue 里的 turn 会在 ensureReady 里看到
708
+ * proc/peer 都空就 start() 拉起一个新进程,而它不在注册表里(liveSessionCount 数不到),
709
+ * 本机就能再起第二个 agy。
710
+ */
711
+ retired = false;
712
+ terminatePromise = null;
713
+ loadSessionSupported = false;
714
+ terminals = /* @__PURE__ */ new Map();
715
+ warnings = [];
716
+ isWarm() {
717
+ return this.state === "warm" && this.proc !== null && this.acpSessionId !== null;
718
+ }
719
+ /** 是否占着本机唯一的 agy 委托槽(含握手窗口与终止中的窗口)。 */
720
+ isOccupyingSlot() {
721
+ return this.state !== "closed" || this.terminating;
722
+ }
723
+ /** 注册表关闭时调用:此后任何 turn 都不许再拉起新进程。 */
724
+ retire() {
725
+ this.retired = true;
726
+ }
727
+ assertNotRetired() {
728
+ if (this.retired) {
729
+ throw new Error(
730
+ `agy ACP session "${this.key}" was closed; refusing to start a new agent process. Start a new cli session instead.`
731
+ );
732
+ }
733
+ }
734
+ updateConfig(config) {
735
+ this.config = config;
736
+ }
737
+ getModelOptions() {
738
+ const modelOption = pickModelOption(this.configOptions);
739
+ return modelOption ? [...modelOption.options] : [];
740
+ }
741
+ getWarnings() {
742
+ return [...this.warnings];
743
+ }
744
+ /** 串行化同一 session 的 turn:ACP 一个会话同时只能跑一个 prompt。 */
745
+ prompt(input, options) {
746
+ const run = () => this.runTurn(input, options);
747
+ const next = this.turnQueue.then(run, run);
748
+ this.turnQueue = next.then(
749
+ () => void 0,
750
+ () => void 0
751
+ );
752
+ return next;
753
+ }
754
+ async runTurn(input, options) {
755
+ this.assertNotRetired();
756
+ if (options.signal?.aborted) {
757
+ if (!this.proc && !this.peer) this.state = "closed";
758
+ throw createAbortError("agy ACP execution was aborted before start");
759
+ }
760
+ const start = Date.now();
761
+ const warningsBefore = this.warnings.length;
762
+ this.clearIdleTimer();
763
+ try {
764
+ return await this.runTurnInner(input, options, start, warningsBefore);
765
+ } finally {
766
+ if (this.proc) this.touchIdleTimer();
767
+ }
768
+ }
769
+ async runTurnInner(input, options, start, warningsBefore) {
770
+ const peer = await this.ensureReady(options);
771
+ this.throwIfAborted(options.signal);
772
+ const sessionId = this.acpSessionId;
773
+ if (!sessionId) {
774
+ throw new Error("agy ACP session is not initialised");
775
+ }
776
+ await this.applyModel(peer, sessionId);
777
+ const promptText = this.buildPromptText(input);
778
+ const collected = [];
779
+ let usage;
780
+ let stopReason = "end_turn";
781
+ const seenToolCalls = /* @__PURE__ */ new Set();
782
+ const onUpdate = (params) => {
783
+ const record = asRecord(params);
784
+ if (!record) return;
785
+ const update = asRecord(record.update) ?? record;
786
+ if (!update) return;
787
+ const kind = asString(update.sessionUpdate) ?? asString(update.type);
788
+ if (kind === "agent_message_chunk") {
789
+ const content = asRecord(update.content);
790
+ const text2 = asString(content?.text);
791
+ if (text2) {
792
+ collected.push(text2);
793
+ options.onChunk?.(text2);
794
+ }
795
+ return;
796
+ }
797
+ if (kind === "agent_thought_chunk") {
798
+ const content = asRecord(update.content);
799
+ const text2 = asString(content?.text);
800
+ if (text2) options.onThoughtChunk?.(text2);
801
+ return;
802
+ }
803
+ if (kind === "tool_call" || kind === "tool_call_update") {
804
+ const toolCallId = asString(update.toolCallId) ?? asString(update.tool_call_id);
805
+ if (!toolCallId) return;
806
+ const status = asString(update.status) ?? "";
807
+ const title = asString(update.title) ?? asString(update.kind) ?? "tool";
808
+ const round = options.toolEventRound ?? 1;
809
+ if (status === "pending" || status === "in_progress" || status === "") {
810
+ if (seenToolCalls.has(toolCallId)) return;
811
+ seenToolCalls.add(toolCallId);
812
+ options.onToolEvent?.({
813
+ type: "tool-call",
814
+ round,
815
+ toolCallId,
816
+ toolName: title,
817
+ summary: `Tool call: ${title}`,
818
+ metadata: { source: "cli-external", cliProvider: "agy" }
819
+ });
820
+ return;
821
+ }
822
+ if (status === "completed") {
823
+ options.onToolEvent?.({
824
+ type: "tool-result",
825
+ round,
826
+ toolCallId,
827
+ toolName: title,
828
+ summary: `Tool completed: ${title}`,
829
+ metadata: { source: "cli-external", cliProvider: "agy" }
830
+ });
831
+ return;
832
+ }
833
+ if (status === "failed") {
834
+ options.onToolEvent?.({
835
+ type: "tool-error",
836
+ round,
837
+ toolCallId,
838
+ toolName: title,
839
+ message: `Tool failed: ${title}`,
840
+ summary: `Tool error: ${title}`,
841
+ metadata: { source: "cli-external", cliProvider: "agy" }
842
+ });
843
+ }
844
+ return;
845
+ }
846
+ };
847
+ this.updateHandlers = { onUpdate };
848
+ const timeoutMs = options.timeoutMs ?? 0;
849
+ const turnPromise = peer.request(
850
+ "session/prompt",
851
+ { sessionId, prompt: [{ type: "text", text: promptText }] },
852
+ timeoutMs
853
+ );
854
+ let abortHandler = null;
855
+ const abortPromise = new Promise((_, rejectPromise) => {
856
+ if (!options.signal) return;
857
+ abortHandler = () => rejectPromise(createAbortError());
858
+ options.signal.addEventListener("abort", abortHandler, { once: true });
859
+ });
860
+ let promptResult;
861
+ try {
862
+ promptResult = await (options.signal ? Promise.race([turnPromise, abortPromise]) : turnPromise);
863
+ } catch (error) {
864
+ this.updateHandlers = null;
865
+ if (options.signal?.aborted) {
866
+ const outcome = await this.cancelTurn(sessionId, turnPromise);
867
+ if (outcome === "timeout") {
868
+ throw attachExecutionStoppedPromise(
869
+ createAbortError("agy ACP execution was aborted (cancel not acknowledged)"),
870
+ this.terminate("aborted")
871
+ );
872
+ }
873
+ throw createAbortError("agy ACP execution was aborted");
874
+ }
875
+ const message = error instanceof Error ? error.message : String(error);
876
+ this.noteQuotaSignal(message);
877
+ if (error instanceof AgyAcpRequestTimeoutError) {
878
+ this.peer?.notify("session/cancel", { sessionId });
879
+ }
880
+ if (/Authentication required/i.test(message)) {
881
+ throw new Error(
882
+ `${message} \u2014 agy ACP requires an interactive sign-in. Run \`agy acp --login\` once in a terminal, then retry.`
883
+ );
884
+ }
885
+ throw error;
886
+ } finally {
887
+ if (abortHandler && options.signal) options.signal.removeEventListener("abort", abortHandler);
888
+ this.updateHandlers = null;
889
+ }
890
+ if (options.signal?.aborted) {
891
+ throw createAbortError("agy ACP execution was aborted");
892
+ }
893
+ const resultRecord = asRecord(promptResult);
894
+ stopReason = asString(resultRecord?.stopReason) ?? "end_turn";
895
+ usage = normalizeAcpUsage(resultRecord?.usage);
896
+ const droppedNotifications = this.peer?.takeDroppedNotifications() ?? 0;
897
+ if (droppedNotifications > 0) {
898
+ this.warnings.push(
899
+ `agy ACP dropped ${droppedNotifications} session/update notification(s): a stream handler threw`
900
+ );
901
+ }
902
+ const text = collected.join("");
903
+ this.history.push(
904
+ { role: "user", content: input },
905
+ { role: "assistant", content: text }
906
+ );
907
+ if (stopReason === "cancelled") {
908
+ throw createAbortError("agy ACP turn was cancelled by the agent");
909
+ }
910
+ if (stopReason === "refusal") {
911
+ this.warnings.push("agy ACP turn ended with stopReason=refusal");
912
+ }
913
+ const turnWarnings = this.warnings.slice(warningsBefore);
914
+ return {
915
+ text,
916
+ raw: text,
917
+ elapsed: Date.now() - start,
918
+ ...usage ? { usage } : {},
919
+ ...turnWarnings.length > 0 ? { warnings: turnWarnings } : {}
920
+ };
921
+ }
922
+ updateHandlers = null;
923
+ throwIfAborted(signal) {
924
+ if (!signal?.aborted) return;
925
+ throw createAbortError("agy ACP execution was aborted during handshake");
926
+ }
927
+ /** 冷启动时把历史拼成上下文前导;系统提示只在首个 prompt 前注入一次。 */
928
+ buildPromptText(input) {
929
+ const parts = [];
930
+ const systemPrompt = this.config.systemPrompt?.trim();
931
+ if (systemPrompt && !this.systemPromptSent) {
932
+ parts.push(systemPrompt);
933
+ this.systemPromptSent = true;
934
+ }
935
+ if (this.needsContextReplay && this.history.length > 0) {
936
+ const transcript = this.history.map((entry, index) => `[${index + 1}] ${entry.role === "user" ? "\u7528\u6237" : "\u52A9\u624B"}
937
+ ${entry.content.trim()}`).join("\n\n");
938
+ parts.push(
939
+ ["\u4EE5\u4E0B\u662F\u540C\u4E00\u4F1A\u8BDD\u6B64\u524D\u5DF2\u53D1\u751F\u7684\u5BF9\u8BDD\uFF08\u8FDB\u7A0B\u91CD\u542F\u540E\u91CD\u5EFA\u4E0A\u4E0B\u6587\uFF09\uFF0C\u8BF7\u5EF6\u7EED\u5B83\u7EE7\u7EED\u56DE\u7B54\u6700\u540E\u4E00\u6761\u7528\u6237\u6D88\u606F\u3002", transcript].join(
940
+ "\n\n"
941
+ )
942
+ );
943
+ this.needsContextReplay = false;
944
+ }
945
+ parts.push(input);
946
+ return parts.join("\n\n");
947
+ }
948
+ async ensureReady(options) {
949
+ this.assertNotRetired();
950
+ if (this.terminatePromise) {
951
+ await this.terminatePromise;
952
+ }
953
+ if (this.peer && this.proc && this.acpSessionId) {
954
+ return this.peer;
955
+ }
956
+ if (this.peer || this.proc) {
957
+ await this.terminate("restart");
958
+ }
959
+ return this.start();
960
+ }
961
+ async start() {
962
+ this.assertNotRetired();
963
+ const binPath = this.config.binPath || process.env.AGY_BIN || "agy";
964
+ const cwd = this.config.cwd || process.cwd();
965
+ const args = ["acp"];
966
+ if (this.config.yolo === false) args.push("--sandbox");
967
+ for (const dir of this.config.addDirs ?? []) {
968
+ args.push("--add-dir", dir);
969
+ }
970
+ this.state = "starting";
971
+ const proc = spawn2(binPath, args, {
972
+ cwd,
973
+ env: buildCliProcessEnv(this.config.env),
974
+ stdio: ["pipe", "pipe", "pipe"],
975
+ detached: process.platform !== "win32"
976
+ });
977
+ this.proc = proc;
978
+ this.stderrTail = "";
979
+ const decoder = new StringDecoder("utf8");
980
+ const peer = new AcpRpcPeer(
981
+ (line) => {
982
+ if (proc.stdin && !proc.stdin.destroyed) proc.stdin.write(line);
983
+ },
984
+ (method, params) => this.handleAgentRequest(method, params),
985
+ (method, params) => {
986
+ if (method === "session/update") this.updateHandlers?.onUpdate(params);
987
+ }
988
+ );
989
+ this.peer = peer;
990
+ let settledExit = false;
991
+ const handleExit = (code, signal) => {
992
+ if (settledExit) return;
993
+ settledExit = true;
994
+ this.handleProcessGone(code, signal);
995
+ };
996
+ proc.on("exit", handleExit);
997
+ proc.on("error", (error) => {
998
+ this.stderrTail += `
999
+ ${error.message}`;
1000
+ handleExit(null, null);
1001
+ });
1002
+ proc.stdout?.on("data", (chunk) => peer.feed(chunk));
1003
+ proc.stderr?.on("data", (chunk) => {
1004
+ this.stderrTail = (this.stderrTail + decoder.write(chunk)).slice(-STDERR_TAIL_CHARS);
1005
+ });
1006
+ try {
1007
+ const initResult = asRecord(
1008
+ await peer.request(
1009
+ "initialize",
1010
+ {
1011
+ protocolVersion: ACP_PROTOCOL_VERSION,
1012
+ clientCapabilities: {
1013
+ fs: { readTextFile: true, writeTextFile: true },
1014
+ terminal: true
1015
+ }
1016
+ },
1017
+ DEFAULT_HANDSHAKE_TIMEOUT_MS
1018
+ )
1019
+ );
1020
+ const capabilities = asRecord(initResult?.agentCapabilities);
1021
+ this.loadSessionSupported = capabilities?.loadSession === true || capabilities?.load_session === true;
1022
+ } catch (error) {
1023
+ await this.terminate("initialize-failed");
1024
+ throw this.describeStartupFailure(error, "initialize");
1025
+ }
1026
+ const reused = await this.tryLoadSession(peer, cwd);
1027
+ if (!reused) {
1028
+ try {
1029
+ const newSession = await peer.request(
1030
+ "session/new",
1031
+ { cwd, mcpServers: [] },
1032
+ DEFAULT_HANDSHAKE_TIMEOUT_MS
1033
+ );
1034
+ const record = asRecord(newSession);
1035
+ const sessionId = asString(record?.sessionId);
1036
+ if (!sessionId) {
1037
+ throw new Error("agy ACP session/new returned no sessionId");
1038
+ }
1039
+ this.acpSessionId = sessionId;
1040
+ this.configOptions = parseConfigOptions(record);
1041
+ this.appliedModel = pickModelOption(this.configOptions)?.currentValue ?? null;
1042
+ } catch (error) {
1043
+ await this.terminate("session-new-failed");
1044
+ throw this.describeStartupFailure(error, "session/new");
1045
+ }
1046
+ }
1047
+ this.state = "warm";
1048
+ return peer;
1049
+ }
1050
+ /** 进程重启后尝试用 `session/load` 接回原会话;不支持或失败则退回 session/new。 */
1051
+ async tryLoadSession(peer, cwd) {
1052
+ if (!this.loadSessionSupported || !this.needsContextReplay || !this.acpSessionId) return false;
1053
+ try {
1054
+ const loaded = await peer.request(
1055
+ "session/load",
1056
+ { sessionId: this.acpSessionId, cwd, mcpServers: [] },
1057
+ DEFAULT_HANDSHAKE_TIMEOUT_MS
1058
+ );
1059
+ const record = asRecord(loaded);
1060
+ if (record && record.configOptions) this.configOptions = parseConfigOptions(record);
1061
+ this.needsContextReplay = false;
1062
+ return true;
1063
+ } catch {
1064
+ return false;
1065
+ }
1066
+ }
1067
+ async applyModel(peer, sessionId) {
1068
+ const requested = this.config.model?.trim();
1069
+ if (!requested) return;
1070
+ const modelOption = pickModelOption(this.configOptions);
1071
+ if (!modelOption) {
1072
+ if (!this.warnings.includes("agy ACP exposes no model configOptions; model selection skipped.")) {
1073
+ this.warnings.push("agy ACP exposes no model configOptions; model selection skipped.");
1074
+ }
1075
+ return;
1076
+ }
1077
+ if (this.appliedModel === requested) return;
1078
+ const known = modelOption.options.some((option) => option.value === requested);
1079
+ if (!known) {
1080
+ const message = `agy ACP model "${requested}" is not in the session's advertised model list; keeping current model.`;
1081
+ if (!this.warnings.includes(message)) this.warnings.push(message);
1082
+ return;
1083
+ }
1084
+ try {
1085
+ const response = await peer.request(
1086
+ "session/set_config_option",
1087
+ { sessionId, configId: modelOption.id, value: requested },
1088
+ DEFAULT_HANDSHAKE_TIMEOUT_MS
1089
+ );
1090
+ const updated = parseConfigOptions(response);
1091
+ if (updated.length > 0) this.configOptions = updated;
1092
+ this.appliedModel = requested;
1093
+ } catch (error) {
1094
+ const message = `agy ACP session/set_config_option failed: ${error instanceof Error ? error.message : String(error)}`;
1095
+ if (!this.warnings.includes(message)) this.warnings.push(message);
1096
+ }
1097
+ }
1098
+ async cancelTurn(sessionId, turnPromise) {
1099
+ this.peer?.notify("session/cancel", { sessionId });
1100
+ const settled = await Promise.race([
1101
+ turnPromise.then(
1102
+ () => true,
1103
+ () => true
1104
+ ),
1105
+ new Promise((resolvePromise) => {
1106
+ const timer = setTimeout(() => resolvePromise(false), CANCEL_GRACE_MS);
1107
+ timer.unref?.();
1108
+ })
1109
+ ]);
1110
+ return settled ? "settled" : "timeout";
1111
+ }
1112
+ handleProcessGone(code, signal) {
1113
+ const reason = `agy acp process exited (code: ${code ?? "null"}, signal: ${signal ?? "none"})` + (this.stderrTail.trim() ? `
1114
+ stderr: ${this.stderrTail.trim()}` : "");
1115
+ this.peer?.dispose(new Error(reason));
1116
+ this.peer = null;
1117
+ this.proc = null;
1118
+ this.acpSessionId = null;
1119
+ this.state = "closed";
1120
+ this.needsContextReplay = this.history.length > 0;
1121
+ this.clearTerminals();
1122
+ this.clearIdleTimer();
1123
+ this.noteQuotaSignal(this.stderrTail);
1124
+ }
1125
+ noteQuotaSignal(text) {
1126
+ if (!text.trim()) return;
1127
+ const quota = detectCliProviderQuotaLimit("agy", "", text, null);
1128
+ if (quota.limited) {
1129
+ this.warnings.push(quota.message ?? "agy quota/rate limit signal");
1130
+ }
1131
+ }
1132
+ describeStartupFailure(error, method) {
1133
+ const message = error instanceof Error ? error.message : String(error);
1134
+ const quota = detectCliProviderQuotaLimit("agy", "", `${message}
1135
+ ${this.stderrTail}`, null);
1136
+ if (quota.limited) {
1137
+ return new CliProviderQuotaError("agy", quota.message ?? "Agy reported quota/limit");
1138
+ }
1139
+ if (message.includes("Authentication required")) {
1140
+ return new Error(
1141
+ `agy ACP requires an interactive sign-in. Run \`agy acp --login\` (or \`agy --login\`) once in a terminal, then retry. (${method} failed: ${message})`
1142
+ );
1143
+ }
1144
+ return new Error(`agy ACP ${method} failed: ${message}`);
1145
+ }
1146
+ /**
1147
+ * 处理 agent 的反向请求。必须是 async:沙箱拒绝等是同步 throw,
1148
+ * 直接返回 `Promise.resolve(fn())` 会让异常冒到 stdout 的 data 监听器(宿主级未捕获异常)。
1149
+ */
1150
+ async handleAgentRequest(method, params) {
1151
+ const record = asRecord(params);
1152
+ switch (method) {
1153
+ case "session/request_permission":
1154
+ return this.resolvePermission(record);
1155
+ case "fs/read_text_file":
1156
+ return this.readTextFile(record);
1157
+ case "fs/write_text_file":
1158
+ return this.writeTextFile(record);
1159
+ case "terminal/create":
1160
+ return this.createTerminal(record);
1161
+ case "terminal/output":
1162
+ return this.readTerminalOutput(record);
1163
+ case "terminal/wait_for_exit":
1164
+ return this.waitForTerminalExit(record);
1165
+ case "terminal/kill":
1166
+ return this.killTerminal(record);
1167
+ case "terminal/release":
1168
+ return this.releaseTerminal(record);
1169
+ default:
1170
+ throw new Error(`Unsupported ACP method: ${method}`);
1171
+ }
1172
+ }
1173
+ /** yolo → 自动 allow;非 yolo → 自动 reject(没人能在线点确认)。 */
1174
+ resolvePermission(params) {
1175
+ const options = Array.isArray(params?.options) ? params.options : [];
1176
+ const candidates = options.map((raw) => asRecord(raw)).filter((raw) => raw !== null).map((raw) => ({
1177
+ optionId: asString(raw.optionId) ?? asString(raw.option_id) ?? "",
1178
+ kind: (asString(raw.kind) ?? "").toLowerCase()
1179
+ })).filter((raw) => raw.optionId !== "");
1180
+ const allow = candidates.find((option) => option.kind.startsWith("allow"));
1181
+ const reject = candidates.find((option) => option.kind.startsWith("reject"));
1182
+ const wantAllow = this.config.yolo !== false;
1183
+ if (!wantAllow && !reject) {
1184
+ return { outcome: { outcome: "cancelled" } };
1185
+ }
1186
+ const chosen = wantAllow ? allow ?? reject : reject;
1187
+ if (!chosen) {
1188
+ return { outcome: { outcome: "cancelled" } };
1189
+ }
1190
+ return { outcome: { outcome: "selected", optionId: chosen.optionId }, optionId: chosen.optionId };
1191
+ }
1192
+ /** 沙箱根的真身(realpath):词法比较会被 `cwd` 内的符号链接绕过。 */
1193
+ realSandboxRoots() {
1194
+ const roots = [this.config.cwd || process.cwd(), ...this.config.addDirs ?? []];
1195
+ return roots.map((root) => {
1196
+ const absolute = resolve(root);
1197
+ try {
1198
+ return realpathSync(absolute);
1199
+ } catch {
1200
+ return absolute;
1201
+ }
1202
+ });
1203
+ }
1204
+ /**
1205
+ * 把请求路径解析成真身并判定是否在沙箱内;越界/无法解析一律拒绝(fail-closed)。
1206
+ * - 读:目标必须存在,`realpathSync` 直接解掉所有中间符号链接;
1207
+ * - 写:取最近的已存在祖先的真身,再拼回尚未创建的后缀。
1208
+ */
1209
+ resolveSandboxPath(target, forWrite) {
1210
+ const absolute = resolve(target);
1211
+ const real = forWrite ? this.realpathForWrite(absolute) : realpathSync(absolute);
1212
+ const roots = this.realSandboxRoots();
1213
+ if (!roots.some((root) => isWithin(root, real))) {
1214
+ throw new Error(`agy ACP requested a path outside the allowed sandbox: ${absolute}`);
1215
+ }
1216
+ return real;
1217
+ }
1218
+ realpathForWrite(absolute) {
1219
+ let existing = absolute;
1220
+ const tail = [];
1221
+ while (!existsSync(existing)) {
1222
+ const parent = dirname(existing);
1223
+ if (parent === existing) break;
1224
+ tail.unshift(basename(existing));
1225
+ existing = parent;
1226
+ }
1227
+ if (tail.length > 0) {
1228
+ const firstMissing = resolve(existing, tail[0]);
1229
+ let stat = null;
1230
+ try {
1231
+ stat = lstatSync(firstMissing);
1232
+ } catch {
1233
+ stat = null;
1234
+ }
1235
+ if (stat?.isSymbolicLink()) {
1236
+ throw new Error(`agy ACP refuses to write through a symbolic link: ${firstMissing}`);
1237
+ }
1238
+ }
1239
+ const realExisting = realpathSync(existing);
1240
+ return tail.length > 0 ? resolve(realExisting, ...tail) : realExisting;
1241
+ }
1242
+ readTextFile(params) {
1243
+ const path = asString(params?.path);
1244
+ if (!path) throw new Error("fs/read_text_file requires a path");
1245
+ let content = readFileSync(this.resolveSandboxPath(path, false), "utf8");
1246
+ const line = asNumber(params?.line);
1247
+ const limit = asNumber(params?.limit);
1248
+ if (line !== void 0 || limit !== void 0) {
1249
+ const lines = content.split("\n");
1250
+ const startIndex = Math.max(0, (line ?? 1) - 1);
1251
+ const endIndex = limit !== void 0 ? startIndex + limit : lines.length;
1252
+ content = lines.slice(startIndex, endIndex).join("\n");
1253
+ }
1254
+ return { content };
1255
+ }
1256
+ writeTextFile(params) {
1257
+ const path = asString(params?.path);
1258
+ const content = asString(params?.content);
1259
+ if (!path || content === void 0) throw new Error("fs/write_text_file requires path and content");
1260
+ const realPath = this.resolveSandboxPath(path, true);
1261
+ mkdirSync(dirname(realPath), { recursive: true });
1262
+ writeFileSync(realPath, content, "utf8");
1263
+ return null;
1264
+ }
1265
+ createTerminal(params) {
1266
+ const command = asString(params?.command);
1267
+ if (!command) throw new Error("terminal/create requires a command");
1268
+ if (this.config.yolo === false) {
1269
+ throw new Error("terminal/create is denied in non-yolo agy ACP sessions");
1270
+ }
1271
+ const requestedCwd = asString(params?.cwd) ?? this.config.cwd ?? process.cwd();
1272
+ const realCwd = this.resolveSandboxPath(requestedCwd, false);
1273
+ const args = Array.isArray(params?.args) ? params.args.filter((value) => typeof value === "string") : [];
1274
+ const envRecord = asRecord(params?.env);
1275
+ const env = { ...buildCliProcessEnv(this.config.env) };
1276
+ if (envRecord) {
1277
+ for (const [key, value] of Object.entries(envRecord)) {
1278
+ const resolved = asString(value);
1279
+ if (resolved !== void 0) env[key] = resolved;
1280
+ }
1281
+ }
1282
+ const child = spawn2(command, args, {
1283
+ cwd: realCwd,
1284
+ env,
1285
+ stdio: ["ignore", "pipe", "pipe"]
1286
+ });
1287
+ const terminalId = `term_${this.terminals.size + 1}_${Date.now().toString(36)}`;
1288
+ const state = {
1289
+ child,
1290
+ output: "",
1291
+ truncated: false,
1292
+ exitCode: null,
1293
+ signal: null,
1294
+ exited: false,
1295
+ waiters: []
1296
+ };
1297
+ this.terminals.set(terminalId, state);
1298
+ const append = (chunk) => {
1299
+ state.output += chunk.toString("utf8");
1300
+ if (state.output.length > MAX_TERMINAL_OUTPUT_CHARS) {
1301
+ state.output = state.output.slice(-MAX_TERMINAL_OUTPUT_CHARS);
1302
+ state.truncated = true;
1303
+ }
1304
+ };
1305
+ child.stdout?.on("data", append);
1306
+ child.stderr?.on("data", append);
1307
+ const finish = (code, signal) => {
1308
+ state.exited = true;
1309
+ state.exitCode = code;
1310
+ state.signal = signal;
1311
+ for (const waiter of state.waiters.splice(0)) waiter();
1312
+ };
1313
+ child.on("exit", finish);
1314
+ child.on("error", (error) => {
1315
+ append(Buffer.from(`
1316
+ ${error.message}`));
1317
+ finish(null, null);
1318
+ });
1319
+ return { terminalId };
1320
+ }
1321
+ readTerminalOutput(params) {
1322
+ const state = this.requireTerminal(params);
1323
+ return {
1324
+ output: state.output,
1325
+ truncated: state.truncated,
1326
+ ...state.exited ? { exitStatus: { exitCode: state.exitCode, signal: state.signal } } : {}
1327
+ };
1328
+ }
1329
+ async waitForTerminalExit(params) {
1330
+ const state = this.requireTerminal(params);
1331
+ if (!state.exited) {
1332
+ await new Promise((resolvePromise) => {
1333
+ const timer = setTimeout(resolvePromise, 12e4);
1334
+ timer.unref?.();
1335
+ state.waiters.push(() => {
1336
+ clearTimeout(timer);
1337
+ resolvePromise();
1338
+ });
1339
+ });
1340
+ }
1341
+ return { exitCode: state.exitCode, signal: state.signal };
1342
+ }
1343
+ killTerminal(params) {
1344
+ const state = this.requireTerminal(params);
1345
+ if (!state.exited) {
1346
+ try {
1347
+ state.child.kill("SIGTERM");
1348
+ } catch {
1349
+ }
1350
+ }
1351
+ return null;
1352
+ }
1353
+ releaseTerminal(params) {
1354
+ const terminalId = asString(params?.terminalId);
1355
+ if (!terminalId) throw new Error("terminal/release requires terminalId");
1356
+ const state = this.terminals.get(terminalId);
1357
+ if (state) {
1358
+ if (!state.exited) {
1359
+ try {
1360
+ state.child.kill("SIGKILL");
1361
+ } catch {
1362
+ }
1363
+ }
1364
+ this.terminals.delete(terminalId);
1365
+ }
1366
+ return null;
1367
+ }
1368
+ requireTerminal(params) {
1369
+ const terminalId = asString(params?.terminalId);
1370
+ if (!terminalId) throw new Error("terminal request requires terminalId");
1371
+ const state = this.terminals.get(terminalId);
1372
+ if (!state) throw new Error(`Unknown terminal: ${terminalId}`);
1373
+ return state;
1374
+ }
1375
+ clearTerminals() {
1376
+ for (const [, state] of this.terminals) {
1377
+ if (state.exited) continue;
1378
+ try {
1379
+ state.child.kill("SIGTERM");
1380
+ } catch {
1381
+ }
1382
+ const escalate = setTimeout(() => {
1383
+ if (state.exited) return;
1384
+ try {
1385
+ state.child.kill("SIGKILL");
1386
+ } catch {
1387
+ }
1388
+ }, 100);
1389
+ escalate.unref?.();
1390
+ }
1391
+ this.terminals.clear();
1392
+ }
1393
+ touchIdleTimer() {
1394
+ this.clearIdleTimer();
1395
+ const idleMs = this.config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
1396
+ if (idleMs <= 0) return;
1397
+ this.idleTimer = setTimeout(() => {
1398
+ this.idleTimer = null;
1399
+ void this.terminate("idle");
1400
+ }, idleMs);
1401
+ this.idleTimer.unref?.();
1402
+ }
1403
+ clearIdleTimer() {
1404
+ if (this.idleTimer) {
1405
+ clearTimeout(this.idleTimer);
1406
+ this.idleTimer = null;
1407
+ }
1408
+ }
1409
+ /**
1410
+ * 收尾:清 timer / 终止进程组 / 判定是否需要历史重放。
1411
+ * 幂等(并发调用复用同一次收尾),且绝不残留监听器(peer.dispose 会先让所有 pending 请求失败)。
1412
+ */
1413
+ async terminate(reason) {
1414
+ const inFlight = this.terminatePromise;
1415
+ if (inFlight) return inFlight;
1416
+ const running = this.doTerminate(reason).finally(() => {
1417
+ this.terminatePromise = null;
1418
+ });
1419
+ this.terminatePromise = running;
1420
+ return running;
1421
+ }
1422
+ async doTerminate(reason) {
1423
+ this.terminating = true;
1424
+ try {
1425
+ await this.terminateProcess(reason);
1426
+ } finally {
1427
+ this.terminating = false;
1428
+ }
1429
+ }
1430
+ async terminateProcess(reason) {
1431
+ this.clearIdleTimer();
1432
+ this.clearTerminals();
1433
+ const proc = this.proc;
1434
+ const peer = this.peer;
1435
+ this.proc = null;
1436
+ this.peer = null;
1437
+ this.acpSessionId = null;
1438
+ this.state = "closed";
1439
+ this.needsContextReplay = this.history.length > 0;
1440
+ this.updateHandlers = null;
1441
+ peer?.dispose(new Error(`agy ACP session closed (${reason})`));
1442
+ if (proc) {
1443
+ proc.removeAllListeners("exit");
1444
+ proc.removeAllListeners("error");
1445
+ proc.stdout?.removeAllListeners("data");
1446
+ proc.stderr?.removeAllListeners("data");
1447
+ proc.on("error", () => {
1448
+ });
1449
+ const stopped = terminateCliProcessGroupEscalating(proc).catch(() => void 0);
1450
+ await Promise.race([
1451
+ stopped,
1452
+ new Promise((resolvePromise) => {
1453
+ const timer = setTimeout(resolvePromise, 12e3);
1454
+ timer.unref?.();
1455
+ })
1456
+ ]);
1457
+ }
1458
+ }
1459
+ };
1460
+ var agyAcpSessions = /* @__PURE__ */ new Map();
1461
+ function isAgyAcpEnabled(env = process.env) {
1462
+ const raw = (env.NOLO_AGY_ACP ?? "").trim().toLowerCase();
1463
+ return !(raw === "0" || raw === "false" || raw === "off" || raw === "no");
1464
+ }
1465
+ function liveSessionCount() {
1466
+ let count = 0;
1467
+ for (const session of agyAcpSessions.values()) {
1468
+ if (session.isOccupyingSlot()) count += 1;
1469
+ }
1470
+ return count;
1471
+ }
1472
+ function hasActiveAgyAcpSession() {
1473
+ return liveSessionCount() > 0;
1474
+ }
1475
+ function assertAgyPrintAllowed(label) {
1476
+ if (!hasActiveAgyAcpSession()) return;
1477
+ throw new CliProviderQuotaError(
1478
+ "agy",
1479
+ `${label} blocked: an agy ACP session is active on this machine. Local agy runs only one stable delegated session at a time; wait for the interactive session to finish (or close that dialog) and retry, or dispatch to another provider.`
1480
+ );
1481
+ }
1482
+ function getAgyAcpSession(key, config) {
1483
+ const existing = agyAcpSessions.get(key);
1484
+ if (existing) {
1485
+ existing.updateConfig(config);
1486
+ return existing;
1487
+ }
1488
+ if (liveSessionCount() > 0) {
1489
+ throw new CliProviderQuotaError(
1490
+ "agy",
1491
+ "another agy ACP session is already active on this machine. Local agy runs only one stable delegated session at a time; finish or close it first, or use another provider."
1492
+ );
1493
+ }
1494
+ const created = new AgyAcpSession(key, config);
1495
+ agyAcpSessions.set(key, created);
1496
+ return created;
1497
+ }
1498
+ function closeAgyAcpSession(key) {
1499
+ const entries = key === void 0 ? [...agyAcpSessions] : [[key, agyAcpSessions.get(key)]];
1500
+ const closing = [];
1501
+ for (const [sessionKey, session] of entries) {
1502
+ if (!session) continue;
1503
+ session.retire();
1504
+ closing.push(
1505
+ session.terminate(key === void 0 ? "registry-close-all" : "registry-close").finally(() => {
1506
+ if (agyAcpSessions.get(sessionKey) === session) agyAcpSessions.delete(sessionKey);
1507
+ })
1508
+ );
1509
+ }
1510
+ return Promise.all(closing).then(() => void 0);
1511
+ }
1512
+
514
1513
  // packages/ai/agent/cliExecutor.ts
515
1514
  var CliProviderQuotaError = class extends Error {
516
1515
  provider;
@@ -681,7 +1680,7 @@ function writeDataUrlToTempImage(dataUrl, tempDir, index) {
681
1680
  const [, mimeExt, b64] = match;
682
1681
  const ext = inferExtFromMime(mimeExt);
683
1682
  const filePath = join(tempDir, `image-${index + 1}${ext}`);
684
- writeFileSync(filePath, Buffer.from(b64, "base64"));
1683
+ writeFileSync2(filePath, Buffer.from(b64, "base64"));
685
1684
  return filePath;
686
1685
  }
687
1686
  function materializeCliImageInputs(imageInputs, cwd) {
@@ -696,7 +1695,7 @@ function materializeCliImageInputs(imageInputs, cwd) {
696
1695
  const localPath = fileUrlMatch[1];
697
1696
  return {
698
1697
  ...input,
699
- materializedPath: isAbsolute(localPath) ? localPath : resolve(cwd, localPath)
1698
+ materializedPath: isAbsolute2(localPath) ? localPath : resolve2(cwd, localPath)
700
1699
  };
701
1700
  }
702
1701
  if (src.startsWith("data:")) {
@@ -708,7 +1707,7 @@ function materializeCliImageInputs(imageInputs, cwd) {
708
1707
  }
709
1708
  return {
710
1709
  ...input,
711
- materializedPath: isAbsolute(src) ? src : resolve(cwd, src)
1710
+ materializedPath: isAbsolute2(src) ? src : resolve2(cwd, src)
712
1711
  };
713
1712
  });
714
1713
  return { materialized, tempDir };
@@ -815,7 +1814,7 @@ function executeCopilot(prompt, options) {
815
1814
  cwd = process.cwd(),
816
1815
  yolo = true
817
1816
  } = options;
818
- return new Promise((resolve2, reject) => {
1817
+ return new Promise((resolve3, reject) => {
819
1818
  const args = [
820
1819
  "copilot",
821
1820
  "--",
@@ -830,25 +1829,16 @@ function executeCopilot(prompt, options) {
830
1829
  if (model) args.push("--model", model);
831
1830
  if (reasoningEffort) args.push("--reasoning-effort", reasoningEffort);
832
1831
  if (yolo) args.push("--yolo");
833
- const start = Date.now();
834
- execFile(
1832
+ runBufferedCli(
1833
+ "Copilot",
835
1834
  "gh",
836
1835
  args,
837
- { timeout, cwd, env: { ...buildCliProcessEnv(options.env), NO_COLOR: "1" } },
838
- (error, stdout, stderr) => {
839
- if (error) {
840
- if (error.killed && error.signal === "SIGTERM") {
841
- return reject(new Error(`Copilot CLI timed out after ${timeout}ms`));
842
- }
843
- return reject(
844
- new Error(`Copilot CLI failed: ${error.message}
845
- stderr: ${stderr}`)
846
- );
847
- }
848
- const text = stdout.split("\n").filter((l) => !l.includes("A new release of gh is available")).filter((l) => !l.includes("To upgrade, run:")).filter((l) => !l.includes("https://github.com/cli/cli/releases")).join("\n").trim();
849
- resolve2({ text, raw: stdout, elapsed: Date.now() - start });
850
- }
851
- );
1836
+ cwd,
1837
+ { ...buildCliProcessEnv(options.env), NO_COLOR: "1" },
1838
+ timeout,
1839
+ options.signal,
1840
+ (stdout) => stdout.split("\n").filter((line) => !line.includes("A new release of gh is available") && !line.includes("To upgrade, run:") && !line.includes("https://github.com/cli/cli/releases")).join("\n").trim()
1841
+ ).then(resolve3, reject);
852
1842
  });
853
1843
  }
854
1844
  function normalizeGeminiContent(content) {
@@ -894,25 +1884,25 @@ function resolveGeminiCommand(env, platform = process.platform) {
894
1884
  if (platform !== "win32") return { command: "gemini", args: [] };
895
1885
  const path = Object.entries(env).find(([key]) => key.toLowerCase() === "path")?.[1] ?? "";
896
1886
  for (const directory of path.split(";")) {
897
- if (!directory || !isAbsolute(directory)) continue;
898
- if (existsSync(join(directory, "gemini.exe"))) {
1887
+ if (!directory || !isAbsolute2(directory)) continue;
1888
+ if (existsSync2(join(directory, "gemini.exe"))) {
899
1889
  return { command: join(directory, "gemini.exe"), args: [] };
900
1890
  }
901
- if (!existsSync(join(directory, "gemini.cmd"))) continue;
1891
+ if (!existsSync2(join(directory, "gemini.cmd"))) continue;
902
1892
  try {
903
- const root = realpathSync(join(directory, "node_modules", "@google", "gemini-cli"));
904
- const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1893
+ const root = realpathSync2(join(directory, "node_modules", "@google", "gemini-cli"));
1894
+ const manifest = JSON.parse(readFileSync2(join(root, "package.json"), "utf8"));
905
1895
  const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.gemini;
906
1896
  if (manifest.name !== "@google/gemini-cli" || typeof bin !== "string" || !bin) {
907
1897
  throw new Error("missing package bin");
908
1898
  }
909
- const entry = realpathSync(resolve(root, bin));
910
- const withinPackage = relative(root, entry);
911
- if (withinPackage.startsWith("..") || isAbsolute(withinPackage) || !/\.[cm]?js$/i.test(entry)) {
1899
+ const entry = realpathSync2(resolve2(root, bin));
1900
+ const withinPackage = relative2(root, entry);
1901
+ if (withinPackage.startsWith("..") || isAbsolute2(withinPackage) || !/\.[cm]?js$/i.test(entry)) {
912
1902
  throw new Error("package bin is not a contained JavaScript entry");
913
1903
  }
914
1904
  const node = join(directory, "node.exe");
915
- return { command: existsSync(node) ? node : "node", args: [entry] };
1905
+ return { command: existsSync2(node) ? node : "node", args: [entry] };
916
1906
  } catch (error) {
917
1907
  throw new Error(`Gemini npm entry could not be resolved: ${String(error)}`);
918
1908
  }
@@ -926,7 +1916,7 @@ function executeGemini(prompt, options) {
926
1916
  cwd = process.cwd(),
927
1917
  yolo = true
928
1918
  } = options;
929
- return new Promise((resolve2, reject) => {
1919
+ return new Promise((resolve3, reject) => {
930
1920
  const args = [
931
1921
  "-p",
932
1922
  prompt,
@@ -937,30 +1927,18 @@ function executeGemini(prompt, options) {
937
1927
  ];
938
1928
  if (yolo) args.push("--yolo");
939
1929
  args.push("-e", "none");
940
- const start = Date.now();
941
1930
  const env = { ...buildCliProcessEnv(options.env), NO_COLOR: "1", NODE_OPTIONS: "--no-deprecation" };
942
1931
  const launcher = resolveGeminiCommand(env);
943
- execFile(
1932
+ runBufferedCli(
1933
+ "Gemini",
944
1934
  launcher.command,
945
1935
  [...launcher.args, ...args],
946
- { timeout, cwd, env },
947
- (error, stdout, stderr) => {
948
- if (error) {
949
- if (error.killed && error.signal === "SIGTERM") {
950
- return reject(new Error(`Gemini CLI timed out after ${timeout}ms`));
951
- }
952
- return reject(
953
- new Error(`Gemini CLI failed: ${error.message}
954
- stderr: ${stderr}`)
955
- );
956
- }
957
- resolve2({
958
- text: parseGeminiStreamJson(stdout),
959
- raw: stdout,
960
- elapsed: Date.now() - start
961
- });
962
- }
963
- );
1936
+ cwd,
1937
+ env,
1938
+ timeout,
1939
+ options.signal,
1940
+ parseGeminiStreamJson
1941
+ ).then(resolve3, reject);
964
1942
  });
965
1943
  }
966
1944
  function executeCodex(prompt, options) {
@@ -969,7 +1947,7 @@ function executeCodex(prompt, options) {
969
1947
  yolo = true
970
1948
  } = options;
971
1949
  const imagePaths = (options.imageInputs ?? []).map((img) => img.materializedPath).filter((p) => Boolean(p));
972
- return new Promise((resolve2, reject) => {
1950
+ return new Promise((resolve3, reject) => {
973
1951
  const tempDir = mkdtempSync(join(tmpdir(), "codex-exec-"));
974
1952
  const outputFile = join(tempDir, "last-message.txt");
975
1953
  const executable = resolveLaunchableCodexCommand(options.env);
@@ -997,7 +1975,7 @@ function executeCodex(prompt, options) {
997
1975
  env: buildCliProcessEnv(options.env),
998
1976
  stdio: ["ignore", "pipe", "pipe"],
999
1977
  signal: options.signal
1000
- });
1978
+ }, reject);
1001
1979
  const stdout = createUtf8Collector();
1002
1980
  const stderr = createUtf8Collector();
1003
1981
  proc.stdout.on("data", (data) => {
@@ -1006,29 +1984,29 @@ function executeCodex(prompt, options) {
1006
1984
  proc.stderr.on("data", (data) => {
1007
1985
  stderr.write(data);
1008
1986
  });
1009
- proc.on("close", (code) => {
1987
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
1010
1988
  const stdoutText = stdout.end();
1011
1989
  const stderrText = stderr.end();
1012
1990
  if (code !== 0 && code !== null) {
1013
1991
  rmSync(tempDir, { recursive: true, force: true });
1014
1992
  const quota = detectCliProviderQuotaLimit("codex", stdoutText, stderrText, code);
1015
1993
  if (quota.limited) {
1016
- reject(new CliProviderQuotaError("codex", quota.message || "Codex reported quota/limit"));
1994
+ reject2(new CliProviderQuotaError("codex", quota.message || "Codex reported quota/limit"));
1017
1995
  return;
1018
1996
  }
1019
- reject(new Error(`Codex CLI exited with code ${code}
1997
+ reject2(new Error(`Codex CLI exited with code ${code}
1020
1998
  stderr: ${stderrText}`));
1021
1999
  return;
1022
2000
  }
1023
2001
  let text = stdoutText.trim();
1024
2002
  try {
1025
- const lastMessage = readFileSync(outputFile, "utf8").trim();
2003
+ const lastMessage = readFileSync2(outputFile, "utf8").trim();
1026
2004
  if (lastMessage) text = lastMessage;
1027
2005
  } catch {
1028
2006
  } finally {
1029
2007
  rmSync(tempDir, { recursive: true, force: true });
1030
2008
  }
1031
- resolve2({
2009
+ resolve4({
1032
2010
  text,
1033
2011
  raw: stdoutText,
1034
2012
  elapsed: Date.now() - start
@@ -1036,7 +2014,7 @@ stderr: ${stderrText}`));
1036
2014
  });
1037
2015
  proc.on("error", (err) => {
1038
2016
  rmSync(tempDir, { recursive: true, force: true });
1039
- reject(err);
2017
+ reject(proc.pid ? stoppingCliError(err, proc) : err);
1040
2018
  });
1041
2019
  });
1042
2020
  }
@@ -1049,7 +2027,7 @@ function executeClaude(prompt, options) {
1049
2027
  cwd = process.cwd(),
1050
2028
  yolo = true
1051
2029
  } = options;
1052
- return new Promise((resolve2, reject) => {
2030
+ return new Promise((resolve3, reject) => {
1053
2031
  const args = ["--add-dir", cwd, "-p", prompt];
1054
2032
  if (model && shouldPassClaudeModel(options)) {
1055
2033
  args.push("--model");
@@ -1073,14 +2051,13 @@ function executeClaude(prompt, options) {
1073
2051
  env: buildCliProcessEnv(options.env),
1074
2052
  stdio: ["ignore", "pipe", "pipe"],
1075
2053
  signal: options.signal
1076
- });
2054
+ }, reject);
1077
2055
  const stdout = createUtf8Collector();
1078
2056
  const stderr = createUtf8Collector();
1079
2057
  let timer;
1080
2058
  if (timeout > 0) {
1081
2059
  timer = setTimeout(() => {
1082
- proc.kill("SIGTERM");
1083
- reject(new Error(`Claude CLI timed out after ${timeout}ms`));
2060
+ reject(stoppingCliError(new Error(`Claude CLI timed out after ${timeout}ms`), proc));
1084
2061
  }, timeout);
1085
2062
  }
1086
2063
  proc.stdout.on("data", (data) => {
@@ -1089,21 +2066,21 @@ function executeClaude(prompt, options) {
1089
2066
  proc.stderr.on("data", (data) => {
1090
2067
  stderr.write(data);
1091
2068
  });
1092
- proc.on("close", (code) => {
2069
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
1093
2070
  if (timer) clearTimeout(timer);
1094
2071
  const stdoutText = stdout.end();
1095
2072
  const stderrText = stderr.end();
1096
2073
  if (code !== 0 && code !== null) {
1097
2074
  const quota = detectCliProviderQuotaLimit("claude", stdoutText, stderrText, code);
1098
2075
  if (quota.limited) {
1099
- reject(new CliProviderQuotaError("claude", quota.message || "Claude reported quota/limit"));
2076
+ reject2(new CliProviderQuotaError("claude", quota.message || "Claude reported quota/limit"));
1100
2077
  return;
1101
2078
  }
1102
- reject(new Error(`Claude CLI exited with code ${code}
2079
+ reject2(new Error(`Claude CLI exited with code ${code}
1103
2080
  stderr: ${stderrText}`));
1104
2081
  return;
1105
2082
  }
1106
- resolve2({
2083
+ resolve4({
1107
2084
  text: stdoutText.trim(),
1108
2085
  raw: stdoutText,
1109
2086
  elapsed: Date.now() - start
@@ -1111,7 +2088,7 @@ stderr: ${stderrText}`));
1111
2088
  });
1112
2089
  proc.on("error", (err) => {
1113
2090
  if (timer) clearTimeout(timer);
1114
- reject(err);
2091
+ reject(proc.pid ? stoppingCliError(err, proc) : err);
1115
2092
  });
1116
2093
  });
1117
2094
  }
@@ -1123,7 +2100,7 @@ function tailText(value, maxChars = 1200) {
1123
2100
  return value.slice(value.length - maxChars);
1124
2101
  }
1125
2102
  function createUtf8Collector() {
1126
- const decoder = new StringDecoder("utf8");
2103
+ const decoder = new StringDecoder2("utf8");
1127
2104
  let text = "";
1128
2105
  let ended = false;
1129
2106
  const finish = () => {
@@ -1151,7 +2128,7 @@ function createUtf8Collector() {
1151
2128
  };
1152
2129
  }
1153
2130
  var CLI_ABORT_SIGKILL_GRACE_MS = 5e3;
1154
- function terminateCliProcessGroup(proc, signal) {
2131
+ function terminateCliProcessGroup(proc, signal, onWindowsTreeStopped) {
1155
2132
  const pid = typeof proc.pid === "number" ? proc.pid : 0;
1156
2133
  if (pid > 0 && process.platform !== "win32") {
1157
2134
  try {
@@ -1162,13 +2139,16 @@ function terminateCliProcessGroup(proc, signal) {
1162
2139
  }
1163
2140
  if (pid > 0 && process.platform === "win32") {
1164
2141
  try {
1165
- const killer = spawn2("taskkill", ["/pid", String(pid), "/T", "/F"], {
2142
+ const killer = spawn3("taskkill", ["/pid", String(pid), "/T", "/F"], {
1166
2143
  stdio: "ignore",
1167
2144
  windowsHide: true
1168
2145
  });
1169
2146
  killer.on("error", () => {
1170
2147
  });
1171
- killer.unref?.();
2148
+ killer.once("close", (code) => {
2149
+ if (code === 0) onWindowsTreeStopped();
2150
+ });
2151
+ return;
1172
2152
  } catch {
1173
2153
  }
1174
2154
  }
@@ -1177,12 +2157,98 @@ function terminateCliProcessGroup(proc, signal) {
1177
2157
  } catch {
1178
2158
  }
1179
2159
  }
2160
+ var executionStopped = Symbol.for("nolo.cli.executionStopped");
2161
+ function attachExecutionStoppedPromise(error, stoppedPromise) {
2162
+ Object.defineProperty(error, executionStopped, { value: stoppedPromise, configurable: true, enumerable: true });
2163
+ return error;
2164
+ }
2165
+ function getExecutionStoppedPromise(error) {
2166
+ const seen = /* @__PURE__ */ new Set();
2167
+ const visit = (value) => {
2168
+ if (typeof value !== "object" || value === null || seen.has(value)) return;
2169
+ seen.add(value);
2170
+ const entry = value;
2171
+ if (entry[executionStopped]) return entry[executionStopped];
2172
+ const pending = [visit(entry.cause), ...value instanceof AggregateError ? value.errors.map(visit) : []].filter((promise) => promise !== void 0);
2173
+ return pending.length ? Promise.all(pending).then(() => {
2174
+ }) : void 0;
2175
+ };
2176
+ return visit(error);
2177
+ }
2178
+ var unconfirmedWindowsClose = new Promise(() => {
2179
+ });
2180
+ var stoppingProcesses = /* @__PURE__ */ new WeakMap();
1180
2181
  function terminateCliProcessGroupEscalating(proc) {
1181
- terminateCliProcessGroup(proc, "SIGTERM");
1182
- const escalate = setTimeout(() => {
1183
- terminateCliProcessGroup(proc, "SIGKILL");
1184
- }, CLI_ABORT_SIGKILL_GRACE_MS);
1185
- escalate.unref?.();
2182
+ const existing = stoppingProcesses.get(proc);
2183
+ if (existing) return existing;
2184
+ const { promise, resolve: resolve3 } = Promise.withResolvers();
2185
+ stoppingProcesses.set(proc, promise);
2186
+ const pid = proc.pid;
2187
+ if (!pid) {
2188
+ terminateCliProcessGroup(proc, "SIGTERM", () => {
2189
+ });
2190
+ resolve3();
2191
+ return promise;
2192
+ }
2193
+ const startedAt = performance.now();
2194
+ let escalated = false;
2195
+ let windowsTreeStopped = false;
2196
+ const markWindowsTreeStopped = () => {
2197
+ windowsTreeStopped = true;
2198
+ };
2199
+ let timer;
2200
+ const inspect = () => {
2201
+ let groupEmpty = windowsTreeStopped;
2202
+ if (process.platform !== "win32") {
2203
+ try {
2204
+ process.kill(-pid, 0);
2205
+ } catch (error) {
2206
+ groupEmpty = error.code === "ESRCH";
2207
+ }
2208
+ }
2209
+ if (groupEmpty && (proc.exitCode != null || proc.signalCode != null)) {
2210
+ clearInterval(timer);
2211
+ resolve3();
2212
+ return;
2213
+ }
2214
+ const elapsed = performance.now() - startedAt;
2215
+ if (!escalated && elapsed >= CLI_ABORT_SIGKILL_GRACE_MS) {
2216
+ escalated = true;
2217
+ terminateCliProcessGroup(proc, "SIGKILL", markWindowsTreeStopped);
2218
+ }
2219
+ if (elapsed >= CLI_ABORT_SIGKILL_GRACE_MS + 1e4) {
2220
+ clearInterval(timer);
2221
+ console.warn("[cliExecutor] Could not confirm CLI process group shutdown", { pid });
2222
+ }
2223
+ };
2224
+ terminateCliProcessGroup(proc, "SIGTERM", markWindowsTreeStopped);
2225
+ timer = setInterval(inspect, 25);
2226
+ timer.unref?.();
2227
+ inspect();
2228
+ return promise;
2229
+ }
2230
+ function onCliClose(proc, resolve3, reject, settle) {
2231
+ proc.on("close", (code, signal) => {
2232
+ let stopped = stoppingProcesses.get(proc);
2233
+ if (!stopped && proc.pid && process.platform === "win32") {
2234
+ stopped = unconfirmedWindowsClose;
2235
+ } else if (!stopped && proc.pid) {
2236
+ try {
2237
+ process.kill(-proc.pid, 0);
2238
+ stopped = terminateCliProcessGroupEscalating(proc);
2239
+ } catch (error) {
2240
+ if (error.code !== "ESRCH") stopped = terminateCliProcessGroupEscalating(proc);
2241
+ }
2242
+ }
2243
+ const annotate = (value) => stopped ? attachExecutionStoppedPromise(value, stopped) : value;
2244
+ settle((value) => resolve3(annotate(value)), (error) => reject(stopped ? annotate(error instanceof Error ? error : new Error(String(error))) : error), code, signal);
2245
+ });
2246
+ }
2247
+ function stoppingCliError(error, proc) {
2248
+ return attachExecutionStoppedPromise(
2249
+ error instanceof Error ? error : new Error(String(error)),
2250
+ terminateCliProcessGroupEscalating(proc)
2251
+ );
1186
2252
  }
1187
2253
  function createCliAbortError(message = "CLI execution aborted") {
1188
2254
  return new DOMException(message, "AbortError");
@@ -1190,32 +2256,55 @@ function createCliAbortError(message = "CLI execution aborted") {
1190
2256
  function attachCliAbortSignal(proc, signal, onAbort) {
1191
2257
  if (!signal) return () => {
1192
2258
  };
2259
+ const handleAbort = () => onAbort(stoppingCliError(createCliAbortError(), proc));
1193
2260
  if (signal.aborted) {
1194
- terminateCliProcessGroupEscalating(proc);
1195
- onAbort(createCliAbortError());
2261
+ handleAbort();
1196
2262
  return () => {
1197
2263
  };
1198
2264
  }
1199
- const handleAbort = () => {
1200
- terminateCliProcessGroupEscalating(proc);
1201
- onAbort(createCliAbortError());
1202
- };
1203
2265
  signal.addEventListener("abort", handleAbort, { once: true });
1204
2266
  return () => signal.removeEventListener("abort", handleAbort);
1205
2267
  }
1206
- function spawnCliProcess(executable, args, options) {
2268
+ function spawnCliProcess(executable, args, options, onAbort) {
1207
2269
  const { signal, ...spawnOptions } = options;
1208
- const proc = spawn2(executable, args, {
2270
+ const proc = spawn3(executable, args, {
1209
2271
  ...spawnOptions,
1210
- ...signal ? { detached: true } : {}
2272
+ detached: process.platform !== "win32"
1211
2273
  });
1212
2274
  if (signal) {
1213
- const detachAbort = attachCliAbortSignal(proc, signal, () => {
1214
- });
2275
+ const detachAbort = attachCliAbortSignal(proc, signal, onAbort ?? (() => {
2276
+ }));
1215
2277
  proc.once("exit", detachAbort);
1216
2278
  }
1217
2279
  return proc;
1218
2280
  }
2281
+ function runBufferedCli(label, executable, args, cwd, env, timeout, signal, parseText) {
2282
+ return new Promise((resolve3, reject) => {
2283
+ const start = Date.now();
2284
+ const stdout = createUtf8Collector();
2285
+ const stderr = createUtf8Collector();
2286
+ let timer;
2287
+ const fail = (error) => {
2288
+ if (timer) clearTimeout(timer);
2289
+ reject(error);
2290
+ };
2291
+ const proc = spawnCliProcess(executable, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], signal }, fail);
2292
+ if (timeout > 0 && !signal?.aborted) timer = setTimeout(() => fail(stoppingCliError(new Error(`${label} CLI timed out after ${timeout}ms`), proc)), timeout);
2293
+ proc.stdout.on("data", (chunk) => stdout.write(chunk));
2294
+ proc.stderr.on("data", (chunk) => stderr.write(chunk));
2295
+ proc.on("error", (error) => fail(proc.pid ? stoppingCliError(error, proc) : error));
2296
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code, exitSignal) => {
2297
+ if (timer) clearTimeout(timer);
2298
+ if (code !== 0 || exitSignal) {
2299
+ reject2(new Error(`${label} CLI failed: ${exitSignal ?? code}
2300
+ stderr: ${stderr.end()}`));
2301
+ return;
2302
+ }
2303
+ const raw = stdout.end();
2304
+ resolve4({ text: parseText(raw), raw, elapsed: Date.now() - start });
2305
+ });
2306
+ });
2307
+ }
1219
2308
  function buildAgyTimeoutError(timeout, stdout, stderr) {
1220
2309
  const parts = [
1221
2310
  `Antigravity CLI timed out after ${timeout}ms.`,
@@ -1236,7 +2325,8 @@ function executeAgy(prompt, options) {
1236
2325
  yolo = true,
1237
2326
  reasoningEffort
1238
2327
  } = options;
1239
- return new Promise((resolve2, reject) => {
2328
+ assertAgyPrintAllowed("agy --print");
2329
+ return new Promise((resolve3, reject) => {
1240
2330
  const args = [
1241
2331
  "--add-dir",
1242
2332
  cwd,
@@ -1259,25 +2349,19 @@ function executeAgy(prompt, options) {
1259
2349
  stdio: ["ignore", "pipe", "pipe"],
1260
2350
  detached: process.platform !== "win32",
1261
2351
  signal: options.signal
1262
- });
2352
+ }, reject);
1263
2353
  const stdout = createUtf8Collector();
1264
2354
  const stderr = createUtf8Collector();
1265
2355
  let timer;
1266
- let forceTimer;
1267
2356
  let settled = false;
1268
2357
  const clearTimers = () => {
1269
2358
  if (timer) clearTimeout(timer);
1270
- if (forceTimer) clearTimeout(forceTimer);
1271
2359
  };
1272
2360
  if (timeout > 0) {
1273
2361
  timer = setTimeout(() => {
1274
2362
  if (settled) return;
1275
2363
  settled = true;
1276
- terminateCliProcessGroup(proc, "SIGTERM");
1277
- forceTimer = setTimeout(() => {
1278
- terminateCliProcessGroup(proc, "SIGKILL");
1279
- }, 3e3);
1280
- reject(buildAgyTimeoutError(timeout, stdout.end(), stderr.end()));
2364
+ reject(stoppingCliError(buildAgyTimeoutError(timeout, stdout.end(), stderr.end()), proc));
1281
2365
  }, timeout + 1e3);
1282
2366
  }
1283
2367
  proc.stdout.on("data", (data) => {
@@ -1286,7 +2370,7 @@ function executeAgy(prompt, options) {
1286
2370
  proc.stderr.on("data", (data) => {
1287
2371
  stderr.write(data);
1288
2372
  });
1289
- proc.on("close", (code) => {
2373
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
1290
2374
  if (settled) {
1291
2375
  clearTimers();
1292
2376
  return;
@@ -1299,15 +2383,15 @@ function executeAgy(prompt, options) {
1299
2383
  console.error("[cliExecutor] agy process exited with non-zero code:", code, "stderr:", stderrText);
1300
2384
  const quota = detectCliProviderQuotaLimit("agy", stdoutText, stderrText, code);
1301
2385
  if (quota.limited) {
1302
- reject(new CliProviderQuotaError("agy", quota.message || "Agy reported quota/limit"));
2386
+ reject2(new CliProviderQuotaError("agy", quota.message || "Agy reported quota/limit"));
1303
2387
  return;
1304
2388
  }
1305
- reject(new Error(`Antigravity CLI exited with code ${code}
2389
+ reject2(new Error(`Antigravity CLI exited with code ${code}
1306
2390
  stderr: ${stderrText}`));
1307
2391
  return;
1308
2392
  }
1309
2393
  const parsed = parseAgyJsonResult(stdoutText);
1310
- resolve2({
2394
+ resolve4({
1311
2395
  text: (parsed?.response ?? stdoutText).trim(),
1312
2396
  raw: stdoutText,
1313
2397
  elapsed: Date.now() - start,
@@ -1319,7 +2403,7 @@ stderr: ${stderrText}`));
1319
2403
  settled = true;
1320
2404
  clearTimers();
1321
2405
  console.error("[cliExecutor] agy process error event:", err);
1322
- reject(err);
2406
+ reject(proc.pid ? stoppingCliError(err, proc) : err);
1323
2407
  });
1324
2408
  });
1325
2409
  }
@@ -1332,7 +2416,8 @@ function executeAgyStreaming(prompt, options) {
1332
2416
  reasoningEffort,
1333
2417
  onChunk
1334
2418
  } = options;
1335
- return new Promise((resolve2, reject) => {
2419
+ assertAgyPrintAllowed("agy --print");
2420
+ return new Promise((resolve3, reject) => {
1336
2421
  const args = [
1337
2422
  "--add-dir",
1338
2423
  cwd,
@@ -1371,8 +2456,7 @@ function executeAgyStreaming(prompt, options) {
1371
2456
  };
1372
2457
  const fail = (error) => {
1373
2458
  if (settled) return;
1374
- terminateCliProcessGroupEscalating(proc);
1375
- finish(() => reject(error));
2459
+ finish(() => reject(stoppingCliError(error, proc)));
1376
2460
  };
1377
2461
  detachAbort = attachCliAbortSignal(proc, options.signal, (error) => {
1378
2462
  finish(() => reject(error));
@@ -1413,7 +2497,7 @@ function executeAgyStreaming(prompt, options) {
1413
2497
  proc.stderr.on("data", (data) => {
1414
2498
  if (!settled) stderr.write(data);
1415
2499
  });
1416
- proc.on("close", (code, signal) => {
2500
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code, signal) => {
1417
2501
  if (settled) return;
1418
2502
  pending += stdout.finish();
1419
2503
  consumeLine(pending);
@@ -1422,11 +2506,11 @@ function executeAgyStreaming(prompt, options) {
1422
2506
  const stderrText = stderr.end();
1423
2507
  if (code !== 0 || signal) {
1424
2508
  const quota = detectCliProviderQuotaLimit("agy", raw, stderrText, code);
1425
- finish(() => reject(quota.limited ? new CliProviderQuotaError("agy", quota.message || "Agy reported quota/limit") : new Error(`Antigravity CLI exited with ${signal ? `signal ${signal}` : `code ${code}`}
2509
+ finish(() => reject2(quota.limited ? new CliProviderQuotaError("agy", quota.message || "Agy reported quota/limit") : new Error(`Antigravity CLI exited with ${signal ? `signal ${signal}` : `code ${code}`}
1426
2510
  stderr: ${stderrText}`)));
1427
2511
  return;
1428
2512
  }
1429
- finish(() => resolve2({
2513
+ finish(() => resolve4({
1430
2514
  text: answer.trim(),
1431
2515
  raw,
1432
2516
  elapsed: Date.now() - start,
@@ -1444,7 +2528,7 @@ function executeQoder(prompt, options) {
1444
2528
  cwd = process.cwd(),
1445
2529
  yolo = true
1446
2530
  } = options;
1447
- return new Promise((resolve2, reject) => {
2531
+ return new Promise((resolve3, reject) => {
1448
2532
  const args = ["-p", prompt, "--cwd", cwd];
1449
2533
  if (model) {
1450
2534
  args.push("--model");
@@ -1463,7 +2547,7 @@ function executeQoder(prompt, options) {
1463
2547
  env: buildCliProcessEnv(options.env),
1464
2548
  stdio: ["ignore", "pipe", "pipe"],
1465
2549
  signal: options.signal
1466
- });
2550
+ }, reject);
1467
2551
  const stdout = createUtf8Collector();
1468
2552
  const stderr = createUtf8Collector();
1469
2553
  let timer;
@@ -1472,12 +2556,10 @@ function executeQoder(prompt, options) {
1472
2556
  const partial = stdout.end() + "\n" + stderr.end();
1473
2557
  const q = detectCliProviderQuotaLimit("qoder", "", partial, null);
1474
2558
  if (q.limited) {
1475
- proc.kill("SIGTERM");
1476
- reject(new CliProviderQuotaError("qoder", q.message || "Qoder quota signal seen before timeout"));
2559
+ reject(stoppingCliError(new CliProviderQuotaError("qoder", q.message || "Qoder quota signal seen before timeout"), proc));
1477
2560
  return;
1478
2561
  }
1479
- proc.kill("SIGTERM");
1480
- reject(new Error(`Qoder CLI timed out after ${timeout}ms`));
2562
+ reject(stoppingCliError(new Error(`Qoder CLI timed out after ${timeout}ms`), proc));
1481
2563
  }, timeout);
1482
2564
  }
1483
2565
  proc.stdout.on("data", (data) => {
@@ -1488,28 +2570,27 @@ function executeQoder(prompt, options) {
1488
2570
  const currentStderr = stderr.text;
1489
2571
  if (detectCliProviderQuotaLimit("qoder", "", currentStderr, null).limited) {
1490
2572
  if (timer) clearTimeout(timer);
1491
- proc.kill("SIGTERM");
1492
- reject(new CliProviderQuotaError("qoder", "quota signal detected incrementally in stderr"));
2573
+ reject(stoppingCliError(new CliProviderQuotaError("qoder", "quota signal detected incrementally in stderr"), proc));
1493
2574
  return;
1494
2575
  }
1495
2576
  });
1496
- proc.on("close", (code) => {
2577
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
1497
2578
  if (timer) clearTimeout(timer);
1498
2579
  const stdoutText = stdout.end();
1499
2580
  const stderrText = stderr.end();
1500
2581
  const quota = detectCliProviderQuotaLimit("qoder", stdoutText, stderrText, code);
1501
2582
  const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
1502
2583
  if (quota.limited && hasRealErrorSignal) {
1503
- reject(new CliProviderQuotaError("qoder", quota.message || "Qoder reported quota/limit"));
2584
+ reject2(new CliProviderQuotaError("qoder", quota.message || "Qoder reported quota/limit"));
1504
2585
  return;
1505
2586
  }
1506
2587
  if (code !== 0 && code !== null) {
1507
2588
  console.error("[cliExecutor] qoder process exited with non-zero code:", code, "stderr:", stderrText);
1508
- reject(new Error(`Qoder CLI exited with code ${code}
2589
+ reject2(new Error(`Qoder CLI exited with code ${code}
1509
2590
  stderr: ${stderrText}`));
1510
2591
  return;
1511
2592
  }
1512
- resolve2({
2593
+ resolve4({
1513
2594
  text: stdoutText.trim(),
1514
2595
  raw: stdoutText,
1515
2596
  elapsed: Date.now() - start
@@ -1518,7 +2599,7 @@ stderr: ${stderrText}`));
1518
2599
  proc.on("error", (err) => {
1519
2600
  if (timer) clearTimeout(timer);
1520
2601
  console.error("[cliExecutor] qoder process error event:", err);
1521
- reject(err);
2602
+ reject(proc.pid ? stoppingCliError(err, proc) : err);
1522
2603
  });
1523
2604
  });
1524
2605
  }
@@ -1545,7 +2626,7 @@ function executeOpenCode(prompt, options) {
1545
2626
  cwd = process.cwd(),
1546
2627
  yolo = true
1547
2628
  } = options;
1548
- return new Promise((resolve2, reject) => {
2629
+ return new Promise((resolve3, reject) => {
1549
2630
  const args = [
1550
2631
  "run",
1551
2632
  "--format",
@@ -1573,7 +2654,7 @@ function executeOpenCode(prompt, options) {
1573
2654
  env: buildCliProcessEnv(options.env),
1574
2655
  stdio: ["ignore", "pipe", "pipe"],
1575
2656
  signal: options.signal
1576
- });
2657
+ }, reject);
1577
2658
  const stdout = createUtf8Collector();
1578
2659
  const stderr = createUtf8Collector();
1579
2660
  let timer;
@@ -1583,12 +2664,10 @@ function executeOpenCode(prompt, options) {
1583
2664
  const stderrPartial = stderr.end();
1584
2665
  const q = detectCliProviderQuotaLimit("opencode", stdoutPartial, stderrPartial, null);
1585
2666
  if (q.limited) {
1586
- proc.kill("SIGTERM");
1587
- reject(new CliProviderQuotaError("opencode", q.message || "OpenCode quota signal seen before timeout"));
2667
+ reject(stoppingCliError(new CliProviderQuotaError("opencode", q.message || "OpenCode quota signal seen before timeout"), proc));
1588
2668
  return;
1589
2669
  }
1590
- proc.kill("SIGTERM");
1591
- reject(new Error(`OpenCode CLI timed out after ${timeout}ms`));
2670
+ reject(stoppingCliError(new Error(`OpenCode CLI timed out after ${timeout}ms`), proc));
1592
2671
  }, timeout);
1593
2672
  }
1594
2673
  proc.stdout.on("data", (data) => {
@@ -1599,28 +2678,27 @@ function executeOpenCode(prompt, options) {
1599
2678
  const currentStderr = stderr.text;
1600
2679
  if (detectCliProviderQuotaLimit("opencode", "", currentStderr, null).limited) {
1601
2680
  if (timer) clearTimeout(timer);
1602
- proc.kill("SIGTERM");
1603
- reject(new CliProviderQuotaError("opencode", "quota signal detected incrementally in stderr"));
2681
+ reject(stoppingCliError(new CliProviderQuotaError("opencode", "quota signal detected incrementally in stderr"), proc));
1604
2682
  return;
1605
2683
  }
1606
2684
  });
1607
- proc.on("close", (code) => {
2685
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
1608
2686
  if (timer) clearTimeout(timer);
1609
2687
  const stdoutText = stdout.end();
1610
2688
  const stderrText = stderr.end();
1611
2689
  const quota = detectCliProviderQuotaLimit("opencode", stdoutText, stderrText, code);
1612
2690
  const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
1613
2691
  if (quota.limited && hasRealErrorSignal) {
1614
- reject(new CliProviderQuotaError("opencode", quota.message || "OpenCode reported quota/limit"));
2692
+ reject2(new CliProviderQuotaError("opencode", quota.message || "OpenCode reported quota/limit"));
1615
2693
  return;
1616
2694
  }
1617
2695
  if (code !== 0 && code !== null) {
1618
2696
  console.error("[cliExecutor] opencode process exited with non-zero code:", code, "stderr:", stderrText);
1619
- reject(new Error(`OpenCode CLI exited with code ${code}
2697
+ reject2(new Error(`OpenCode CLI exited with code ${code}
1620
2698
  stderr: ${stderrText}`));
1621
2699
  return;
1622
2700
  }
1623
- resolve2({
2701
+ resolve4({
1624
2702
  text: parseOpenCodeJsonlEvents(stdoutText).trim(),
1625
2703
  raw: stdoutText,
1626
2704
  elapsed: Date.now() - start
@@ -1629,7 +2707,7 @@ stderr: ${stderrText}`));
1629
2707
  proc.on("error", (err) => {
1630
2708
  if (timer) clearTimeout(timer);
1631
2709
  console.error("[cliExecutor] opencode process error event:", err);
1632
- reject(err);
2710
+ reject(proc.pid ? stoppingCliError(err, proc) : err);
1633
2711
  });
1634
2712
  });
1635
2713
  }
@@ -1659,7 +2737,7 @@ function executeGrok(prompt, options) {
1659
2737
  cwd = process.cwd(),
1660
2738
  yolo = true
1661
2739
  } = options;
1662
- return new Promise((resolve2, reject) => {
2740
+ return new Promise((resolve3, reject) => {
1663
2741
  const args = ["-p", prompt, "--cwd", cwd, "--output-format", "json"];
1664
2742
  if (model) {
1665
2743
  args.push("-m", model);
@@ -1676,7 +2754,7 @@ function executeGrok(prompt, options) {
1676
2754
  env: buildGrokProcessEnv(options.env),
1677
2755
  stdio: ["ignore", "pipe", "pipe"],
1678
2756
  signal: options.signal
1679
- });
2757
+ }, reject);
1680
2758
  const stdout = createUtf8Collector();
1681
2759
  const stderr = createUtf8Collector();
1682
2760
  let timer;
@@ -1685,12 +2763,10 @@ function executeGrok(prompt, options) {
1685
2763
  const partial = stdout.end() + "\n" + stderr.end();
1686
2764
  const q = detectCliProviderQuotaLimit("grok", "", partial, null);
1687
2765
  if (q.limited) {
1688
- proc.kill("SIGTERM");
1689
- reject(new CliProviderQuotaError("grok", q.message || "Grok quota signal seen before timeout"));
2766
+ reject(stoppingCliError(new CliProviderQuotaError("grok", q.message || "Grok quota signal seen before timeout"), proc));
1690
2767
  return;
1691
2768
  }
1692
- proc.kill("SIGTERM");
1693
- reject(new Error(`Grok CLI timed out after ${timeout}ms`));
2769
+ reject(stoppingCliError(new Error(`Grok CLI timed out after ${timeout}ms`), proc));
1694
2770
  }, timeout);
1695
2771
  }
1696
2772
  proc.stdout.on("data", (data) => {
@@ -1701,41 +2777,40 @@ function executeGrok(prompt, options) {
1701
2777
  const currentStderr = stderr.text;
1702
2778
  if (detectCliProviderQuotaLimit("grok", "", currentStderr, null).limited) {
1703
2779
  if (timer) clearTimeout(timer);
1704
- proc.kill("SIGTERM");
1705
- reject(new CliProviderQuotaError("grok", "quota signal detected incrementally in stderr"));
2780
+ reject(stoppingCliError(new CliProviderQuotaError("grok", "quota signal detected incrementally in stderr"), proc));
1706
2781
  return;
1707
2782
  }
1708
2783
  });
1709
- proc.on("close", (code) => {
2784
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
1710
2785
  if (timer) clearTimeout(timer);
1711
2786
  const stdoutText = stdout.end();
1712
2787
  const stderrText = stderr.end();
1713
2788
  const quota = detectCliProviderQuotaLimit("grok", stdoutText, stderrText, code);
1714
2789
  const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
1715
2790
  if (quota.limited && hasRealErrorSignal) {
1716
- reject(new CliProviderQuotaError("grok", quota.message || "Grok reported quota/limit"));
2791
+ reject2(new CliProviderQuotaError("grok", quota.message || "Grok reported quota/limit"));
1717
2792
  return;
1718
2793
  }
1719
2794
  if (code !== 0 && code !== null) {
1720
2795
  console.error("[cliExecutor] grok process exited with non-zero code:", code, "stderr:", stderrText);
1721
- reject(new Error(`Grok CLI exited with code ${code}
2796
+ reject2(new Error(`Grok CLI exited with code ${code}
1722
2797
  stderr: ${stderrText}`));
1723
2798
  return;
1724
2799
  }
1725
2800
  try {
1726
- resolve2({
2801
+ resolve4({
1727
2802
  text: parseGrokJsonOutput(stdoutText).trim(),
1728
2803
  raw: stdoutText,
1729
2804
  elapsed: Date.now() - start
1730
2805
  });
1731
2806
  } catch (error) {
1732
- reject(error);
2807
+ reject2(error);
1733
2808
  }
1734
2809
  });
1735
2810
  proc.on("error", (err) => {
1736
2811
  if (timer) clearTimeout(timer);
1737
2812
  console.error("[cliExecutor] grok process error event:", err);
1738
- reject(err);
2813
+ reject(proc.pid ? stoppingCliError(err, proc) : err);
1739
2814
  });
1740
2815
  });
1741
2816
  }
@@ -1760,7 +2835,7 @@ function executeKimi(prompt, options) {
1760
2835
  timeout = 12e4,
1761
2836
  cwd = process.cwd()
1762
2837
  } = options;
1763
- return new Promise((resolve2, reject) => {
2838
+ return new Promise((resolve3, reject) => {
1764
2839
  const args = ["-p", prompt, "--output-format", "stream-json"];
1765
2840
  if (model) {
1766
2841
  args.push("-m", model);
@@ -1771,7 +2846,7 @@ function executeKimi(prompt, options) {
1771
2846
  env: buildCliProcessEnv(options.env),
1772
2847
  stdio: ["ignore", "pipe", "pipe"],
1773
2848
  signal: options.signal
1774
- });
2849
+ }, reject);
1775
2850
  const stdout = createUtf8Collector();
1776
2851
  const stderr = createUtf8Collector();
1777
2852
  let timer;
@@ -1780,12 +2855,10 @@ function executeKimi(prompt, options) {
1780
2855
  const partial = stdout.end() + "\n" + stderr.end();
1781
2856
  const q = detectCliProviderQuotaLimit("kimi", "", partial, null);
1782
2857
  if (q.limited) {
1783
- proc.kill("SIGTERM");
1784
- reject(new CliProviderQuotaError("kimi", q.message || "Kimi quota signal seen before timeout"));
2858
+ reject(stoppingCliError(new CliProviderQuotaError("kimi", q.message || "Kimi quota signal seen before timeout"), proc));
1785
2859
  return;
1786
2860
  }
1787
- proc.kill("SIGTERM");
1788
- reject(new Error(`Kimi CLI timed out after ${timeout}ms`));
2861
+ reject(stoppingCliError(new Error(`Kimi CLI timed out after ${timeout}ms`), proc));
1789
2862
  }, timeout);
1790
2863
  }
1791
2864
  proc.stdout.on("data", (data) => {
@@ -1796,28 +2869,27 @@ function executeKimi(prompt, options) {
1796
2869
  const currentStderr = stderr.text;
1797
2870
  if (detectCliProviderQuotaLimit("kimi", "", currentStderr, null).limited) {
1798
2871
  if (timer) clearTimeout(timer);
1799
- proc.kill("SIGTERM");
1800
- reject(new CliProviderQuotaError("kimi", "quota signal detected incrementally in stderr"));
2872
+ reject(stoppingCliError(new CliProviderQuotaError("kimi", "quota signal detected incrementally in stderr"), proc));
1801
2873
  return;
1802
2874
  }
1803
2875
  });
1804
- proc.on("close", (code) => {
2876
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
1805
2877
  if (timer) clearTimeout(timer);
1806
2878
  const stdoutText = stdout.end();
1807
2879
  const stderrText = stderr.end();
1808
2880
  const quota = detectCliProviderQuotaLimit("kimi", stdoutText, stderrText, code);
1809
2881
  const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
1810
2882
  if (quota.limited && hasRealErrorSignal) {
1811
- reject(new CliProviderQuotaError("kimi", quota.message || "Kimi reported quota/limit"));
2883
+ reject2(new CliProviderQuotaError("kimi", quota.message || "Kimi reported quota/limit"));
1812
2884
  return;
1813
2885
  }
1814
2886
  if (code !== 0 && code !== null) {
1815
2887
  console.error("[cliExecutor] kimi process exited with non-zero code:", code, "stderr:", stderrText);
1816
- reject(new Error(`Kimi CLI exited with code ${code}
2888
+ reject2(new Error(`Kimi CLI exited with code ${code}
1817
2889
  stderr: ${stderrText}`));
1818
2890
  return;
1819
2891
  }
1820
- resolve2({
2892
+ resolve4({
1821
2893
  text: parseKimiStreamJson(stdoutText).trim(),
1822
2894
  raw: stdoutText,
1823
2895
  elapsed: Date.now() - start
@@ -1826,7 +2898,7 @@ stderr: ${stderrText}`));
1826
2898
  proc.on("error", (err) => {
1827
2899
  if (timer) clearTimeout(timer);
1828
2900
  console.error("[cliExecutor] kimi process error event:", err);
1829
- reject(err);
2901
+ reject(proc.pid ? stoppingCliError(err, proc) : err);
1830
2902
  });
1831
2903
  });
1832
2904
  }
@@ -1918,14 +2990,62 @@ function getCliSession(sessionId) {
1918
2990
  return cliSessions.get(sessionId) ?? null;
1919
2991
  }
1920
2992
  function closeCliSession(sessionId) {
2993
+ void closeAgyAcpSession(sessionId).catch((error) => {
2994
+ console.warn("[cliExecutor] closeAgyAcpSession failed:", error);
2995
+ });
1921
2996
  return cliSessions.delete(sessionId);
1922
2997
  }
2998
+ async function executeAgyAcpTurn(session, userInput, options, onChunk) {
2999
+ const resolved = resolveCliExecution(session.provider, userInput, {
3000
+ ...session.options,
3001
+ ...options
3002
+ });
3003
+ try {
3004
+ const acp = getAgyAcpSession(session.sessionId, {
3005
+ cwd: resolved.options.cwd ?? process.cwd(),
3006
+ env: { ...session.options.env, ...resolved.options.env },
3007
+ model: resolved.options.model,
3008
+ // 用 resolveCliExecution 的产物:非原生 systemPrompt 的 provider 已经被内联进 prompt,
3009
+ // 这里再传一份会让 ACP 的 buildPromptText 前置第二次(首轮系统提示重复)。
3010
+ systemPrompt: resolved.options.systemPrompt,
3011
+ yolo: session.options.yolo
3012
+ });
3013
+ const result = await acp.prompt(resolved.prompt, {
3014
+ signal: resolved.options.signal,
3015
+ timeoutMs: resolved.options.timeout ?? DEFAULT_AGY_TIMEOUT_MS,
3016
+ ...onChunk ? { onChunk } : {},
3017
+ onToolEvent: resolved.options.onToolEvent,
3018
+ toolEventRound: resolved.options.toolEventRound
3019
+ });
3020
+ session.messages.push(
3021
+ { role: "user", content: userInput },
3022
+ { role: "assistant", content: result.text }
3023
+ );
3024
+ session.updatedAt = Date.now();
3025
+ const warnings = [...resolved.warnings, ...result.warnings ?? []];
3026
+ return {
3027
+ text: result.text,
3028
+ raw: result.raw,
3029
+ elapsed: result.elapsed,
3030
+ ...result.usage ? { usage: result.usage } : {},
3031
+ ...warnings.length > 0 ? { warnings } : {},
3032
+ sessionId: session.sessionId
3033
+ };
3034
+ } finally {
3035
+ if (resolved.imageTempDir) {
3036
+ rmSync(resolved.imageTempDir, { recursive: true, force: true });
3037
+ }
3038
+ }
3039
+ }
1923
3040
  async function executeCliSessionTurn(sessionId, userInput, options = {}) {
1924
3041
  const trimmedInput = userInput.trim();
1925
3042
  if (!trimmedInput) {
1926
3043
  throw new Error("CLI session turn requires non-empty user input.");
1927
3044
  }
1928
3045
  const session = getCliSessionOrThrow(sessionId);
3046
+ if (session.provider === "agy" && isAgyAcpEnabled()) {
3047
+ return executeAgyAcpTurn(session, trimmedInput, options);
3048
+ }
1929
3049
  const prompt = buildCliSessionPrompt(session, trimmedInput);
1930
3050
  const result = await executeCli(session.provider, prompt, {
1931
3051
  ...session.options,
@@ -1947,6 +3067,9 @@ async function executeCliSessionTurnStreaming(sessionId, userInput, options) {
1947
3067
  throw new Error("CLI session turn requires non-empty user input.");
1948
3068
  }
1949
3069
  const session = getCliSessionOrThrow(sessionId);
3070
+ if (session.provider === "agy" && isAgyAcpEnabled()) {
3071
+ return executeAgyAcpTurn(session, trimmedInput, options, options.onChunk);
3072
+ }
1950
3073
  const prompt = buildCliSessionPrompt(session, trimmedInput);
1951
3074
  const result = await executeCliStreaming(session.provider, prompt, {
1952
3075
  ...session.options,
@@ -2031,7 +3154,7 @@ function executeCliStreaming(provider, prompt, options) {
2031
3154
  yolo = true,
2032
3155
  onChunk
2033
3156
  } = resolved.options;
2034
- return withCleanup(new Promise((resolve2, reject) => {
3157
+ return withCleanup(new Promise((resolve3, reject) => {
2035
3158
  const args = [
2036
3159
  "copilot",
2037
3160
  "--",
@@ -2046,7 +3169,7 @@ function executeCliStreaming(provider, prompt, options) {
2046
3169
  }
2047
3170
  if (yolo) args.push("--yolo");
2048
3171
  const start = Date.now();
2049
- const proc = spawn2("gh", args, {
3172
+ const proc = spawn3("gh", args, {
2050
3173
  cwd,
2051
3174
  env: buildCliProcessEnv(resolved.options.env),
2052
3175
  ...resolved.options.signal ? { detached: true } : {}
@@ -2061,31 +3184,38 @@ function executeCliStreaming(provider, prompt, options) {
2061
3184
  detachAbort();
2062
3185
  cb();
2063
3186
  };
2064
- const detachAbort = attachCliAbortSignal(
3187
+ let detachAbort = () => {
3188
+ };
3189
+ detachAbort = attachCliAbortSignal(
2065
3190
  proc,
2066
3191
  resolved.options.signal,
2067
3192
  (error) => finish(() => reject(error))
2068
3193
  );
2069
3194
  if (timeout > 0) {
2070
3195
  timer = setTimeout(() => {
2071
- terminateCliProcessGroup(proc, "SIGTERM");
2072
- finish(() => reject(new Error(`Copilot CLI timed out after ${timeout}ms`)));
3196
+ finish(() => reject(stoppingCliError(new Error(`Copilot CLI timed out after ${timeout}ms`), proc)));
2073
3197
  }, timeout);
2074
3198
  }
2075
3199
  proc.stdout.on("data", (data) => {
2076
3200
  const chunk = stdout.write(data);
2077
3201
  const cleaned = chunk.split("\n").filter(filterNoiseLine).join("\n");
2078
- if (cleaned) onChunk(cleaned);
3202
+ if (cleaned && !settled) {
3203
+ try {
3204
+ onChunk(cleaned);
3205
+ } catch (error) {
3206
+ finish(() => reject(stoppingCliError(error, proc)));
3207
+ }
3208
+ }
2079
3209
  });
2080
- proc.on("close", (code) => {
3210
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2081
3211
  const raw = stdout.end();
2082
3212
  if (code !== 0 && code !== null) {
2083
- finish(() => reject(new Error(`Copilot CLI exited with code ${code}`)));
3213
+ finish(() => reject2(new Error(`Copilot CLI exited with code ${code}`)));
2084
3214
  return;
2085
3215
  }
2086
3216
  const text = raw.split("\n").filter(filterNoiseLine).join("\n").trim();
2087
3217
  finish(
2088
- () => resolve2({
3218
+ () => resolve4({
2089
3219
  text,
2090
3220
  raw,
2091
3221
  elapsed: Date.now() - start,
@@ -2094,7 +3224,7 @@ function executeCliStreaming(provider, prompt, options) {
2094
3224
  );
2095
3225
  });
2096
3226
  proc.on("error", (err) => {
2097
- finish(() => reject(err));
3227
+ finish(() => reject(proc.pid ? stoppingCliError(err, proc) : err));
2098
3228
  });
2099
3229
  }));
2100
3230
  }
@@ -2106,18 +3236,18 @@ function executeGeminiStreaming(prompt, options) {
2106
3236
  yolo = true,
2107
3237
  onChunk
2108
3238
  } = options;
2109
- return new Promise((resolve2, reject) => {
3239
+ return new Promise((resolve3, reject) => {
2110
3240
  const args = ["-p", prompt, "--output-format", "stream-json", "-m", model];
2111
3241
  if (yolo) args.push("--yolo");
2112
3242
  args.push("-e", "none");
2113
3243
  const start = Date.now();
2114
- const proc = spawn2("gemini", args, {
3244
+ const proc = spawn3("gemini", args, {
2115
3245
  cwd,
2116
3246
  env: buildCliProcessEnv({
2117
3247
  ...options.env,
2118
3248
  NODE_OPTIONS: "--no-deprecation"
2119
3249
  }),
2120
- ...options.signal ? { detached: true } : {}
3250
+ detached: process.platform !== "win32"
2121
3251
  });
2122
3252
  const stdout = createUtf8Collector();
2123
3253
  const stderr = createUtf8Collector();
@@ -2131,12 +3261,15 @@ function executeGeminiStreaming(prompt, options) {
2131
3261
  detachAbort();
2132
3262
  cb();
2133
3263
  };
2134
- const detachAbort = attachCliAbortSignal(
3264
+ let detachAbort = () => {
3265
+ };
3266
+ detachAbort = attachCliAbortSignal(
2135
3267
  proc,
2136
3268
  options.signal,
2137
3269
  (error) => finish(() => reject(error))
2138
3270
  );
2139
3271
  const flushLineBuffer = () => {
3272
+ if (settled) return;
2140
3273
  const trimmed = lineBuffer.trim();
2141
3274
  if (!trimmed) return;
2142
3275
  try {
@@ -2149,8 +3282,7 @@ function executeGeminiStreaming(prompt, options) {
2149
3282
  };
2150
3283
  if (timeout > 0) {
2151
3284
  timer = setTimeout(() => {
2152
- terminateCliProcessGroup(proc, "SIGTERM");
2153
- finish(() => reject(new Error(`Gemini CLI timed out after ${timeout}ms`)));
3285
+ finish(() => reject(stoppingCliError(new Error(`Gemini CLI timed out after ${timeout}ms`), proc)));
2154
3286
  }, timeout);
2155
3287
  }
2156
3288
  proc.stdout.on("data", (data) => {
@@ -2164,7 +3296,13 @@ function executeGeminiStreaming(prompt, options) {
2164
3296
  try {
2165
3297
  const event = JSON.parse(line);
2166
3298
  const text = extractGeminiEventText(event);
2167
- if (text) onChunk(text);
3299
+ if (text && !settled) {
3300
+ try {
3301
+ onChunk(text);
3302
+ } catch (error) {
3303
+ finish(() => reject(stoppingCliError(error, proc)));
3304
+ }
3305
+ }
2168
3306
  } catch {
2169
3307
  }
2170
3308
  }
@@ -2174,20 +3312,20 @@ function executeGeminiStreaming(prompt, options) {
2174
3312
  proc.stderr.on("data", (data) => {
2175
3313
  stderr.write(data);
2176
3314
  });
2177
- proc.on("close", (code) => {
3315
+ onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2178
3316
  lineBuffer += stdout.finish();
2179
3317
  const raw = stdout.text;
2180
3318
  const stderrText = stderr.end();
2181
3319
  flushLineBuffer();
2182
3320
  if (code !== 0 && code !== null) {
2183
3321
  finish(
2184
- () => reject(new Error(`Gemini CLI exited with code ${code}
3322
+ () => reject2(new Error(`Gemini CLI exited with code ${code}
2185
3323
  stderr: ${stderrText}`))
2186
3324
  );
2187
3325
  return;
2188
3326
  }
2189
3327
  finish(
2190
- () => resolve2({
3328
+ () => resolve4({
2191
3329
  text: parseGeminiStreamJson(raw),
2192
3330
  raw,
2193
3331
  elapsed: Date.now() - start
@@ -2195,7 +3333,7 @@ stderr: ${stderrText}`))
2195
3333
  );
2196
3334
  });
2197
3335
  proc.on("error", (err) => {
2198
- finish(() => reject(err));
3336
+ finish(() => reject(proc.pid ? stoppingCliError(err, proc) : err));
2199
3337
  });
2200
3338
  });
2201
3339
  }
@@ -2207,6 +3345,9 @@ export {
2207
3345
  CLI_PROBE_BINARIES,
2208
3346
  materializeCliImageInputs,
2209
3347
  resolveGeminiCommand,
3348
+ attachExecutionStoppedPromise,
3349
+ getExecutionStoppedPromise,
3350
+ terminateCliProcessGroupEscalating,
2210
3351
  executeCli,
2211
3352
  startCliSession,
2212
3353
  getCliSession,