nolo-cli 0.265.0-alpha.1 → 0.266.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 (539) hide show
  1. package/{chunk-LXP53WGF.js → chunk-05wkntba.js} +44 -40
  2. package/{chunk-XFYFMTOM.js → chunk-08ts2q1n.js} +9 -11
  3. package/{chromeCommands-MVEEIY4R.js → chunk-0a3m1n6h.js} +182 -238
  4. package/chunk-0gfvc7g8.js +13 -0
  5. package/{chunk-CF7PE763.js → chunk-0h0sncy4.js} +3 -4
  6. package/{chunk-3UH7SS4W.js → chunk-0nsxwrge.js} +232 -241
  7. package/chunk-0ra8cne4.js +11 -0
  8. package/{chunk-MRACVEPZ.js → chunk-0sgwk7am.js} +1 -3
  9. package/{chunk-PEXGRTTQ.js → chunk-0tsfn0dk.js} +44 -45
  10. package/{chunk-WOAZVUSN.js → chunk-0y8cbwzy.js} +26 -30
  11. package/chunk-12gz55kk.js +6 -0
  12. package/{chunk-GLKOYSRU.js → chunk-186gshgw.js} +3 -6
  13. package/chunk-19w4ss38.js +44 -0
  14. package/{chunk-RF576RYE.js → chunk-1cakzp6r.js} +23 -23
  15. package/chunk-1fbfwbzp.js +27 -0
  16. package/{chunk-4IVMDQBA.js → chunk-1fv9k8zt.js} +103 -68
  17. package/{chunk-Q5FJJ6XI.js → chunk-1js4cdzp.js} +11 -19
  18. package/{chunk-YECCIUYU.js → chunk-1nhx0er5.js} +63 -63
  19. package/chunk-1p152b7g.js +12 -0
  20. package/{chunk-LBPW6OCD.js → chunk-1ynbq3yr.js} +322 -353
  21. package/{chunk-6UBGXX2W.js → chunk-1zrg4h5n.js} +3 -4
  22. package/{chunk-Y5GCAMGP.js → chunk-2g6zsfq8.js} +1 -3
  23. package/chunk-2hekb0eh.js +17 -0
  24. package/chunk-2pj6qzq5.js +12 -0
  25. package/chunk-2tvd4jyp.js +226 -0
  26. package/chunk-2ygg7azv.js +846 -0
  27. package/chunk-33405wtv.js +50 -0
  28. package/chunk-34axejtd.js +30 -0
  29. package/{tableCommands-FCPDULSU.js → chunk-3700dvt3.js} +224 -276
  30. package/{pdf-KE3QI2V7.js → chunk-3j08t1nm.js} +12505 -10133
  31. package/chunk-3j9gq18v.js +111 -0
  32. package/{chunk-2QKIWEZS.js → chunk-3qfpcdkm.js} +486 -505
  33. package/{settingThunks-PNC7ZISV.js → chunk-3r2x7h64.js} +189 -272
  34. package/{agentGrantCommands-2VLLXGIU.js → chunk-3tbj5fxt.js} +61 -56
  35. package/chunk-40whhjj5.js +168 -0
  36. package/chunk-4301919y.js +7 -0
  37. package/chunk-43adz39e.js +77 -0
  38. package/{chunk-5ZUL4CUO.js → chunk-49v3zc4g.js} +1 -3
  39. package/chunk-4dd7mxkb.js +72 -0
  40. package/{chunk-BKP325XS.js → chunk-4hapfzpq.js} +66 -62
  41. package/chunk-4mm7dz0m.js +95 -0
  42. package/chunk-4pqxempz.js +440 -0
  43. package/chunk-4x9zf5pv.js +10 -0
  44. package/{chunk-CA7LGAHV.js → chunk-511q8qzv.js} +66 -57
  45. package/{chunk-S52BPZ7A.js → chunk-53v9g0np.js} +49 -64
  46. package/chunk-572mg6q5.js +19 -0
  47. package/{chunk-DXDCL3Z6.js → chunk-57eyhmwr.js} +17173 -16165
  48. package/chunk-5hsr0zjm.js +156 -0
  49. package/chunk-5k883yyd.js +20 -0
  50. package/chunk-5m0wsee4.js +639 -0
  51. package/{memberThunks-IPS3SLOF.js → chunk-5r1sq2gt.js} +299 -373
  52. package/chunk-648rq4np.js +255 -0
  53. package/{chunk-IYRZKHA6.js → chunk-666yjw5c.js} +63 -86
  54. package/{chunk-4O22PGNQ.js → chunk-6cdcbmtp.js} +19 -19
  55. package/chunk-6dbyqcf7.js +59 -0
  56. package/{agentProviderCommands-2W3VXDLV.js → chunk-6e8mgp1x.js} +82 -105
  57. package/chunk-6n0pw7sx.js +44 -0
  58. package/chunk-6q1b7381.js +361 -0
  59. package/chunk-6sj756ry.js +23 -0
  60. package/{chunk-XGYQCBWS.js → chunk-6t7a7zck.js} +14785 -14454
  61. package/chunk-6yarwtxh.js +776 -0
  62. package/chunk-708h542p.js +18 -0
  63. package/chunk-76f076t8.js +266 -0
  64. package/chunk-782rrrwv.js +523 -0
  65. package/{workloadLifecycle-P2SJVV3S.js → chunk-7gk330wp.js} +77 -84
  66. package/{chunk-EZKIRVLJ.js → chunk-7ks60vxy.js} +146 -128
  67. package/{chunk-FI4DPLR7.js → chunk-7mrqbxe8.js} +342 -228
  68. package/chunk-7sztayrd.js +169 -0
  69. package/chunk-7vgt2mxz.js +15 -0
  70. package/{localFirstLog-OIETGK66.js → chunk-7z8y4k6y.js} +0 -2
  71. package/{chunk-KDDXC2IH.js → chunk-82htft2m.js} +49 -11
  72. package/{updateDialogTitleAction-OPAZF5VC.js → chunk-88vrtxxg.js} +65 -137
  73. package/{chunk-LS5KAVFQ.js → chunk-8dtjbp79.js} +293 -229
  74. package/chunk-8fajbkaz.js +50 -0
  75. package/chunk-8m1ebxpw.js +65 -0
  76. package/{accountResolver-JYG5L7YP.js → chunk-8mgfeg0w.js} +37 -30
  77. package/{chunk-LPXBBC32.js → chunk-8myksy35.js} +156 -160
  78. package/{chunk-BMQ2MJUK.js → chunk-8nrj7dc7.js} +75 -66
  79. package/{commandRegistry-XPLM5SWC.js → chunk-8t8x64ec.js} +228 -286
  80. package/chunk-8yj4pq79.js +458 -0
  81. package/{chunk-5MKPNTJP.js → chunk-8z6pepcx.js} +43 -48
  82. package/{chunk-UYQILGDR.js → chunk-90egc9vb.js} +122 -102
  83. package/{chunk-Z6LVL5MC.js → chunk-91q5dc5r.js} +10 -14
  84. package/{chunk-U6VC4MU4.js → chunk-96jtrqk1.js} +2 -4
  85. package/{chunk-H57T64RA.js → chunk-996j61av.js} +28 -31
  86. package/{chunk-Q6FKWH66.js → chunk-9cxgb9jy.js} +137 -243
  87. package/{chunk-2ZBPWX7N.js → chunk-9q1gbmet.js} +62 -104
  88. package/chunk-9qtjh73q.js +344 -0
  89. package/{chunk-SR57FDTX.js → chunk-9raka469.js} +72 -155
  90. package/{chunk-V6K5U4YE.js → chunk-9vh4v046.js} +32 -41
  91. package/{chunk-AGIM7IMJ.js → chunk-9yr1fy7j.js} +14 -49
  92. package/{chunk-FGFJUFPS.js → chunk-a16x0wt6.js} +11 -18
  93. package/chunk-a5b2rvzs.js +131 -0
  94. package/{chunk-7DPNBQSV.js → chunk-a7bz6nc3.js} +3 -4
  95. package/chunk-ac85azv9.js +29 -0
  96. package/{chunk-VXL2FZTP.js → chunk-ahhbkad4.js} +16 -20
  97. package/{chunk-37DGW762.js → chunk-anhksj2j.js} +16 -29
  98. package/{cliAuthorityBrokerServer-27C5YBYP.js → chunk-atvmx76t.js} +180 -186
  99. package/{chunk-E6A5NHDH.js → chunk-av2mzeqz.js} +16 -17
  100. package/chunk-avbwrb0z.js +614 -0
  101. package/chunk-avr6rqe5.js +544 -0
  102. package/{workContextQueryProjection-CACY5VFE.js → chunk-axx60d5a.js} +7 -7
  103. package/{chunk-EWQ3HGNZ.js → chunk-b00vzjkb.js} +30 -23
  104. package/chunk-b0m6ezxr.js +132 -0
  105. package/chunk-bbd5mgdt.js +47 -0
  106. package/chunk-bcecft0r.js +28 -0
  107. package/chunk-beyr4pyp.js +33 -0
  108. package/{chunk-BR3GT6MR.js → chunk-bge0cagn.js} +7 -18
  109. package/{offlineMarxistsAgentCommand-MFURGWHL.js → chunk-bh53zg3t.js} +33 -43
  110. package/chunk-bmx1cw89.js +37 -0
  111. package/chunk-br2195h4.js +22 -0
  112. package/chunk-bsqkwveq.js +56 -0
  113. package/{chunk-DZJWSGCV.js → chunk-c09s2z1m.js} +139 -98
  114. package/chunk-c235kypv.js +24636 -0
  115. package/{chunk-2JMYAH5O.js → chunk-c30j6pyh.js} +213 -256
  116. package/chunk-c3v6r6sq.js +29 -0
  117. package/{chunk-NACE7NWO.js → chunk-c5z7qspt.js} +1177 -1196
  118. package/{chunk-GWB6AGME.js → chunk-c6jvz0mp.js} +34 -50
  119. package/{chunk-PRJ473FK.js → chunk-cd6h9qqs.js} +14 -12
  120. package/chunk-cdt0amyy.js +37 -0
  121. package/{chunk-2AJLG6PY.js → chunk-cfh6tfc3.js} +73 -86
  122. package/{chunk-WIVVNJUS.js → chunk-ch4ck1yz.js} +38 -68
  123. package/chunk-chtvrtp5.js +55 -0
  124. package/{chunk-EYLGAEB4.js → chunk-ckvz7abv.js} +170 -165
  125. package/{chunk-YZMNK53S.js → chunk-csf18m5w.js} +32 -25
  126. package/{chunk-C36L6ZID.js → chunk-cwnvf8dt.js} +2 -10
  127. package/chunk-cy7thb6n.js +19877 -0
  128. package/{dialogPortabilityCommands-YQJNB2KL.js → chunk-d61q9nah.js} +439 -487
  129. package/chunk-d6xdy0gp.js +142 -0
  130. package/{chunk-SCEPD46O.js → chunk-dh69vqbd.js} +6386 -6498
  131. package/{chunk-KJ4J2XQB.js → chunk-dj4ggbc6.js} +17 -19
  132. package/{chunk-LISC7BD4.js → chunk-djrrhbk3.js} +29 -37
  133. package/chunk-drqzzzvr.js +822 -0
  134. package/chunk-e1n7edjk.js +33 -0
  135. package/chunk-e3atr4hk.js +59 -0
  136. package/chunk-e9bn2aav.js +13 -0
  137. package/chunk-ed396rfq.js +87 -0
  138. package/chunk-eha8ggh6.js +10 -0
  139. package/{chunk-B7CTVEUV.js → chunk-ek122zzt.js} +893 -948
  140. package/chunk-epnmvek4.js +22 -0
  141. package/{chunk-S25VJYXV.js → chunk-eqzvk3xm.js} +69 -80
  142. package/chunk-ex34n71b.js +2874 -0
  143. package/{chunk-56OAS5RZ.js → chunk-f3ad6q4h.js} +7 -11
  144. package/{chunk-3PVYUPXK.js → chunk-f8jepva1.js} +6 -7
  145. package/{chunk-GH34JXNV.js → chunk-f9yvy9t9.js} +114 -92
  146. package/chunk-fbdz4f0j.js +90 -0
  147. package/{chunk-J44TXB4J.js → chunk-fcsc2day.js} +216 -164
  148. package/chunk-fevdhnbh.js +19 -0
  149. package/chunk-fkrgqq8w.js +3300 -0
  150. package/{chunk-TSBJVMNW.js → chunk-fs3bvh2p.js} +42 -57
  151. package/chunk-fvwzyhah.js +134 -0
  152. package/chunk-g0mpxdp9.js +101 -0
  153. package/{chunk-JGUHOA42.js → chunk-g35f20d1.js} +450 -414
  154. package/{chunk-3L2WKC3W.js → chunk-g5fhtjqg.js} +13 -16
  155. package/{chunk-APOIIIB4.js → chunk-gcq01td7.js} +270 -227
  156. package/{chunk-ADMRXWXJ.js → chunk-ge97b11r.js} +121 -42
  157. package/chunk-ghjtgbkw.js +180 -0
  158. package/chunk-gkra36c1.js +16 -0
  159. package/chunk-gmz86t60.js +1000 -0
  160. package/{localDialogRead-GWGWSL5K.js → chunk-gszpesze.js} +5 -12
  161. package/chunk-gvsfec9m.js +16536 -0
  162. package/{chunk-QSJ3HFEF.js → chunk-h1hzmqph.js} +1 -3
  163. package/chunk-h30dg154.js +17 -0
  164. package/chunk-h3hkb7cw.js +241 -0
  165. package/chunk-h40py996.js +28 -0
  166. package/{chunk-47T3QP4V.js → chunk-h60gnewh.js} +112 -116
  167. package/{agentPullCommand-XEGOUYQT.js → chunk-hkwsv9xf.js} +33 -45
  168. package/chunk-hnyg0gwj.js +28 -0
  169. package/{chunk-KSV6T4AH.js → chunk-hqqqph5w.js} +12 -4
  170. package/{chunk-YQJEXXDK.js → chunk-hrngs1wy.js} +157 -246
  171. package/{chunk-LRLLWD4P.js → chunk-htf69s94.js} +14 -12
  172. package/chunk-j0yxesh3.js +83 -0
  173. package/{chunk-VF4K2QE6.js → chunk-j22t9g05.js} +3 -6
  174. package/{chunk-3R4AYHJR.js → chunk-j4a8m2zn.js} +5 -34
  175. package/chunk-j9p4jnwg.js +27 -0
  176. package/{chunk-R72QWIFO.js → chunk-jdycmfsm.js} +9 -9
  177. package/chunk-jdyvrne0.js +52 -0
  178. package/{spacePruneCommand-YKIEUIDQ.js → chunk-je0b66qf.js} +44 -62
  179. package/{chunk-HNMXYYJR.js → chunk-jec44fkj.js} +3 -4
  180. package/{chunk-526GLZJE.js → chunk-jf1ex00r.js} +107 -73
  181. package/chunk-jgqdec9b.js +31 -0
  182. package/{chunk-56GBUMO5.js → chunk-jkw9n4h5.js} +16 -25
  183. package/{chunk-BY2CHBIZ.js → chunk-jmnzdwjt.js} +867 -965
  184. package/chunk-jqq57s0a.js +58 -0
  185. package/{chunk-OKUSDVRS.js → chunk-jtkn5aj6.js} +27 -38
  186. package/chunk-jwvzn9r0.js +316 -0
  187. package/chunk-k1re0fc7.js +107 -0
  188. package/chunk-k2ep3rb2.js +103 -0
  189. package/{chunk-JEXVIMYZ.js → chunk-k6ycb24w.js} +5 -8
  190. package/{chunk-RI7SXDJW.js → chunk-kawvydbk.js} +383 -195
  191. package/chunk-kf2ghpzh.js +10 -0
  192. package/{chunk-S6FAHQDH.js → chunk-kgah9e46.js} +28 -59
  193. package/{chunk-6A6CTCMC.js → chunk-kjjepkvc.js} +71 -82
  194. package/chunk-kn4dgg4j.js +4113 -0
  195. package/{chunk-2LFYMWM3.js → chunk-kn5p91n8.js} +43 -53
  196. package/{chunk-MVOZ22RZ.js → chunk-kntqrbwc.js} +8 -12
  197. package/{chunk-I6YIA2TY.js → chunk-kq3vr7mx.js} +25 -20
  198. package/chunk-kz1x1d8n.js +15 -0
  199. package/{mcpLocalAuthorizeCommand-IKOFKY5U.js → chunk-m22e7tt2.js} +53 -71
  200. package/{chunk-ZNFJWEN4.js → chunk-m32rwr4d.js} +11 -8
  201. package/chunk-m39e9m18.js +93 -0
  202. package/{chunk-4D4QD7FT.js → chunk-m5518371.js} +64 -56
  203. package/{chunk-LHTXSC2E.js → chunk-mb5hnfyp.js} +9 -11
  204. package/chunk-mexet11v.js +11 -0
  205. package/chunk-mg2hgfgh.js +185 -0
  206. package/chunk-mmdhm4kx.js +10317 -0
  207. package/chunk-mz002yz8.js +2821 -0
  208. package/chunk-mzadqnyq.js +56 -0
  209. package/{chunk-VIDPVFP3.js → chunk-n3r1ebdm.js} +5 -6
  210. package/chunk-n438qea7.js +33 -0
  211. package/chunk-n5ffnhnb.js +93 -0
  212. package/chunk-nbvd87fy.js +9 -0
  213. package/{chunk-E36V7MPY.js → chunk-ndej7jc9.js} +53 -43
  214. package/{chunk-B767MA64.js → chunk-nen6rwe4.js} +62 -22
  215. package/chunk-nf06tr3v.js +16 -0
  216. package/chunk-ng8z355q.js +16 -0
  217. package/{chunk-4MEKE5D3.js → chunk-nhtxfv8k.js} +78 -63
  218. package/{runAgentClientLoop-ELTV5MSJ.js → chunk-nj62jscj.js} +132 -214
  219. package/{chunk-GBWGPTA7.js → chunk-nkryrkyp.js} +16 -19
  220. package/chunk-nmesxem8.js +197 -0
  221. package/{chunk-YR4J7RFS.js → chunk-nmq0qwbn.js} +117 -164
  222. package/chunk-nph8brvw.js +7 -0
  223. package/chunk-nr8fees9.js +10 -0
  224. package/{chunk-DFI7MVCQ.js → chunk-nvewvf7h.js} +1441 -1427
  225. package/{chunk-G7Y4GXTY.js → chunk-nyamhphs.js} +70 -79
  226. package/chunk-nz1c8tcg.js +111 -0
  227. package/{chunk-GPLUFN2E.js → chunk-nzc5yffh.js} +176 -217
  228. package/{chunk-G3SUCT4W.js → chunk-p1vg4bx8.js} +2 -4
  229. package/chunk-p3k3abe8.js +202 -0
  230. package/chunk-p4zy30q5.js +8 -0
  231. package/{chunk-ZJACPM5O.js → chunk-p6se1rx0.js} +102 -102
  232. package/chunk-p9dpshev.js +6968 -0
  233. package/chunk-pa42wxr0.js +116 -0
  234. package/{chunk-TA5QI4MM.js → chunk-paxthgqp.js} +56 -107
  235. package/{readlineWorkspace-5EASNOQ4.js → chunk-pb35s8d9.js} +5395 -5786
  236. package/{chunk-XT6C2QZW.js → chunk-pbebzbcq.js} +8 -8
  237. package/chunk-pbx7e1mb.js +11 -0
  238. package/chunk-pe5czfn9.js +8 -0
  239. package/chunk-pextk1j4.js +62 -0
  240. package/chunk-pf5rywc6.js +575 -0
  241. package/chunk-pjfhd3fz.js +136 -0
  242. package/chunk-pkhqb0fs.js +243 -0
  243. package/chunk-pm5xb9jh.js +26 -0
  244. package/{chunk-Y3KGWZKF.js → chunk-ppdmmdkx.js} +110 -97
  245. package/chunk-pqp6y2hs.js +9 -0
  246. package/{chunk-QHEN7NZ7.js → chunk-ptz8fm2n.js} +12 -17
  247. package/{chunk-EUHMI5KG.js → chunk-pwqnvbt7.js} +65 -46
  248. package/chunk-pzr31nz7.js +12 -0
  249. package/{chunk-WWC7I6TA.js → chunk-q3cx89sw.js} +2 -4
  250. package/chunk-q5pe7be3.js +78 -0
  251. package/{chunk-ZHWTBHT3.js → chunk-q6zqbxp2.js} +418 -409
  252. package/chunk-q7r0e1p3.js +15 -0
  253. package/chunk-q8t2fecd.js +6 -0
  254. package/{chunk-2QAZCYOM.js → chunk-q94zx4d0.js} +721 -753
  255. package/{runtimeDoctorCommands-52MBG5JN.js → chunk-qarz1az1.js} +65 -85
  256. package/{chunk-4INJGWE3.js → chunk-qdcvr25b.js} +72 -53
  257. package/{streamAgentChatTurn-BL3ESUEN.js → chunk-qxs27wfg.js} +1079 -1475
  258. package/{chunk-GIXWVN2W.js → chunk-r06ycjjr.js} +50 -47
  259. package/{chunk-63W5N6P3.js → chunk-r20jw5hb.js} +57 -38
  260. package/{chunk-I5BYFTYK.js → chunk-r7sfwdka.js} +1201 -1142
  261. package/{chunk-UMADT6B2.js → chunk-r9sp1yyb.js} +6 -8
  262. package/{handleSendMessageAction-VQP5HT5I.js → chunk-rbd2vgb3.js} +627 -757
  263. package/chunk-rc37js46.js +12 -0
  264. package/{chunk-5YI447UL.js → chunk-rmngk6r3.js} +67 -76
  265. package/chunk-rnhbnbrq.js +15 -0
  266. package/{chunk-WRHVVIGI.js → chunk-rsfnmrt5.js} +111 -131
  267. package/{chunk-YFSM2366.js → chunk-rvvn2rhj.js} +28 -22
  268. package/{chunk-4Y6CZ2N4.js → chunk-s0fpz7ht.js} +37 -33
  269. package/{chunk-VI4SWTUO.js → chunk-s1cqzb2r.js} +77 -65
  270. package/{chunk-6QDYSCPW.js → chunk-s8q81tda.js} +73 -65
  271. package/chunk-s9hy639e.js +6 -0
  272. package/{chunk-R5GO3YZP.js → chunk-s9vbwme8.js} +115 -106
  273. package/chunk-sger1m1b.js +20 -0
  274. package/chunk-spe6crvk.js +60 -0
  275. package/chunk-spwsrvh9.js +70 -0
  276. package/chunk-sr05zpk7.js +573 -0
  277. package/{chunk-M2EJHDJP.js → chunk-srncrd3f.js} +1 -12
  278. package/{chunk-QXHFIX7W.js → chunk-sry80bpx.js} +71 -53
  279. package/{chunk-PSCNXBYA.js → chunk-t6q69p83.js} +3 -4
  280. package/{chunk-UAD2WT54.js → chunk-t714r4q0.js} +9 -28
  281. package/chunk-t7vbraqe.js +42 -0
  282. package/{chunk-CVMMWN6P.js → chunk-td7653rr.js} +10 -20
  283. package/{chunk-3BQDF4QB.js → chunk-tmytcetz.js} +17 -21
  284. package/{chunk-AMWMV56B.js → chunk-tta4prwg.js} +16 -15
  285. package/chunk-tvh8azgq.js +4829 -0
  286. package/{chunk-ID4G2MAR.js → chunk-v08kbfm8.js} +10 -11
  287. package/{chunk-IHU2ZFCQ.js → chunk-v1x702q8.js} +801 -852
  288. package/{chunk-KHCLMKZZ.js → chunk-v39fea91.js} +576 -247
  289. package/{chunk-OW765XBU.js → chunk-vejtd8p2.js} +3 -4
  290. package/chunk-vep7zkha.js +368 -0
  291. package/chunk-vfwn1k7n.js +142 -0
  292. package/chunk-vg68vxhx.js +20 -0
  293. package/chunk-vgcqgnsm.js +31 -0
  294. package/{chunk-NF64D32W.js → chunk-vnzyjdea.js} +1 -3
  295. package/{chunk-ZCLSM5AK.js → chunk-vqgtw1px.js} +800 -717
  296. package/chunk-vv1gr5xz.js +76 -0
  297. package/{spaceCommands-Z2CTQD6G.js → chunk-w1qeadpq.js} +176 -242
  298. package/chunk-w468ez1p.js +13 -0
  299. package/chunk-w49s0t79.js +14 -0
  300. package/{mcpLocalManageCommands-KUDZQRM4.js → chunk-w58zhfbn.js} +91 -93
  301. package/chunk-w5b74aq6.js +11 -0
  302. package/chunk-w7y41qyw.js +117 -0
  303. package/chunk-w820gg1w.js +4165 -0
  304. package/{chunk-DBJAJ4UD.js → chunk-wdsmaqmt.js} +399 -453
  305. package/{chunk-3EUW3WEO.js → chunk-wfvvnmmj.js} +1 -3
  306. package/{chunk-QY4NZCDA.js → chunk-wkr04bhk.js} +432 -651
  307. package/{chunk-KUG52IAP.js → chunk-ws402twv.js} +1 -3
  308. package/chunk-wzwh311q.js +164 -0
  309. package/{runtimeModeArgs-X7DL7PUN.js → chunk-x5vtgvwn.js} +6 -5
  310. package/{agentMachineCommands-AXPZRHUY.js → chunk-x8h2csmq.js} +152 -195
  311. package/{chunk-BAZCS5XG.js → chunk-x9zfjnrc.js} +59 -47
  312. package/{chunk-WTIJKWCI.js → chunk-xcarc2rf.js} +50 -56
  313. package/chunk-xf33gz0a.js +8 -0
  314. package/{chunk-PVFYPUIM.js → chunk-y7b3gwx1.js} +78 -71
  315. package/{memoryCommands-SVLAVFCV.js → chunk-y7sphmnh.js} +119 -95
  316. package/{agentListCommands-436FHOIT.js → chunk-ycvaafhc.js} +260 -374
  317. package/chunk-yd7zprb0.js +9 -0
  318. package/chunk-yfz3d27k.js +40 -0
  319. package/{chunk-MKR6KDD3.js → chunk-ykv9g3m4.js} +141 -125
  320. package/chunk-ystjgb9e.js +544 -0
  321. package/chunk-yysxn7ep.js +12 -0
  322. package/{chunk-AL3TYDIF.js → chunk-z17eyawk.js} +18 -16
  323. package/{machineCommands-LHJMILRA.js → chunk-z17q416p.js} +442 -563
  324. package/chunk-z1n98pcf.js +12 -0
  325. package/{dialogTraceCommand-HWXGIGZX.js → chunk-z566jx5r.js} +292 -397
  326. package/chunk-zjxd6942.js +6 -0
  327. package/{versionChangeNotice-RFABJGJE.js → chunk-zk11x9y5.js} +7 -9
  328. package/{chunk-TEFD5E2D.js → chunk-zt73yc33.js} +48 -51
  329. package/chunk-zvs2fra1.js +5 -0
  330. package/{chunk-SVFFKLMR.js → chunk-zwee84rh.js} +117 -141
  331. package/chunk-zxgfqv72.js +8 -0
  332. package/index.js +53 -69
  333. package/package.json +4 -4
  334. package/_executeModel-B3ENLKM4.js +0 -341
  335. package/action-UK3HXGXF.js +0 -30
  336. package/addContentAction-CAKFVBDM.js +0 -38
  337. package/addDialogAgentAction-KLJ2YWWM.js +0 -77
  338. package/agentDeleteCommand-R4LKLXQR.js +0 -523
  339. package/agentEmailCommands-SUEXVAY4.js +0 -742
  340. package/agentRecordCommands-NE4OPX5K.js +0 -211
  341. package/agentRun-NSNLIOM7.js +0 -251
  342. package/agentRunCommand-T6QTKMCJ.js +0 -249
  343. package/agentRunControl-U2MV74WR.js +0 -211
  344. package/agentRuntimeLocal-P4MMGIR6.js +0 -189
  345. package/agentSlice-FZJZONCT.js +0 -52
  346. package/appConfigCommands-W4JQHMOJ.js +0 -417
  347. package/appDeleteCommands-IXR47IAV.js +0 -183
  348. package/appDeployCommands-LB6DHDF4.js +0 -232
  349. package/appDeployStatusCommands-UQ6MJL6D.js +0 -204
  350. package/appGetCommands-M5JCTDDQ.js +0 -185
  351. package/appListCommands-TE3ZHE3I.js +0 -186
  352. package/appMigrateCommands-FOXH6R4B.js +0 -230
  353. package/appSourceCommands-3ACYB6I7.js +0 -279
  354. package/authCommand-I5OBJP5S.js +0 -66
  355. package/authCommands-I6KCGOCN.js +0 -54
  356. package/builtinSkillRegistry-MIXYSZUU.js +0 -35
  357. package/chromeOpsCommands-IZRCYDSW.js +0 -579
  358. package/chunk-24BICQPB.js +0 -25
  359. package/chunk-2E4BYAUE.js +0 -69
  360. package/chunk-2O72G3U2.js +0 -17157
  361. package/chunk-2OROOEOQ.js +0 -229
  362. package/chunk-2R6M34JP.js +0 -27225
  363. package/chunk-2SXN7LAY.js +0 -15
  364. package/chunk-35JIFLIG.js +0 -30
  365. package/chunk-3VXVE2LF.js +0 -12
  366. package/chunk-4DBTBNTX.js +0 -477
  367. package/chunk-4JH2UMJR.js +0 -40
  368. package/chunk-4SN6J65J.js +0 -38
  369. package/chunk-4TDUT2LC.js +0 -441
  370. package/chunk-5MMAK75Q.js +0 -15
  371. package/chunk-6NYQHXMV.js +0 -1737
  372. package/chunk-6R4IY46J.js +0 -14
  373. package/chunk-7K4J76JQ.js +0 -917
  374. package/chunk-7LR2IFUH.js +0 -100
  375. package/chunk-AETZ7AD6.js +0 -274
  376. package/chunk-ATNTHIZI.js +0 -13
  377. package/chunk-BPB3T5EU.js +0 -791
  378. package/chunk-BV3FLP2L.js +0 -133
  379. package/chunk-BVYHE6QD.js +0 -110
  380. package/chunk-BWJLEN6X.js +0 -1388
  381. package/chunk-CHOZJMJS.js +0 -78
  382. package/chunk-CYS6HOJ2.js +0 -1710
  383. package/chunk-D2LTQAGN.js +0 -464
  384. package/chunk-DALXH7BG.js +0 -3392
  385. package/chunk-DKEOYC4L.js +0 -15210
  386. package/chunk-DLXL4NSL.js +0 -1179
  387. package/chunk-DSBRIUX5.js +0 -23
  388. package/chunk-DWLEOOGR.js +0 -8
  389. package/chunk-E2KZNP6C.js +0 -13
  390. package/chunk-E5JV4DCB.js +0 -272
  391. package/chunk-EUGTFFO6.js +0 -42
  392. package/chunk-FBNVJ2TO.js +0 -294
  393. package/chunk-FGXG6OLW.js +0 -34
  394. package/chunk-FRFFUKGH.js +0 -3085
  395. package/chunk-G22P2J7O.js +0 -1775
  396. package/chunk-G5KDYBTG.js +0 -432
  397. package/chunk-GBXRKW26.js +0 -613
  398. package/chunk-HEVRQGGH.js +0 -106
  399. package/chunk-HHXF57CL.js +0 -180
  400. package/chunk-HI5RS2O4.js +0 -2109
  401. package/chunk-HJTI7RZV.js +0 -94
  402. package/chunk-HRWRIPTB.js +0 -531
  403. package/chunk-HYCVEESH.js +0 -2824
  404. package/chunk-I42VC5KR.js +0 -15
  405. package/chunk-IB5AR52X.js +0 -15
  406. package/chunk-IIRJ4P4I.js +0 -24
  407. package/chunk-IT3ZZRJE.js +0 -12
  408. package/chunk-IV6VUVLJ.js +0 -88
  409. package/chunk-J42X32PV.js +0 -472
  410. package/chunk-JDMWYVUF.js +0 -449
  411. package/chunk-JKVOKKMQ.js +0 -53
  412. package/chunk-JRTNUU5Z.js +0 -54
  413. package/chunk-K7HLFORE.js +0 -226
  414. package/chunk-KGBASAB5.js +0 -74
  415. package/chunk-KGKTN2NX.js +0 -25
  416. package/chunk-KX6YBIHG.js +0 -8
  417. package/chunk-KYHNSSL2.js +0 -62
  418. package/chunk-KZO2MTVM.js +0 -140
  419. package/chunk-L2DHCG6C.js +0 -779
  420. package/chunk-LKZPX6YH.js +0 -0
  421. package/chunk-LLP2NDED.js +0 -201
  422. package/chunk-LOFRSJX2.js +0 -47
  423. package/chunk-M75RM77T.js +0 -3970
  424. package/chunk-MDAYRIP7.js +0 -1889
  425. package/chunk-MI6HRMCK.js +0 -25
  426. package/chunk-MTNQNLSE.js +0 -1029
  427. package/chunk-NH4PUEWK.js +0 -762
  428. package/chunk-NHLLXINQ.js +0 -8
  429. package/chunk-NTUNHTJV.js +0 -40
  430. package/chunk-OJKUU3LP.js +0 -67
  431. package/chunk-OQH3TAB7.js +0 -299
  432. package/chunk-P62DHV4F.js +0 -443
  433. package/chunk-PHIERFHT.js +0 -574
  434. package/chunk-PKDFU6MY.js +0 -102
  435. package/chunk-PL5RKESU.js +0 -40
  436. package/chunk-PSJJBBWV.js +0 -42
  437. package/chunk-QKM55LP2.js +0 -739
  438. package/chunk-QQ56R7KS.js +0 -88
  439. package/chunk-QYPE3TS3.js +0 -43
  440. package/chunk-REAE2SZK.js +0 -62
  441. package/chunk-RGQ4UUWZ.js +0 -208
  442. package/chunk-RIRFHJTW.js +0 -353
  443. package/chunk-RYMLMTPZ.js +0 -547
  444. package/chunk-SSGTV4FC.js +0 -303
  445. package/chunk-SVKWZ3EG.js +0 -607
  446. package/chunk-T7KODHYS.js +0 -317
  447. package/chunk-TZXPT53C.js +0 -8
  448. package/chunk-U67V476Y.js +0 -35
  449. package/chunk-UEILX4EV.js +0 -15
  450. package/chunk-VIWDGTDA.js +0 -8
  451. package/chunk-VXUQWCEZ.js +0 -138
  452. package/chunk-W5GKF5ZW.js +0 -32
  453. package/chunk-WDWZPASX.js +0 -29
  454. package/chunk-WX266G2C.js +0 -9594
  455. package/chunk-YCITCYSJ.js +0 -356
  456. package/chunk-Z3KTXWWB.js +0 -76
  457. package/chunk-ZC3CMUKU.js +0 -322
  458. package/chunk-ZV7ZY46L.js +0 -1343
  459. package/cliAgentConfigHelpers-WB2S7PDO.js +0 -47
  460. package/cliAuthorityBrokerClient-3SKOA7OZ.js +0 -23
  461. package/cliAuthorityBrokerProcess-BMBVXPKU.js +0 -24
  462. package/cliAuthorityStoreDriver-6FE3BJNB.js +0 -20
  463. package/cliEnvHelpers-7V5ZWUJA.js +0 -34
  464. package/cliExecutor-N3445G2Z.js +0 -45
  465. package/cliLocalAgentRecordReader-QKKRK53P.js +0 -113
  466. package/cloudAutomationCommands-S52NKCLL.js +0 -310
  467. package/contentThunks-RK6MJWBY.js +0 -100
  468. package/cooldownCommands-ZFDAL4MR.js +0 -79
  469. package/createAgentAutomationAction-KN7XLCU2.js +0 -173
  470. package/createDialogAction-KAG6DBVM.js +0 -87
  471. package/createPageAction-7XNPH76L.js +0 -91
  472. package/cursorProvider-2RACMEMF.js +0 -6123
  473. package/db-LTHLW7QA.js +0 -178
  474. package/dbSlice-WNUHTF4C.js +0 -76
  475. package/deleteDbKey-MUCJP6DK.js +0 -87
  476. package/desktopFolderProjects-4POAMVJN.js +0 -45
  477. package/dialogCommands-4MOLJW4G.js +0 -165
  478. package/dialogMessageRecord-2HJTEXQX.js +0 -7
  479. package/dialogNotifyCommand-YL2GFKLO.js +0 -45
  480. package/dialogSlice-BD6WOOD3.js +0 -200
  481. package/dialogUsageCommand-IO2BQKL2.js +0 -31
  482. package/docCreateCommands-OYLRBK2M.js +0 -255
  483. package/docDeleteCommands-3NF6QPJU.js +0 -226
  484. package/docReadCommands-CBAERJAP.js +0 -184
  485. package/docStore-RK4CD4QN.js +0 -89
  486. package/docUpdateCommands-BAMCGX6F.js +0 -326
  487. package/ebookDownloaderAgentCommand-NOIZ6U7Y.js +0 -675
  488. package/fetchMessages-P7FSCSXV.js +0 -19
  489. package/getPricing-KNXVEIUI.js +0 -40
  490. package/hostCredentialCreate-CPIWBALC.js +0 -402
  491. package/i18n-SAK6DDY4.js +0 -51
  492. package/keys-FXEGMKSG.js +0 -183
  493. package/legacyMigration-TF4SYJCZ.js +0 -19
  494. package/levelAuthorityStore-L5SVDM5O.js +0 -10
  495. package/localAutomationCommands-WPYIYTDP.js +0 -199
  496. package/localAutomationRuntime-M7WWU6WY.js +0 -61
  497. package/localRecall-BDYKXB46.js +0 -17
  498. package/localRuntimeAdapter-SNE2NUDN.js +0 -310
  499. package/localRuntimeAuthority-Q5C2KWGF.js +0 -45
  500. package/localRuntimeDb-MM3DINZM.js +0 -12
  501. package/machineInfo-HNPJHQFU.js +0 -14
  502. package/machineWsRunDispatch-VHEIHXWY.js +0 -228
  503. package/models-TOXYINNM.js +0 -10
  504. package/oauthTokenStore-RUYNYALS.js +0 -24
  505. package/overlay-JA3SPVUS.js +0 -15
  506. package/parityCommands-5OCBPVES.js +0 -613
  507. package/processSpawn-6GEO77KV.js +0 -11
  508. package/profileConfig-KOWK4HOG.js +0 -49
  509. package/projectArchive-HUET56SH.js +0 -132
  510. package/providerPresetApply-YCVSP2WX.js +0 -235
  511. package/providerRegistry-26PAUYH2.js +0 -24
  512. package/read-D4WYJQJQ.js +0 -32
  513. package/readDocTool-3S3OQFOH.js +0 -22
  514. package/rememberExplicit-ZPI6KK5M.js +0 -16
  515. package/remove-AHRMUDMH.js +0 -32
  516. package/removeDialogAgentAction-AALRBFSA.js +0 -81
  517. package/secretCommands-2PSS3QNZ.js +0 -24
  518. package/setDialogExtraReferencesAction-SLHQ3GYL.js +0 -39
  519. package/setPrimaryDialogAgentAction-XKCSGJ7M.js +0 -96
  520. package/skillDiscovery-IUEZZG2B.js +0 -29
  521. package/skillSummaryMarker-62UW7HI7.js +0 -9
  522. package/slateToRenderMarkdown-R3X74MCX.js +0 -7
  523. package/slateUtils-ESQAJ6RN.js +0 -19
  524. package/store-WSAVTR32.js +0 -50
  525. package/switchDialogAgentAction-YJIWQGIR.js +0 -70
  526. package/tombstones-FQQMEDOW.js +0 -32
  527. package/toolApiClient-FVXTIIEN.js +0 -42
  528. package/tools-KB6CJ2KT.js +0 -147
  529. package/tuiRestart-LU2BDLAW.js +0 -50
  530. package/tuiSummaryLlmCaller-Z2ZVBIGN.js +0 -53
  531. package/updateCommands-4QP7WJLA.js +0 -63
  532. package/usageCommand-AZX7D3LB.js +0 -31
  533. package/usageRebuildCommand-XV5QQCHK.js +0 -623
  534. package/userDataMerge-HT2ZVHBJ.js +0 -13
  535. package/windowsSelfUpdate-5OFKSW6Y.js +0 -14
  536. package/workContext-ZAW6VXT7.js +0 -18
  537. package/workContextAccess-VU5I4LKZ.js +0 -11
  538. package/workContextWriteNotice-YCSSMHN4.js +0 -7
  539. /package/{chunk-BYXBJQAS.js → chunk-0bcc25vg.js} +0 -0
package/chunk-DALXH7BG.js DELETED
@@ -1,3392 +0,0 @@
1
- import {
2
- buildCliPrompt
3
- } from "./chunk-ATNTHIZI.js";
4
- import {
5
- buildCliProcessEnv,
6
- resolveLaunchableCodexCommand
7
- } from "./chunk-YFSM2366.js";
8
-
9
- // packages/ai/agent/cliExecutor.ts
10
- import { spawn as spawn3 } from "child_process";
11
- import { randomUUID as randomUUID2 } from "node:crypto";
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
- import { tmpdir } from "node:os";
15
- import { StringDecoder as StringDecoder2 } from "node:string_decoder";
16
-
17
- // packages/ai/agent/executors/opencodeExecutor.ts
18
- import { spawn } from "node:child_process";
19
- import { randomUUID } from "node:crypto";
20
- async function executeOpenCodeStreaming(prompt, options) {
21
- if (options.imageInputs && options.imageInputs.length > 0) {
22
- throw new Error("OpenCode executor does not support imageInputs (unsupported)");
23
- }
24
- const startTime = Date.now();
25
- const timeoutMs = options.timeout ?? 12e4;
26
- const deadline = startTime + timeoutMs;
27
- if (options.signal?.aborted) {
28
- throw new DOMException("Execution was aborted before start", "AbortError");
29
- }
30
- if (timeoutMs <= 0 || deadline <= startTime) {
31
- throw new Error(`OpenCode timed out after ${timeoutMs}ms`);
32
- }
33
- const internalAbortController = new AbortController();
34
- let abortReason = null;
35
- const onExternalAbort = () => {
36
- abortReason = options.signal?.reason || new DOMException("OpenCode execution was aborted", "AbortError");
37
- internalAbortController.abort(abortReason);
38
- };
39
- if (options.signal) {
40
- options.signal.addEventListener("abort", onExternalAbort, { once: true });
41
- }
42
- const remainingTimeout = deadline - Date.now();
43
- let deadlineTimer = null;
44
- if (remainingTimeout <= 0) {
45
- abortReason = new Error(`OpenCode execution timed out after ${timeoutMs}ms`);
46
- internalAbortController.abort(abortReason);
47
- } else {
48
- deadlineTimer = setTimeout(() => {
49
- deadlineTimer = null;
50
- abortReason = new Error(`OpenCode execution timed out after ${timeoutMs}ms`);
51
- internalAbortController.abort(abortReason);
52
- }, remainingTimeout);
53
- deadlineTimer?.unref?.();
54
- }
55
- const getAbortError = () => {
56
- return abortReason || internalAbortController.signal.reason || new DOMException("OpenCode execution was aborted", "AbortError");
57
- };
58
- const env = buildCliProcessEnv(options.env);
59
- const binPath = options.env?.OPENCODE_BIN || process.env.OPENCODE_BIN || "opencode";
60
- const cwd = options.cwd || process.cwd();
61
- const serveProc = spawn(
62
- binPath,
63
- ["serve", "--port", "0", "--hostname", "127.0.0.1"],
64
- {
65
- cwd,
66
- env,
67
- detached: process.platform !== "win32",
68
- stdio: ["ignore", "pipe", "pipe"]
69
- }
70
- );
71
- let serverBaseUrl = null;
72
- let activeSessionId = null;
73
- let hasCleanedUp = false;
74
- const onProcExit = (code, sig) => {
75
- if (hasCleanedUp) return;
76
- const err = new Error(
77
- serverBaseUrl ? `OpenCode serve process exited prematurely (code: ${code}, signal: ${sig})` : `opencode serve exited before address detected (code: ${code}, signal: ${sig})`
78
- );
79
- if (!internalAbortController.signal.aborted) {
80
- abortReason = err;
81
- internalAbortController.abort(err);
82
- }
83
- };
84
- serveProc.on("exit", onProcExit);
85
- serveProc.on("error", (err) => {
86
- if (hasCleanedUp) return;
87
- const procErr = new Error(`Failed to spawn opencode serve: ${err.message}`);
88
- if (!internalAbortController.signal.aborted) {
89
- abortReason = procErr;
90
- internalAbortController.abort(procErr);
91
- }
92
- });
93
- const cleanup = () => {
94
- hasCleanedUp = true;
95
- if (!internalAbortController.signal.aborted) internalAbortController.abort();
96
- return (async () => {
97
- if (activeSessionId && serverBaseUrl) {
98
- const timeout = AbortSignal.timeout(800);
99
- try {
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 {
105
- }
106
- }
107
- await terminateCliProcessGroupEscalating(serveProc);
108
- })();
109
- };
110
- try {
111
- const portPromise = new Promise((resolve3, reject) => {
112
- let buffer = "";
113
- const checkUrl = (chunk) => {
114
- buffer += chunk.toString();
115
- const match = buffer.match(/http:\/\/127\.0\.0\.1:(\d+)/);
116
- if (match) {
117
- cleanupStartup();
118
- resolve3(match[0]);
119
- return;
120
- }
121
- const nonLoopback = buffer.match(/http:\/\/(?!127\.0\.0\.1)[a-zA-Z0-9.-]+:\d+/);
122
- if (nonLoopback) {
123
- cleanupStartup();
124
- reject(new Error(`Rejected untrusted non-loopback OpenCode server url: ${nonLoopback[0]}`));
125
- }
126
- };
127
- const onAbort = () => {
128
- cleanupStartup();
129
- reject(getAbortError());
130
- };
131
- const cleanupStartup = () => {
132
- serveProc.stdout?.off("data", checkUrl);
133
- serveProc.stderr?.off("data", checkUrl);
134
- internalAbortController.signal.removeEventListener("abort", onAbort);
135
- };
136
- if (internalAbortController.signal.aborted) {
137
- cleanupStartup();
138
- reject(getAbortError());
139
- return;
140
- }
141
- serveProc.stdout?.on("data", checkUrl);
142
- serveProc.stderr?.on("data", checkUrl);
143
- internalAbortController.signal.addEventListener("abort", onAbort, { once: true });
144
- });
145
- serverBaseUrl = await portPromise;
146
- if (internalAbortController.signal.aborted || Date.now() > deadline) {
147
- throw getAbortError();
148
- }
149
- const sseResponse = await fetch(`${serverBaseUrl}/event`, {
150
- method: "GET",
151
- headers: { Accept: "text/event-stream" },
152
- signal: internalAbortController.signal
153
- }).catch((err) => {
154
- if (internalAbortController.signal.aborted) {
155
- throw getAbortError();
156
- }
157
- throw new Error(`Failed to connect to OpenCode SSE stream: ${err.message}`);
158
- });
159
- if (!sseResponse.ok || !sseResponse.body) {
160
- throw new Error(`OpenCode /event returned HTTP ${sseResponse.status}: ${sseResponse.statusText}`);
161
- }
162
- let sessionModel;
163
- let promptModel;
164
- if (options.model) {
165
- const slashIndex = options.model.indexOf("/");
166
- if (slashIndex > 0) {
167
- const providerID = options.model.slice(0, slashIndex);
168
- const id = options.model.slice(slashIndex + 1);
169
- sessionModel = {
170
- id,
171
- providerID,
172
- ...options.reasoningEffort ? { variant: options.reasoningEffort } : {}
173
- };
174
- promptModel = { modelID: id, providerID };
175
- } else {
176
- sessionModel = {
177
- id: options.model,
178
- ...options.reasoningEffort ? { variant: options.reasoningEffort } : {}
179
- };
180
- promptModel = { modelID: options.model };
181
- }
182
- }
183
- const sessionTitle = `nolo-opencode-${randomUUID().slice(0, 8)}`;
184
- const createSessionResp = await fetch(`${serverBaseUrl}/session`, {
185
- method: "POST",
186
- headers: { "Content-Type": "application/json" },
187
- body: JSON.stringify({
188
- title: sessionTitle,
189
- ...sessionModel ? { model: sessionModel } : {}
190
- }),
191
- signal: internalAbortController.signal
192
- }).catch((err) => {
193
- if (internalAbortController.signal.aborted) {
194
- throw getAbortError();
195
- }
196
- throw err;
197
- });
198
- if (!createSessionResp.ok) {
199
- const errText = await createSessionResp.text().catch(() => "");
200
- throw new Error(`Failed to create OpenCode session (HTTP ${createSessionResp.status}): ${errText}`);
201
- }
202
- const sessionData = await createSessionResp.json();
203
- if (!sessionData.id) {
204
- throw new Error("OpenCode create session response did not return an id");
205
- }
206
- const sessionId = sessionData.id;
207
- activeSessionId = sessionId;
208
- let fullText = "";
209
- let hasBeenBusy = false;
210
- let isCompleted = false;
211
- const seenPartTexts = /* @__PURE__ */ new Map();
212
- const emittedToolCalls = /* @__PURE__ */ new Set();
213
- const emittedToolResults = /* @__PURE__ */ new Set();
214
- const emittedToolErrors = /* @__PURE__ */ new Set();
215
- const streamPromise = new Promise((resolve3, reject) => {
216
- let buffer = "";
217
- const reader = sseResponse.body.getReader();
218
- const decoder = new TextDecoder("utf-8");
219
- const markCompleted = () => {
220
- isCompleted = true;
221
- resolve3();
222
- };
223
- const handleEventJson = (parsed) => {
224
- const type = parsed?.type;
225
- const properties = parsed?.properties || parsed?.data || {};
226
- if (properties.sessionID && properties.sessionID !== sessionId) {
227
- return;
228
- }
229
- if (properties.part?.sessionID && properties.part.sessionID !== sessionId) {
230
- return;
231
- }
232
- if (parsed?.sessionID && parsed.sessionID !== sessionId) {
233
- return;
234
- }
235
- if (type === "permission.asked" || type === "permission.v2.asked") {
236
- reject(new Error(`OpenCode requested unsupported permission: ${properties.permission || properties.action || properties.id || "unsupported"}`));
237
- return;
238
- }
239
- if (type === "session.error") {
240
- const errDetail = properties.error ? JSON.stringify(properties.error) : "Session error";
241
- reject(new Error(`OpenCode session error: ${errDetail}`));
242
- return;
243
- }
244
- if (type === "session.status") {
245
- const statusType = properties.status?.type;
246
- if (statusType === "busy") {
247
- hasBeenBusy = true;
248
- } else if (statusType === "idle") {
249
- if (hasBeenBusy) {
250
- markCompleted();
251
- return;
252
- }
253
- }
254
- }
255
- if (type === "session.idle") {
256
- if (hasBeenBusy) {
257
- markCompleted();
258
- return;
259
- }
260
- }
261
- if (type === "message.part.delta") {
262
- const field = properties.field;
263
- const delta = properties.delta;
264
- if (field === "text" && typeof delta === "string" && delta.length > 0) {
265
- hasBeenBusy = true;
266
- const partId = properties.partID || "default";
267
- const currentSeen = seenPartTexts.get(partId) || "";
268
- seenPartTexts.set(partId, currentSeen + delta);
269
- fullText += delta;
270
- options.onChunk?.(delta);
271
- }
272
- return;
273
- }
274
- if (type === "message.part.updated") {
275
- const part = properties.part;
276
- if (!part) return;
277
- if (part.type === "tool") {
278
- hasBeenBusy = true;
279
- const callId = part.callID || part.id || `tool-${randomUUID().slice(0, 6)}`;
280
- const toolName = part.tool || "unknown";
281
- const state = part.state;
282
- const round = options.toolEventRound ?? 1;
283
- if (state?.status === "pending" || state?.status === "running") {
284
- if (!emittedToolCalls.has(callId)) {
285
- emittedToolCalls.add(callId);
286
- options.onToolEvent?.({
287
- type: "tool-call",
288
- round,
289
- toolCallId: callId,
290
- toolName,
291
- summary: `Tool call: ${toolName}`,
292
- metadata: { source: "cli-external", cliProvider: "opencode" }
293
- });
294
- }
295
- } else if (state?.status === "completed") {
296
- if (!emittedToolResults.has(callId)) {
297
- emittedToolResults.add(callId);
298
- options.onToolEvent?.({
299
- type: "tool-result",
300
- round,
301
- toolCallId: callId,
302
- toolName,
303
- summary: `Tool completed: ${toolName}`,
304
- metadata: { source: "cli-external", cliProvider: "opencode" }
305
- });
306
- }
307
- } else if (state?.status === "error") {
308
- if (!emittedToolErrors.has(callId)) {
309
- emittedToolErrors.add(callId);
310
- options.onToolEvent?.({
311
- type: "tool-error",
312
- round,
313
- toolCallId: callId,
314
- toolName,
315
- message: "Tool execution failed",
316
- summary: `Tool error: ${toolName}`,
317
- metadata: { source: "cli-external", cliProvider: "opencode" }
318
- });
319
- }
320
- }
321
- } else if (part.type === "text") {
322
- hasBeenBusy = true;
323
- const partId = part.id || part.partID || "default";
324
- const fullPartText = typeof part.text === "string" ? part.text : "";
325
- const seen = seenPartTexts.get(partId) || "";
326
- if (fullPartText.length > seen.length) {
327
- const diff = fullPartText.slice(seen.length);
328
- if (diff.length > 0) {
329
- seenPartTexts.set(partId, seen + diff);
330
- fullText += diff;
331
- options.onChunk?.(diff);
332
- }
333
- }
334
- }
335
- }
336
- };
337
- const pump = async () => {
338
- try {
339
- while (true) {
340
- const { done, value } = await reader.read();
341
- if (done) {
342
- if (!isCompleted) {
343
- reject(new Error("OpenCode SSE stream disconnected prematurely (unexpected EOF)"));
344
- }
345
- break;
346
- }
347
- buffer += decoder.decode(value, { stream: true });
348
- const lines = buffer.split(/\r?\n/);
349
- buffer = lines.pop() ?? "";
350
- for (const line of lines) {
351
- const trimmed = line.trim();
352
- if (trimmed.startsWith("data:")) {
353
- const payload = trimmed.slice(5).trim();
354
- if (payload === "[DONE]") {
355
- markCompleted();
356
- return;
357
- }
358
- let parsed;
359
- try {
360
- parsed = JSON.parse(payload);
361
- } catch {
362
- continue;
363
- }
364
- handleEventJson(parsed);
365
- if (isCompleted) {
366
- return;
367
- }
368
- }
369
- }
370
- }
371
- } catch (err) {
372
- if (isCompleted) {
373
- return;
374
- }
375
- if (internalAbortController.signal.aborted) {
376
- reject(getAbortError());
377
- return;
378
- }
379
- if (err?.name === "AbortError") {
380
- reject(getAbortError());
381
- return;
382
- }
383
- reject(err);
384
- }
385
- };
386
- pump();
387
- });
388
- const promptPayload = {
389
- parts: [{ type: "text", text: prompt }],
390
- ...promptModel ? { model: promptModel } : {},
391
- ...options.systemPrompt ? { system: options.systemPrompt } : {}
392
- };
393
- const promptResp = await fetch(`${serverBaseUrl}/session/${sessionId}/prompt_async`, {
394
- method: "POST",
395
- headers: { "Content-Type": "application/json" },
396
- body: JSON.stringify(promptPayload),
397
- signal: internalAbortController.signal
398
- }).catch((err) => {
399
- if (internalAbortController.signal.aborted) {
400
- throw getAbortError();
401
- }
402
- throw err;
403
- });
404
- if (!promptResp.ok) {
405
- const errText = await promptResp.text().catch(() => "");
406
- throw new Error(`Failed to send prompt to OpenCode session (HTTP ${promptResp.status}): ${errText}`);
407
- }
408
- let abortListener = null;
409
- const abortPromise = new Promise((_, reject) => {
410
- if (internalAbortController.signal.aborted) {
411
- reject(getAbortError());
412
- return;
413
- }
414
- abortListener = () => reject(getAbortError());
415
- internalAbortController.signal.addEventListener("abort", abortListener, { once: true });
416
- });
417
- try {
418
- await Promise.race([streamPromise, abortPromise]);
419
- } finally {
420
- if (abortListener) {
421
- internalAbortController.signal.removeEventListener("abort", abortListener);
422
- abortListener = null;
423
- }
424
- }
425
- const elapsed = Date.now() - startTime;
426
- return attachExecutionStoppedPromise({ text: fullText, raw: fullText, elapsed }, cleanup());
427
- } catch (error) {
428
- throw attachExecutionStoppedPromise(error instanceof Error ? error : new Error(String(error)), cleanup());
429
- } finally {
430
- if (deadlineTimer) {
431
- clearTimeout(deadlineTimer);
432
- deadlineTimer = null;
433
- }
434
- if (options.signal) {
435
- options.signal.removeEventListener("abort", onExternalAbort);
436
- }
437
- serveProc.off("exit", onProcExit);
438
- }
439
- }
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
- assertAgyAcpAllowed();
964
- const binPath = this.config.binPath || process.env.AGY_BIN || "agy";
965
- const cwd = this.config.cwd || process.cwd();
966
- const args = ["acp"];
967
- if (this.config.yolo === false) args.push("--sandbox");
968
- for (const dir of this.config.addDirs ?? []) {
969
- args.push("--add-dir", dir);
970
- }
971
- this.state = "starting";
972
- const proc = spawn2(binPath, args, {
973
- cwd,
974
- env: buildCliProcessEnv(this.config.env),
975
- stdio: ["pipe", "pipe", "pipe"],
976
- detached: process.platform !== "win32"
977
- });
978
- this.proc = proc;
979
- this.stderrTail = "";
980
- const decoder = new StringDecoder("utf8");
981
- const peer = new AcpRpcPeer(
982
- (line) => {
983
- if (proc.stdin && !proc.stdin.destroyed) proc.stdin.write(line);
984
- },
985
- (method, params) => this.handleAgentRequest(method, params),
986
- (method, params) => {
987
- if (method === "session/update") this.updateHandlers?.onUpdate(params);
988
- }
989
- );
990
- this.peer = peer;
991
- let settledExit = false;
992
- const handleExit = (code, signal) => {
993
- if (settledExit) return;
994
- settledExit = true;
995
- this.handleProcessGone(code, signal);
996
- };
997
- proc.on("exit", handleExit);
998
- proc.on("error", (error) => {
999
- this.stderrTail += `
1000
- ${error.message}`;
1001
- handleExit(null, null);
1002
- });
1003
- proc.stdout?.on("data", (chunk) => peer.feed(chunk));
1004
- proc.stderr?.on("data", (chunk) => {
1005
- this.stderrTail = (this.stderrTail + decoder.write(chunk)).slice(-STDERR_TAIL_CHARS);
1006
- });
1007
- try {
1008
- const initResult = asRecord(
1009
- await peer.request(
1010
- "initialize",
1011
- {
1012
- protocolVersion: ACP_PROTOCOL_VERSION,
1013
- clientCapabilities: {
1014
- fs: { readTextFile: true, writeTextFile: true },
1015
- terminal: true
1016
- }
1017
- },
1018
- DEFAULT_HANDSHAKE_TIMEOUT_MS
1019
- )
1020
- );
1021
- const capabilities = asRecord(initResult?.agentCapabilities);
1022
- this.loadSessionSupported = capabilities?.loadSession === true || capabilities?.load_session === true;
1023
- } catch (error) {
1024
- await this.terminate("initialize-failed");
1025
- throw this.describeStartupFailure(error, "initialize");
1026
- }
1027
- const reused = await this.tryLoadSession(peer, cwd);
1028
- if (!reused) {
1029
- try {
1030
- const newSession = await peer.request(
1031
- "session/new",
1032
- { cwd, mcpServers: [] },
1033
- DEFAULT_HANDSHAKE_TIMEOUT_MS
1034
- );
1035
- const record = asRecord(newSession);
1036
- const sessionId = asString(record?.sessionId);
1037
- if (!sessionId) {
1038
- throw new Error("agy ACP session/new returned no sessionId");
1039
- }
1040
- this.acpSessionId = sessionId;
1041
- this.configOptions = parseConfigOptions(record);
1042
- this.appliedModel = pickModelOption(this.configOptions)?.currentValue ?? null;
1043
- } catch (error) {
1044
- await this.terminate("session-new-failed");
1045
- throw this.describeStartupFailure(error, "session/new");
1046
- }
1047
- }
1048
- this.state = "warm";
1049
- return peer;
1050
- }
1051
- /** 进程重启后尝试用 `session/load` 接回原会话;不支持或失败则退回 session/new。 */
1052
- async tryLoadSession(peer, cwd) {
1053
- if (!this.loadSessionSupported || !this.needsContextReplay || !this.acpSessionId) return false;
1054
- try {
1055
- const loaded = await peer.request(
1056
- "session/load",
1057
- { sessionId: this.acpSessionId, cwd, mcpServers: [] },
1058
- DEFAULT_HANDSHAKE_TIMEOUT_MS
1059
- );
1060
- const record = asRecord(loaded);
1061
- if (record && record.configOptions) this.configOptions = parseConfigOptions(record);
1062
- this.needsContextReplay = false;
1063
- return true;
1064
- } catch {
1065
- return false;
1066
- }
1067
- }
1068
- async applyModel(peer, sessionId) {
1069
- const requested = this.config.model?.trim();
1070
- if (!requested) return;
1071
- const modelOption = pickModelOption(this.configOptions);
1072
- if (!modelOption) {
1073
- if (!this.warnings.includes("agy ACP exposes no model configOptions; model selection skipped.")) {
1074
- this.warnings.push("agy ACP exposes no model configOptions; model selection skipped.");
1075
- }
1076
- return;
1077
- }
1078
- if (this.appliedModel === requested) return;
1079
- const known = modelOption.options.some((option) => option.value === requested);
1080
- if (!known) {
1081
- const message = `agy ACP model "${requested}" is not in the session's advertised model list; keeping current model.`;
1082
- if (!this.warnings.includes(message)) this.warnings.push(message);
1083
- return;
1084
- }
1085
- try {
1086
- const response = await peer.request(
1087
- "session/set_config_option",
1088
- { sessionId, configId: modelOption.id, value: requested },
1089
- DEFAULT_HANDSHAKE_TIMEOUT_MS
1090
- );
1091
- const updated = parseConfigOptions(response);
1092
- if (updated.length > 0) this.configOptions = updated;
1093
- this.appliedModel = requested;
1094
- } catch (error) {
1095
- const message = `agy ACP session/set_config_option failed: ${error instanceof Error ? error.message : String(error)}`;
1096
- if (!this.warnings.includes(message)) this.warnings.push(message);
1097
- }
1098
- }
1099
- async cancelTurn(sessionId, turnPromise) {
1100
- this.peer?.notify("session/cancel", { sessionId });
1101
- const settled = await Promise.race([
1102
- turnPromise.then(
1103
- () => true,
1104
- () => true
1105
- ),
1106
- new Promise((resolvePromise) => {
1107
- const timer = setTimeout(() => resolvePromise(false), CANCEL_GRACE_MS);
1108
- timer.unref?.();
1109
- })
1110
- ]);
1111
- return settled ? "settled" : "timeout";
1112
- }
1113
- handleProcessGone(code, signal) {
1114
- const reason = `agy acp process exited (code: ${code ?? "null"}, signal: ${signal ?? "none"})` + (this.stderrTail.trim() ? `
1115
- stderr: ${this.stderrTail.trim()}` : "");
1116
- this.peer?.dispose(new Error(reason));
1117
- this.peer = null;
1118
- this.proc = null;
1119
- this.acpSessionId = null;
1120
- this.state = "closed";
1121
- this.needsContextReplay = this.history.length > 0;
1122
- this.clearTerminals();
1123
- this.clearIdleTimer();
1124
- this.noteQuotaSignal(this.stderrTail);
1125
- }
1126
- noteQuotaSignal(text) {
1127
- if (!text.trim()) return;
1128
- const quota = detectCliProviderQuotaLimit("agy", "", text, null);
1129
- if (quota.limited) {
1130
- this.warnings.push(quota.message ?? "agy quota/rate limit signal");
1131
- }
1132
- }
1133
- describeStartupFailure(error, method) {
1134
- const message = error instanceof Error ? error.message : String(error);
1135
- const quota = detectCliProviderQuotaLimit("agy", "", `${message}
1136
- ${this.stderrTail}`, null);
1137
- if (quota.limited) {
1138
- return new CliProviderQuotaError("agy", quota.message ?? "Agy reported quota/limit");
1139
- }
1140
- if (message.includes("Authentication required")) {
1141
- return new Error(
1142
- `agy ACP requires an interactive sign-in. Run \`agy acp --login\` (or \`agy --login\`) once in a terminal, then retry. (${method} failed: ${message})`
1143
- );
1144
- }
1145
- return new Error(`agy ACP ${method} failed: ${message}`);
1146
- }
1147
- /**
1148
- * 处理 agent 的反向请求。必须是 async:沙箱拒绝等是同步 throw,
1149
- * 直接返回 `Promise.resolve(fn())` 会让异常冒到 stdout 的 data 监听器(宿主级未捕获异常)。
1150
- */
1151
- async handleAgentRequest(method, params) {
1152
- const record = asRecord(params);
1153
- switch (method) {
1154
- case "session/request_permission":
1155
- return this.resolvePermission(record);
1156
- case "fs/read_text_file":
1157
- return this.readTextFile(record);
1158
- case "fs/write_text_file":
1159
- return this.writeTextFile(record);
1160
- case "terminal/create":
1161
- return this.createTerminal(record);
1162
- case "terminal/output":
1163
- return this.readTerminalOutput(record);
1164
- case "terminal/wait_for_exit":
1165
- return this.waitForTerminalExit(record);
1166
- case "terminal/kill":
1167
- return this.killTerminal(record);
1168
- case "terminal/release":
1169
- return this.releaseTerminal(record);
1170
- default:
1171
- throw new Error(`Unsupported ACP method: ${method}`);
1172
- }
1173
- }
1174
- /** yolo → 自动 allow;非 yolo → 自动 reject(没人能在线点确认)。 */
1175
- resolvePermission(params) {
1176
- const options = Array.isArray(params?.options) ? params.options : [];
1177
- const candidates = options.map((raw) => asRecord(raw)).filter((raw) => raw !== null).map((raw) => ({
1178
- optionId: asString(raw.optionId) ?? asString(raw.option_id) ?? "",
1179
- kind: (asString(raw.kind) ?? "").toLowerCase()
1180
- })).filter((raw) => raw.optionId !== "");
1181
- const allow = candidates.find((option) => option.kind.startsWith("allow"));
1182
- const reject = candidates.find((option) => option.kind.startsWith("reject"));
1183
- const wantAllow = this.config.yolo !== false;
1184
- if (!wantAllow && !reject) {
1185
- return { outcome: { outcome: "cancelled" } };
1186
- }
1187
- const chosen = wantAllow ? allow ?? reject : reject;
1188
- if (!chosen) {
1189
- return { outcome: { outcome: "cancelled" } };
1190
- }
1191
- return { outcome: { outcome: "selected", optionId: chosen.optionId }, optionId: chosen.optionId };
1192
- }
1193
- /** 沙箱根的真身(realpath):词法比较会被 `cwd` 内的符号链接绕过。 */
1194
- realSandboxRoots() {
1195
- const roots = [this.config.cwd || process.cwd(), ...this.config.addDirs ?? []];
1196
- return roots.map((root) => {
1197
- const absolute = resolve(root);
1198
- try {
1199
- return realpathSync(absolute);
1200
- } catch {
1201
- return absolute;
1202
- }
1203
- });
1204
- }
1205
- /**
1206
- * 把请求路径解析成真身并判定是否在沙箱内;越界/无法解析一律拒绝(fail-closed)。
1207
- * - 读:目标必须存在,`realpathSync` 直接解掉所有中间符号链接;
1208
- * - 写:取最近的已存在祖先的真身,再拼回尚未创建的后缀。
1209
- */
1210
- resolveSandboxPath(target, forWrite) {
1211
- const absolute = resolve(target);
1212
- const real = forWrite ? this.realpathForWrite(absolute) : realpathSync(absolute);
1213
- const roots = this.realSandboxRoots();
1214
- if (!roots.some((root) => isWithin(root, real))) {
1215
- throw new Error(`agy ACP requested a path outside the allowed sandbox: ${absolute}`);
1216
- }
1217
- return real;
1218
- }
1219
- realpathForWrite(absolute) {
1220
- let existing = absolute;
1221
- const tail = [];
1222
- while (!existsSync(existing)) {
1223
- const parent = dirname(existing);
1224
- if (parent === existing) break;
1225
- tail.unshift(basename(existing));
1226
- existing = parent;
1227
- }
1228
- if (tail.length > 0) {
1229
- const firstMissing = resolve(existing, tail[0]);
1230
- let stat = null;
1231
- try {
1232
- stat = lstatSync(firstMissing);
1233
- } catch {
1234
- stat = null;
1235
- }
1236
- if (stat?.isSymbolicLink()) {
1237
- throw new Error(`agy ACP refuses to write through a symbolic link: ${firstMissing}`);
1238
- }
1239
- }
1240
- const realExisting = realpathSync(existing);
1241
- return tail.length > 0 ? resolve(realExisting, ...tail) : realExisting;
1242
- }
1243
- readTextFile(params) {
1244
- const path = asString(params?.path);
1245
- if (!path) throw new Error("fs/read_text_file requires a path");
1246
- let content = readFileSync(this.resolveSandboxPath(path, false), "utf8");
1247
- const line = asNumber(params?.line);
1248
- const limit = asNumber(params?.limit);
1249
- if (line !== void 0 || limit !== void 0) {
1250
- const lines = content.split("\n");
1251
- const startIndex = Math.max(0, (line ?? 1) - 1);
1252
- const endIndex = limit !== void 0 ? startIndex + limit : lines.length;
1253
- content = lines.slice(startIndex, endIndex).join("\n");
1254
- }
1255
- return { content };
1256
- }
1257
- writeTextFile(params) {
1258
- const path = asString(params?.path);
1259
- const content = asString(params?.content);
1260
- if (!path || content === void 0) throw new Error("fs/write_text_file requires path and content");
1261
- const realPath = this.resolveSandboxPath(path, true);
1262
- mkdirSync(dirname(realPath), { recursive: true });
1263
- writeFileSync(realPath, content, "utf8");
1264
- return null;
1265
- }
1266
- createTerminal(params) {
1267
- const command = asString(params?.command);
1268
- if (!command) throw new Error("terminal/create requires a command");
1269
- if (this.config.yolo === false) {
1270
- throw new Error("terminal/create is denied in non-yolo agy ACP sessions");
1271
- }
1272
- const requestedCwd = asString(params?.cwd) ?? this.config.cwd ?? process.cwd();
1273
- const realCwd = this.resolveSandboxPath(requestedCwd, false);
1274
- const args = Array.isArray(params?.args) ? params.args.filter((value) => typeof value === "string") : [];
1275
- const envRecord = asRecord(params?.env);
1276
- const env = { ...buildCliProcessEnv(this.config.env) };
1277
- if (envRecord) {
1278
- for (const [key, value] of Object.entries(envRecord)) {
1279
- const resolved = asString(value);
1280
- if (resolved !== void 0) env[key] = resolved;
1281
- }
1282
- }
1283
- const child = spawn2(command, args, {
1284
- cwd: realCwd,
1285
- env,
1286
- stdio: ["ignore", "pipe", "pipe"]
1287
- });
1288
- const terminalId = `term_${this.terminals.size + 1}_${Date.now().toString(36)}`;
1289
- const state = {
1290
- child,
1291
- output: "",
1292
- truncated: false,
1293
- exitCode: null,
1294
- signal: null,
1295
- exited: false,
1296
- waiters: []
1297
- };
1298
- this.terminals.set(terminalId, state);
1299
- const append = (chunk) => {
1300
- state.output += chunk.toString("utf8");
1301
- if (state.output.length > MAX_TERMINAL_OUTPUT_CHARS) {
1302
- state.output = state.output.slice(-MAX_TERMINAL_OUTPUT_CHARS);
1303
- state.truncated = true;
1304
- }
1305
- };
1306
- child.stdout?.on("data", append);
1307
- child.stderr?.on("data", append);
1308
- const finish = (code, signal) => {
1309
- state.exited = true;
1310
- state.exitCode = code;
1311
- state.signal = signal;
1312
- for (const waiter of state.waiters.splice(0)) waiter();
1313
- };
1314
- child.on("exit", finish);
1315
- child.on("error", (error) => {
1316
- append(Buffer.from(`
1317
- ${error.message}`));
1318
- finish(null, null);
1319
- });
1320
- return { terminalId };
1321
- }
1322
- readTerminalOutput(params) {
1323
- const state = this.requireTerminal(params);
1324
- return {
1325
- output: state.output,
1326
- truncated: state.truncated,
1327
- ...state.exited ? { exitStatus: { exitCode: state.exitCode, signal: state.signal } } : {}
1328
- };
1329
- }
1330
- async waitForTerminalExit(params) {
1331
- const state = this.requireTerminal(params);
1332
- if (!state.exited) {
1333
- await new Promise((resolvePromise) => {
1334
- const timer = setTimeout(resolvePromise, 12e4);
1335
- timer.unref?.();
1336
- state.waiters.push(() => {
1337
- clearTimeout(timer);
1338
- resolvePromise();
1339
- });
1340
- });
1341
- }
1342
- return { exitCode: state.exitCode, signal: state.signal };
1343
- }
1344
- killTerminal(params) {
1345
- const state = this.requireTerminal(params);
1346
- if (!state.exited) {
1347
- try {
1348
- state.child.kill("SIGTERM");
1349
- } catch {
1350
- }
1351
- }
1352
- return null;
1353
- }
1354
- releaseTerminal(params) {
1355
- const terminalId = asString(params?.terminalId);
1356
- if (!terminalId) throw new Error("terminal/release requires terminalId");
1357
- const state = this.terminals.get(terminalId);
1358
- if (state) {
1359
- if (!state.exited) {
1360
- try {
1361
- state.child.kill("SIGKILL");
1362
- } catch {
1363
- }
1364
- }
1365
- this.terminals.delete(terminalId);
1366
- }
1367
- return null;
1368
- }
1369
- requireTerminal(params) {
1370
- const terminalId = asString(params?.terminalId);
1371
- if (!terminalId) throw new Error("terminal request requires terminalId");
1372
- const state = this.terminals.get(terminalId);
1373
- if (!state) throw new Error(`Unknown terminal: ${terminalId}`);
1374
- return state;
1375
- }
1376
- clearTerminals() {
1377
- for (const [, state] of this.terminals) {
1378
- if (state.exited) continue;
1379
- try {
1380
- state.child.kill("SIGTERM");
1381
- } catch {
1382
- }
1383
- const escalate = setTimeout(() => {
1384
- if (state.exited) return;
1385
- try {
1386
- state.child.kill("SIGKILL");
1387
- } catch {
1388
- }
1389
- }, 100);
1390
- escalate.unref?.();
1391
- }
1392
- this.terminals.clear();
1393
- }
1394
- touchIdleTimer() {
1395
- this.clearIdleTimer();
1396
- const idleMs = this.config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
1397
- if (idleMs <= 0) return;
1398
- this.idleTimer = setTimeout(() => {
1399
- this.idleTimer = null;
1400
- void this.terminate("idle");
1401
- }, idleMs);
1402
- this.idleTimer.unref?.();
1403
- }
1404
- clearIdleTimer() {
1405
- if (this.idleTimer) {
1406
- clearTimeout(this.idleTimer);
1407
- this.idleTimer = null;
1408
- }
1409
- }
1410
- /**
1411
- * 收尾:清 timer / 终止进程组 / 判定是否需要历史重放。
1412
- * 幂等(并发调用复用同一次收尾),且绝不残留监听器(peer.dispose 会先让所有 pending 请求失败)。
1413
- */
1414
- async terminate(reason) {
1415
- const inFlight = this.terminatePromise;
1416
- if (inFlight) return inFlight;
1417
- const running = this.doTerminate(reason).finally(() => {
1418
- this.terminatePromise = null;
1419
- });
1420
- this.terminatePromise = running;
1421
- return running;
1422
- }
1423
- async doTerminate(reason) {
1424
- this.terminating = true;
1425
- try {
1426
- await this.terminateProcess(reason);
1427
- } finally {
1428
- this.terminating = false;
1429
- }
1430
- }
1431
- async terminateProcess(reason) {
1432
- this.clearIdleTimer();
1433
- this.clearTerminals();
1434
- const proc = this.proc;
1435
- const peer = this.peer;
1436
- this.proc = null;
1437
- this.peer = null;
1438
- this.acpSessionId = null;
1439
- this.state = "closed";
1440
- this.needsContextReplay = this.history.length > 0;
1441
- this.updateHandlers = null;
1442
- peer?.dispose(new Error(`agy ACP session closed (${reason})`));
1443
- if (proc) {
1444
- proc.removeAllListeners("exit");
1445
- proc.removeAllListeners("error");
1446
- proc.stdout?.removeAllListeners("data");
1447
- proc.stderr?.removeAllListeners("data");
1448
- proc.on("error", () => {
1449
- });
1450
- const stopped = terminateCliProcessGroupEscalating(proc).catch(() => void 0);
1451
- await Promise.race([
1452
- stopped,
1453
- new Promise((resolvePromise) => {
1454
- const timer = setTimeout(resolvePromise, 12e3);
1455
- timer.unref?.();
1456
- })
1457
- ]);
1458
- }
1459
- }
1460
- };
1461
- var agyAcpSessions = /* @__PURE__ */ new Map();
1462
- var activeAgyPrintCount = 0;
1463
- function isAgyAcpEnabled(env = process.env) {
1464
- const raw = (env.NOLO_AGY_ACP ?? "").trim().toLowerCase();
1465
- return !(raw === "0" || raw === "false" || raw === "off" || raw === "no");
1466
- }
1467
- function liveSessionCount() {
1468
- let count = 0;
1469
- for (const session of agyAcpSessions.values()) {
1470
- if (session.isOccupyingSlot()) count += 1;
1471
- }
1472
- return count;
1473
- }
1474
- function hasActiveAgyAcpSession() {
1475
- return liveSessionCount() > 0;
1476
- }
1477
- function assertAgyPrintAllowed(label) {
1478
- if (!hasActiveAgyAcpSession()) return;
1479
- throw new CliProviderQuotaError(
1480
- "agy",
1481
- `${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.`
1482
- );
1483
- }
1484
- function assertAgyAcpAllowed() {
1485
- if (activeAgyPrintCount <= 0) return;
1486
- throw new CliProviderQuotaError(
1487
- "agy",
1488
- "agy ACP blocked: an agy --print run is active on this machine. Local agy runs only one stable delegated session at a time; wait for the print run to finish and retry, or dispatch to another provider."
1489
- );
1490
- }
1491
- function acquireAgyPrintSlot(label) {
1492
- assertAgyPrintAllowed(label);
1493
- activeAgyPrintCount += 1;
1494
- let released = false;
1495
- return () => {
1496
- if (released) return;
1497
- released = true;
1498
- activeAgyPrintCount = Math.max(0, activeAgyPrintCount - 1);
1499
- };
1500
- }
1501
- function getAgyAcpSession(key, config) {
1502
- const existing = agyAcpSessions.get(key);
1503
- if (existing) {
1504
- if (!existing.isOccupyingSlot()) assertAgyAcpAllowed();
1505
- existing.updateConfig(config);
1506
- return existing;
1507
- }
1508
- assertAgyAcpAllowed();
1509
- if (liveSessionCount() > 0) {
1510
- throw new CliProviderQuotaError(
1511
- "agy",
1512
- "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."
1513
- );
1514
- }
1515
- const created = new AgyAcpSession(key, config);
1516
- agyAcpSessions.set(key, created);
1517
- return created;
1518
- }
1519
- function closeAgyAcpSession(key) {
1520
- const entries = key === void 0 ? [...agyAcpSessions] : [[key, agyAcpSessions.get(key)]];
1521
- const closing = [];
1522
- for (const [sessionKey, session] of entries) {
1523
- if (!session) continue;
1524
- session.retire();
1525
- closing.push(
1526
- session.terminate(key === void 0 ? "registry-close-all" : "registry-close").finally(() => {
1527
- if (agyAcpSessions.get(sessionKey) === session) agyAcpSessions.delete(sessionKey);
1528
- })
1529
- );
1530
- }
1531
- return Promise.all(closing).then(() => void 0);
1532
- }
1533
-
1534
- // packages/ai/agent/cliExecutor.ts
1535
- var CliProviderQuotaError = class extends Error {
1536
- provider;
1537
- constructor(provider, message) {
1538
- super(`[QUOTA_LIMITED:${provider}] ${message}`);
1539
- this.name = "CliProviderQuotaError";
1540
- this.provider = provider;
1541
- }
1542
- };
1543
- function detectCliProviderQuotaLimit(provider, stdout, stderr, exitCode) {
1544
- const stderrText = String(stderr || "");
1545
- const stdoutText = String(stdout || "");
1546
- const combined = stderrText + "\n" + stdoutText;
1547
- const isQuotaText = (text) => {
1548
- const t = text.toLowerCase();
1549
- const strongPatterns = [
1550
- /quota (exceeded|reached|limit|used up|insufficient|hit)/i,
1551
- /usage limit (reached|exceeded|hit)/i,
1552
- /weekly usage limit/i,
1553
- /rate.?limit (exceeded|reached|hit)/i,
1554
- /\b429\b.*(limit|quota|rate)/i,
1555
- /too many request/i,
1556
- /no (more|remaining) (credit|quota|usage)/i,
1557
- /plan limit|membership limit/i,
1558
- /daily limit|hourly limit reached/i,
1559
- /limit reached.*reset/i,
1560
- /resets in .* days/i
1561
- // from real opencode error
1562
- ];
1563
- for (const re of strongPatterns) {
1564
- if (re.test(t)) return true;
1565
- }
1566
- return false;
1567
- };
1568
- if (isQuotaText(stderrText)) {
1569
- return { limited: true, message: `quota/rate limit signal from ${provider} (stderr)` };
1570
- }
1571
- if (isQuotaText(combined)) {
1572
- return { limited: true, message: `quota/rate limit signal from ${provider}` };
1573
- }
1574
- return { limited: false };
1575
- }
1576
- var DEFAULT_AGY_TIMEOUT_MS = 6e5;
1577
- var DEFAULT_OPENCODE_TIMEOUT_MS = 6e5;
1578
- var DEFAULT_GROK_TIMEOUT_MS = 6e5;
1579
- var BUFFERED_STREAMING_PROVIDERS = /* @__PURE__ */ new Set([
1580
- "codex",
1581
- "claude",
1582
- "qoder",
1583
- "grok",
1584
- "kimi"
1585
- ]);
1586
- function isBufferedCliStreamingProvider(provider) {
1587
- return BUFFERED_STREAMING_PROVIDERS.has(provider);
1588
- }
1589
- var cliSessions = /* @__PURE__ */ new Map();
1590
- var CLI_PROBE_BINARIES = {
1591
- copilot: ["gh", "copilot"],
1592
- gemini: ["gemini"],
1593
- codex: ["codex"],
1594
- claude: ["claude"],
1595
- agy: ["agy"],
1596
- qoder: ["qoder"],
1597
- opencode: ["opencode"],
1598
- grok: ["grok"],
1599
- kimi: ["kimi"]
1600
- };
1601
- function getCliProviderLabel(provider) {
1602
- switch (provider) {
1603
- case "claude":
1604
- return "Claude CLI";
1605
- case "codex":
1606
- return "Codex CLI";
1607
- case "copilot":
1608
- return "Copilot CLI";
1609
- case "agy":
1610
- return "Antigravity CLI";
1611
- case "qoder":
1612
- return "Qoder CLI";
1613
- case "gemini":
1614
- return "Gemini CLI";
1615
- case "opencode":
1616
- return "OpenCode CLI";
1617
- case "grok":
1618
- return "Grok CLI";
1619
- case "kimi":
1620
- return "Kimi Code CLI";
1621
- }
1622
- }
1623
- function supportsNativeSystemPrompt(provider) {
1624
- return provider === "claude";
1625
- }
1626
- function supportsModel(provider) {
1627
- return provider !== "codex";
1628
- }
1629
- function supportsReasoningEffort(provider) {
1630
- return provider === "claude" || provider === "copilot" || provider === "qoder" || provider === "opencode" || provider === "grok" || // agy 1.5.9 支持 --effort low|medium|high|xhigh|max(无 ultra,见 mapAgyEffort)
1631
- provider === "agy";
1632
- }
1633
- function mapAgyEffort(effort) {
1634
- return effort === "ultra" ? "max" : effort;
1635
- }
1636
- function normalizeAgyUsage(raw) {
1637
- if (!raw || typeof raw !== "object") return void 0;
1638
- const u = raw;
1639
- const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1640
- const input = num(u.input_tokens);
1641
- const output = num(u.output_tokens);
1642
- const total = num(u.total_tokens);
1643
- const cacheRead = num(u.cache_read_tokens);
1644
- if (input === void 0 && output === void 0 && total === void 0 && cacheRead === void 0) {
1645
- return void 0;
1646
- }
1647
- return {
1648
- ...input !== void 0 ? { input_tokens: input } : {},
1649
- ...output !== void 0 ? { output_tokens: output } : {},
1650
- ...total !== void 0 ? { total_tokens: total } : {},
1651
- ...cacheRead !== void 0 ? { cache_read_input_tokens: cacheRead } : {}
1652
- };
1653
- }
1654
- function parseAgyJsonResult(raw) {
1655
- let last;
1656
- for (const line of raw.split("\n")) {
1657
- const trimmed = line.trim();
1658
- if (!trimmed.startsWith("{")) continue;
1659
- let parsed;
1660
- try {
1661
- parsed = JSON.parse(trimmed);
1662
- } catch {
1663
- continue;
1664
- }
1665
- if (!parsed || typeof parsed !== "object") continue;
1666
- const obj = parsed;
1667
- const response = typeof obj.response === "string" ? obj.response : void 0;
1668
- const usage = normalizeAgyUsage(obj.usage);
1669
- if (response === void 0 && usage === void 0) continue;
1670
- last = {
1671
- ...response !== void 0 ? { response } : {},
1672
- ...usage ? { usage } : {}
1673
- };
1674
- }
1675
- return last;
1676
- }
1677
- function shouldPassClaudeModel(options) {
1678
- return (options.env?.NOLO_CLAUDE_CLI_ALLOW_MODEL ?? process.env.NOLO_CLAUDE_CLI_ALLOW_MODEL) === "1";
1679
- }
1680
- var DATA_URL_RE = /^data:image\/([\w.+-]+);base64,([A-Za-z0-9+/=]+)$/;
1681
- var MIME_EXT = {
1682
- "png": ".png",
1683
- "jpeg": ".jpg",
1684
- "jpg": ".jpg",
1685
- "gif": ".gif",
1686
- "webp": ".webp",
1687
- "svg+xml": ".svg",
1688
- "bmp": ".bmp",
1689
- "tiff": ".tiff",
1690
- "avif": ".avif"
1691
- };
1692
- function inferExtFromMime(extPart) {
1693
- return MIME_EXT[extPart.toLowerCase().trim()] ?? ".bin";
1694
- }
1695
- var FILE_URL_RE = /^file:\/\/(.+)$/;
1696
- function writeDataUrlToTempImage(dataUrl, tempDir, index) {
1697
- const match = dataUrl.match(DATA_URL_RE);
1698
- if (!match) {
1699
- throw new Error(`Invalid data URL format for image #${index + 1}; expected data:image/<type>;base64,<data>`);
1700
- }
1701
- const [, mimeExt, b64] = match;
1702
- const ext = inferExtFromMime(mimeExt);
1703
- const filePath = join(tempDir, `image-${index + 1}${ext}`);
1704
- writeFileSync2(filePath, Buffer.from(b64, "base64"));
1705
- return filePath;
1706
- }
1707
- function materializeCliImageInputs(imageInputs, cwd) {
1708
- let tempDir = null;
1709
- const materialized = imageInputs.map((input, index) => {
1710
- const src = input.source.trim();
1711
- if (src.startsWith("http://") || src.startsWith("https://")) {
1712
- return { ...input, materializedPath: void 0 };
1713
- }
1714
- const fileUrlMatch = src.match(FILE_URL_RE);
1715
- if (fileUrlMatch) {
1716
- const localPath = fileUrlMatch[1];
1717
- return {
1718
- ...input,
1719
- materializedPath: isAbsolute2(localPath) ? localPath : resolve2(cwd, localPath)
1720
- };
1721
- }
1722
- if (src.startsWith("data:")) {
1723
- if (!tempDir) {
1724
- tempDir = mkdtempSync(join(tmpdir(), "nolo-cli-assets-"));
1725
- }
1726
- const filePath = writeDataUrlToTempImage(src, tempDir, index);
1727
- return { ...input, materializedPath: filePath };
1728
- }
1729
- return {
1730
- ...input,
1731
- materializedPath: isAbsolute2(src) ? src : resolve2(cwd, src)
1732
- };
1733
- });
1734
- return { materialized, tempDir };
1735
- }
1736
- function buildImageReferencePromptBlock(provider, materialized) {
1737
- const label = getCliProviderLabel(provider);
1738
- const localPaths = materialized.filter((img) => img.materializedPath).map((img) => img.materializedPath);
1739
- const httpUrls = materialized.filter((img) => !img.materializedPath).map((img) => img.source);
1740
- const lines = [];
1741
- if (localPaths.length > 0) {
1742
- lines.push(
1743
- `[User attached image(s) - local file references (accessible at these paths):]`,
1744
- ...localPaths.map((p) => ` - ${p}`),
1745
- `Please read and analyze these image files as part of the user's request.`
1746
- );
1747
- }
1748
- if (httpUrls.length > 0) {
1749
- lines.push(
1750
- `[User attached image(s) - remote URLs (content not available locally):]`,
1751
- ...httpUrls.map((u) => ` - ${u}`),
1752
- `These remote URLs could not be downloaded automatically. If you cannot access them, describe what you can infer from context.`
1753
- );
1754
- }
1755
- const warning = materialized.length > 0 ? `${label} image input is passed as local file references; native image flags are not available in this wrapper.` : null;
1756
- return {
1757
- promptSuffix: lines.length > 0 ? lines.join("\n") + "\n\n" : "",
1758
- warning
1759
- };
1760
- }
1761
- function collectCliCapabilityWarnings(provider, options) {
1762
- const warnings = [];
1763
- const label = getCliProviderLabel(provider);
1764
- if (options.reasoningEffort !== void 0 && !supportsReasoningEffort(provider)) {
1765
- warnings.push(`${label} does not support reasoning_effort; ignored.`);
1766
- }
1767
- if (provider === "claude" && options.model !== void 0 && !shouldPassClaudeModel(options)) {
1768
- warnings.push(
1769
- "Claude CLI model selection is disabled by default because current installs can reject --model; set NOLO_CLAUDE_CLI_ALLOW_MODEL=1 to pass it through."
1770
- );
1771
- } else if (options.model !== void 0 && !supportsModel(provider)) {
1772
- warnings.push(`${label} does not support model selection; ignored.`);
1773
- }
1774
- const unsupportedFields = [
1775
- ["temperature", options.temperature],
1776
- ["top_p", options.topP],
1777
- ["frequency_penalty", options.frequencyPenalty],
1778
- ["presence_penalty", options.presencePenalty],
1779
- ["max_tokens", options.maxTokens],
1780
- ["enableThinking", options.enableThinking ? true : void 0],
1781
- ["thinkingBudget", options.thinkingBudget]
1782
- ];
1783
- for (const [field, value] of unsupportedFields) {
1784
- if (value !== void 0) {
1785
- warnings.push(`${label} does not support ${field}; ignored.`);
1786
- }
1787
- }
1788
- return warnings;
1789
- }
1790
- function resolveCliExecution(provider, prompt, options) {
1791
- const warnings = collectCliCapabilityWarnings(provider, options);
1792
- const imageInputs = options.imageInputs ?? [];
1793
- let resolvedPrompt = prompt;
1794
- let resolvedOptions = options;
1795
- let imageTempDir;
1796
- if (imageInputs.length > 0) {
1797
- const { materialized, tempDir } = materializeCliImageInputs(
1798
- imageInputs,
1799
- options.cwd ?? process.cwd()
1800
- );
1801
- imageTempDir = tempDir ?? void 0;
1802
- if (provider === "codex") {
1803
- resolvedOptions = {
1804
- ...resolvedOptions,
1805
- imageInputs: materialized
1806
- };
1807
- } else {
1808
- const block = buildImageReferencePromptBlock(provider, materialized);
1809
- if (block.promptSuffix) {
1810
- resolvedPrompt = block.promptSuffix + resolvedPrompt;
1811
- }
1812
- if (block.warning) {
1813
- warnings.push(block.warning);
1814
- }
1815
- }
1816
- }
1817
- if (supportsNativeSystemPrompt(provider) || !options.systemPrompt?.trim()) {
1818
- return { prompt: resolvedPrompt, options: resolvedOptions, warnings, imageTempDir };
1819
- }
1820
- return {
1821
- prompt: buildCliPrompt(options.systemPrompt, resolvedPrompt),
1822
- options: {
1823
- ...resolvedOptions,
1824
- systemPrompt: void 0
1825
- },
1826
- warnings,
1827
- imageTempDir
1828
- };
1829
- }
1830
- function executeCopilot(prompt, options) {
1831
- const {
1832
- model,
1833
- reasoningEffort,
1834
- timeout = 12e4,
1835
- cwd = process.cwd(),
1836
- yolo = true
1837
- } = options;
1838
- return new Promise((resolve3, reject) => {
1839
- const args = [
1840
- "copilot",
1841
- "--",
1842
- "-p",
1843
- prompt,
1844
- "--silent",
1845
- "--disable-builtin-mcps",
1846
- "--stream",
1847
- "off",
1848
- "--no-color"
1849
- ];
1850
- if (model) args.push("--model", model);
1851
- if (reasoningEffort) args.push("--reasoning-effort", reasoningEffort);
1852
- if (yolo) args.push("--yolo");
1853
- runBufferedCli(
1854
- "Copilot",
1855
- "gh",
1856
- args,
1857
- cwd,
1858
- { ...buildCliProcessEnv(options.env), NO_COLOR: "1" },
1859
- timeout,
1860
- options.signal,
1861
- (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()
1862
- ).then(resolve3, reject);
1863
- });
1864
- }
1865
- function normalizeGeminiContent(content) {
1866
- if (typeof content === "string") return content;
1867
- if (Array.isArray(content)) {
1868
- return content.map((part) => {
1869
- if (typeof part === "string") return part;
1870
- if (part && typeof part === "object" && typeof part.text === "string") {
1871
- return part.text;
1872
- }
1873
- return "";
1874
- }).join("");
1875
- }
1876
- if (content && typeof content === "object" && typeof content.text === "string") {
1877
- return content.text;
1878
- }
1879
- return "";
1880
- }
1881
- function extractGeminiEventText(event) {
1882
- if (event?.type === "message" && event.role === "assistant") {
1883
- return normalizeGeminiContent(event.content);
1884
- }
1885
- if (event?.type === "result" && typeof event.result === "string") {
1886
- return event.result;
1887
- }
1888
- return "";
1889
- }
1890
- function parseGeminiStreamJson(stdout) {
1891
- const parts = [];
1892
- for (const line of stdout.split("\n")) {
1893
- const trimmed = line.trim();
1894
- if (!trimmed) continue;
1895
- try {
1896
- const event = JSON.parse(trimmed);
1897
- const text = extractGeminiEventText(event);
1898
- if (text) parts.push(text);
1899
- } catch {
1900
- }
1901
- }
1902
- return parts.join("");
1903
- }
1904
- function resolveGeminiCommand(env, platform = process.platform) {
1905
- if (platform !== "win32") return { command: "gemini", args: [] };
1906
- const path = Object.entries(env).find(([key]) => key.toLowerCase() === "path")?.[1] ?? "";
1907
- for (const directory of path.split(";")) {
1908
- if (!directory || !isAbsolute2(directory)) continue;
1909
- if (existsSync2(join(directory, "gemini.exe"))) {
1910
- return { command: join(directory, "gemini.exe"), args: [] };
1911
- }
1912
- if (!existsSync2(join(directory, "gemini.cmd"))) continue;
1913
- try {
1914
- const root = realpathSync2(join(directory, "node_modules", "@google", "gemini-cli"));
1915
- const manifest = JSON.parse(readFileSync2(join(root, "package.json"), "utf8"));
1916
- const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.gemini;
1917
- if (manifest.name !== "@google/gemini-cli" || typeof bin !== "string" || !bin) {
1918
- throw new Error("missing package bin");
1919
- }
1920
- const entry = realpathSync2(resolve2(root, bin));
1921
- const withinPackage = relative2(root, entry);
1922
- if (withinPackage.startsWith("..") || isAbsolute2(withinPackage) || !/\.[cm]?js$/i.test(entry)) {
1923
- throw new Error("package bin is not a contained JavaScript entry");
1924
- }
1925
- const node = join(directory, "node.exe");
1926
- return { command: existsSync2(node) ? node : "node", args: [entry] };
1927
- } catch (error) {
1928
- throw new Error(`Gemini npm entry could not be resolved: ${String(error)}`);
1929
- }
1930
- }
1931
- return { command: "gemini", args: [] };
1932
- }
1933
- function executeGemini(prompt, options) {
1934
- const {
1935
- model = "gemini-3.8-flash",
1936
- timeout = 12e4,
1937
- cwd = process.cwd(),
1938
- yolo = true
1939
- } = options;
1940
- return new Promise((resolve3, reject) => {
1941
- const args = [
1942
- "-p",
1943
- prompt,
1944
- "--output-format",
1945
- "stream-json",
1946
- "-m",
1947
- model
1948
- ];
1949
- if (yolo) args.push("--yolo");
1950
- args.push("-e", "none");
1951
- const env = { ...buildCliProcessEnv(options.env), NO_COLOR: "1", NODE_OPTIONS: "--no-deprecation" };
1952
- const launcher = resolveGeminiCommand(env);
1953
- runBufferedCli(
1954
- "Gemini",
1955
- launcher.command,
1956
- [...launcher.args, ...args],
1957
- cwd,
1958
- env,
1959
- timeout,
1960
- options.signal,
1961
- parseGeminiStreamJson
1962
- ).then(resolve3, reject);
1963
- });
1964
- }
1965
- function executeCodex(prompt, options) {
1966
- const {
1967
- cwd = process.cwd(),
1968
- yolo = true
1969
- } = options;
1970
- const imagePaths = (options.imageInputs ?? []).map((img) => img.materializedPath).filter((p) => Boolean(p));
1971
- return new Promise((resolve3, reject) => {
1972
- const tempDir = mkdtempSync(join(tmpdir(), "codex-exec-"));
1973
- const outputFile = join(tempDir, "last-message.txt");
1974
- const executable = resolveLaunchableCodexCommand(options.env);
1975
- const args = [
1976
- "exec",
1977
- "--skip-git-repo-check",
1978
- "--ephemeral",
1979
- "--color",
1980
- "never",
1981
- "--output-last-message",
1982
- outputFile,
1983
- "--cd",
1984
- cwd
1985
- ];
1986
- if (yolo) {
1987
- args.push("--sandbox");
1988
- args.push("danger-full-access");
1989
- }
1990
- for (const imgPath of imagePaths) {
1991
- args.push("-i", imgPath);
1992
- }
1993
- const start = Date.now();
1994
- const proc = spawnCliProcess(executable, [...args, prompt], {
1995
- cwd,
1996
- env: buildCliProcessEnv(options.env),
1997
- stdio: ["ignore", "pipe", "pipe"],
1998
- signal: options.signal
1999
- }, reject);
2000
- const stdout = createUtf8Collector();
2001
- const stderr = createUtf8Collector();
2002
- proc.stdout.on("data", (data) => {
2003
- stdout.write(data);
2004
- });
2005
- proc.stderr.on("data", (data) => {
2006
- stderr.write(data);
2007
- });
2008
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2009
- const stdoutText = stdout.end();
2010
- const stderrText = stderr.end();
2011
- if (code !== 0 && code !== null) {
2012
- rmSync(tempDir, { recursive: true, force: true });
2013
- const quota = detectCliProviderQuotaLimit("codex", stdoutText, stderrText, code);
2014
- if (quota.limited) {
2015
- reject2(new CliProviderQuotaError("codex", quota.message || "Codex reported quota/limit"));
2016
- return;
2017
- }
2018
- reject2(new Error(`Codex CLI exited with code ${code}
2019
- stderr: ${stderrText}`));
2020
- return;
2021
- }
2022
- let text = stdoutText.trim();
2023
- try {
2024
- const lastMessage = readFileSync2(outputFile, "utf8").trim();
2025
- if (lastMessage) text = lastMessage;
2026
- } catch {
2027
- } finally {
2028
- rmSync(tempDir, { recursive: true, force: true });
2029
- }
2030
- resolve4({
2031
- text,
2032
- raw: stdoutText,
2033
- elapsed: Date.now() - start
2034
- });
2035
- });
2036
- proc.on("error", (err) => {
2037
- rmSync(tempDir, { recursive: true, force: true });
2038
- reject(proc.pid ? stoppingCliError(err, proc) : err);
2039
- });
2040
- });
2041
- }
2042
- function executeClaude(prompt, options) {
2043
- const {
2044
- model,
2045
- systemPrompt,
2046
- reasoningEffort,
2047
- timeout = 12e4,
2048
- cwd = process.cwd(),
2049
- yolo = true
2050
- } = options;
2051
- return new Promise((resolve3, reject) => {
2052
- const args = ["--add-dir", cwd, "-p", prompt];
2053
- if (model && shouldPassClaudeModel(options)) {
2054
- args.push("--model");
2055
- args.push(model);
2056
- }
2057
- if (systemPrompt?.trim()) {
2058
- args.push("--system-prompt");
2059
- args.push(systemPrompt.trim());
2060
- }
2061
- if (reasoningEffort) {
2062
- args.push("--effort");
2063
- args.push(reasoningEffort);
2064
- }
2065
- if (yolo) {
2066
- args.push("--permission-mode");
2067
- args.push("bypassPermissions");
2068
- }
2069
- const start = Date.now();
2070
- const proc = spawnCliProcess("claude", args, {
2071
- cwd,
2072
- env: buildCliProcessEnv(options.env),
2073
- stdio: ["ignore", "pipe", "pipe"],
2074
- signal: options.signal
2075
- }, reject);
2076
- const stdout = createUtf8Collector();
2077
- const stderr = createUtf8Collector();
2078
- let timer;
2079
- if (timeout > 0) {
2080
- timer = setTimeout(() => {
2081
- reject(stoppingCliError(new Error(`Claude CLI timed out after ${timeout}ms`), proc));
2082
- }, timeout);
2083
- }
2084
- proc.stdout.on("data", (data) => {
2085
- stdout.write(data);
2086
- });
2087
- proc.stderr.on("data", (data) => {
2088
- stderr.write(data);
2089
- });
2090
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2091
- if (timer) clearTimeout(timer);
2092
- const stdoutText = stdout.end();
2093
- const stderrText = stderr.end();
2094
- if (code !== 0 && code !== null) {
2095
- const quota = detectCliProviderQuotaLimit("claude", stdoutText, stderrText, code);
2096
- if (quota.limited) {
2097
- reject2(new CliProviderQuotaError("claude", quota.message || "Claude reported quota/limit"));
2098
- return;
2099
- }
2100
- reject2(new Error(`Claude CLI exited with code ${code}
2101
- stderr: ${stderrText}`));
2102
- return;
2103
- }
2104
- resolve4({
2105
- text: stdoutText.trim(),
2106
- raw: stdoutText,
2107
- elapsed: Date.now() - start
2108
- });
2109
- });
2110
- proc.on("error", (err) => {
2111
- if (timer) clearTimeout(timer);
2112
- reject(proc.pid ? stoppingCliError(err, proc) : err);
2113
- });
2114
- });
2115
- }
2116
- function formatCliTimeout(timeoutMs) {
2117
- return `${Math.max(1, Math.ceil(timeoutMs / 1e3))}s`;
2118
- }
2119
- function tailText(value, maxChars = 1200) {
2120
- if (value.length <= maxChars) return value;
2121
- return value.slice(value.length - maxChars);
2122
- }
2123
- function createUtf8Collector() {
2124
- const decoder = new StringDecoder2("utf8");
2125
- let text = "";
2126
- let ended = false;
2127
- const finish = () => {
2128
- if (ended) return "";
2129
- ended = true;
2130
- const chunk = decoder.end();
2131
- if (chunk) text += chunk;
2132
- return chunk;
2133
- };
2134
- return {
2135
- write(data) {
2136
- if (ended) return "";
2137
- const chunk = decoder.write(data);
2138
- text += chunk;
2139
- return chunk;
2140
- },
2141
- finish,
2142
- end() {
2143
- finish();
2144
- return text;
2145
- },
2146
- get text() {
2147
- return text;
2148
- }
2149
- };
2150
- }
2151
- var CLI_ABORT_SIGKILL_GRACE_MS = 5e3;
2152
- function terminateCliProcessGroup(proc, signal, onWindowsTreeStopped) {
2153
- const pid = typeof proc.pid === "number" ? proc.pid : 0;
2154
- if (pid > 0 && process.platform !== "win32") {
2155
- try {
2156
- process.kill(-pid, signal);
2157
- return;
2158
- } catch {
2159
- }
2160
- }
2161
- if (pid > 0 && process.platform === "win32") {
2162
- try {
2163
- const killer = spawn3("taskkill", ["/pid", String(pid), "/T", "/F"], {
2164
- stdio: "ignore",
2165
- windowsHide: true
2166
- });
2167
- killer.on("error", () => {
2168
- });
2169
- killer.once("close", (code) => {
2170
- if (code === 0) onWindowsTreeStopped();
2171
- });
2172
- return;
2173
- } catch {
2174
- }
2175
- }
2176
- try {
2177
- proc.kill(signal);
2178
- } catch {
2179
- }
2180
- }
2181
- var executionStopped = Symbol.for("nolo.cli.executionStopped");
2182
- function attachExecutionStoppedPromise(error, stoppedPromise) {
2183
- Object.defineProperty(error, executionStopped, { value: stoppedPromise, configurable: true, enumerable: true });
2184
- return error;
2185
- }
2186
- function getExecutionStoppedPromise(error) {
2187
- const seen = /* @__PURE__ */ new Set();
2188
- const visit = (value) => {
2189
- if (typeof value !== "object" || value === null || seen.has(value)) return;
2190
- seen.add(value);
2191
- const entry = value;
2192
- if (entry[executionStopped]) return entry[executionStopped];
2193
- const pending = [visit(entry.cause), ...value instanceof AggregateError ? value.errors.map(visit) : []].filter((promise) => promise !== void 0);
2194
- return pending.length ? Promise.all(pending).then(() => {
2195
- }) : void 0;
2196
- };
2197
- return visit(error);
2198
- }
2199
- var unconfirmedWindowsClose = new Promise(() => {
2200
- });
2201
- var stoppingProcesses = /* @__PURE__ */ new WeakMap();
2202
- function terminateCliProcessGroupEscalating(proc) {
2203
- const existing = stoppingProcesses.get(proc);
2204
- if (existing) return existing;
2205
- const { promise, resolve: resolve3 } = Promise.withResolvers();
2206
- stoppingProcesses.set(proc, promise);
2207
- const pid = proc.pid;
2208
- if (!pid) {
2209
- terminateCliProcessGroup(proc, "SIGTERM", () => {
2210
- });
2211
- resolve3();
2212
- return promise;
2213
- }
2214
- const startedAt = performance.now();
2215
- let escalated = false;
2216
- let windowsTreeStopped = false;
2217
- const markWindowsTreeStopped = () => {
2218
- windowsTreeStopped = true;
2219
- };
2220
- let timer;
2221
- const inspect = () => {
2222
- let groupEmpty = windowsTreeStopped;
2223
- if (process.platform !== "win32") {
2224
- try {
2225
- process.kill(-pid, 0);
2226
- } catch (error) {
2227
- groupEmpty = error.code === "ESRCH";
2228
- }
2229
- }
2230
- if (groupEmpty && (proc.exitCode != null || proc.signalCode != null)) {
2231
- clearInterval(timer);
2232
- resolve3();
2233
- return;
2234
- }
2235
- const elapsed = performance.now() - startedAt;
2236
- if (!escalated && elapsed >= CLI_ABORT_SIGKILL_GRACE_MS) {
2237
- escalated = true;
2238
- terminateCliProcessGroup(proc, "SIGKILL", markWindowsTreeStopped);
2239
- }
2240
- if (elapsed >= CLI_ABORT_SIGKILL_GRACE_MS + 1e4) {
2241
- clearInterval(timer);
2242
- console.warn("[cliExecutor] Could not confirm CLI process group shutdown", { pid });
2243
- }
2244
- };
2245
- terminateCliProcessGroup(proc, "SIGTERM", markWindowsTreeStopped);
2246
- timer = setInterval(inspect, 25);
2247
- timer.unref?.();
2248
- inspect();
2249
- return promise;
2250
- }
2251
- function onCliClose(proc, resolve3, reject, settle) {
2252
- proc.on("close", (code, signal) => {
2253
- let stopped = stoppingProcesses.get(proc);
2254
- if (!stopped && proc.pid && process.platform === "win32") {
2255
- stopped = unconfirmedWindowsClose;
2256
- } else if (!stopped && proc.pid) {
2257
- try {
2258
- process.kill(-proc.pid, 0);
2259
- stopped = terminateCliProcessGroupEscalating(proc);
2260
- } catch (error) {
2261
- if (error.code !== "ESRCH") stopped = terminateCliProcessGroupEscalating(proc);
2262
- }
2263
- }
2264
- const annotate = (value) => stopped ? attachExecutionStoppedPromise(value, stopped) : value;
2265
- settle((value) => resolve3(annotate(value)), (error) => reject(stopped ? annotate(error instanceof Error ? error : new Error(String(error))) : error), code, signal);
2266
- });
2267
- }
2268
- function stoppingCliError(error, proc) {
2269
- return attachExecutionStoppedPromise(
2270
- error instanceof Error ? error : new Error(String(error)),
2271
- terminateCliProcessGroupEscalating(proc)
2272
- );
2273
- }
2274
- function createCliAbortError(message = "CLI execution aborted") {
2275
- return new DOMException(message, "AbortError");
2276
- }
2277
- function attachCliAbortSignal(proc, signal, onAbort) {
2278
- if (!signal) return () => {
2279
- };
2280
- const handleAbort = () => onAbort(stoppingCliError(createCliAbortError(), proc));
2281
- if (signal.aborted) {
2282
- handleAbort();
2283
- return () => {
2284
- };
2285
- }
2286
- signal.addEventListener("abort", handleAbort, { once: true });
2287
- return () => signal.removeEventListener("abort", handleAbort);
2288
- }
2289
- function spawnCliProcess(executable, args, options, onAbort) {
2290
- const { signal, ...spawnOptions } = options;
2291
- const proc = spawn3(executable, args, {
2292
- ...spawnOptions,
2293
- detached: process.platform !== "win32"
2294
- });
2295
- if (signal) {
2296
- const detachAbort = attachCliAbortSignal(proc, signal, onAbort ?? (() => {
2297
- }));
2298
- proc.once("exit", detachAbort);
2299
- }
2300
- return proc;
2301
- }
2302
- function runBufferedCli(label, executable, args, cwd, env, timeout, signal, parseText) {
2303
- return new Promise((resolve3, reject) => {
2304
- const start = Date.now();
2305
- const stdout = createUtf8Collector();
2306
- const stderr = createUtf8Collector();
2307
- let timer;
2308
- const fail = (error) => {
2309
- if (timer) clearTimeout(timer);
2310
- reject(error);
2311
- };
2312
- const proc = spawnCliProcess(executable, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], signal }, fail);
2313
- if (timeout > 0 && !signal?.aborted) timer = setTimeout(() => fail(stoppingCliError(new Error(`${label} CLI timed out after ${timeout}ms`), proc)), timeout);
2314
- proc.stdout.on("data", (chunk) => stdout.write(chunk));
2315
- proc.stderr.on("data", (chunk) => stderr.write(chunk));
2316
- proc.on("error", (error) => fail(proc.pid ? stoppingCliError(error, proc) : error));
2317
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code, exitSignal) => {
2318
- if (timer) clearTimeout(timer);
2319
- if (code !== 0 || exitSignal) {
2320
- reject2(new Error(`${label} CLI failed: ${exitSignal ?? code}
2321
- stderr: ${stderr.end()}`));
2322
- return;
2323
- }
2324
- const raw = stdout.end();
2325
- resolve4({ text: parseText(raw), raw, elapsed: Date.now() - start });
2326
- });
2327
- });
2328
- }
2329
- function buildAgyTimeoutError(timeout, stdout, stderr) {
2330
- const parts = [
2331
- `Antigravity CLI timed out after ${timeout}ms.`,
2332
- "agy print mode is agentic and can keep waiting for the conversation to become fully idle; prefer shorter scoped prompts or split the task into multiple turns."
2333
- ];
2334
- const stdoutTail = tailText(stdout).trim();
2335
- const stderrTail = tailText(stderr).trim();
2336
- if (stdoutTail) parts.push(`stdout tail:
2337
- ${stdoutTail}`);
2338
- if (stderrTail) parts.push(`stderr tail:
2339
- ${stderrTail}`);
2340
- return new Error(parts.join("\n"));
2341
- }
2342
- function executeAgy(prompt, options) {
2343
- const {
2344
- timeout = DEFAULT_AGY_TIMEOUT_MS,
2345
- cwd = process.cwd(),
2346
- yolo = true,
2347
- reasoningEffort
2348
- } = options;
2349
- const releasePrintSlot = acquireAgyPrintSlot("agy --print");
2350
- let promise;
2351
- try {
2352
- promise = new Promise((resolve3, reject) => {
2353
- const args = [
2354
- "--add-dir",
2355
- cwd,
2356
- "--print=" + prompt,
2357
- "--output-format",
2358
- "json",
2359
- "--print-timeout",
2360
- formatCliTimeout(timeout)
2361
- ];
2362
- if (options.model) args.push("--model", options.model);
2363
- if (reasoningEffort) args.push("--effort", mapAgyEffort(reasoningEffort));
2364
- if (yolo) {
2365
- args.push("--dangerously-skip-permissions");
2366
- }
2367
- const start = Date.now();
2368
- const proc = spawnCliProcess("agy", args, {
2369
- cwd,
2370
- env: buildCliProcessEnv(options.env),
2371
- stdio: ["ignore", "pipe", "pipe"],
2372
- detached: process.platform !== "win32",
2373
- signal: options.signal
2374
- }, reject);
2375
- const stdout = createUtf8Collector();
2376
- const stderr = createUtf8Collector();
2377
- let timer;
2378
- let settled = false;
2379
- const clearTimers = () => {
2380
- if (timer) clearTimeout(timer);
2381
- };
2382
- if (timeout > 0) {
2383
- timer = setTimeout(() => {
2384
- if (settled) return;
2385
- settled = true;
2386
- reject(stoppingCliError(buildAgyTimeoutError(timeout, stdout.end(), stderr.end()), proc));
2387
- }, timeout + 1e3);
2388
- }
2389
- proc.stdout.on("data", (data) => {
2390
- stdout.write(data);
2391
- });
2392
- proc.stderr.on("data", (data) => {
2393
- stderr.write(data);
2394
- });
2395
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2396
- if (settled) {
2397
- clearTimers();
2398
- return;
2399
- }
2400
- settled = true;
2401
- clearTimers();
2402
- const stdoutText = stdout.end();
2403
- const stderrText = stderr.end();
2404
- if (code !== 0 && code !== null) {
2405
- console.error("[cliExecutor] agy process exited with non-zero code:", code, "stderr:", stderrText);
2406
- const quota = detectCliProviderQuotaLimit("agy", stdoutText, stderrText, code);
2407
- if (quota.limited) {
2408
- reject2(new CliProviderQuotaError("agy", quota.message || "Agy reported quota/limit"));
2409
- return;
2410
- }
2411
- reject2(new Error(`Antigravity CLI exited with code ${code}
2412
- stderr: ${stderrText}`));
2413
- return;
2414
- }
2415
- const parsed = parseAgyJsonResult(stdoutText);
2416
- resolve4({
2417
- text: (parsed?.response ?? stdoutText).trim(),
2418
- raw: stdoutText,
2419
- elapsed: Date.now() - start,
2420
- ...parsed?.usage ? { usage: parsed.usage } : {}
2421
- });
2422
- });
2423
- proc.on("error", (err) => {
2424
- if (settled) return;
2425
- settled = true;
2426
- clearTimers();
2427
- console.error("[cliExecutor] agy process error event:", err);
2428
- reject(proc.pid ? stoppingCliError(err, proc) : err);
2429
- });
2430
- });
2431
- } catch (err) {
2432
- releasePrintSlot();
2433
- throw err;
2434
- }
2435
- return promise.finally(releasePrintSlot);
2436
- }
2437
- function executeAgyStreaming(prompt, options) {
2438
- const {
2439
- cwd = process.cwd(),
2440
- timeout = DEFAULT_AGY_TIMEOUT_MS,
2441
- yolo = true,
2442
- model,
2443
- reasoningEffort,
2444
- onChunk
2445
- } = options;
2446
- const releasePrintSlot = acquireAgyPrintSlot("agy --print");
2447
- let promise;
2448
- try {
2449
- promise = new Promise((resolve3, reject) => {
2450
- const args = [
2451
- "--add-dir",
2452
- cwd,
2453
- "--print=" + prompt,
2454
- "--output-format",
2455
- "stream-json",
2456
- "--print-timeout",
2457
- formatCliTimeout(timeout)
2458
- ];
2459
- if (model) args.push("--model", model);
2460
- if (reasoningEffort) args.push("--effort", mapAgyEffort(reasoningEffort));
2461
- if (yolo) args.push("--dangerously-skip-permissions");
2462
- const start = Date.now();
2463
- const proc = spawnCliProcess("agy", args, {
2464
- cwd,
2465
- env: buildCliProcessEnv(options.env),
2466
- stdio: ["ignore", "pipe", "pipe"],
2467
- detached: process.platform !== "win32",
2468
- signal: options.signal
2469
- });
2470
- const stdout = createUtf8Collector();
2471
- const stderr = createUtf8Collector();
2472
- let pending = "";
2473
- let answer = "";
2474
- let agyUsage;
2475
- let settled = false;
2476
- let timer;
2477
- let detachAbort = () => {
2478
- };
2479
- const finish = (callback) => {
2480
- if (settled) return;
2481
- settled = true;
2482
- if (timer) clearTimeout(timer);
2483
- detachAbort();
2484
- callback();
2485
- };
2486
- const fail = (error) => {
2487
- if (settled) return;
2488
- finish(() => reject(stoppingCliError(error, proc)));
2489
- };
2490
- detachAbort = attachCliAbortSignal(proc, options.signal, (error) => {
2491
- finish(() => reject(error));
2492
- });
2493
- if (!settled && timeout > 0) {
2494
- timer = setTimeout(() => {
2495
- fail(buildAgyTimeoutError(timeout, stdout.end(), stderr.end()));
2496
- }, timeout + 1e3);
2497
- }
2498
- const consumeLine = (line) => {
2499
- if (settled || !line.trim()) return;
2500
- let event;
2501
- try {
2502
- event = JSON.parse(line);
2503
- } catch {
2504
- return;
2505
- }
2506
- const usageSource = event?.event === "result" ? event.result?.usage : event?.event === "step_update" ? event.step_update?.usage : void 0;
2507
- const normalizedUsage = normalizeAgyUsage(usageSource);
2508
- if (normalizedUsage) agyUsage = normalizedUsage;
2509
- if (event?.event !== "step_update" || event.step_update?.step_type !== "agent_response" || typeof event.step_update.text_delta !== "string") return;
2510
- const delta = event.step_update.text_delta;
2511
- if (!delta) return;
2512
- answer += delta;
2513
- try {
2514
- onChunk(delta);
2515
- } catch (error) {
2516
- fail(error);
2517
- }
2518
- };
2519
- proc.stdout.on("data", (data) => {
2520
- if (settled) return;
2521
- pending += stdout.write(data);
2522
- const lines = pending.split("\n");
2523
- pending = lines.pop() ?? "";
2524
- for (const line of lines) consumeLine(line);
2525
- });
2526
- proc.stderr.on("data", (data) => {
2527
- if (!settled) stderr.write(data);
2528
- });
2529
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code, signal) => {
2530
- if (settled) return;
2531
- pending += stdout.finish();
2532
- consumeLine(pending);
2533
- if (settled) return;
2534
- const raw = stdout.end();
2535
- const stderrText = stderr.end();
2536
- if (code !== 0 || signal) {
2537
- const quota = detectCliProviderQuotaLimit("agy", raw, stderrText, code);
2538
- finish(() => reject2(quota.limited ? new CliProviderQuotaError("agy", quota.message || "Agy reported quota/limit") : new Error(`Antigravity CLI exited with ${signal ? `signal ${signal}` : `code ${code}`}
2539
- stderr: ${stderrText}`)));
2540
- return;
2541
- }
2542
- finish(() => resolve4({
2543
- text: answer.trim(),
2544
- raw,
2545
- elapsed: Date.now() - start,
2546
- ...agyUsage ? { usage: agyUsage } : {}
2547
- }));
2548
- });
2549
- proc.on("error", (error) => fail(error));
2550
- });
2551
- } catch (err) {
2552
- releasePrintSlot();
2553
- throw err;
2554
- }
2555
- return promise.finally(releasePrintSlot);
2556
- }
2557
- function executeQoder(prompt, options) {
2558
- const {
2559
- model,
2560
- reasoningEffort,
2561
- timeout = 12e4,
2562
- cwd = process.cwd(),
2563
- yolo = true
2564
- } = options;
2565
- return new Promise((resolve3, reject) => {
2566
- const args = ["-p", prompt, "--cwd", cwd];
2567
- if (model) {
2568
- args.push("--model");
2569
- args.push(model);
2570
- }
2571
- if (reasoningEffort) {
2572
- args.push("--reasoning-effort");
2573
- args.push(reasoningEffort);
2574
- }
2575
- if (yolo) {
2576
- args.push("--dangerously-skip-permissions");
2577
- }
2578
- const start = Date.now();
2579
- const proc = spawnCliProcess("qoder", args, {
2580
- cwd,
2581
- env: buildCliProcessEnv(options.env),
2582
- stdio: ["ignore", "pipe", "pipe"],
2583
- signal: options.signal
2584
- }, reject);
2585
- const stdout = createUtf8Collector();
2586
- const stderr = createUtf8Collector();
2587
- let timer;
2588
- if (timeout > 0) {
2589
- timer = setTimeout(() => {
2590
- const partial = stdout.end() + "\n" + stderr.end();
2591
- const q = detectCliProviderQuotaLimit("qoder", "", partial, null);
2592
- if (q.limited) {
2593
- reject(stoppingCliError(new CliProviderQuotaError("qoder", q.message || "Qoder quota signal seen before timeout"), proc));
2594
- return;
2595
- }
2596
- reject(stoppingCliError(new Error(`Qoder CLI timed out after ${timeout}ms`), proc));
2597
- }, timeout);
2598
- }
2599
- proc.stdout.on("data", (data) => {
2600
- stdout.write(data);
2601
- });
2602
- proc.stderr.on("data", (data) => {
2603
- stderr.write(data);
2604
- const currentStderr = stderr.text;
2605
- if (detectCliProviderQuotaLimit("qoder", "", currentStderr, null).limited) {
2606
- if (timer) clearTimeout(timer);
2607
- reject(stoppingCliError(new CliProviderQuotaError("qoder", "quota signal detected incrementally in stderr"), proc));
2608
- return;
2609
- }
2610
- });
2611
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2612
- if (timer) clearTimeout(timer);
2613
- const stdoutText = stdout.end();
2614
- const stderrText = stderr.end();
2615
- const quota = detectCliProviderQuotaLimit("qoder", stdoutText, stderrText, code);
2616
- const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
2617
- if (quota.limited && hasRealErrorSignal) {
2618
- reject2(new CliProviderQuotaError("qoder", quota.message || "Qoder reported quota/limit"));
2619
- return;
2620
- }
2621
- if (code !== 0 && code !== null) {
2622
- console.error("[cliExecutor] qoder process exited with non-zero code:", code, "stderr:", stderrText);
2623
- reject2(new Error(`Qoder CLI exited with code ${code}
2624
- stderr: ${stderrText}`));
2625
- return;
2626
- }
2627
- resolve4({
2628
- text: stdoutText.trim(),
2629
- raw: stdoutText,
2630
- elapsed: Date.now() - start
2631
- });
2632
- });
2633
- proc.on("error", (err) => {
2634
- if (timer) clearTimeout(timer);
2635
- console.error("[cliExecutor] qoder process error event:", err);
2636
- reject(proc.pid ? stoppingCliError(err, proc) : err);
2637
- });
2638
- });
2639
- }
2640
- function parseOpenCodeJsonlEvents(stdout) {
2641
- const parts = [];
2642
- for (const line of stdout.split("\n")) {
2643
- const trimmed = line.trim();
2644
- if (!trimmed) continue;
2645
- try {
2646
- const event = JSON.parse(trimmed);
2647
- if (event.type === "text" && event.part?.type === "text" && typeof event.part.text === "string") {
2648
- parts.push(event.part.text);
2649
- }
2650
- } catch {
2651
- }
2652
- }
2653
- return parts.join("");
2654
- }
2655
- function executeOpenCode(prompt, options) {
2656
- const {
2657
- model,
2658
- reasoningEffort,
2659
- timeout = DEFAULT_OPENCODE_TIMEOUT_MS,
2660
- cwd = process.cwd(),
2661
- yolo = true
2662
- } = options;
2663
- return new Promise((resolve3, reject) => {
2664
- const args = [
2665
- "run",
2666
- "--format",
2667
- "json",
2668
- "--dir",
2669
- cwd,
2670
- "--print-logs"
2671
- // surface stream errors / quota / limit messages to stderr for fast detection
2672
- ];
2673
- if (model) {
2674
- args.push("--model");
2675
- args.push(model);
2676
- }
2677
- if (reasoningEffort) {
2678
- args.push("--variant");
2679
- args.push(reasoningEffort);
2680
- }
2681
- if (yolo) {
2682
- args.push("--dangerously-skip-permissions");
2683
- }
2684
- args.push(prompt);
2685
- const start = Date.now();
2686
- const proc = spawnCliProcess("opencode", args, {
2687
- cwd,
2688
- env: buildCliProcessEnv(options.env),
2689
- stdio: ["ignore", "pipe", "pipe"],
2690
- signal: options.signal
2691
- }, reject);
2692
- const stdout = createUtf8Collector();
2693
- const stderr = createUtf8Collector();
2694
- let timer;
2695
- if (timeout > 0) {
2696
- timer = setTimeout(() => {
2697
- const stdoutPartial = stdout.end();
2698
- const stderrPartial = stderr.end();
2699
- const q = detectCliProviderQuotaLimit("opencode", stdoutPartial, stderrPartial, null);
2700
- if (q.limited) {
2701
- reject(stoppingCliError(new CliProviderQuotaError("opencode", q.message || "OpenCode quota signal seen before timeout"), proc));
2702
- return;
2703
- }
2704
- reject(stoppingCliError(new Error(`OpenCode CLI timed out after ${timeout}ms`), proc));
2705
- }, timeout);
2706
- }
2707
- proc.stdout.on("data", (data) => {
2708
- stdout.write(data);
2709
- });
2710
- proc.stderr.on("data", (data) => {
2711
- stderr.write(data);
2712
- const currentStderr = stderr.text;
2713
- if (detectCliProviderQuotaLimit("opencode", "", currentStderr, null).limited) {
2714
- if (timer) clearTimeout(timer);
2715
- reject(stoppingCliError(new CliProviderQuotaError("opencode", "quota signal detected incrementally in stderr"), proc));
2716
- return;
2717
- }
2718
- });
2719
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2720
- if (timer) clearTimeout(timer);
2721
- const stdoutText = stdout.end();
2722
- const stderrText = stderr.end();
2723
- const quota = detectCliProviderQuotaLimit("opencode", stdoutText, stderrText, code);
2724
- const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
2725
- if (quota.limited && hasRealErrorSignal) {
2726
- reject2(new CliProviderQuotaError("opencode", quota.message || "OpenCode reported quota/limit"));
2727
- return;
2728
- }
2729
- if (code !== 0 && code !== null) {
2730
- console.error("[cliExecutor] opencode process exited with non-zero code:", code, "stderr:", stderrText);
2731
- reject2(new Error(`OpenCode CLI exited with code ${code}
2732
- stderr: ${stderrText}`));
2733
- return;
2734
- }
2735
- resolve4({
2736
- text: parseOpenCodeJsonlEvents(stdoutText).trim(),
2737
- raw: stdoutText,
2738
- elapsed: Date.now() - start
2739
- });
2740
- });
2741
- proc.on("error", (err) => {
2742
- if (timer) clearTimeout(timer);
2743
- console.error("[cliExecutor] opencode process error event:", err);
2744
- reject(proc.pid ? stoppingCliError(err, proc) : err);
2745
- });
2746
- });
2747
- }
2748
- function parseGrokJsonOutput(stdout) {
2749
- const trimmed = stdout.trim();
2750
- if (!trimmed) return "";
2751
- const parsed = JSON.parse(trimmed);
2752
- if (parsed.type === "error") {
2753
- throw new Error(typeof parsed.message === "string" ? parsed.message : "Grok CLI failed");
2754
- }
2755
- return typeof parsed.text === "string" ? parsed.text : "";
2756
- }
2757
- function buildGrokProcessEnv(extraEnv) {
2758
- return buildCliProcessEnv({
2759
- GROK_TELEMETRY_TRACE_UPLOAD: "0",
2760
- GROK_TELEMETRY_ENABLED: "0",
2761
- GROK_FEEDBACK_ENABLED: "0",
2762
- GROK_TELEMETRY_MIXPANEL_ENABLED: "0",
2763
- ...extraEnv
2764
- });
2765
- }
2766
- function executeGrok(prompt, options) {
2767
- const {
2768
- model,
2769
- reasoningEffort,
2770
- timeout = DEFAULT_GROK_TIMEOUT_MS,
2771
- cwd = process.cwd(),
2772
- yolo = true
2773
- } = options;
2774
- return new Promise((resolve3, reject) => {
2775
- const args = ["-p", prompt, "--cwd", cwd, "--output-format", "json"];
2776
- if (model) {
2777
- args.push("-m", model);
2778
- }
2779
- if (reasoningEffort) {
2780
- args.push("--effort", reasoningEffort);
2781
- }
2782
- if (yolo) {
2783
- args.push("--yolo");
2784
- }
2785
- const start = Date.now();
2786
- const proc = spawnCliProcess("grok", args, {
2787
- cwd,
2788
- env: buildGrokProcessEnv(options.env),
2789
- stdio: ["ignore", "pipe", "pipe"],
2790
- signal: options.signal
2791
- }, reject);
2792
- const stdout = createUtf8Collector();
2793
- const stderr = createUtf8Collector();
2794
- let timer;
2795
- if (timeout > 0) {
2796
- timer = setTimeout(() => {
2797
- const partial = stdout.end() + "\n" + stderr.end();
2798
- const q = detectCliProviderQuotaLimit("grok", "", partial, null);
2799
- if (q.limited) {
2800
- reject(stoppingCliError(new CliProviderQuotaError("grok", q.message || "Grok quota signal seen before timeout"), proc));
2801
- return;
2802
- }
2803
- reject(stoppingCliError(new Error(`Grok CLI timed out after ${timeout}ms`), proc));
2804
- }, timeout);
2805
- }
2806
- proc.stdout.on("data", (data) => {
2807
- stdout.write(data);
2808
- });
2809
- proc.stderr.on("data", (data) => {
2810
- stderr.write(data);
2811
- const currentStderr = stderr.text;
2812
- if (detectCliProviderQuotaLimit("grok", "", currentStderr, null).limited) {
2813
- if (timer) clearTimeout(timer);
2814
- reject(stoppingCliError(new CliProviderQuotaError("grok", "quota signal detected incrementally in stderr"), proc));
2815
- return;
2816
- }
2817
- });
2818
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2819
- if (timer) clearTimeout(timer);
2820
- const stdoutText = stdout.end();
2821
- const stderrText = stderr.end();
2822
- const quota = detectCliProviderQuotaLimit("grok", stdoutText, stderrText, code);
2823
- const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
2824
- if (quota.limited && hasRealErrorSignal) {
2825
- reject2(new CliProviderQuotaError("grok", quota.message || "Grok reported quota/limit"));
2826
- return;
2827
- }
2828
- if (code !== 0 && code !== null) {
2829
- console.error("[cliExecutor] grok process exited with non-zero code:", code, "stderr:", stderrText);
2830
- reject2(new Error(`Grok CLI exited with code ${code}
2831
- stderr: ${stderrText}`));
2832
- return;
2833
- }
2834
- try {
2835
- resolve4({
2836
- text: parseGrokJsonOutput(stdoutText).trim(),
2837
- raw: stdoutText,
2838
- elapsed: Date.now() - start
2839
- });
2840
- } catch (error) {
2841
- reject2(error);
2842
- }
2843
- });
2844
- proc.on("error", (err) => {
2845
- if (timer) clearTimeout(timer);
2846
- console.error("[cliExecutor] grok process error event:", err);
2847
- reject(proc.pid ? stoppingCliError(err, proc) : err);
2848
- });
2849
- });
2850
- }
2851
- function parseKimiStreamJson(stdout) {
2852
- const parts = [];
2853
- for (const line of stdout.split("\n")) {
2854
- const trimmed = line.trim();
2855
- if (!trimmed) continue;
2856
- try {
2857
- const event = JSON.parse(trimmed);
2858
- if (event.role === "assistant" && typeof event.content === "string" && event.content.length > 0) {
2859
- parts.push(event.content);
2860
- }
2861
- } catch {
2862
- }
2863
- }
2864
- return parts.join("");
2865
- }
2866
- function executeKimi(prompt, options) {
2867
- const {
2868
- model,
2869
- timeout = 12e4,
2870
- cwd = process.cwd()
2871
- } = options;
2872
- return new Promise((resolve3, reject) => {
2873
- const args = ["-p", prompt, "--output-format", "stream-json"];
2874
- if (model) {
2875
- args.push("-m", model);
2876
- }
2877
- const start = Date.now();
2878
- const proc = spawnCliProcess("kimi", args, {
2879
- cwd,
2880
- env: buildCliProcessEnv(options.env),
2881
- stdio: ["ignore", "pipe", "pipe"],
2882
- signal: options.signal
2883
- }, reject);
2884
- const stdout = createUtf8Collector();
2885
- const stderr = createUtf8Collector();
2886
- let timer;
2887
- if (timeout > 0) {
2888
- timer = setTimeout(() => {
2889
- const partial = stdout.end() + "\n" + stderr.end();
2890
- const q = detectCliProviderQuotaLimit("kimi", "", partial, null);
2891
- if (q.limited) {
2892
- reject(stoppingCliError(new CliProviderQuotaError("kimi", q.message || "Kimi quota signal seen before timeout"), proc));
2893
- return;
2894
- }
2895
- reject(stoppingCliError(new Error(`Kimi CLI timed out after ${timeout}ms`), proc));
2896
- }, timeout);
2897
- }
2898
- proc.stdout.on("data", (data) => {
2899
- stdout.write(data);
2900
- });
2901
- proc.stderr.on("data", (data) => {
2902
- stderr.write(data);
2903
- const currentStderr = stderr.text;
2904
- if (detectCliProviderQuotaLimit("kimi", "", currentStderr, null).limited) {
2905
- if (timer) clearTimeout(timer);
2906
- reject(stoppingCliError(new CliProviderQuotaError("kimi", "quota signal detected incrementally in stderr"), proc));
2907
- return;
2908
- }
2909
- });
2910
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
2911
- if (timer) clearTimeout(timer);
2912
- const stdoutText = stdout.end();
2913
- const stderrText = stderr.end();
2914
- const quota = detectCliProviderQuotaLimit("kimi", stdoutText, stderrText, code);
2915
- const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
2916
- if (quota.limited && hasRealErrorSignal) {
2917
- reject2(new CliProviderQuotaError("kimi", quota.message || "Kimi reported quota/limit"));
2918
- return;
2919
- }
2920
- if (code !== 0 && code !== null) {
2921
- console.error("[cliExecutor] kimi process exited with non-zero code:", code, "stderr:", stderrText);
2922
- reject2(new Error(`Kimi CLI exited with code ${code}
2923
- stderr: ${stderrText}`));
2924
- return;
2925
- }
2926
- resolve4({
2927
- text: parseKimiStreamJson(stdoutText).trim(),
2928
- raw: stdoutText,
2929
- elapsed: Date.now() - start
2930
- });
2931
- });
2932
- proc.on("error", (err) => {
2933
- if (timer) clearTimeout(timer);
2934
- console.error("[cliExecutor] kimi process error event:", err);
2935
- reject(proc.pid ? stoppingCliError(err, proc) : err);
2936
- });
2937
- });
2938
- }
2939
- var EXECUTORS = {
2940
- copilot: executeCopilot,
2941
- gemini: executeGemini,
2942
- codex: executeCodex,
2943
- claude: executeClaude,
2944
- agy: executeAgy,
2945
- qoder: executeQoder,
2946
- opencode: executeOpenCode,
2947
- grok: executeGrok,
2948
- kimi: executeKimi
2949
- };
2950
- function formatCliSessionTask(messages) {
2951
- return messages.map((message, index) => {
2952
- const speaker = message.role === "user" ? "\u7528\u6237" : "\u52A9\u624B";
2953
- return `[${index + 1}] ${speaker}
2954
- ${message.content.trim()}`;
2955
- }).join("\n\n");
2956
- }
2957
- function buildCliSessionPrompt(session, userInput) {
2958
- const transcript = formatCliSessionTask([
2959
- ...session.messages,
2960
- { role: "user", content: userInput }
2961
- ]);
2962
- return [
2963
- "\u4EE5\u4E0B\u662F\u5F53\u524D\u5BF9\u8BDD\uFF0C\u8BF7\u57FA\u4E8E\u5B8C\u6574\u4E0A\u4E0B\u6587\u7EE7\u7EED\u56DE\u7B54\u6700\u540E\u4E00\u6761\u7528\u6237\u6D88\u606F\u3002",
2964
- transcript
2965
- ].join("\n\n");
2966
- }
2967
- function getCliSessionOrThrow(sessionId) {
2968
- const session = cliSessions.get(sessionId);
2969
- if (!session) {
2970
- throw new Error(`Unknown CLI session: "${sessionId}"`);
2971
- }
2972
- return session;
2973
- }
2974
- async function executeCli(provider, prompt, options = {}) {
2975
- const executor = EXECUTORS[provider];
2976
- if (!executor) {
2977
- throw new Error(`Unknown CLI provider: "${provider}". Supported: ${Object.keys(EXECUTORS).join(", ")}`);
2978
- }
2979
- const resolved = resolveCliExecution(provider, prompt, options);
2980
- try {
2981
- const result = await executor(resolved.prompt, resolved.options);
2982
- return {
2983
- ...result,
2984
- warnings: [...resolved.warnings, ...result.warnings ?? []]
2985
- };
2986
- } finally {
2987
- if (resolved.imageTempDir) {
2988
- rmSync(resolved.imageTempDir, { recursive: true, force: true });
2989
- }
2990
- }
2991
- }
2992
- function startCliSession(provider, options = {}) {
2993
- if (!EXECUTORS[provider]) {
2994
- throw new Error(`Unknown CLI provider: "${provider}". Supported: ${Object.keys(EXECUTORS).join(", ")}`);
2995
- }
2996
- const sessionId = randomUUID2();
2997
- cliSessions.set(sessionId, {
2998
- sessionId,
2999
- provider,
3000
- systemPrompt: options.systemPrompt,
3001
- options: {
3002
- model: options.model,
3003
- timeout: options.timeout,
3004
- cwd: options.cwd,
3005
- env: options.env,
3006
- yolo: options.yolo,
3007
- systemPrompt: options.systemPrompt,
3008
- reasoningEffort: options.reasoningEffort,
3009
- temperature: options.temperature,
3010
- topP: options.topP,
3011
- frequencyPenalty: options.frequencyPenalty,
3012
- presencePenalty: options.presencePenalty,
3013
- maxTokens: options.maxTokens,
3014
- enableThinking: options.enableThinking,
3015
- thinkingBudget: options.thinkingBudget
3016
- },
3017
- messages: [],
3018
- createdAt: Date.now(),
3019
- updatedAt: Date.now()
3020
- });
3021
- return { sessionId, provider };
3022
- }
3023
- function getCliSession(sessionId) {
3024
- return cliSessions.get(sessionId) ?? null;
3025
- }
3026
- function closeCliSession(sessionId) {
3027
- void closeAgyAcpSession(sessionId).catch((error) => {
3028
- console.warn("[cliExecutor] closeAgyAcpSession failed:", error);
3029
- });
3030
- return cliSessions.delete(sessionId);
3031
- }
3032
- async function executeAgyAcpTurn(session, userInput, options, onChunk) {
3033
- const resolved = resolveCliExecution(session.provider, userInput, {
3034
- ...session.options,
3035
- ...options
3036
- });
3037
- try {
3038
- const acp = getAgyAcpSession(session.sessionId, {
3039
- cwd: resolved.options.cwd ?? process.cwd(),
3040
- env: { ...session.options.env, ...resolved.options.env },
3041
- model: resolved.options.model,
3042
- // 用 resolveCliExecution 的产物:非原生 systemPrompt 的 provider 已经被内联进 prompt,
3043
- // 这里再传一份会让 ACP 的 buildPromptText 前置第二次(首轮系统提示重复)。
3044
- systemPrompt: resolved.options.systemPrompt,
3045
- yolo: resolved.options.yolo
3046
- });
3047
- const result = await acp.prompt(resolved.prompt, {
3048
- signal: resolved.options.signal,
3049
- timeoutMs: resolved.options.timeout ?? DEFAULT_AGY_TIMEOUT_MS,
3050
- ...onChunk ? { onChunk } : {},
3051
- onToolEvent: resolved.options.onToolEvent,
3052
- toolEventRound: resolved.options.toolEventRound
3053
- });
3054
- session.messages.push(
3055
- { role: "user", content: userInput },
3056
- { role: "assistant", content: result.text }
3057
- );
3058
- session.updatedAt = Date.now();
3059
- const warnings = [...resolved.warnings, ...result.warnings ?? []];
3060
- return {
3061
- text: result.text,
3062
- raw: result.raw,
3063
- elapsed: result.elapsed,
3064
- ...result.usage ? { usage: result.usage } : {},
3065
- ...warnings.length > 0 ? { warnings } : {},
3066
- sessionId: session.sessionId
3067
- };
3068
- } finally {
3069
- if (resolved.imageTempDir) {
3070
- rmSync(resolved.imageTempDir, { recursive: true, force: true });
3071
- }
3072
- }
3073
- }
3074
- async function executeCliSessionTurn(sessionId, userInput, options = {}) {
3075
- const trimmedInput = userInput.trim();
3076
- if (!trimmedInput) {
3077
- throw new Error("CLI session turn requires non-empty user input.");
3078
- }
3079
- const session = getCliSessionOrThrow(sessionId);
3080
- if (session.provider === "agy" && isAgyAcpEnabled()) {
3081
- return executeAgyAcpTurn(session, trimmedInput, options);
3082
- }
3083
- const prompt = buildCliSessionPrompt(session, trimmedInput);
3084
- const result = await executeCli(session.provider, prompt, {
3085
- ...session.options,
3086
- ...options
3087
- });
3088
- session.messages.push(
3089
- { role: "user", content: trimmedInput },
3090
- { role: "assistant", content: result.text }
3091
- );
3092
- session.updatedAt = Date.now();
3093
- return {
3094
- ...result,
3095
- sessionId: session.sessionId
3096
- };
3097
- }
3098
- async function executeCliSessionTurnStreaming(sessionId, userInput, options) {
3099
- const trimmedInput = userInput.trim();
3100
- if (!trimmedInput) {
3101
- throw new Error("CLI session turn requires non-empty user input.");
3102
- }
3103
- const session = getCliSessionOrThrow(sessionId);
3104
- if (session.provider === "agy" && isAgyAcpEnabled()) {
3105
- return executeAgyAcpTurn(session, trimmedInput, options, options.onChunk);
3106
- }
3107
- const prompt = buildCliSessionPrompt(session, trimmedInput);
3108
- const result = await executeCliStreaming(session.provider, prompt, {
3109
- ...session.options,
3110
- ...options
3111
- });
3112
- session.messages.push(
3113
- { role: "user", content: trimmedInput },
3114
- { role: "assistant", content: result.text }
3115
- );
3116
- session.updatedAt = Date.now();
3117
- return {
3118
- ...result,
3119
- sessionId: session.sessionId
3120
- };
3121
- }
3122
- function filterNoiseLine(line) {
3123
- return !line.includes("A new release of gh is available") && !line.includes("To upgrade, run:") && !line.includes("https://github.com/cli/cli/releases");
3124
- }
3125
- function executeCliStreaming(provider, prompt, options) {
3126
- const resolved = resolveCliExecution(provider, prompt, options);
3127
- const executor = EXECUTORS[provider];
3128
- const cleanupImageTempDir = () => {
3129
- if (resolved.imageTempDir) {
3130
- rmSync(resolved.imageTempDir, { recursive: true, force: true });
3131
- }
3132
- };
3133
- const withCleanup = (promise) => promise.finally(cleanupImageTempDir);
3134
- if (provider === "gemini") {
3135
- return withCleanup(
3136
- executeGeminiStreaming(resolved.prompt, resolved.options).then((result) => ({ ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] }))
3137
- );
3138
- }
3139
- if (provider === "codex") {
3140
- return withCleanup(
3141
- executor(resolved.prompt, resolved.options).then((result) => {
3142
- const merged = { ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] };
3143
- if (merged.text) options.onChunk(merged.text);
3144
- return merged;
3145
- })
3146
- );
3147
- }
3148
- if (provider === "claude") {
3149
- return withCleanup(
3150
- executor(resolved.prompt, resolved.options).then((result) => {
3151
- const merged = { ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] };
3152
- if (merged.text) options.onChunk(merged.text);
3153
- return merged;
3154
- })
3155
- );
3156
- }
3157
- if (provider === "agy") {
3158
- return withCleanup(
3159
- executeAgyStreaming(resolved.prompt, resolved.options).then((result) => ({ ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] }))
3160
- );
3161
- }
3162
- if (provider === "opencode") {
3163
- return withCleanup(
3164
- executeOpenCodeStreaming(resolved.prompt, resolved.options).then((result) => ({ ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] }))
3165
- );
3166
- }
3167
- if (provider === "qoder" || provider === "grok" || provider === "kimi") {
3168
- return withCleanup(
3169
- executor(resolved.prompt, resolved.options).then((result) => {
3170
- const merged = { ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] };
3171
- if (merged.text) options.onChunk(merged.text);
3172
- return merged;
3173
- })
3174
- );
3175
- }
3176
- if (provider !== "copilot") {
3177
- return withCleanup(
3178
- executor(resolved.prompt, resolved.options).then((result) => ({
3179
- ...result,
3180
- warnings: [...resolved.warnings, ...result.warnings ?? []]
3181
- }))
3182
- );
3183
- }
3184
- const {
3185
- model,
3186
- timeout = 12e4,
3187
- cwd = process.cwd(),
3188
- yolo = true,
3189
- onChunk
3190
- } = resolved.options;
3191
- return withCleanup(new Promise((resolve3, reject) => {
3192
- const args = [
3193
- "copilot",
3194
- "--",
3195
- "-p",
3196
- resolved.prompt,
3197
- "--silent",
3198
- "--disable-builtin-mcps"
3199
- ];
3200
- if (model) {
3201
- args.push("--model");
3202
- args.push(model);
3203
- }
3204
- if (yolo) args.push("--yolo");
3205
- const start = Date.now();
3206
- const proc = spawn3("gh", args, {
3207
- cwd,
3208
- env: buildCliProcessEnv(resolved.options.env),
3209
- ...resolved.options.signal ? { detached: true } : {}
3210
- });
3211
- const stdout = createUtf8Collector();
3212
- let timer;
3213
- let settled = false;
3214
- const finish = (cb) => {
3215
- if (settled) return;
3216
- settled = true;
3217
- if (timer) clearTimeout(timer);
3218
- detachAbort();
3219
- cb();
3220
- };
3221
- let detachAbort = () => {
3222
- };
3223
- detachAbort = attachCliAbortSignal(
3224
- proc,
3225
- resolved.options.signal,
3226
- (error) => finish(() => reject(error))
3227
- );
3228
- if (timeout > 0) {
3229
- timer = setTimeout(() => {
3230
- finish(() => reject(stoppingCliError(new Error(`Copilot CLI timed out after ${timeout}ms`), proc)));
3231
- }, timeout);
3232
- }
3233
- proc.stdout.on("data", (data) => {
3234
- const chunk = stdout.write(data);
3235
- const cleaned = chunk.split("\n").filter(filterNoiseLine).join("\n");
3236
- if (cleaned && !settled) {
3237
- try {
3238
- onChunk(cleaned);
3239
- } catch (error) {
3240
- finish(() => reject(stoppingCliError(error, proc)));
3241
- }
3242
- }
3243
- });
3244
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
3245
- const raw = stdout.end();
3246
- if (code !== 0 && code !== null) {
3247
- finish(() => reject2(new Error(`Copilot CLI exited with code ${code}`)));
3248
- return;
3249
- }
3250
- const text = raw.split("\n").filter(filterNoiseLine).join("\n").trim();
3251
- finish(
3252
- () => resolve4({
3253
- text,
3254
- raw,
3255
- elapsed: Date.now() - start,
3256
- warnings: [...resolved.warnings]
3257
- })
3258
- );
3259
- });
3260
- proc.on("error", (err) => {
3261
- finish(() => reject(proc.pid ? stoppingCliError(err, proc) : err));
3262
- });
3263
- }));
3264
- }
3265
- function executeGeminiStreaming(prompt, options) {
3266
- const {
3267
- model = "gemini-3.8-flash",
3268
- timeout = 12e4,
3269
- cwd = process.cwd(),
3270
- yolo = true,
3271
- onChunk
3272
- } = options;
3273
- return new Promise((resolve3, reject) => {
3274
- const args = ["-p", prompt, "--output-format", "stream-json", "-m", model];
3275
- if (yolo) args.push("--yolo");
3276
- args.push("-e", "none");
3277
- const start = Date.now();
3278
- const proc = spawn3("gemini", args, {
3279
- cwd,
3280
- env: buildCliProcessEnv({
3281
- ...options.env,
3282
- NODE_OPTIONS: "--no-deprecation"
3283
- }),
3284
- detached: process.platform !== "win32"
3285
- });
3286
- const stdout = createUtf8Collector();
3287
- const stderr = createUtf8Collector();
3288
- let lineBuffer = "";
3289
- let timer;
3290
- let settled = false;
3291
- const finish = (cb) => {
3292
- if (settled) return;
3293
- settled = true;
3294
- if (timer) clearTimeout(timer);
3295
- detachAbort();
3296
- cb();
3297
- };
3298
- let detachAbort = () => {
3299
- };
3300
- detachAbort = attachCliAbortSignal(
3301
- proc,
3302
- options.signal,
3303
- (error) => finish(() => reject(error))
3304
- );
3305
- const flushLineBuffer = () => {
3306
- if (settled) return;
3307
- const trimmed = lineBuffer.trim();
3308
- if (!trimmed) return;
3309
- try {
3310
- const event = JSON.parse(trimmed);
3311
- const text = extractGeminiEventText(event);
3312
- if (text) onChunk(text);
3313
- } catch {
3314
- }
3315
- lineBuffer = "";
3316
- };
3317
- if (timeout > 0) {
3318
- timer = setTimeout(() => {
3319
- finish(() => reject(stoppingCliError(new Error(`Gemini CLI timed out after ${timeout}ms`), proc)));
3320
- }, timeout);
3321
- }
3322
- proc.stdout.on("data", (data) => {
3323
- const chunk = stdout.write(data);
3324
- lineBuffer += chunk;
3325
- let newlineIndex = lineBuffer.indexOf("\n");
3326
- while (newlineIndex !== -1) {
3327
- const line = lineBuffer.slice(0, newlineIndex).trim();
3328
- lineBuffer = lineBuffer.slice(newlineIndex + 1);
3329
- if (line) {
3330
- try {
3331
- const event = JSON.parse(line);
3332
- const text = extractGeminiEventText(event);
3333
- if (text && !settled) {
3334
- try {
3335
- onChunk(text);
3336
- } catch (error) {
3337
- finish(() => reject(stoppingCliError(error, proc)));
3338
- }
3339
- }
3340
- } catch {
3341
- }
3342
- }
3343
- newlineIndex = lineBuffer.indexOf("\n");
3344
- }
3345
- });
3346
- proc.stderr.on("data", (data) => {
3347
- stderr.write(data);
3348
- });
3349
- onCliClose(proc, resolve3, reject, (resolve4, reject2, code) => {
3350
- lineBuffer += stdout.finish();
3351
- const raw = stdout.text;
3352
- const stderrText = stderr.end();
3353
- flushLineBuffer();
3354
- if (code !== 0 && code !== null) {
3355
- finish(
3356
- () => reject2(new Error(`Gemini CLI exited with code ${code}
3357
- stderr: ${stderrText}`))
3358
- );
3359
- return;
3360
- }
3361
- finish(
3362
- () => resolve4({
3363
- text: parseGeminiStreamJson(raw),
3364
- raw,
3365
- elapsed: Date.now() - start
3366
- })
3367
- );
3368
- });
3369
- proc.on("error", (err) => {
3370
- finish(() => reject(proc.pid ? stoppingCliError(err, proc) : err));
3371
- });
3372
- });
3373
- }
3374
-
3375
- export {
3376
- CliProviderQuotaError,
3377
- detectCliProviderQuotaLimit,
3378
- isBufferedCliStreamingProvider,
3379
- CLI_PROBE_BINARIES,
3380
- materializeCliImageInputs,
3381
- resolveGeminiCommand,
3382
- attachExecutionStoppedPromise,
3383
- getExecutionStoppedPromise,
3384
- terminateCliProcessGroupEscalating,
3385
- executeCli,
3386
- startCliSession,
3387
- getCliSession,
3388
- closeCliSession,
3389
- executeCliSessionTurn,
3390
- executeCliSessionTurnStreaming,
3391
- executeCliStreaming
3392
- };