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.
- package/{chunk-LXP53WGF.js → chunk-05wkntba.js} +44 -40
- package/{chunk-XFYFMTOM.js → chunk-08ts2q1n.js} +9 -11
- package/{chromeCommands-MVEEIY4R.js → chunk-0a3m1n6h.js} +182 -238
- package/chunk-0gfvc7g8.js +13 -0
- package/{chunk-CF7PE763.js → chunk-0h0sncy4.js} +3 -4
- package/{chunk-3UH7SS4W.js → chunk-0nsxwrge.js} +232 -241
- package/chunk-0ra8cne4.js +11 -0
- package/{chunk-MRACVEPZ.js → chunk-0sgwk7am.js} +1 -3
- package/{chunk-PEXGRTTQ.js → chunk-0tsfn0dk.js} +44 -45
- package/{chunk-WOAZVUSN.js → chunk-0y8cbwzy.js} +26 -30
- package/chunk-12gz55kk.js +6 -0
- package/{chunk-GLKOYSRU.js → chunk-186gshgw.js} +3 -6
- package/chunk-19w4ss38.js +44 -0
- package/{chunk-RF576RYE.js → chunk-1cakzp6r.js} +23 -23
- package/chunk-1fbfwbzp.js +27 -0
- package/{chunk-4IVMDQBA.js → chunk-1fv9k8zt.js} +103 -68
- package/{chunk-Q5FJJ6XI.js → chunk-1js4cdzp.js} +11 -19
- package/{chunk-YECCIUYU.js → chunk-1nhx0er5.js} +63 -63
- package/chunk-1p152b7g.js +12 -0
- package/{chunk-LBPW6OCD.js → chunk-1ynbq3yr.js} +322 -353
- package/{chunk-6UBGXX2W.js → chunk-1zrg4h5n.js} +3 -4
- package/{chunk-Y5GCAMGP.js → chunk-2g6zsfq8.js} +1 -3
- package/chunk-2hekb0eh.js +17 -0
- package/chunk-2pj6qzq5.js +12 -0
- package/chunk-2tvd4jyp.js +226 -0
- package/chunk-2ygg7azv.js +846 -0
- package/chunk-33405wtv.js +50 -0
- package/chunk-34axejtd.js +30 -0
- package/{tableCommands-FCPDULSU.js → chunk-3700dvt3.js} +224 -276
- package/{pdf-KE3QI2V7.js → chunk-3j08t1nm.js} +12505 -10133
- package/chunk-3j9gq18v.js +111 -0
- package/{chunk-2QKIWEZS.js → chunk-3qfpcdkm.js} +486 -505
- package/{settingThunks-PNC7ZISV.js → chunk-3r2x7h64.js} +189 -272
- package/{agentGrantCommands-2VLLXGIU.js → chunk-3tbj5fxt.js} +61 -56
- package/chunk-40whhjj5.js +168 -0
- package/chunk-4301919y.js +7 -0
- package/chunk-43adz39e.js +77 -0
- package/{chunk-5ZUL4CUO.js → chunk-49v3zc4g.js} +1 -3
- package/chunk-4dd7mxkb.js +72 -0
- package/{chunk-BKP325XS.js → chunk-4hapfzpq.js} +66 -62
- package/chunk-4mm7dz0m.js +95 -0
- package/chunk-4pqxempz.js +440 -0
- package/chunk-4x9zf5pv.js +10 -0
- package/{chunk-CA7LGAHV.js → chunk-511q8qzv.js} +66 -57
- package/{chunk-S52BPZ7A.js → chunk-53v9g0np.js} +49 -64
- package/chunk-572mg6q5.js +19 -0
- package/{chunk-DXDCL3Z6.js → chunk-57eyhmwr.js} +17173 -16165
- package/chunk-5hsr0zjm.js +156 -0
- package/chunk-5k883yyd.js +20 -0
- package/chunk-5m0wsee4.js +639 -0
- package/{memberThunks-IPS3SLOF.js → chunk-5r1sq2gt.js} +299 -373
- package/chunk-648rq4np.js +255 -0
- package/{chunk-IYRZKHA6.js → chunk-666yjw5c.js} +63 -86
- package/{chunk-4O22PGNQ.js → chunk-6cdcbmtp.js} +19 -19
- package/chunk-6dbyqcf7.js +59 -0
- package/{agentProviderCommands-2W3VXDLV.js → chunk-6e8mgp1x.js} +82 -105
- package/chunk-6n0pw7sx.js +44 -0
- package/chunk-6q1b7381.js +361 -0
- package/chunk-6sj756ry.js +23 -0
- package/{chunk-XGYQCBWS.js → chunk-6t7a7zck.js} +14785 -14454
- package/chunk-6yarwtxh.js +776 -0
- package/chunk-708h542p.js +18 -0
- package/chunk-76f076t8.js +266 -0
- package/chunk-782rrrwv.js +523 -0
- package/{workloadLifecycle-P2SJVV3S.js → chunk-7gk330wp.js} +77 -84
- package/{chunk-EZKIRVLJ.js → chunk-7ks60vxy.js} +146 -128
- package/{chunk-FI4DPLR7.js → chunk-7mrqbxe8.js} +342 -228
- package/chunk-7sztayrd.js +169 -0
- package/chunk-7vgt2mxz.js +15 -0
- package/{localFirstLog-OIETGK66.js → chunk-7z8y4k6y.js} +0 -2
- package/{chunk-KDDXC2IH.js → chunk-82htft2m.js} +49 -11
- package/{updateDialogTitleAction-OPAZF5VC.js → chunk-88vrtxxg.js} +65 -137
- package/{chunk-LS5KAVFQ.js → chunk-8dtjbp79.js} +293 -229
- package/chunk-8fajbkaz.js +50 -0
- package/chunk-8m1ebxpw.js +65 -0
- package/{accountResolver-JYG5L7YP.js → chunk-8mgfeg0w.js} +37 -30
- package/{chunk-LPXBBC32.js → chunk-8myksy35.js} +156 -160
- package/{chunk-BMQ2MJUK.js → chunk-8nrj7dc7.js} +75 -66
- package/{commandRegistry-XPLM5SWC.js → chunk-8t8x64ec.js} +228 -286
- package/chunk-8yj4pq79.js +458 -0
- package/{chunk-5MKPNTJP.js → chunk-8z6pepcx.js} +43 -48
- package/{chunk-UYQILGDR.js → chunk-90egc9vb.js} +122 -102
- package/{chunk-Z6LVL5MC.js → chunk-91q5dc5r.js} +10 -14
- package/{chunk-U6VC4MU4.js → chunk-96jtrqk1.js} +2 -4
- package/{chunk-H57T64RA.js → chunk-996j61av.js} +28 -31
- package/{chunk-Q6FKWH66.js → chunk-9cxgb9jy.js} +137 -243
- package/{chunk-2ZBPWX7N.js → chunk-9q1gbmet.js} +62 -104
- package/chunk-9qtjh73q.js +344 -0
- package/{chunk-SR57FDTX.js → chunk-9raka469.js} +72 -155
- package/{chunk-V6K5U4YE.js → chunk-9vh4v046.js} +32 -41
- package/{chunk-AGIM7IMJ.js → chunk-9yr1fy7j.js} +14 -49
- package/{chunk-FGFJUFPS.js → chunk-a16x0wt6.js} +11 -18
- package/chunk-a5b2rvzs.js +131 -0
- package/{chunk-7DPNBQSV.js → chunk-a7bz6nc3.js} +3 -4
- package/chunk-ac85azv9.js +29 -0
- package/{chunk-VXL2FZTP.js → chunk-ahhbkad4.js} +16 -20
- package/{chunk-37DGW762.js → chunk-anhksj2j.js} +16 -29
- package/{cliAuthorityBrokerServer-27C5YBYP.js → chunk-atvmx76t.js} +180 -186
- package/{chunk-E6A5NHDH.js → chunk-av2mzeqz.js} +16 -17
- package/chunk-avbwrb0z.js +614 -0
- package/chunk-avr6rqe5.js +544 -0
- package/{workContextQueryProjection-CACY5VFE.js → chunk-axx60d5a.js} +7 -7
- package/{chunk-EWQ3HGNZ.js → chunk-b00vzjkb.js} +30 -23
- package/chunk-b0m6ezxr.js +132 -0
- package/chunk-bbd5mgdt.js +47 -0
- package/chunk-bcecft0r.js +28 -0
- package/chunk-beyr4pyp.js +33 -0
- package/{chunk-BR3GT6MR.js → chunk-bge0cagn.js} +7 -18
- package/{offlineMarxistsAgentCommand-MFURGWHL.js → chunk-bh53zg3t.js} +33 -43
- package/chunk-bmx1cw89.js +37 -0
- package/chunk-br2195h4.js +22 -0
- package/chunk-bsqkwveq.js +56 -0
- package/{chunk-DZJWSGCV.js → chunk-c09s2z1m.js} +139 -98
- package/chunk-c235kypv.js +24636 -0
- package/{chunk-2JMYAH5O.js → chunk-c30j6pyh.js} +213 -256
- package/chunk-c3v6r6sq.js +29 -0
- package/{chunk-NACE7NWO.js → chunk-c5z7qspt.js} +1177 -1196
- package/{chunk-GWB6AGME.js → chunk-c6jvz0mp.js} +34 -50
- package/{chunk-PRJ473FK.js → chunk-cd6h9qqs.js} +14 -12
- package/chunk-cdt0amyy.js +37 -0
- package/{chunk-2AJLG6PY.js → chunk-cfh6tfc3.js} +73 -86
- package/{chunk-WIVVNJUS.js → chunk-ch4ck1yz.js} +38 -68
- package/chunk-chtvrtp5.js +55 -0
- package/{chunk-EYLGAEB4.js → chunk-ckvz7abv.js} +170 -165
- package/{chunk-YZMNK53S.js → chunk-csf18m5w.js} +32 -25
- package/{chunk-C36L6ZID.js → chunk-cwnvf8dt.js} +2 -10
- package/chunk-cy7thb6n.js +19877 -0
- package/{dialogPortabilityCommands-YQJNB2KL.js → chunk-d61q9nah.js} +439 -487
- package/chunk-d6xdy0gp.js +142 -0
- package/{chunk-SCEPD46O.js → chunk-dh69vqbd.js} +6386 -6498
- package/{chunk-KJ4J2XQB.js → chunk-dj4ggbc6.js} +17 -19
- package/{chunk-LISC7BD4.js → chunk-djrrhbk3.js} +29 -37
- package/chunk-drqzzzvr.js +822 -0
- package/chunk-e1n7edjk.js +33 -0
- package/chunk-e3atr4hk.js +59 -0
- package/chunk-e9bn2aav.js +13 -0
- package/chunk-ed396rfq.js +87 -0
- package/chunk-eha8ggh6.js +10 -0
- package/{chunk-B7CTVEUV.js → chunk-ek122zzt.js} +893 -948
- package/chunk-epnmvek4.js +22 -0
- package/{chunk-S25VJYXV.js → chunk-eqzvk3xm.js} +69 -80
- package/chunk-ex34n71b.js +2874 -0
- package/{chunk-56OAS5RZ.js → chunk-f3ad6q4h.js} +7 -11
- package/{chunk-3PVYUPXK.js → chunk-f8jepva1.js} +6 -7
- package/{chunk-GH34JXNV.js → chunk-f9yvy9t9.js} +114 -92
- package/chunk-fbdz4f0j.js +90 -0
- package/{chunk-J44TXB4J.js → chunk-fcsc2day.js} +216 -164
- package/chunk-fevdhnbh.js +19 -0
- package/chunk-fkrgqq8w.js +3300 -0
- package/{chunk-TSBJVMNW.js → chunk-fs3bvh2p.js} +42 -57
- package/chunk-fvwzyhah.js +134 -0
- package/chunk-g0mpxdp9.js +101 -0
- package/{chunk-JGUHOA42.js → chunk-g35f20d1.js} +450 -414
- package/{chunk-3L2WKC3W.js → chunk-g5fhtjqg.js} +13 -16
- package/{chunk-APOIIIB4.js → chunk-gcq01td7.js} +270 -227
- package/{chunk-ADMRXWXJ.js → chunk-ge97b11r.js} +121 -42
- package/chunk-ghjtgbkw.js +180 -0
- package/chunk-gkra36c1.js +16 -0
- package/chunk-gmz86t60.js +1000 -0
- package/{localDialogRead-GWGWSL5K.js → chunk-gszpesze.js} +5 -12
- package/chunk-gvsfec9m.js +16536 -0
- package/{chunk-QSJ3HFEF.js → chunk-h1hzmqph.js} +1 -3
- package/chunk-h30dg154.js +17 -0
- package/chunk-h3hkb7cw.js +241 -0
- package/chunk-h40py996.js +28 -0
- package/{chunk-47T3QP4V.js → chunk-h60gnewh.js} +112 -116
- package/{agentPullCommand-XEGOUYQT.js → chunk-hkwsv9xf.js} +33 -45
- package/chunk-hnyg0gwj.js +28 -0
- package/{chunk-KSV6T4AH.js → chunk-hqqqph5w.js} +12 -4
- package/{chunk-YQJEXXDK.js → chunk-hrngs1wy.js} +157 -246
- package/{chunk-LRLLWD4P.js → chunk-htf69s94.js} +14 -12
- package/chunk-j0yxesh3.js +83 -0
- package/{chunk-VF4K2QE6.js → chunk-j22t9g05.js} +3 -6
- package/{chunk-3R4AYHJR.js → chunk-j4a8m2zn.js} +5 -34
- package/chunk-j9p4jnwg.js +27 -0
- package/{chunk-R72QWIFO.js → chunk-jdycmfsm.js} +9 -9
- package/chunk-jdyvrne0.js +52 -0
- package/{spacePruneCommand-YKIEUIDQ.js → chunk-je0b66qf.js} +44 -62
- package/{chunk-HNMXYYJR.js → chunk-jec44fkj.js} +3 -4
- package/{chunk-526GLZJE.js → chunk-jf1ex00r.js} +107 -73
- package/chunk-jgqdec9b.js +31 -0
- package/{chunk-56GBUMO5.js → chunk-jkw9n4h5.js} +16 -25
- package/{chunk-BY2CHBIZ.js → chunk-jmnzdwjt.js} +867 -965
- package/chunk-jqq57s0a.js +58 -0
- package/{chunk-OKUSDVRS.js → chunk-jtkn5aj6.js} +27 -38
- package/chunk-jwvzn9r0.js +316 -0
- package/chunk-k1re0fc7.js +107 -0
- package/chunk-k2ep3rb2.js +103 -0
- package/{chunk-JEXVIMYZ.js → chunk-k6ycb24w.js} +5 -8
- package/{chunk-RI7SXDJW.js → chunk-kawvydbk.js} +383 -195
- package/chunk-kf2ghpzh.js +10 -0
- package/{chunk-S6FAHQDH.js → chunk-kgah9e46.js} +28 -59
- package/{chunk-6A6CTCMC.js → chunk-kjjepkvc.js} +71 -82
- package/chunk-kn4dgg4j.js +4113 -0
- package/{chunk-2LFYMWM3.js → chunk-kn5p91n8.js} +43 -53
- package/{chunk-MVOZ22RZ.js → chunk-kntqrbwc.js} +8 -12
- package/{chunk-I6YIA2TY.js → chunk-kq3vr7mx.js} +25 -20
- package/chunk-kz1x1d8n.js +15 -0
- package/{mcpLocalAuthorizeCommand-IKOFKY5U.js → chunk-m22e7tt2.js} +53 -71
- package/{chunk-ZNFJWEN4.js → chunk-m32rwr4d.js} +11 -8
- package/chunk-m39e9m18.js +93 -0
- package/{chunk-4D4QD7FT.js → chunk-m5518371.js} +64 -56
- package/{chunk-LHTXSC2E.js → chunk-mb5hnfyp.js} +9 -11
- package/chunk-mexet11v.js +11 -0
- package/chunk-mg2hgfgh.js +185 -0
- package/chunk-mmdhm4kx.js +10317 -0
- package/chunk-mz002yz8.js +2821 -0
- package/chunk-mzadqnyq.js +56 -0
- package/{chunk-VIDPVFP3.js → chunk-n3r1ebdm.js} +5 -6
- package/chunk-n438qea7.js +33 -0
- package/chunk-n5ffnhnb.js +93 -0
- package/chunk-nbvd87fy.js +9 -0
- package/{chunk-E36V7MPY.js → chunk-ndej7jc9.js} +53 -43
- package/{chunk-B767MA64.js → chunk-nen6rwe4.js} +62 -22
- package/chunk-nf06tr3v.js +16 -0
- package/chunk-ng8z355q.js +16 -0
- package/{chunk-4MEKE5D3.js → chunk-nhtxfv8k.js} +78 -63
- package/{runAgentClientLoop-ELTV5MSJ.js → chunk-nj62jscj.js} +132 -214
- package/{chunk-GBWGPTA7.js → chunk-nkryrkyp.js} +16 -19
- package/chunk-nmesxem8.js +197 -0
- package/{chunk-YR4J7RFS.js → chunk-nmq0qwbn.js} +117 -164
- package/chunk-nph8brvw.js +7 -0
- package/chunk-nr8fees9.js +10 -0
- package/{chunk-DFI7MVCQ.js → chunk-nvewvf7h.js} +1441 -1427
- package/{chunk-G7Y4GXTY.js → chunk-nyamhphs.js} +70 -79
- package/chunk-nz1c8tcg.js +111 -0
- package/{chunk-GPLUFN2E.js → chunk-nzc5yffh.js} +176 -217
- package/{chunk-G3SUCT4W.js → chunk-p1vg4bx8.js} +2 -4
- package/chunk-p3k3abe8.js +202 -0
- package/chunk-p4zy30q5.js +8 -0
- package/{chunk-ZJACPM5O.js → chunk-p6se1rx0.js} +102 -102
- package/chunk-p9dpshev.js +6968 -0
- package/chunk-pa42wxr0.js +116 -0
- package/{chunk-TA5QI4MM.js → chunk-paxthgqp.js} +56 -107
- package/{readlineWorkspace-5EASNOQ4.js → chunk-pb35s8d9.js} +5395 -5786
- package/{chunk-XT6C2QZW.js → chunk-pbebzbcq.js} +8 -8
- package/chunk-pbx7e1mb.js +11 -0
- package/chunk-pe5czfn9.js +8 -0
- package/chunk-pextk1j4.js +62 -0
- package/chunk-pf5rywc6.js +575 -0
- package/chunk-pjfhd3fz.js +136 -0
- package/chunk-pkhqb0fs.js +243 -0
- package/chunk-pm5xb9jh.js +26 -0
- package/{chunk-Y3KGWZKF.js → chunk-ppdmmdkx.js} +110 -97
- package/chunk-pqp6y2hs.js +9 -0
- package/{chunk-QHEN7NZ7.js → chunk-ptz8fm2n.js} +12 -17
- package/{chunk-EUHMI5KG.js → chunk-pwqnvbt7.js} +65 -46
- package/chunk-pzr31nz7.js +12 -0
- package/{chunk-WWC7I6TA.js → chunk-q3cx89sw.js} +2 -4
- package/chunk-q5pe7be3.js +78 -0
- package/{chunk-ZHWTBHT3.js → chunk-q6zqbxp2.js} +418 -409
- package/chunk-q7r0e1p3.js +15 -0
- package/chunk-q8t2fecd.js +6 -0
- package/{chunk-2QAZCYOM.js → chunk-q94zx4d0.js} +721 -753
- package/{runtimeDoctorCommands-52MBG5JN.js → chunk-qarz1az1.js} +65 -85
- package/{chunk-4INJGWE3.js → chunk-qdcvr25b.js} +72 -53
- package/{streamAgentChatTurn-BL3ESUEN.js → chunk-qxs27wfg.js} +1079 -1475
- package/{chunk-GIXWVN2W.js → chunk-r06ycjjr.js} +50 -47
- package/{chunk-63W5N6P3.js → chunk-r20jw5hb.js} +57 -38
- package/{chunk-I5BYFTYK.js → chunk-r7sfwdka.js} +1201 -1142
- package/{chunk-UMADT6B2.js → chunk-r9sp1yyb.js} +6 -8
- package/{handleSendMessageAction-VQP5HT5I.js → chunk-rbd2vgb3.js} +627 -757
- package/chunk-rc37js46.js +12 -0
- package/{chunk-5YI447UL.js → chunk-rmngk6r3.js} +67 -76
- package/chunk-rnhbnbrq.js +15 -0
- package/{chunk-WRHVVIGI.js → chunk-rsfnmrt5.js} +111 -131
- package/{chunk-YFSM2366.js → chunk-rvvn2rhj.js} +28 -22
- package/{chunk-4Y6CZ2N4.js → chunk-s0fpz7ht.js} +37 -33
- package/{chunk-VI4SWTUO.js → chunk-s1cqzb2r.js} +77 -65
- package/{chunk-6QDYSCPW.js → chunk-s8q81tda.js} +73 -65
- package/chunk-s9hy639e.js +6 -0
- package/{chunk-R5GO3YZP.js → chunk-s9vbwme8.js} +115 -106
- package/chunk-sger1m1b.js +20 -0
- package/chunk-spe6crvk.js +60 -0
- package/chunk-spwsrvh9.js +70 -0
- package/chunk-sr05zpk7.js +573 -0
- package/{chunk-M2EJHDJP.js → chunk-srncrd3f.js} +1 -12
- package/{chunk-QXHFIX7W.js → chunk-sry80bpx.js} +71 -53
- package/{chunk-PSCNXBYA.js → chunk-t6q69p83.js} +3 -4
- package/{chunk-UAD2WT54.js → chunk-t714r4q0.js} +9 -28
- package/chunk-t7vbraqe.js +42 -0
- package/{chunk-CVMMWN6P.js → chunk-td7653rr.js} +10 -20
- package/{chunk-3BQDF4QB.js → chunk-tmytcetz.js} +17 -21
- package/{chunk-AMWMV56B.js → chunk-tta4prwg.js} +16 -15
- package/chunk-tvh8azgq.js +4829 -0
- package/{chunk-ID4G2MAR.js → chunk-v08kbfm8.js} +10 -11
- package/{chunk-IHU2ZFCQ.js → chunk-v1x702q8.js} +801 -852
- package/{chunk-KHCLMKZZ.js → chunk-v39fea91.js} +576 -247
- package/{chunk-OW765XBU.js → chunk-vejtd8p2.js} +3 -4
- package/chunk-vep7zkha.js +368 -0
- package/chunk-vfwn1k7n.js +142 -0
- package/chunk-vg68vxhx.js +20 -0
- package/chunk-vgcqgnsm.js +31 -0
- package/{chunk-NF64D32W.js → chunk-vnzyjdea.js} +1 -3
- package/{chunk-ZCLSM5AK.js → chunk-vqgtw1px.js} +800 -717
- package/chunk-vv1gr5xz.js +76 -0
- package/{spaceCommands-Z2CTQD6G.js → chunk-w1qeadpq.js} +176 -242
- package/chunk-w468ez1p.js +13 -0
- package/chunk-w49s0t79.js +14 -0
- package/{mcpLocalManageCommands-KUDZQRM4.js → chunk-w58zhfbn.js} +91 -93
- package/chunk-w5b74aq6.js +11 -0
- package/chunk-w7y41qyw.js +117 -0
- package/chunk-w820gg1w.js +4165 -0
- package/{chunk-DBJAJ4UD.js → chunk-wdsmaqmt.js} +399 -453
- package/{chunk-3EUW3WEO.js → chunk-wfvvnmmj.js} +1 -3
- package/{chunk-QY4NZCDA.js → chunk-wkr04bhk.js} +432 -651
- package/{chunk-KUG52IAP.js → chunk-ws402twv.js} +1 -3
- package/chunk-wzwh311q.js +164 -0
- package/{runtimeModeArgs-X7DL7PUN.js → chunk-x5vtgvwn.js} +6 -5
- package/{agentMachineCommands-AXPZRHUY.js → chunk-x8h2csmq.js} +152 -195
- package/{chunk-BAZCS5XG.js → chunk-x9zfjnrc.js} +59 -47
- package/{chunk-WTIJKWCI.js → chunk-xcarc2rf.js} +50 -56
- package/chunk-xf33gz0a.js +8 -0
- package/{chunk-PVFYPUIM.js → chunk-y7b3gwx1.js} +78 -71
- package/{memoryCommands-SVLAVFCV.js → chunk-y7sphmnh.js} +119 -95
- package/{agentListCommands-436FHOIT.js → chunk-ycvaafhc.js} +260 -374
- package/chunk-yd7zprb0.js +9 -0
- package/chunk-yfz3d27k.js +40 -0
- package/{chunk-MKR6KDD3.js → chunk-ykv9g3m4.js} +141 -125
- package/chunk-ystjgb9e.js +544 -0
- package/chunk-yysxn7ep.js +12 -0
- package/{chunk-AL3TYDIF.js → chunk-z17eyawk.js} +18 -16
- package/{machineCommands-LHJMILRA.js → chunk-z17q416p.js} +442 -563
- package/chunk-z1n98pcf.js +12 -0
- package/{dialogTraceCommand-HWXGIGZX.js → chunk-z566jx5r.js} +292 -397
- package/chunk-zjxd6942.js +6 -0
- package/{versionChangeNotice-RFABJGJE.js → chunk-zk11x9y5.js} +7 -9
- package/{chunk-TEFD5E2D.js → chunk-zt73yc33.js} +48 -51
- package/chunk-zvs2fra1.js +5 -0
- package/{chunk-SVFFKLMR.js → chunk-zwee84rh.js} +117 -141
- package/chunk-zxgfqv72.js +8 -0
- package/index.js +53 -69
- package/package.json +4 -4
- package/_executeModel-B3ENLKM4.js +0 -341
- package/action-UK3HXGXF.js +0 -30
- package/addContentAction-CAKFVBDM.js +0 -38
- package/addDialogAgentAction-KLJ2YWWM.js +0 -77
- package/agentDeleteCommand-R4LKLXQR.js +0 -523
- package/agentEmailCommands-SUEXVAY4.js +0 -742
- package/agentRecordCommands-NE4OPX5K.js +0 -211
- package/agentRun-NSNLIOM7.js +0 -251
- package/agentRunCommand-T6QTKMCJ.js +0 -249
- package/agentRunControl-U2MV74WR.js +0 -211
- package/agentRuntimeLocal-P4MMGIR6.js +0 -189
- package/agentSlice-FZJZONCT.js +0 -52
- package/appConfigCommands-W4JQHMOJ.js +0 -417
- package/appDeleteCommands-IXR47IAV.js +0 -183
- package/appDeployCommands-LB6DHDF4.js +0 -232
- package/appDeployStatusCommands-UQ6MJL6D.js +0 -204
- package/appGetCommands-M5JCTDDQ.js +0 -185
- package/appListCommands-TE3ZHE3I.js +0 -186
- package/appMigrateCommands-FOXH6R4B.js +0 -230
- package/appSourceCommands-3ACYB6I7.js +0 -279
- package/authCommand-I5OBJP5S.js +0 -66
- package/authCommands-I6KCGOCN.js +0 -54
- package/builtinSkillRegistry-MIXYSZUU.js +0 -35
- package/chromeOpsCommands-IZRCYDSW.js +0 -579
- package/chunk-24BICQPB.js +0 -25
- package/chunk-2E4BYAUE.js +0 -69
- package/chunk-2O72G3U2.js +0 -17157
- package/chunk-2OROOEOQ.js +0 -229
- package/chunk-2R6M34JP.js +0 -27225
- package/chunk-2SXN7LAY.js +0 -15
- package/chunk-35JIFLIG.js +0 -30
- package/chunk-3VXVE2LF.js +0 -12
- package/chunk-4DBTBNTX.js +0 -477
- package/chunk-4JH2UMJR.js +0 -40
- package/chunk-4SN6J65J.js +0 -38
- package/chunk-4TDUT2LC.js +0 -441
- package/chunk-5MMAK75Q.js +0 -15
- package/chunk-6NYQHXMV.js +0 -1737
- package/chunk-6R4IY46J.js +0 -14
- package/chunk-7K4J76JQ.js +0 -917
- package/chunk-7LR2IFUH.js +0 -100
- package/chunk-AETZ7AD6.js +0 -274
- package/chunk-ATNTHIZI.js +0 -13
- package/chunk-BPB3T5EU.js +0 -791
- package/chunk-BV3FLP2L.js +0 -133
- package/chunk-BVYHE6QD.js +0 -110
- package/chunk-BWJLEN6X.js +0 -1388
- package/chunk-CHOZJMJS.js +0 -78
- package/chunk-CYS6HOJ2.js +0 -1710
- package/chunk-D2LTQAGN.js +0 -464
- package/chunk-DALXH7BG.js +0 -3392
- package/chunk-DKEOYC4L.js +0 -15210
- package/chunk-DLXL4NSL.js +0 -1179
- package/chunk-DSBRIUX5.js +0 -23
- package/chunk-DWLEOOGR.js +0 -8
- package/chunk-E2KZNP6C.js +0 -13
- package/chunk-E5JV4DCB.js +0 -272
- package/chunk-EUGTFFO6.js +0 -42
- package/chunk-FBNVJ2TO.js +0 -294
- package/chunk-FGXG6OLW.js +0 -34
- package/chunk-FRFFUKGH.js +0 -3085
- package/chunk-G22P2J7O.js +0 -1775
- package/chunk-G5KDYBTG.js +0 -432
- package/chunk-GBXRKW26.js +0 -613
- package/chunk-HEVRQGGH.js +0 -106
- package/chunk-HHXF57CL.js +0 -180
- package/chunk-HI5RS2O4.js +0 -2109
- package/chunk-HJTI7RZV.js +0 -94
- package/chunk-HRWRIPTB.js +0 -531
- package/chunk-HYCVEESH.js +0 -2824
- package/chunk-I42VC5KR.js +0 -15
- package/chunk-IB5AR52X.js +0 -15
- package/chunk-IIRJ4P4I.js +0 -24
- package/chunk-IT3ZZRJE.js +0 -12
- package/chunk-IV6VUVLJ.js +0 -88
- package/chunk-J42X32PV.js +0 -472
- package/chunk-JDMWYVUF.js +0 -449
- package/chunk-JKVOKKMQ.js +0 -53
- package/chunk-JRTNUU5Z.js +0 -54
- package/chunk-K7HLFORE.js +0 -226
- package/chunk-KGBASAB5.js +0 -74
- package/chunk-KGKTN2NX.js +0 -25
- package/chunk-KX6YBIHG.js +0 -8
- package/chunk-KYHNSSL2.js +0 -62
- package/chunk-KZO2MTVM.js +0 -140
- package/chunk-L2DHCG6C.js +0 -779
- package/chunk-LKZPX6YH.js +0 -0
- package/chunk-LLP2NDED.js +0 -201
- package/chunk-LOFRSJX2.js +0 -47
- package/chunk-M75RM77T.js +0 -3970
- package/chunk-MDAYRIP7.js +0 -1889
- package/chunk-MI6HRMCK.js +0 -25
- package/chunk-MTNQNLSE.js +0 -1029
- package/chunk-NH4PUEWK.js +0 -762
- package/chunk-NHLLXINQ.js +0 -8
- package/chunk-NTUNHTJV.js +0 -40
- package/chunk-OJKUU3LP.js +0 -67
- package/chunk-OQH3TAB7.js +0 -299
- package/chunk-P62DHV4F.js +0 -443
- package/chunk-PHIERFHT.js +0 -574
- package/chunk-PKDFU6MY.js +0 -102
- package/chunk-PL5RKESU.js +0 -40
- package/chunk-PSJJBBWV.js +0 -42
- package/chunk-QKM55LP2.js +0 -739
- package/chunk-QQ56R7KS.js +0 -88
- package/chunk-QYPE3TS3.js +0 -43
- package/chunk-REAE2SZK.js +0 -62
- package/chunk-RGQ4UUWZ.js +0 -208
- package/chunk-RIRFHJTW.js +0 -353
- package/chunk-RYMLMTPZ.js +0 -547
- package/chunk-SSGTV4FC.js +0 -303
- package/chunk-SVKWZ3EG.js +0 -607
- package/chunk-T7KODHYS.js +0 -317
- package/chunk-TZXPT53C.js +0 -8
- package/chunk-U67V476Y.js +0 -35
- package/chunk-UEILX4EV.js +0 -15
- package/chunk-VIWDGTDA.js +0 -8
- package/chunk-VXUQWCEZ.js +0 -138
- package/chunk-W5GKF5ZW.js +0 -32
- package/chunk-WDWZPASX.js +0 -29
- package/chunk-WX266G2C.js +0 -9594
- package/chunk-YCITCYSJ.js +0 -356
- package/chunk-Z3KTXWWB.js +0 -76
- package/chunk-ZC3CMUKU.js +0 -322
- package/chunk-ZV7ZY46L.js +0 -1343
- package/cliAgentConfigHelpers-WB2S7PDO.js +0 -47
- package/cliAuthorityBrokerClient-3SKOA7OZ.js +0 -23
- package/cliAuthorityBrokerProcess-BMBVXPKU.js +0 -24
- package/cliAuthorityStoreDriver-6FE3BJNB.js +0 -20
- package/cliEnvHelpers-7V5ZWUJA.js +0 -34
- package/cliExecutor-N3445G2Z.js +0 -45
- package/cliLocalAgentRecordReader-QKKRK53P.js +0 -113
- package/cloudAutomationCommands-S52NKCLL.js +0 -310
- package/contentThunks-RK6MJWBY.js +0 -100
- package/cooldownCommands-ZFDAL4MR.js +0 -79
- package/createAgentAutomationAction-KN7XLCU2.js +0 -173
- package/createDialogAction-KAG6DBVM.js +0 -87
- package/createPageAction-7XNPH76L.js +0 -91
- package/cursorProvider-2RACMEMF.js +0 -6123
- package/db-LTHLW7QA.js +0 -178
- package/dbSlice-WNUHTF4C.js +0 -76
- package/deleteDbKey-MUCJP6DK.js +0 -87
- package/desktopFolderProjects-4POAMVJN.js +0 -45
- package/dialogCommands-4MOLJW4G.js +0 -165
- package/dialogMessageRecord-2HJTEXQX.js +0 -7
- package/dialogNotifyCommand-YL2GFKLO.js +0 -45
- package/dialogSlice-BD6WOOD3.js +0 -200
- package/dialogUsageCommand-IO2BQKL2.js +0 -31
- package/docCreateCommands-OYLRBK2M.js +0 -255
- package/docDeleteCommands-3NF6QPJU.js +0 -226
- package/docReadCommands-CBAERJAP.js +0 -184
- package/docStore-RK4CD4QN.js +0 -89
- package/docUpdateCommands-BAMCGX6F.js +0 -326
- package/ebookDownloaderAgentCommand-NOIZ6U7Y.js +0 -675
- package/fetchMessages-P7FSCSXV.js +0 -19
- package/getPricing-KNXVEIUI.js +0 -40
- package/hostCredentialCreate-CPIWBALC.js +0 -402
- package/i18n-SAK6DDY4.js +0 -51
- package/keys-FXEGMKSG.js +0 -183
- package/legacyMigration-TF4SYJCZ.js +0 -19
- package/levelAuthorityStore-L5SVDM5O.js +0 -10
- package/localAutomationCommands-WPYIYTDP.js +0 -199
- package/localAutomationRuntime-M7WWU6WY.js +0 -61
- package/localRecall-BDYKXB46.js +0 -17
- package/localRuntimeAdapter-SNE2NUDN.js +0 -310
- package/localRuntimeAuthority-Q5C2KWGF.js +0 -45
- package/localRuntimeDb-MM3DINZM.js +0 -12
- package/machineInfo-HNPJHQFU.js +0 -14
- package/machineWsRunDispatch-VHEIHXWY.js +0 -228
- package/models-TOXYINNM.js +0 -10
- package/oauthTokenStore-RUYNYALS.js +0 -24
- package/overlay-JA3SPVUS.js +0 -15
- package/parityCommands-5OCBPVES.js +0 -613
- package/processSpawn-6GEO77KV.js +0 -11
- package/profileConfig-KOWK4HOG.js +0 -49
- package/projectArchive-HUET56SH.js +0 -132
- package/providerPresetApply-YCVSP2WX.js +0 -235
- package/providerRegistry-26PAUYH2.js +0 -24
- package/read-D4WYJQJQ.js +0 -32
- package/readDocTool-3S3OQFOH.js +0 -22
- package/rememberExplicit-ZPI6KK5M.js +0 -16
- package/remove-AHRMUDMH.js +0 -32
- package/removeDialogAgentAction-AALRBFSA.js +0 -81
- package/secretCommands-2PSS3QNZ.js +0 -24
- package/setDialogExtraReferencesAction-SLHQ3GYL.js +0 -39
- package/setPrimaryDialogAgentAction-XKCSGJ7M.js +0 -96
- package/skillDiscovery-IUEZZG2B.js +0 -29
- package/skillSummaryMarker-62UW7HI7.js +0 -9
- package/slateToRenderMarkdown-R3X74MCX.js +0 -7
- package/slateUtils-ESQAJ6RN.js +0 -19
- package/store-WSAVTR32.js +0 -50
- package/switchDialogAgentAction-YJIWQGIR.js +0 -70
- package/tombstones-FQQMEDOW.js +0 -32
- package/toolApiClient-FVXTIIEN.js +0 -42
- package/tools-KB6CJ2KT.js +0 -147
- package/tuiRestart-LU2BDLAW.js +0 -50
- package/tuiSummaryLlmCaller-Z2ZVBIGN.js +0 -53
- package/updateCommands-4QP7WJLA.js +0 -63
- package/usageCommand-AZX7D3LB.js +0 -31
- package/usageRebuildCommand-XV5QQCHK.js +0 -623
- package/userDataMerge-HT2ZVHBJ.js +0 -13
- package/windowsSelfUpdate-5OFKSW6Y.js +0 -14
- package/workContext-ZAW6VXT7.js +0 -18
- package/workContextAccess-VU5I4LKZ.js +0 -11
- package/workContextWriteNotice-YCSSMHN4.js +0 -7
- /package/{chunk-BYXBJQAS.js → chunk-0bcc25vg.js} +0 -0
|
@@ -0,0 +1,4829 @@
|
|
|
1
|
+
import {
|
|
2
|
+
REASONING_EFFORT_OPTIONS
|
|
3
|
+
} from "./chunk-kawvydbk.js";
|
|
4
|
+
import {
|
|
5
|
+
hasReasoningEffortSuffix
|
|
6
|
+
} from "./chunk-mz002yz8.js";
|
|
7
|
+
import {
|
|
8
|
+
buildCliPrompt
|
|
9
|
+
} from "./chunk-2pj6qzq5.js";
|
|
10
|
+
import {
|
|
11
|
+
buildCliProcessEnv2,
|
|
12
|
+
resolveLaunchableCodexCommand
|
|
13
|
+
} from "./chunk-rvvn2rhj.js";
|
|
14
|
+
|
|
15
|
+
// packages/ai/agent/cliExecutor.ts
|
|
16
|
+
import { spawn as spawn4 } from "child_process";
|
|
17
|
+
import { existsSync as existsSync4, mkdtempSync, readFileSync as readFileSync4, realpathSync as realpathSync3, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
|
|
18
|
+
import { isAbsolute as isAbsolute3, join, relative as relative3, resolve as resolve3 } from "node:path";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import { StringDecoder as StringDecoder3 } from "node:string_decoder";
|
|
21
|
+
// packages/ai/agent/executors/opencodeExecutor.ts
|
|
22
|
+
import { spawn } from "node:child_process";
|
|
23
|
+
import { randomUUID } from "node:crypto";
|
|
24
|
+
async function executeOpenCodeStreaming(prompt, options) {
|
|
25
|
+
if (options.imageInputs && options.imageInputs.length > 0) {
|
|
26
|
+
throw new Error("OpenCode executor does not support imageInputs (unsupported)");
|
|
27
|
+
}
|
|
28
|
+
const startTime = Date.now();
|
|
29
|
+
const timeoutMs = options.timeout ?? 120000;
|
|
30
|
+
const deadline = startTime + timeoutMs;
|
|
31
|
+
if (options.signal?.aborted) {
|
|
32
|
+
throw new DOMException("Execution was aborted before start", "AbortError");
|
|
33
|
+
}
|
|
34
|
+
if (timeoutMs <= 0 || deadline <= startTime) {
|
|
35
|
+
throw new Error(`OpenCode timed out after ${timeoutMs}ms`);
|
|
36
|
+
}
|
|
37
|
+
const internalAbortController = new AbortController;
|
|
38
|
+
let abortReason = null;
|
|
39
|
+
const onExternalAbort = () => {
|
|
40
|
+
abortReason = options.signal?.reason || new DOMException("OpenCode execution was aborted", "AbortError");
|
|
41
|
+
internalAbortController.abort(abortReason);
|
|
42
|
+
};
|
|
43
|
+
if (options.signal) {
|
|
44
|
+
options.signal.addEventListener("abort", onExternalAbort, { once: true });
|
|
45
|
+
}
|
|
46
|
+
const remainingTimeout = deadline - Date.now();
|
|
47
|
+
let deadlineTimer = null;
|
|
48
|
+
if (remainingTimeout <= 0) {
|
|
49
|
+
abortReason = new Error(`OpenCode execution timed out after ${timeoutMs}ms`);
|
|
50
|
+
internalAbortController.abort(abortReason);
|
|
51
|
+
} else {
|
|
52
|
+
deadlineTimer = setTimeout(() => {
|
|
53
|
+
deadlineTimer = null;
|
|
54
|
+
abortReason = new Error(`OpenCode execution timed out after ${timeoutMs}ms`);
|
|
55
|
+
internalAbortController.abort(abortReason);
|
|
56
|
+
}, remainingTimeout);
|
|
57
|
+
deadlineTimer?.unref?.();
|
|
58
|
+
}
|
|
59
|
+
const getAbortError = () => {
|
|
60
|
+
return abortReason || internalAbortController.signal.reason || new DOMException("OpenCode execution was aborted", "AbortError");
|
|
61
|
+
};
|
|
62
|
+
const env = buildCliProcessEnv2(options.env);
|
|
63
|
+
const binPath = options.env?.OPENCODE_BIN || process.env.OPENCODE_BIN || "opencode";
|
|
64
|
+
const cwd = options.cwd || process.cwd();
|
|
65
|
+
const serveProc = spawn(binPath, ["serve", "--port", "0", "--hostname", "127.0.0.1"], {
|
|
66
|
+
cwd,
|
|
67
|
+
env,
|
|
68
|
+
detached: process.platform !== "win32",
|
|
69
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
70
|
+
});
|
|
71
|
+
let serverBaseUrl = null;
|
|
72
|
+
let activeSessionId = null;
|
|
73
|
+
let hasCleanedUp = false;
|
|
74
|
+
const onProcExit = (code, sig) => {
|
|
75
|
+
if (hasCleanedUp)
|
|
76
|
+
return;
|
|
77
|
+
const err = new Error(serverBaseUrl ? `OpenCode serve process exited prematurely (code: ${code}, signal: ${sig})` : `opencode serve exited before address detected (code: ${code}, signal: ${sig})`);
|
|
78
|
+
if (!internalAbortController.signal.aborted) {
|
|
79
|
+
abortReason = err;
|
|
80
|
+
internalAbortController.abort(err);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
serveProc.on("exit", onProcExit);
|
|
84
|
+
serveProc.on("error", (err) => {
|
|
85
|
+
if (hasCleanedUp)
|
|
86
|
+
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)
|
|
96
|
+
internalAbortController.abort();
|
|
97
|
+
return (async () => {
|
|
98
|
+
if (activeSessionId && serverBaseUrl) {
|
|
99
|
+
const timeout = AbortSignal.timeout(800);
|
|
100
|
+
try {
|
|
101
|
+
await Promise.race([
|
|
102
|
+
fetch(`${serverBaseUrl}/session/${activeSessionId}/abort`, { method: "POST", signal: timeout }),
|
|
103
|
+
new Promise((resolve) => timeout.addEventListener("abort", () => resolve(), { once: true }))
|
|
104
|
+
]);
|
|
105
|
+
} catch {}
|
|
106
|
+
}
|
|
107
|
+
await terminateCliProcessGroupEscalating2(serveProc);
|
|
108
|
+
})();
|
|
109
|
+
};
|
|
110
|
+
try {
|
|
111
|
+
const portPromise = new Promise((resolve, 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
|
+
resolve(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 = new Map;
|
|
212
|
+
const emittedToolCalls = new Set;
|
|
213
|
+
const emittedToolResults = new Set;
|
|
214
|
+
const emittedToolErrors = new Set;
|
|
215
|
+
const streamPromise = new Promise((resolve, reject) => {
|
|
216
|
+
let buffer = "";
|
|
217
|
+
const reader = sseResponse.body.getReader();
|
|
218
|
+
const decoder = new TextDecoder("utf-8");
|
|
219
|
+
const markCompleted = () => {
|
|
220
|
+
isCompleted = true;
|
|
221
|
+
resolve();
|
|
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)
|
|
277
|
+
return;
|
|
278
|
+
if (part.type === "tool") {
|
|
279
|
+
hasBeenBusy = true;
|
|
280
|
+
const callId = part.callID || part.id || `tool-${randomUUID().slice(0, 6)}`;
|
|
281
|
+
const toolName = part.tool || "unknown";
|
|
282
|
+
const state = part.state;
|
|
283
|
+
const round = options.toolEventRound ?? 1;
|
|
284
|
+
if (state?.status === "pending" || state?.status === "running") {
|
|
285
|
+
if (!emittedToolCalls.has(callId)) {
|
|
286
|
+
emittedToolCalls.add(callId);
|
|
287
|
+
options.onToolEvent?.({
|
|
288
|
+
type: "tool-call",
|
|
289
|
+
round,
|
|
290
|
+
toolCallId: callId,
|
|
291
|
+
toolName,
|
|
292
|
+
summary: `Tool call: ${toolName}`,
|
|
293
|
+
metadata: { source: "cli-external", cliProvider: "opencode" }
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
} else if (state?.status === "completed") {
|
|
297
|
+
if (!emittedToolResults.has(callId)) {
|
|
298
|
+
emittedToolResults.add(callId);
|
|
299
|
+
options.onToolEvent?.({
|
|
300
|
+
type: "tool-result",
|
|
301
|
+
round,
|
|
302
|
+
toolCallId: callId,
|
|
303
|
+
toolName,
|
|
304
|
+
summary: `Tool completed: ${toolName}`,
|
|
305
|
+
metadata: { source: "cli-external", cliProvider: "opencode" }
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
} else if (state?.status === "error") {
|
|
309
|
+
if (!emittedToolErrors.has(callId)) {
|
|
310
|
+
emittedToolErrors.add(callId);
|
|
311
|
+
options.onToolEvent?.({
|
|
312
|
+
type: "tool-error",
|
|
313
|
+
round,
|
|
314
|
+
toolCallId: callId,
|
|
315
|
+
toolName,
|
|
316
|
+
message: "Tool execution failed",
|
|
317
|
+
summary: `Tool error: ${toolName}`,
|
|
318
|
+
metadata: { source: "cli-external", cliProvider: "opencode" }
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
} else if (part.type === "text") {
|
|
323
|
+
hasBeenBusy = true;
|
|
324
|
+
const partId = part.id || part.partID || "default";
|
|
325
|
+
const fullPartText = typeof part.text === "string" ? part.text : "";
|
|
326
|
+
const seen = seenPartTexts.get(partId) || "";
|
|
327
|
+
if (fullPartText.length > seen.length) {
|
|
328
|
+
const diff = fullPartText.slice(seen.length);
|
|
329
|
+
if (diff.length > 0) {
|
|
330
|
+
seenPartTexts.set(partId, seen + diff);
|
|
331
|
+
fullText += diff;
|
|
332
|
+
options.onChunk?.(diff);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
const pump = async () => {
|
|
339
|
+
try {
|
|
340
|
+
while (true) {
|
|
341
|
+
const { done, value } = await reader.read();
|
|
342
|
+
if (done) {
|
|
343
|
+
if (!isCompleted) {
|
|
344
|
+
reject(new Error("OpenCode SSE stream disconnected prematurely (unexpected EOF)"));
|
|
345
|
+
}
|
|
346
|
+
break;
|
|
347
|
+
}
|
|
348
|
+
buffer += decoder.decode(value, { stream: true });
|
|
349
|
+
const lines = buffer.split(/\r?\n/);
|
|
350
|
+
buffer = lines.pop() ?? "";
|
|
351
|
+
for (const line of lines) {
|
|
352
|
+
const trimmed = line.trim();
|
|
353
|
+
if (trimmed.startsWith("data:")) {
|
|
354
|
+
const payload = trimmed.slice(5).trim();
|
|
355
|
+
if (payload === "[DONE]") {
|
|
356
|
+
markCompleted();
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
let parsed;
|
|
360
|
+
try {
|
|
361
|
+
parsed = JSON.parse(payload);
|
|
362
|
+
} catch {
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
handleEventJson(parsed);
|
|
366
|
+
if (isCompleted) {
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
} catch (err) {
|
|
373
|
+
if (isCompleted) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (internalAbortController.signal.aborted) {
|
|
377
|
+
reject(getAbortError());
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
if (err?.name === "AbortError") {
|
|
381
|
+
reject(getAbortError());
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
reject(err);
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
pump();
|
|
388
|
+
});
|
|
389
|
+
streamPromise.catch(() => {});
|
|
390
|
+
const promptPayload = {
|
|
391
|
+
parts: [{ type: "text", text: prompt }],
|
|
392
|
+
...promptModel ? { model: promptModel } : {},
|
|
393
|
+
...options.systemPrompt ? { system: options.systemPrompt } : {}
|
|
394
|
+
};
|
|
395
|
+
const promptResp = await fetch(`${serverBaseUrl}/session/${sessionId}/prompt_async`, {
|
|
396
|
+
method: "POST",
|
|
397
|
+
headers: { "Content-Type": "application/json" },
|
|
398
|
+
body: JSON.stringify(promptPayload),
|
|
399
|
+
signal: internalAbortController.signal
|
|
400
|
+
}).catch((err) => {
|
|
401
|
+
if (internalAbortController.signal.aborted) {
|
|
402
|
+
throw getAbortError();
|
|
403
|
+
}
|
|
404
|
+
throw err;
|
|
405
|
+
});
|
|
406
|
+
if (!promptResp.ok) {
|
|
407
|
+
const errText = await promptResp.text().catch(() => "");
|
|
408
|
+
throw new Error(`Failed to send prompt to OpenCode session (HTTP ${promptResp.status}): ${errText}`);
|
|
409
|
+
}
|
|
410
|
+
let abortListener = null;
|
|
411
|
+
const abortPromise = new Promise((_, reject) => {
|
|
412
|
+
if (internalAbortController.signal.aborted) {
|
|
413
|
+
reject(getAbortError());
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
abortListener = () => reject(getAbortError());
|
|
417
|
+
internalAbortController.signal.addEventListener("abort", abortListener, { once: true });
|
|
418
|
+
});
|
|
419
|
+
try {
|
|
420
|
+
await Promise.race([streamPromise, abortPromise]);
|
|
421
|
+
} finally {
|
|
422
|
+
if (abortListener) {
|
|
423
|
+
internalAbortController.signal.removeEventListener("abort", abortListener);
|
|
424
|
+
abortListener = null;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const elapsed = Date.now() - startTime;
|
|
428
|
+
return attachExecutionStoppedPromise2({ text: fullText, raw: fullText, elapsed }, cleanup());
|
|
429
|
+
} catch (error) {
|
|
430
|
+
throw attachExecutionStoppedPromise2(error instanceof Error ? error : new Error(String(error)), cleanup());
|
|
431
|
+
} finally {
|
|
432
|
+
if (deadlineTimer) {
|
|
433
|
+
clearTimeout(deadlineTimer);
|
|
434
|
+
deadlineTimer = null;
|
|
435
|
+
}
|
|
436
|
+
if (options.signal) {
|
|
437
|
+
options.signal.removeEventListener("abort", onExternalAbort);
|
|
438
|
+
}
|
|
439
|
+
serveProc.off("exit", onProcExit);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// packages/ai/agent/executors/agyAcpClient.ts
|
|
444
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
445
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
446
|
+
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
|
447
|
+
import { StringDecoder } from "node:string_decoder";
|
|
448
|
+
|
|
449
|
+
// packages/ai/agent/executors/agyAcpToolEvents.ts
|
|
450
|
+
var GENERIC_ACP_TITLES = new Set(["", "tool", "other", "unknown"]);
|
|
451
|
+
function asRecord(value) {
|
|
452
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
453
|
+
}
|
|
454
|
+
function asNonEmptyString(value) {
|
|
455
|
+
if (typeof value !== "string")
|
|
456
|
+
return;
|
|
457
|
+
const trimmed = value.trim();
|
|
458
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
459
|
+
}
|
|
460
|
+
function asPositiveInt(value) {
|
|
461
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
|
462
|
+
}
|
|
463
|
+
function isInformativeTitle(title) {
|
|
464
|
+
return Boolean(title && !GENERIC_ACP_TITLES.has(title.toLowerCase()));
|
|
465
|
+
}
|
|
466
|
+
function parseRawInputRecord(rawInput) {
|
|
467
|
+
const direct = asRecord(rawInput);
|
|
468
|
+
if (direct)
|
|
469
|
+
return direct;
|
|
470
|
+
if (typeof rawInput === "string") {
|
|
471
|
+
const trimmed = rawInput.trim();
|
|
472
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
473
|
+
try {
|
|
474
|
+
return asRecord(JSON.parse(trimmed));
|
|
475
|
+
} catch {
|
|
476
|
+
return null;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
function parseLocations(value) {
|
|
483
|
+
if (!Array.isArray(value))
|
|
484
|
+
return;
|
|
485
|
+
const parsed = [];
|
|
486
|
+
for (const item of value) {
|
|
487
|
+
const rec = asRecord(item);
|
|
488
|
+
if (!rec)
|
|
489
|
+
continue;
|
|
490
|
+
const path = asNonEmptyString(rec.path);
|
|
491
|
+
const line = asPositiveInt(rec.line);
|
|
492
|
+
if (path || line !== undefined)
|
|
493
|
+
parsed.push({ ...path ? { path } : {}, ...line !== undefined ? { line } : {} });
|
|
494
|
+
}
|
|
495
|
+
return parsed.length > 0 ? parsed : undefined;
|
|
496
|
+
}
|
|
497
|
+
function extractFirstString(record, keys) {
|
|
498
|
+
if (!record)
|
|
499
|
+
return;
|
|
500
|
+
for (const key of keys) {
|
|
501
|
+
const value = asNonEmptyString(record[key]);
|
|
502
|
+
if (value)
|
|
503
|
+
return value;
|
|
504
|
+
}
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
function extractErrorText(update) {
|
|
508
|
+
const direct = asNonEmptyString(update.error) ?? asNonEmptyString(update.message) ?? asNonEmptyString(asRecord(update.error)?.message);
|
|
509
|
+
if (direct)
|
|
510
|
+
return direct;
|
|
511
|
+
const rawOutput = asRecord(update.rawOutput) ?? asRecord(update.raw_output);
|
|
512
|
+
const rawErr = asNonEmptyString(rawOutput?.error) ?? asNonEmptyString(rawOutput?.stderr) ?? asNonEmptyString(rawOutput?.message);
|
|
513
|
+
if (rawErr)
|
|
514
|
+
return rawErr;
|
|
515
|
+
if (Array.isArray(update.content)) {
|
|
516
|
+
for (const item of update.content) {
|
|
517
|
+
const rec = asRecord(item);
|
|
518
|
+
const inner = asRecord(rec?.content);
|
|
519
|
+
const text = asNonEmptyString(inner?.text) ?? asNonEmptyString(rec?.text);
|
|
520
|
+
if (text)
|
|
521
|
+
return text;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
function extractStructuredFields(entry) {
|
|
527
|
+
const input = parseRawInputRecord(entry.rawInput);
|
|
528
|
+
const firstLoc = entry.locations?.find((loc) => loc.path);
|
|
529
|
+
const path = extractFirstString(input, [
|
|
530
|
+
"path",
|
|
531
|
+
"Path",
|
|
532
|
+
"filePath",
|
|
533
|
+
"file_path",
|
|
534
|
+
"AbsolutePath",
|
|
535
|
+
"TargetFile",
|
|
536
|
+
"SearchPath",
|
|
537
|
+
"SearchDirectory",
|
|
538
|
+
"DirectoryPath"
|
|
539
|
+
]) ?? firstLoc?.path;
|
|
540
|
+
const startLine = asPositiveInt(input?.startLine) ?? asPositiveInt(input?.StartLine) ?? asPositiveInt(input?.start_line) ?? firstLoc?.line;
|
|
541
|
+
const endLine = asPositiveInt(input?.endLine) ?? asPositiveInt(input?.EndLine) ?? asPositiveInt(input?.end_line);
|
|
542
|
+
const command = extractFirstString(input, ["command", "Command", "CommandLine", "command_line", "cmd", "Cmd"]);
|
|
543
|
+
const query = extractFirstString(input, ["query", "Query", "pattern", "Pattern", "search_query"]);
|
|
544
|
+
const url = extractFirstString(input, ["url", "Url", "URL"]);
|
|
545
|
+
const role = extractFirstString(input, ["Role", "role"]);
|
|
546
|
+
const toolSummary = extractFirstString(input, ["toolSummary", "description", "Description"]);
|
|
547
|
+
let acpTitle;
|
|
548
|
+
if (isInformativeTitle(entry.title)) {
|
|
549
|
+
acpTitle = entry.title;
|
|
550
|
+
}
|
|
551
|
+
if (toolSummary && (!acpTitle || /^(?:run_command|exec_shell|bash|shell|terminal)$/i.test(acpTitle))) {
|
|
552
|
+
acpTitle = toolSummary;
|
|
553
|
+
} else if (role && (!acpTitle || /^(?:invoke_subagent|subagent|agent|task)$/i.test(acpTitle))) {
|
|
554
|
+
acpTitle = role;
|
|
555
|
+
}
|
|
556
|
+
return {
|
|
557
|
+
...path ? { path } : {},
|
|
558
|
+
...startLine !== undefined ? { startLine } : {},
|
|
559
|
+
...endLine !== undefined ? { endLine } : {},
|
|
560
|
+
...command ? { command } : {},
|
|
561
|
+
...query ? { query } : {},
|
|
562
|
+
...url ? { url } : {},
|
|
563
|
+
...acpTitle ? { acpTitle } : {}
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
function resolveCanonicalToolName(entry, fields) {
|
|
567
|
+
const kind = entry.kind?.toLowerCase();
|
|
568
|
+
const title = entry.title;
|
|
569
|
+
if (kind === "read") {
|
|
570
|
+
return fields.path ? "readFile" : isInformativeTitle(title) ? title : "readFile";
|
|
571
|
+
}
|
|
572
|
+
if (kind === "execute") {
|
|
573
|
+
return "runCommand";
|
|
574
|
+
}
|
|
575
|
+
if (kind === "edit" || kind === "move") {
|
|
576
|
+
if (fields.path) {
|
|
577
|
+
return title && /\b(write|create)\b/i.test(title) ? "writeFile" : "editFile";
|
|
578
|
+
}
|
|
579
|
+
return isInformativeTitle(title) ? title : "editFile";
|
|
580
|
+
}
|
|
581
|
+
if (kind === "search") {
|
|
582
|
+
if (fields.query || fields.path) {
|
|
583
|
+
return title && /\bweb\b/i.test(title) ? "exa_search" : "searchFiles";
|
|
584
|
+
}
|
|
585
|
+
return isInformativeTitle(title) ? title : "searchFiles";
|
|
586
|
+
}
|
|
587
|
+
if (kind === "fetch") {
|
|
588
|
+
return fields.url ? "fetchWebpage" : isInformativeTitle(title) ? title : "fetchWebpage";
|
|
589
|
+
}
|
|
590
|
+
if (kind === "delete") {
|
|
591
|
+
return isInformativeTitle(title) ? title : "deleteFile";
|
|
592
|
+
}
|
|
593
|
+
if (fields.command)
|
|
594
|
+
return "runCommand";
|
|
595
|
+
if (fields.url && (!title || /\b(fetch|url|web)\b/i.test(title)))
|
|
596
|
+
return "fetchWebpage";
|
|
597
|
+
if (isInformativeTitle(title))
|
|
598
|
+
return title;
|
|
599
|
+
if (fields.query)
|
|
600
|
+
return "searchFiles";
|
|
601
|
+
if (fields.path)
|
|
602
|
+
return "readFile";
|
|
603
|
+
return kind && kind !== "other" ? kind : "tool";
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
class AgyAcpToolEventTracker {
|
|
607
|
+
calls = new Map;
|
|
608
|
+
now;
|
|
609
|
+
constructor(now = () => Date.now()) {
|
|
610
|
+
this.now = now;
|
|
611
|
+
}
|
|
612
|
+
get inFlightCount() {
|
|
613
|
+
let count = 0;
|
|
614
|
+
for (const entry of this.calls.values()) {
|
|
615
|
+
if (!entry.emittedTerminal)
|
|
616
|
+
count += 1;
|
|
617
|
+
}
|
|
618
|
+
return count;
|
|
619
|
+
}
|
|
620
|
+
handleUpdate(update, round) {
|
|
621
|
+
const kind = asNonEmptyString(update.sessionUpdate) ?? asNonEmptyString(update.type);
|
|
622
|
+
if (kind !== "tool_call" && kind !== "tool_call_update")
|
|
623
|
+
return null;
|
|
624
|
+
const toolCallId = asNonEmptyString(update.toolCallId) ?? asNonEmptyString(update.tool_call_id);
|
|
625
|
+
if (!toolCallId)
|
|
626
|
+
return null;
|
|
627
|
+
let entry = this.calls.get(toolCallId);
|
|
628
|
+
if (!entry) {
|
|
629
|
+
entry = {
|
|
630
|
+
startedAt: this.now(),
|
|
631
|
+
emittedCall: false,
|
|
632
|
+
emittedTerminal: false
|
|
633
|
+
};
|
|
634
|
+
this.calls.set(toolCallId, entry);
|
|
635
|
+
}
|
|
636
|
+
const incomingTitle = asNonEmptyString(update.title);
|
|
637
|
+
if (incomingTitle && (!entry.title || isInformativeTitle(incomingTitle))) {
|
|
638
|
+
entry.title = incomingTitle;
|
|
639
|
+
}
|
|
640
|
+
const incomingKind = asNonEmptyString(update.kind);
|
|
641
|
+
if (incomingKind && (!entry.kind || incomingKind.toLowerCase() !== "other")) {
|
|
642
|
+
entry.kind = incomingKind;
|
|
643
|
+
}
|
|
644
|
+
const incomingRawInput = update.rawInput ?? update.raw_input;
|
|
645
|
+
if (incomingRawInput !== undefined && incomingRawInput !== null) {
|
|
646
|
+
const incomingRec = parseRawInputRecord(incomingRawInput);
|
|
647
|
+
if (incomingRec) {
|
|
648
|
+
if (Object.keys(incomingRec).length > 0) {
|
|
649
|
+
const prevRec = parseRawInputRecord(entry.rawInput);
|
|
650
|
+
entry.rawInput = prevRec ? { ...prevRec, ...incomingRec } : incomingRec;
|
|
651
|
+
}
|
|
652
|
+
} else if (typeof incomingRawInput === "string") {
|
|
653
|
+
if (incomingRawInput.trim().length > 0)
|
|
654
|
+
entry.rawInput = incomingRawInput;
|
|
655
|
+
} else {
|
|
656
|
+
entry.rawInput = incomingRawInput;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
const incomingLocations = parseLocations(update.locations);
|
|
660
|
+
if (incomingLocations) {
|
|
661
|
+
entry.locations = incomingLocations;
|
|
662
|
+
}
|
|
663
|
+
const errorText = extractErrorText(update);
|
|
664
|
+
if (errorText) {
|
|
665
|
+
entry.lastErrorMessage = errorText;
|
|
666
|
+
}
|
|
667
|
+
const status = (asNonEmptyString(update.status) ?? "").toLowerCase();
|
|
668
|
+
const fields = extractStructuredFields(entry);
|
|
669
|
+
const toolName = resolveCanonicalToolName(entry, fields);
|
|
670
|
+
const displayTitle = fields.acpTitle ?? entry.title ?? toolName;
|
|
671
|
+
const metadata = {
|
|
672
|
+
source: "cli-external",
|
|
673
|
+
cliProvider: "agy",
|
|
674
|
+
...entry.kind ? { acpKind: entry.kind } : {},
|
|
675
|
+
...fields.acpTitle ? { acpTitle: fields.acpTitle } : {},
|
|
676
|
+
...fields.path ? { path: fields.path } : {},
|
|
677
|
+
...fields.startLine !== undefined ? { startLine: fields.startLine } : {},
|
|
678
|
+
...fields.endLine !== undefined ? { endLine: fields.endLine } : {},
|
|
679
|
+
...fields.command ? { command: fields.command } : {},
|
|
680
|
+
...fields.query ? { query: fields.query } : {},
|
|
681
|
+
...fields.url ? { url: fields.url } : {}
|
|
682
|
+
};
|
|
683
|
+
if (status === "pending" || status === "in_progress" || status === "") {
|
|
684
|
+
if (entry.emittedCall)
|
|
685
|
+
return null;
|
|
686
|
+
entry.emittedCall = true;
|
|
687
|
+
return {
|
|
688
|
+
type: "tool-call",
|
|
689
|
+
round,
|
|
690
|
+
toolCallId,
|
|
691
|
+
toolName,
|
|
692
|
+
summary: `Tool call: ${displayTitle}`,
|
|
693
|
+
metadata
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
if (status === "completed") {
|
|
697
|
+
if (entry.emittedTerminal)
|
|
698
|
+
return null;
|
|
699
|
+
entry.emittedTerminal = true;
|
|
700
|
+
const elapsedMs = Math.max(0, this.now() - entry.startedAt);
|
|
701
|
+
return {
|
|
702
|
+
type: "tool-result",
|
|
703
|
+
round,
|
|
704
|
+
toolCallId,
|
|
705
|
+
toolName,
|
|
706
|
+
elapsedMs,
|
|
707
|
+
summary: `Tool completed: ${displayTitle}`,
|
|
708
|
+
metadata
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
if (status === "failed") {
|
|
712
|
+
if (entry.emittedTerminal)
|
|
713
|
+
return null;
|
|
714
|
+
entry.emittedTerminal = true;
|
|
715
|
+
const elapsedMs = Math.max(0, this.now() - entry.startedAt);
|
|
716
|
+
const message = entry.lastErrorMessage ?? `Tool failed: ${displayTitle}`;
|
|
717
|
+
return {
|
|
718
|
+
type: "tool-error",
|
|
719
|
+
round,
|
|
720
|
+
toolCallId,
|
|
721
|
+
toolName,
|
|
722
|
+
elapsedMs,
|
|
723
|
+
message,
|
|
724
|
+
summary: `Tool error: ${displayTitle}`,
|
|
725
|
+
metadata
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
return null;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// packages/ai/agent/executors/agyAcpClient.ts
|
|
733
|
+
var ACP_PROTOCOL_VERSION = 1;
|
|
734
|
+
var DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;
|
|
735
|
+
var DEFAULT_HANDSHAKE_TIMEOUT_MS = 60000;
|
|
736
|
+
var CANCEL_GRACE_MS = 800;
|
|
737
|
+
var AGY_ACP_NO_OUTPUT_TIMEOUT_MS = 180000;
|
|
738
|
+
var MAX_TERMINAL_OUTPUT_CHARS = 200000;
|
|
739
|
+
var STDERR_TAIL_CHARS = 4000;
|
|
740
|
+
function asRecord2(value) {
|
|
741
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
742
|
+
}
|
|
743
|
+
function asString(value) {
|
|
744
|
+
return typeof value === "string" ? value : undefined;
|
|
745
|
+
}
|
|
746
|
+
function asNumber(value) {
|
|
747
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
748
|
+
}
|
|
749
|
+
function createAbortError(message = "agy ACP execution aborted") {
|
|
750
|
+
return new DOMException(message, "AbortError");
|
|
751
|
+
}
|
|
752
|
+
function isWithin(root, target) {
|
|
753
|
+
const rel = relative(resolve(root), resolve(target));
|
|
754
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
class AgyAcpRequestTimeoutError extends Error {
|
|
758
|
+
timedOutMethod;
|
|
759
|
+
kind;
|
|
760
|
+
lastEventKind;
|
|
761
|
+
idleMs;
|
|
762
|
+
constructor(timedOutMethod, detail) {
|
|
763
|
+
super(detail === undefined ? `agy ACP request timed out: ${timedOutMethod}` : detail.kind === "no_output" ? `agy ACP request timed out: ${timedOutMethod} stalled (no output for ${Math.round(detail.idleMs / 1000)}s, ` + `lastEvent=${detail.lastEventKind}; 长静默活可用 NOLO_AGY_NO_OUTPUT_TIMEOUT_MS 放宽或设 0 关闭看门狗)` : `agy ACP request timed out: ${timedOutMethod} total timeout (lastEvent=${detail.lastEventKind}, ` + `idle=${detail.idleMs}ms)`);
|
|
764
|
+
this.timedOutMethod = timedOutMethod;
|
|
765
|
+
this.name = "AgyAcpRequestTimeoutError";
|
|
766
|
+
this.kind = detail?.kind ?? "unspecified";
|
|
767
|
+
this.lastEventKind = detail?.lastEventKind ?? "unspecified";
|
|
768
|
+
this.idleMs = detail?.idleMs ?? 0;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
772
|
+
var clampTimerDelay = (ms) => Math.min(ms, MAX_TIMER_DELAY_MS);
|
|
773
|
+
function createTurnWatchdog(options) {
|
|
774
|
+
let lastEventKind = "turn-start";
|
|
775
|
+
let lastActivityAt = Date.now();
|
|
776
|
+
let idleTimer = null;
|
|
777
|
+
let totalTimer = null;
|
|
778
|
+
let settled = false;
|
|
779
|
+
let rejectPromise = () => {};
|
|
780
|
+
const promise = new Promise((_resolve, reject) => {
|
|
781
|
+
rejectPromise = reject;
|
|
782
|
+
});
|
|
783
|
+
promise.catch(() => {});
|
|
784
|
+
const clearIdle = () => {
|
|
785
|
+
if (idleTimer) {
|
|
786
|
+
clearTimeout(idleTimer);
|
|
787
|
+
idleTimer = null;
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
const clearTotal = () => {
|
|
791
|
+
if (totalTimer) {
|
|
792
|
+
clearTimeout(totalTimer);
|
|
793
|
+
totalTimer = null;
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
const dispose = () => {
|
|
797
|
+
clearIdle();
|
|
798
|
+
clearTotal();
|
|
799
|
+
};
|
|
800
|
+
const fire = (kind) => {
|
|
801
|
+
if (settled)
|
|
802
|
+
return;
|
|
803
|
+
settled = true;
|
|
804
|
+
dispose();
|
|
805
|
+
rejectPromise(new AgyAcpRequestTimeoutError("session/prompt", {
|
|
806
|
+
kind,
|
|
807
|
+
lastEventKind,
|
|
808
|
+
idleMs: Date.now() - lastActivityAt
|
|
809
|
+
}));
|
|
810
|
+
};
|
|
811
|
+
const armIdle = () => {
|
|
812
|
+
clearIdle();
|
|
813
|
+
if (options.noOutputMs <= 0)
|
|
814
|
+
return;
|
|
815
|
+
idleTimer = setTimeout(() => fire("no_output"), clampTimerDelay(options.noOutputMs));
|
|
816
|
+
idleTimer.unref?.();
|
|
817
|
+
};
|
|
818
|
+
armIdle();
|
|
819
|
+
if (options.totalMs > 0) {
|
|
820
|
+
totalTimer = setTimeout(() => fire("total"), clampTimerDelay(options.totalMs));
|
|
821
|
+
totalTimer.unref?.();
|
|
822
|
+
}
|
|
823
|
+
return {
|
|
824
|
+
promise,
|
|
825
|
+
noteActivity(eventKind) {
|
|
826
|
+
if (settled)
|
|
827
|
+
return;
|
|
828
|
+
lastEventKind = eventKind;
|
|
829
|
+
lastActivityAt = Date.now();
|
|
830
|
+
armIdle();
|
|
831
|
+
},
|
|
832
|
+
dispose
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
function toRpcError(value) {
|
|
836
|
+
const record = asRecord2(value);
|
|
837
|
+
if (!record)
|
|
838
|
+
return null;
|
|
839
|
+
const code = asNumber(record.code);
|
|
840
|
+
const message = asString(record.message);
|
|
841
|
+
if (code === undefined && message === undefined)
|
|
842
|
+
return null;
|
|
843
|
+
return { code: code ?? -32000, message: message ?? "unknown JSON-RPC error" };
|
|
844
|
+
}
|
|
845
|
+
function normalizeAcpUsage(value) {
|
|
846
|
+
const record = asRecord2(value);
|
|
847
|
+
if (!record)
|
|
848
|
+
return;
|
|
849
|
+
const pick = (...keys) => {
|
|
850
|
+
for (const key of keys) {
|
|
851
|
+
const found = asNumber(record[key]);
|
|
852
|
+
if (found !== undefined)
|
|
853
|
+
return found;
|
|
854
|
+
}
|
|
855
|
+
return;
|
|
856
|
+
};
|
|
857
|
+
const input = pick("inputTokens", "input_tokens", "prompt_tokens");
|
|
858
|
+
const output = pick("outputTokens", "output_tokens", "completion_tokens");
|
|
859
|
+
const total = pick("totalTokens", "total_tokens");
|
|
860
|
+
const cacheRead = pick("cachedReadTokens", "cache_read_tokens", "cache_read_input_tokens");
|
|
861
|
+
if (input === undefined && output === undefined && total === undefined && cacheRead === undefined) {
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
return {
|
|
865
|
+
...input !== undefined ? { input_tokens: input } : {},
|
|
866
|
+
...output !== undefined ? { output_tokens: output } : {},
|
|
867
|
+
...total !== undefined ? { total_tokens: total } : {},
|
|
868
|
+
...cacheRead !== undefined ? { cache_read_input_tokens: cacheRead } : {}
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
class AcpRpcPeer {
|
|
873
|
+
writeLine;
|
|
874
|
+
onRequest;
|
|
875
|
+
onNotification;
|
|
876
|
+
onFrame;
|
|
877
|
+
buffer = "";
|
|
878
|
+
decoder = new StringDecoder("utf8");
|
|
879
|
+
pending = new Map;
|
|
880
|
+
nextId = 1;
|
|
881
|
+
disposed = false;
|
|
882
|
+
droppedNotifications = 0;
|
|
883
|
+
constructor(writeLine, onRequest, onNotification, onFrame) {
|
|
884
|
+
this.writeLine = writeLine;
|
|
885
|
+
this.onRequest = onRequest;
|
|
886
|
+
this.onNotification = onNotification;
|
|
887
|
+
this.onFrame = onFrame;
|
|
888
|
+
}
|
|
889
|
+
feed(chunk) {
|
|
890
|
+
this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
|
|
891
|
+
while (true) {
|
|
892
|
+
const newlineIndex = this.buffer.indexOf(`
|
|
893
|
+
`);
|
|
894
|
+
if (newlineIndex < 0)
|
|
895
|
+
return;
|
|
896
|
+
const line = this.buffer.slice(0, newlineIndex).trim();
|
|
897
|
+
this.buffer = this.buffer.slice(newlineIndex + 1);
|
|
898
|
+
if (line)
|
|
899
|
+
this.handleLine(line);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
handleLine(line) {
|
|
903
|
+
let parsed;
|
|
904
|
+
try {
|
|
905
|
+
parsed = JSON.parse(line);
|
|
906
|
+
} catch {
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
const message = asRecord2(parsed);
|
|
910
|
+
if (!message)
|
|
911
|
+
return;
|
|
912
|
+
try {
|
|
913
|
+
this.onFrame?.(message);
|
|
914
|
+
} catch {}
|
|
915
|
+
const id = asNumber(message.id);
|
|
916
|
+
const method = asString(message.method);
|
|
917
|
+
if (method === undefined) {
|
|
918
|
+
if (id === undefined)
|
|
919
|
+
return;
|
|
920
|
+
const pending = this.pending.get(id);
|
|
921
|
+
if (!pending)
|
|
922
|
+
return;
|
|
923
|
+
this.pending.delete(id);
|
|
924
|
+
if (pending.timer)
|
|
925
|
+
clearTimeout(pending.timer);
|
|
926
|
+
const error = toRpcError(message.error);
|
|
927
|
+
if (error) {
|
|
928
|
+
pending.reject(new Error(`${error.message} (code ${error.code})`));
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
pending.resolve(message.result);
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
if (id === undefined) {
|
|
935
|
+
try {
|
|
936
|
+
this.onNotification(method, message.params);
|
|
937
|
+
} catch {
|
|
938
|
+
this.droppedNotifications += 1;
|
|
939
|
+
}
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
Promise.resolve().then(() => this.onRequest(method, message.params)).then((result) => this.send({ jsonrpc: "2.0", id, result: result ?? null }), (error) => this.send({
|
|
943
|
+
jsonrpc: "2.0",
|
|
944
|
+
id,
|
|
945
|
+
error: {
|
|
946
|
+
code: -32603,
|
|
947
|
+
message: error instanceof Error ? error.message : String(error)
|
|
948
|
+
}
|
|
949
|
+
}));
|
|
950
|
+
}
|
|
951
|
+
request(method, params, timeoutMs) {
|
|
952
|
+
if (this.disposed) {
|
|
953
|
+
return Promise.reject(new Error(`agy ACP peer is closed (request ${method})`));
|
|
954
|
+
}
|
|
955
|
+
const id = this.nextId++;
|
|
956
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
957
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
958
|
+
this.pending.delete(id);
|
|
959
|
+
rejectPromise(new AgyAcpRequestTimeoutError(method));
|
|
960
|
+
}, timeoutMs) : null;
|
|
961
|
+
timer?.unref?.();
|
|
962
|
+
this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
|
|
963
|
+
this.send({ jsonrpc: "2.0", id, method, params });
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
notify(method, params) {
|
|
967
|
+
if (this.disposed)
|
|
968
|
+
return;
|
|
969
|
+
this.send({ jsonrpc: "2.0", method, params });
|
|
970
|
+
}
|
|
971
|
+
takeDroppedNotifications() {
|
|
972
|
+
const dropped = this.droppedNotifications;
|
|
973
|
+
this.droppedNotifications = 0;
|
|
974
|
+
return dropped;
|
|
975
|
+
}
|
|
976
|
+
send(payload) {
|
|
977
|
+
try {
|
|
978
|
+
this.writeLine(`${JSON.stringify(payload)}
|
|
979
|
+
`);
|
|
980
|
+
} catch {}
|
|
981
|
+
}
|
|
982
|
+
dispose(reason) {
|
|
983
|
+
if (this.disposed)
|
|
984
|
+
return;
|
|
985
|
+
this.disposed = true;
|
|
986
|
+
for (const [id, pending] of this.pending) {
|
|
987
|
+
this.pending.delete(id);
|
|
988
|
+
if (pending.timer)
|
|
989
|
+
clearTimeout(pending.timer);
|
|
990
|
+
pending.reject(reason);
|
|
991
|
+
}
|
|
992
|
+
this.buffer = "";
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
var ACP_MODEL_EFFORT_SUFFIX_RE = /^(.+)-(low|medium|high|xhigh|max)$/i;
|
|
996
|
+
function resolveAcpModelAndEffort(modelOption, requestedModel) {
|
|
997
|
+
const trimmed = requestedModel?.trim();
|
|
998
|
+
if (!trimmed || !modelOption)
|
|
999
|
+
return { model: null };
|
|
1000
|
+
if (modelOption.options.some((option) => option.value === trimmed)) {
|
|
1001
|
+
return { model: trimmed };
|
|
1002
|
+
}
|
|
1003
|
+
const match = ACP_MODEL_EFFORT_SUFFIX_RE.exec(trimmed);
|
|
1004
|
+
if (!match)
|
|
1005
|
+
return { model: null };
|
|
1006
|
+
const [, base, suffix] = match;
|
|
1007
|
+
const baseHit = modelOption.options.find((option) => option.value === base);
|
|
1008
|
+
if (!baseHit)
|
|
1009
|
+
return { model: null };
|
|
1010
|
+
return { model: baseHit.value, derivedEffort: suffix.toLowerCase() };
|
|
1011
|
+
}
|
|
1012
|
+
function parseModelOptions(raw) {
|
|
1013
|
+
if (!Array.isArray(raw))
|
|
1014
|
+
return [];
|
|
1015
|
+
const result = [];
|
|
1016
|
+
for (const item of raw) {
|
|
1017
|
+
const record = asRecord2(item);
|
|
1018
|
+
if (!record)
|
|
1019
|
+
continue;
|
|
1020
|
+
const value = asString(record.value) ?? asString(record.modelId) ?? asString(record.id);
|
|
1021
|
+
if (!value)
|
|
1022
|
+
continue;
|
|
1023
|
+
result.push({
|
|
1024
|
+
value,
|
|
1025
|
+
name: asString(record.name) ?? value,
|
|
1026
|
+
...asString(record.description) ? { description: asString(record.description) } : {}
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
return result;
|
|
1030
|
+
}
|
|
1031
|
+
function parseConfigOptions(result) {
|
|
1032
|
+
const record = asRecord2(result);
|
|
1033
|
+
if (!record)
|
|
1034
|
+
return [];
|
|
1035
|
+
const options = [];
|
|
1036
|
+
for (const raw of Array.isArray(record.configOptions) ? record.configOptions : []) {
|
|
1037
|
+
const item = asRecord2(raw);
|
|
1038
|
+
if (!item)
|
|
1039
|
+
continue;
|
|
1040
|
+
const id = asString(item.id);
|
|
1041
|
+
if (!id)
|
|
1042
|
+
continue;
|
|
1043
|
+
options.push({
|
|
1044
|
+
id,
|
|
1045
|
+
name: asString(item.name) ?? id,
|
|
1046
|
+
category: asString(item.category) ?? null,
|
|
1047
|
+
currentValue: asString(item.currentValue) ?? null,
|
|
1048
|
+
options: parseModelOptions(item.options)
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
const models = asRecord2(record.models);
|
|
1052
|
+
if (models && options.every((option) => !isModelOption(option))) {
|
|
1053
|
+
const available = parseModelOptions(models.availableModels);
|
|
1054
|
+
if (available.length > 0) {
|
|
1055
|
+
options.push({
|
|
1056
|
+
id: "model",
|
|
1057
|
+
name: "Model",
|
|
1058
|
+
category: "model",
|
|
1059
|
+
currentValue: asString(models.currentModelId) ?? null,
|
|
1060
|
+
options: available
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
return options;
|
|
1065
|
+
}
|
|
1066
|
+
function isModelOption(option) {
|
|
1067
|
+
const haystack = `${option.id} ${option.name} ${option.category ?? ""}`.toLowerCase();
|
|
1068
|
+
return haystack.includes("model");
|
|
1069
|
+
}
|
|
1070
|
+
function pickModelOption(options) {
|
|
1071
|
+
const byCategory = options.find((option) => {
|
|
1072
|
+
const category = (option.category ?? "").toLowerCase();
|
|
1073
|
+
return category === "model" || category === "model_config";
|
|
1074
|
+
});
|
|
1075
|
+
if (byCategory)
|
|
1076
|
+
return byCategory;
|
|
1077
|
+
return options.find(isModelOption) ?? null;
|
|
1078
|
+
}
|
|
1079
|
+
var THOUGHT_LEVEL_ID = "thought_level";
|
|
1080
|
+
function pickThoughtLevelOption(options) {
|
|
1081
|
+
const byCategory = options.find((option) => (option.category ?? "").toLowerCase() === THOUGHT_LEVEL_ID);
|
|
1082
|
+
if (byCategory)
|
|
1083
|
+
return byCategory;
|
|
1084
|
+
return options.find((option) => option.id.toLowerCase() === THOUGHT_LEVEL_ID) ?? null;
|
|
1085
|
+
}
|
|
1086
|
+
function effortRank(value) {
|
|
1087
|
+
return REASONING_EFFORT_OPTIONS.indexOf(value.trim().toLowerCase());
|
|
1088
|
+
}
|
|
1089
|
+
function resolveThoughtLevel(configOptions, requestedEffort) {
|
|
1090
|
+
const option = pickThoughtLevelOption(configOptions);
|
|
1091
|
+
if (!option)
|
|
1092
|
+
return { kind: "missing" };
|
|
1093
|
+
const requested = requestedEffort.trim();
|
|
1094
|
+
const normalized = requested.toLowerCase();
|
|
1095
|
+
const exact = option.options.find((candidate) => candidate.value.toLowerCase() === normalized);
|
|
1096
|
+
if (exact)
|
|
1097
|
+
return { kind: "exact", option, value: exact.value };
|
|
1098
|
+
const requestedRank = effortRank(normalized);
|
|
1099
|
+
if (requestedRank >= 0) {
|
|
1100
|
+
let best = null;
|
|
1101
|
+
for (const candidate of option.options) {
|
|
1102
|
+
const rank = effortRank(candidate.value);
|
|
1103
|
+
if (rank < 0 || rank > requestedRank)
|
|
1104
|
+
continue;
|
|
1105
|
+
if (!best || rank > best.rank)
|
|
1106
|
+
best = { value: candidate.value, rank };
|
|
1107
|
+
}
|
|
1108
|
+
if (best)
|
|
1109
|
+
return { kind: "clamped", option, value: best.value, requested };
|
|
1110
|
+
}
|
|
1111
|
+
return { kind: "no-match", option, requested };
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
class AgyAcpSession {
|
|
1115
|
+
key;
|
|
1116
|
+
config;
|
|
1117
|
+
peer = null;
|
|
1118
|
+
proc = null;
|
|
1119
|
+
acpSessionId = null;
|
|
1120
|
+
configOptions = [];
|
|
1121
|
+
appliedModel = null;
|
|
1122
|
+
appliedThoughtLevel = null;
|
|
1123
|
+
idleTimer = null;
|
|
1124
|
+
turnQueue = Promise.resolve();
|
|
1125
|
+
history = [];
|
|
1126
|
+
stderrTail = "";
|
|
1127
|
+
systemPromptSent = false;
|
|
1128
|
+
needsContextReplay = false;
|
|
1129
|
+
state = "starting";
|
|
1130
|
+
terminating = false;
|
|
1131
|
+
retired = false;
|
|
1132
|
+
terminatePromise = null;
|
|
1133
|
+
loadSessionSupported = false;
|
|
1134
|
+
terminals = new Map;
|
|
1135
|
+
warnings = [];
|
|
1136
|
+
turnWatchdog = null;
|
|
1137
|
+
lastEventKind = "none";
|
|
1138
|
+
constructor(key, config) {
|
|
1139
|
+
this.key = key;
|
|
1140
|
+
this.config = config;
|
|
1141
|
+
}
|
|
1142
|
+
isWarm() {
|
|
1143
|
+
return this.state === "warm" && this.proc !== null && this.acpSessionId !== null;
|
|
1144
|
+
}
|
|
1145
|
+
hasHistory() {
|
|
1146
|
+
return this.history.length > 0;
|
|
1147
|
+
}
|
|
1148
|
+
usesProcessPerSession() {
|
|
1149
|
+
if (this.config.processPerSession === true)
|
|
1150
|
+
return true;
|
|
1151
|
+
if (isAgyAcpProcessPerSessionEnabled2(this.config.env))
|
|
1152
|
+
return true;
|
|
1153
|
+
return (this.config.mcpServers ?? []).some((server) => ("type" in server) && (server.type === "http" || server.type === "sse"));
|
|
1154
|
+
}
|
|
1155
|
+
prewarm() {
|
|
1156
|
+
if (this.isWarm())
|
|
1157
|
+
return Promise.resolve();
|
|
1158
|
+
const run = async () => {
|
|
1159
|
+
if (this.retired || this.isWarm())
|
|
1160
|
+
return;
|
|
1161
|
+
this.clearIdleTimer();
|
|
1162
|
+
try {
|
|
1163
|
+
const peer = await this.ensureReady({});
|
|
1164
|
+
const sessionId = this.acpSessionId;
|
|
1165
|
+
if (sessionId) {
|
|
1166
|
+
const derivedEffort = await this.applyModel(peer, sessionId);
|
|
1167
|
+
await this.applyThoughtLevel(peer, sessionId, derivedEffort);
|
|
1168
|
+
}
|
|
1169
|
+
} finally {
|
|
1170
|
+
if (this.proc)
|
|
1171
|
+
this.touchIdleTimer();
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
const next = this.turnQueue.then(run, run);
|
|
1175
|
+
this.turnQueue = next.then(() => {
|
|
1176
|
+
return;
|
|
1177
|
+
}, () => {
|
|
1178
|
+
return;
|
|
1179
|
+
});
|
|
1180
|
+
return next;
|
|
1181
|
+
}
|
|
1182
|
+
isOccupyingSlot() {
|
|
1183
|
+
return this.state !== "closed" || this.terminating;
|
|
1184
|
+
}
|
|
1185
|
+
retire() {
|
|
1186
|
+
this.retired = true;
|
|
1187
|
+
}
|
|
1188
|
+
assertNotRetired() {
|
|
1189
|
+
if (this.retired) {
|
|
1190
|
+
throw new Error(`agy ACP session "${this.key}" was closed; refusing to start a new agent process. ` + "Start a new cli session instead.");
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
updateConfig(config) {
|
|
1194
|
+
this.config = config;
|
|
1195
|
+
}
|
|
1196
|
+
getModelOptions() {
|
|
1197
|
+
const modelOption = pickModelOption(this.configOptions);
|
|
1198
|
+
return modelOption ? [...modelOption.options] : [];
|
|
1199
|
+
}
|
|
1200
|
+
getWarnings() {
|
|
1201
|
+
return [...this.warnings];
|
|
1202
|
+
}
|
|
1203
|
+
prompt(input, options) {
|
|
1204
|
+
const run = () => this.runTurn(input, options);
|
|
1205
|
+
const next = this.turnQueue.then(run, run);
|
|
1206
|
+
this.turnQueue = next.then(() => {
|
|
1207
|
+
return;
|
|
1208
|
+
}, () => {
|
|
1209
|
+
return;
|
|
1210
|
+
});
|
|
1211
|
+
return next;
|
|
1212
|
+
}
|
|
1213
|
+
async runTurn(input, options) {
|
|
1214
|
+
this.assertNotRetired();
|
|
1215
|
+
if (options.signal?.aborted) {
|
|
1216
|
+
if (!this.proc && !this.peer)
|
|
1217
|
+
this.state = "closed";
|
|
1218
|
+
throw createAbortError("agy ACP execution was aborted before start");
|
|
1219
|
+
}
|
|
1220
|
+
const start = Date.now();
|
|
1221
|
+
const warningsBefore = this.warnings.length;
|
|
1222
|
+
this.clearIdleTimer();
|
|
1223
|
+
try {
|
|
1224
|
+
return await this.runTurnInner(input, options, start, warningsBefore);
|
|
1225
|
+
} finally {
|
|
1226
|
+
if (this.proc)
|
|
1227
|
+
this.touchIdleTimer();
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
async runTurnInner(input, options, start, warningsBefore) {
|
|
1231
|
+
const peer = await this.ensureReady(options);
|
|
1232
|
+
this.throwIfAborted(options.signal);
|
|
1233
|
+
const sessionId = this.acpSessionId;
|
|
1234
|
+
if (!sessionId) {
|
|
1235
|
+
throw new Error("agy ACP session is not initialised");
|
|
1236
|
+
}
|
|
1237
|
+
const derivedEffort = await this.applyModel(peer, sessionId);
|
|
1238
|
+
await this.applyThoughtLevel(peer, sessionId, derivedEffort);
|
|
1239
|
+
const promptText = this.buildPromptText(input);
|
|
1240
|
+
const collected = [];
|
|
1241
|
+
let usage;
|
|
1242
|
+
let stopReason = "end_turn";
|
|
1243
|
+
const toolEvents = new AgyAcpToolEventTracker;
|
|
1244
|
+
const onUpdate = (params) => {
|
|
1245
|
+
const record = asRecord2(params);
|
|
1246
|
+
if (!record)
|
|
1247
|
+
return;
|
|
1248
|
+
const update = asRecord2(record.update) ?? record;
|
|
1249
|
+
if (!update)
|
|
1250
|
+
return;
|
|
1251
|
+
const kind = asString(update.sessionUpdate) ?? asString(update.type);
|
|
1252
|
+
if (kind === "agent_message_chunk") {
|
|
1253
|
+
const content = asRecord2(update.content);
|
|
1254
|
+
const text = asString(content?.text);
|
|
1255
|
+
if (text) {
|
|
1256
|
+
collected.push(text);
|
|
1257
|
+
options.onChunk?.(text);
|
|
1258
|
+
}
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
if (kind === "agent_thought_chunk") {
|
|
1262
|
+
const content = asRecord2(update.content);
|
|
1263
|
+
const text = asString(content?.text);
|
|
1264
|
+
if (text)
|
|
1265
|
+
options.onThoughtChunk?.(text);
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1268
|
+
if (kind === "tool_call" || kind === "tool_call_update") {
|
|
1269
|
+
const event = toolEvents.handleUpdate(update, options.toolEventRound ?? 1);
|
|
1270
|
+
if (event)
|
|
1271
|
+
options.onToolEvent?.(event);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
};
|
|
1275
|
+
this.updateHandlers = { onUpdate };
|
|
1276
|
+
const timeoutMs = options.timeoutMs ?? 0;
|
|
1277
|
+
const noOutputTimeoutMs = options.noOutputTimeoutMs ?? AGY_ACP_NO_OUTPUT_TIMEOUT_MS;
|
|
1278
|
+
const watchdog = createTurnWatchdog({ totalMs: timeoutMs, noOutputMs: noOutputTimeoutMs });
|
|
1279
|
+
this.turnWatchdog = watchdog;
|
|
1280
|
+
this.lastEventKind = "turn-start";
|
|
1281
|
+
const turnPromise = peer.request("session/prompt", { sessionId, prompt: [{ type: "text", text: promptText }] }, 0);
|
|
1282
|
+
let abortHandler = null;
|
|
1283
|
+
const abortPromise = new Promise((_, rejectPromise) => {
|
|
1284
|
+
if (!options.signal)
|
|
1285
|
+
return;
|
|
1286
|
+
abortHandler = () => rejectPromise(createAbortError());
|
|
1287
|
+
options.signal.addEventListener("abort", abortHandler, { once: true });
|
|
1288
|
+
});
|
|
1289
|
+
let promptResult;
|
|
1290
|
+
try {
|
|
1291
|
+
const races = [turnPromise, watchdog.promise];
|
|
1292
|
+
if (options.signal)
|
|
1293
|
+
races.push(abortPromise);
|
|
1294
|
+
promptResult = await Promise.race(races);
|
|
1295
|
+
} catch (error) {
|
|
1296
|
+
this.updateHandlers = null;
|
|
1297
|
+
this.turnWatchdog = null;
|
|
1298
|
+
watchdog.dispose();
|
|
1299
|
+
if (options.signal?.aborted) {
|
|
1300
|
+
const outcome = await this.cancelTurn(sessionId, turnPromise);
|
|
1301
|
+
if (outcome === "timeout") {
|
|
1302
|
+
throw attachExecutionStoppedPromise2(createAbortError("agy ACP execution was aborted (cancel not acknowledged)"), this.terminate("aborted"));
|
|
1303
|
+
}
|
|
1304
|
+
throw createAbortError("agy ACP execution was aborted");
|
|
1305
|
+
}
|
|
1306
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1307
|
+
if (error instanceof AgyAcpRequestTimeoutError) {
|
|
1308
|
+
const outcome = await this.cancelTurn(sessionId, turnPromise);
|
|
1309
|
+
if (outcome === "timeout") {
|
|
1310
|
+
await this.terminate("timeout");
|
|
1311
|
+
}
|
|
1312
|
+
throw error;
|
|
1313
|
+
}
|
|
1314
|
+
const quota = detectCliProviderQuotaLimit2("agy", "", `${message}
|
|
1315
|
+
${this.stderrTail}`, null);
|
|
1316
|
+
if (quota.limited) {
|
|
1317
|
+
throw new CliProviderQuotaError2("agy", `${quota.message ?? "Agy reported quota/limit"}: ${message}`);
|
|
1318
|
+
}
|
|
1319
|
+
if (/Authentication required/i.test(message)) {
|
|
1320
|
+
throw new Error(`${message} — agy ACP requires an interactive sign-in. Run \`agy acp --login\` once in a terminal, then retry.`);
|
|
1321
|
+
}
|
|
1322
|
+
throw error;
|
|
1323
|
+
} finally {
|
|
1324
|
+
if (abortHandler && options.signal)
|
|
1325
|
+
options.signal.removeEventListener("abort", abortHandler);
|
|
1326
|
+
this.updateHandlers = null;
|
|
1327
|
+
this.turnWatchdog = null;
|
|
1328
|
+
watchdog.dispose();
|
|
1329
|
+
}
|
|
1330
|
+
if (options.signal?.aborted) {
|
|
1331
|
+
throw createAbortError("agy ACP execution was aborted");
|
|
1332
|
+
}
|
|
1333
|
+
const resultRecord = asRecord2(promptResult);
|
|
1334
|
+
stopReason = asString(resultRecord?.stopReason) ?? "end_turn";
|
|
1335
|
+
usage = normalizeAcpUsage(resultRecord?.usage);
|
|
1336
|
+
const droppedNotifications = this.peer?.takeDroppedNotifications() ?? 0;
|
|
1337
|
+
if (droppedNotifications > 0) {
|
|
1338
|
+
this.warnings.push(`agy ACP dropped ${droppedNotifications} session/update notification(s): a stream handler threw`);
|
|
1339
|
+
}
|
|
1340
|
+
const text = collected.join("");
|
|
1341
|
+
this.history.push({ role: "user", content: input }, { role: "assistant", content: text });
|
|
1342
|
+
if (stopReason === "cancelled") {
|
|
1343
|
+
throw createAbortError("agy ACP turn was cancelled by the agent");
|
|
1344
|
+
}
|
|
1345
|
+
if (stopReason === "refusal") {
|
|
1346
|
+
this.warnings.push("agy ACP turn ended with stopReason=refusal");
|
|
1347
|
+
}
|
|
1348
|
+
const turnWarnings = this.warnings.slice(warningsBefore);
|
|
1349
|
+
return {
|
|
1350
|
+
text,
|
|
1351
|
+
raw: text,
|
|
1352
|
+
elapsed: Date.now() - start,
|
|
1353
|
+
...usage ? { usage } : {},
|
|
1354
|
+
...turnWarnings.length > 0 ? { warnings: turnWarnings } : {}
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
updateHandlers = null;
|
|
1358
|
+
throwIfAborted(signal) {
|
|
1359
|
+
if (!signal?.aborted)
|
|
1360
|
+
return;
|
|
1361
|
+
throw createAbortError("agy ACP execution was aborted during handshake");
|
|
1362
|
+
}
|
|
1363
|
+
noteAcpFrame(frame) {
|
|
1364
|
+
const method = asString(frame.method);
|
|
1365
|
+
if (method === undefined) {
|
|
1366
|
+
this.noteTurnActivity("rpc-response");
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
if (method === "session/update") {
|
|
1370
|
+
const record = asRecord2(frame.params);
|
|
1371
|
+
const update = asRecord2(record?.update) ?? record;
|
|
1372
|
+
const kind = asString(update?.sessionUpdate) ?? asString(update?.type) ?? "update";
|
|
1373
|
+
this.noteTurnActivity(`session/update:${kind}`);
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
this.noteTurnActivity(`agent-request:${method}`);
|
|
1377
|
+
}
|
|
1378
|
+
noteTurnActivity(eventKind) {
|
|
1379
|
+
this.lastEventKind = eventKind;
|
|
1380
|
+
this.turnWatchdog?.noteActivity(eventKind);
|
|
1381
|
+
}
|
|
1382
|
+
buildPromptText(input) {
|
|
1383
|
+
const parts = [];
|
|
1384
|
+
const systemPrompt = this.config.systemPrompt?.trim();
|
|
1385
|
+
if (systemPrompt && !this.systemPromptSent) {
|
|
1386
|
+
parts.push(systemPrompt);
|
|
1387
|
+
this.systemPromptSent = true;
|
|
1388
|
+
}
|
|
1389
|
+
if (this.needsContextReplay && this.history.length > 0) {
|
|
1390
|
+
const transcript = this.history.map((entry, index) => `[${index + 1}] ${entry.role === "user" ? "用户" : "助手"}
|
|
1391
|
+
${entry.content.trim()}`).join(`
|
|
1392
|
+
|
|
1393
|
+
`);
|
|
1394
|
+
parts.push(["以下是同一会话此前已发生的对话(进程重启后重建上下文),请延续它继续回答最后一条用户消息。", transcript].join(`
|
|
1395
|
+
|
|
1396
|
+
`));
|
|
1397
|
+
this.needsContextReplay = false;
|
|
1398
|
+
}
|
|
1399
|
+
parts.push(input);
|
|
1400
|
+
return parts.join(`
|
|
1401
|
+
|
|
1402
|
+
`);
|
|
1403
|
+
}
|
|
1404
|
+
async ensureReady(options) {
|
|
1405
|
+
this.assertNotRetired();
|
|
1406
|
+
if (this.terminatePromise) {
|
|
1407
|
+
await this.terminatePromise;
|
|
1408
|
+
}
|
|
1409
|
+
if (this.peer && this.proc && this.acpSessionId) {
|
|
1410
|
+
return this.peer;
|
|
1411
|
+
}
|
|
1412
|
+
if (this.peer || this.proc) {
|
|
1413
|
+
await this.terminate("restart");
|
|
1414
|
+
}
|
|
1415
|
+
return this.start();
|
|
1416
|
+
}
|
|
1417
|
+
async start() {
|
|
1418
|
+
this.assertNotRetired();
|
|
1419
|
+
if (!this.usesProcessPerSession())
|
|
1420
|
+
assertAgyAcpAllowed();
|
|
1421
|
+
const binPath = this.config.binPath || process.env.AGY_BIN || "agy";
|
|
1422
|
+
const cwd = this.config.cwd || process.cwd();
|
|
1423
|
+
const args = ["acp"];
|
|
1424
|
+
if (this.usesProcessPerSession())
|
|
1425
|
+
args.push("--process-per-session");
|
|
1426
|
+
if (this.config.yolo === false)
|
|
1427
|
+
args.push("--sandbox");
|
|
1428
|
+
for (const dir of this.config.addDirs ?? []) {
|
|
1429
|
+
args.push("--add-dir", dir);
|
|
1430
|
+
}
|
|
1431
|
+
this.state = "starting";
|
|
1432
|
+
const proc = spawn2(binPath, args, {
|
|
1433
|
+
cwd,
|
|
1434
|
+
env: buildCliProcessEnv2(this.config.env),
|
|
1435
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1436
|
+
detached: process.platform !== "win32"
|
|
1437
|
+
});
|
|
1438
|
+
this.proc = proc;
|
|
1439
|
+
this.stderrTail = "";
|
|
1440
|
+
const decoder = new StringDecoder("utf8");
|
|
1441
|
+
const peer = new AcpRpcPeer((line) => {
|
|
1442
|
+
if (proc.stdin && !proc.stdin.destroyed)
|
|
1443
|
+
proc.stdin.write(line);
|
|
1444
|
+
}, (method, params) => this.handleAgentRequest(method, params), (method, params) => {
|
|
1445
|
+
if (method === "session/update")
|
|
1446
|
+
this.updateHandlers?.onUpdate(params);
|
|
1447
|
+
}, (frame) => this.noteAcpFrame(frame));
|
|
1448
|
+
this.peer = peer;
|
|
1449
|
+
let settledExit = false;
|
|
1450
|
+
const handleExit = (code, signal) => {
|
|
1451
|
+
if (settledExit)
|
|
1452
|
+
return;
|
|
1453
|
+
settledExit = true;
|
|
1454
|
+
this.handleProcessGone(code, signal);
|
|
1455
|
+
};
|
|
1456
|
+
proc.on("exit", handleExit);
|
|
1457
|
+
proc.on("error", (error) => {
|
|
1458
|
+
this.stderrTail += `
|
|
1459
|
+
${error.message}`;
|
|
1460
|
+
handleExit(null, null);
|
|
1461
|
+
});
|
|
1462
|
+
proc.stdout?.on("data", (chunk) => peer.feed(chunk));
|
|
1463
|
+
proc.stderr?.on("data", (chunk) => {
|
|
1464
|
+
this.stderrTail = (this.stderrTail + decoder.write(chunk)).slice(-STDERR_TAIL_CHARS);
|
|
1465
|
+
});
|
|
1466
|
+
try {
|
|
1467
|
+
const initResult = asRecord2(await peer.request("initialize", {
|
|
1468
|
+
protocolVersion: ACP_PROTOCOL_VERSION,
|
|
1469
|
+
clientCapabilities: {
|
|
1470
|
+
fs: { readTextFile: true, writeTextFile: true },
|
|
1471
|
+
terminal: true
|
|
1472
|
+
}
|
|
1473
|
+
}, DEFAULT_HANDSHAKE_TIMEOUT_MS));
|
|
1474
|
+
const capabilities = asRecord2(initResult?.agentCapabilities);
|
|
1475
|
+
this.loadSessionSupported = capabilities?.loadSession === true || capabilities?.load_session === true;
|
|
1476
|
+
} catch (error) {
|
|
1477
|
+
await this.terminate("initialize-failed");
|
|
1478
|
+
throw this.describeStartupFailure(error, "initialize");
|
|
1479
|
+
}
|
|
1480
|
+
const mcpServers = this.config.mcpServers ?? [];
|
|
1481
|
+
const reused = await this.tryLoadSession(peer, cwd, mcpServers);
|
|
1482
|
+
if (!reused) {
|
|
1483
|
+
try {
|
|
1484
|
+
const newSession = await peer.request("session/new", { cwd, mcpServers }, DEFAULT_HANDSHAKE_TIMEOUT_MS);
|
|
1485
|
+
const record = asRecord2(newSession);
|
|
1486
|
+
const sessionId = asString(record?.sessionId);
|
|
1487
|
+
if (!sessionId) {
|
|
1488
|
+
throw new Error("agy ACP session/new returned no sessionId");
|
|
1489
|
+
}
|
|
1490
|
+
this.acpSessionId = sessionId;
|
|
1491
|
+
this.configOptions = parseConfigOptions(record);
|
|
1492
|
+
this.appliedModel = pickModelOption(this.configOptions)?.currentValue ?? null;
|
|
1493
|
+
this.appliedThoughtLevel = null;
|
|
1494
|
+
} catch (error) {
|
|
1495
|
+
await this.terminate("session-new-failed");
|
|
1496
|
+
throw this.describeStartupFailure(error, "session/new");
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
this.state = "warm";
|
|
1500
|
+
return peer;
|
|
1501
|
+
}
|
|
1502
|
+
async tryLoadSession(peer, cwd, mcpServers) {
|
|
1503
|
+
if (!this.loadSessionSupported || !this.needsContextReplay || !this.acpSessionId)
|
|
1504
|
+
return false;
|
|
1505
|
+
try {
|
|
1506
|
+
const loaded = await peer.request("session/load", { sessionId: this.acpSessionId, cwd, mcpServers }, DEFAULT_HANDSHAKE_TIMEOUT_MS);
|
|
1507
|
+
const record = asRecord2(loaded);
|
|
1508
|
+
if (record && record.configOptions)
|
|
1509
|
+
this.configOptions = parseConfigOptions(record);
|
|
1510
|
+
this.appliedThoughtLevel = null;
|
|
1511
|
+
this.needsContextReplay = false;
|
|
1512
|
+
return true;
|
|
1513
|
+
} catch {
|
|
1514
|
+
return false;
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
async applyModel(peer, sessionId) {
|
|
1518
|
+
const requested = this.config.model?.trim();
|
|
1519
|
+
if (!requested)
|
|
1520
|
+
return;
|
|
1521
|
+
const modelOption = pickModelOption(this.configOptions);
|
|
1522
|
+
if (!modelOption) {
|
|
1523
|
+
if (!this.warnings.includes("agy ACP exposes no model configOptions; model selection skipped.")) {
|
|
1524
|
+
this.warnings.push("agy ACP exposes no model configOptions; model selection skipped.");
|
|
1525
|
+
}
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
const resolved = resolveAcpModelAndEffort(modelOption, requested);
|
|
1529
|
+
if (!resolved.model) {
|
|
1530
|
+
const message = `agy ACP model "${requested}" is not in the session's advertised model list; keeping current model.`;
|
|
1531
|
+
if (!this.warnings.includes(message))
|
|
1532
|
+
this.warnings.push(message);
|
|
1533
|
+
return;
|
|
1534
|
+
}
|
|
1535
|
+
if (this.appliedModel === resolved.model)
|
|
1536
|
+
return resolved.derivedEffort;
|
|
1537
|
+
try {
|
|
1538
|
+
const response = await peer.request("session/set_config_option", { sessionId, configId: modelOption.id, value: resolved.model }, DEFAULT_HANDSHAKE_TIMEOUT_MS);
|
|
1539
|
+
const updated = parseConfigOptions(response);
|
|
1540
|
+
if (updated.length > 0)
|
|
1541
|
+
this.configOptions = updated;
|
|
1542
|
+
this.appliedModel = resolved.model;
|
|
1543
|
+
this.appliedThoughtLevel = null;
|
|
1544
|
+
} catch (error) {
|
|
1545
|
+
const message = `agy ACP session/set_config_option failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
1546
|
+
if (!this.warnings.includes(message))
|
|
1547
|
+
this.warnings.push(message);
|
|
1548
|
+
}
|
|
1549
|
+
return resolved.derivedEffort;
|
|
1550
|
+
}
|
|
1551
|
+
pushWarningOnce(message) {
|
|
1552
|
+
if (!this.warnings.includes(message))
|
|
1553
|
+
this.warnings.push(message);
|
|
1554
|
+
}
|
|
1555
|
+
async applyThoughtLevel(peer, sessionId, derivedEffort) {
|
|
1556
|
+
const explicit = this.config.reasoningEffort?.trim();
|
|
1557
|
+
if (!derivedEffort && hasReasoningEffortSuffix(this.config.model))
|
|
1558
|
+
return;
|
|
1559
|
+
const requested = explicit || derivedEffort;
|
|
1560
|
+
if (!requested)
|
|
1561
|
+
return;
|
|
1562
|
+
const resolution = resolveThoughtLevel(this.configOptions, requested);
|
|
1563
|
+
if (resolution.kind === "missing") {
|
|
1564
|
+
this.pushWarningOnce(`agy ACP exposes no thought_level configOption; reasoning effort "${requested}" not applied this turn.`);
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
if (resolution.kind === "no-match") {
|
|
1568
|
+
const advertised = resolution.option.options.map((option) => option.value).join(", ");
|
|
1569
|
+
this.pushWarningOnce(`agy ACP thought_level "${resolution.option.id}" offers no option at or below ` + `"${resolution.requested}" (advertised: ${advertised || "none"}); reasoning effort not applied this turn.`);
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
if (resolution.kind === "clamped") {
|
|
1573
|
+
this.pushWarningOnce(`agy ACP thought_level clamped "${resolution.requested}" to "${resolution.value}"`);
|
|
1574
|
+
}
|
|
1575
|
+
const token = `${resolution.option.id}=${resolution.value}`;
|
|
1576
|
+
if (this.appliedThoughtLevel === token)
|
|
1577
|
+
return;
|
|
1578
|
+
try {
|
|
1579
|
+
const response = await peer.request("session/set_config_option", { sessionId, configId: resolution.option.id, value: resolution.value }, DEFAULT_HANDSHAKE_TIMEOUT_MS);
|
|
1580
|
+
const updated = parseConfigOptions(response);
|
|
1581
|
+
if (updated.length > 0)
|
|
1582
|
+
this.configOptions = updated;
|
|
1583
|
+
this.appliedThoughtLevel = token;
|
|
1584
|
+
} catch (error) {
|
|
1585
|
+
this.pushWarningOnce(`agy ACP session/set_config_option (thought_level "${resolution.value}") failed: ` + `${error instanceof Error ? error.message : String(error)}`);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
async cancelTurn(sessionId, turnPromise) {
|
|
1589
|
+
this.peer?.notify("session/cancel", { sessionId });
|
|
1590
|
+
const settled = await Promise.race([
|
|
1591
|
+
turnPromise.then(() => true, () => true),
|
|
1592
|
+
new Promise((resolvePromise) => {
|
|
1593
|
+
const timer = setTimeout(() => resolvePromise(false), CANCEL_GRACE_MS);
|
|
1594
|
+
timer.unref?.();
|
|
1595
|
+
})
|
|
1596
|
+
]);
|
|
1597
|
+
return settled ? "settled" : "timeout";
|
|
1598
|
+
}
|
|
1599
|
+
handleProcessGone(code, signal) {
|
|
1600
|
+
const reason = `agy acp process exited (code: ${code ?? "null"}, signal: ${signal ?? "none"}, ` + `lastEvent=${this.lastEventKind})` + (this.stderrTail.trim() ? `
|
|
1601
|
+
stderr: ${this.stderrTail.trim()}` : "");
|
|
1602
|
+
this.peer?.dispose(new Error(reason));
|
|
1603
|
+
this.peer = null;
|
|
1604
|
+
this.proc = null;
|
|
1605
|
+
this.acpSessionId = null;
|
|
1606
|
+
this.state = "closed";
|
|
1607
|
+
this.appliedThoughtLevel = null;
|
|
1608
|
+
this.needsContextReplay = this.history.length > 0;
|
|
1609
|
+
this.clearTerminals();
|
|
1610
|
+
this.clearIdleTimer();
|
|
1611
|
+
this.noteQuotaSignal(this.stderrTail);
|
|
1612
|
+
}
|
|
1613
|
+
noteQuotaSignal(text) {
|
|
1614
|
+
if (!text.trim())
|
|
1615
|
+
return;
|
|
1616
|
+
const quota = detectCliProviderQuotaLimit2("agy", "", text, null);
|
|
1617
|
+
if (quota.limited) {
|
|
1618
|
+
this.warnings.push(quota.message ?? "agy quota/rate limit signal");
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
describeStartupFailure(error, method) {
|
|
1622
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1623
|
+
const quota = detectCliProviderQuotaLimit2("agy", "", `${message}
|
|
1624
|
+
${this.stderrTail}`, null);
|
|
1625
|
+
if (quota.limited) {
|
|
1626
|
+
return new CliProviderQuotaError2("agy", quota.message ?? "Agy reported quota/limit");
|
|
1627
|
+
}
|
|
1628
|
+
if (message.includes("Authentication required")) {
|
|
1629
|
+
return new Error("agy ACP requires an interactive sign-in. Run `agy acp --login` (or `agy --login`) once in a terminal, " + `then retry. (${method} failed: ${message})`);
|
|
1630
|
+
}
|
|
1631
|
+
return new Error(`agy ACP ${method} failed: ${message}`);
|
|
1632
|
+
}
|
|
1633
|
+
async handleAgentRequest(method, params) {
|
|
1634
|
+
const record = asRecord2(params);
|
|
1635
|
+
switch (method) {
|
|
1636
|
+
case "session/request_permission":
|
|
1637
|
+
return this.resolvePermission(record);
|
|
1638
|
+
case "fs/read_text_file":
|
|
1639
|
+
return this.readTextFile(record);
|
|
1640
|
+
case "fs/write_text_file":
|
|
1641
|
+
return this.writeTextFile(record);
|
|
1642
|
+
case "terminal/create":
|
|
1643
|
+
return this.createTerminal(record);
|
|
1644
|
+
case "terminal/output":
|
|
1645
|
+
return this.readTerminalOutput(record);
|
|
1646
|
+
case "terminal/wait_for_exit":
|
|
1647
|
+
return this.waitForTerminalExit(record);
|
|
1648
|
+
case "terminal/kill":
|
|
1649
|
+
return this.killTerminal(record);
|
|
1650
|
+
case "terminal/release":
|
|
1651
|
+
return this.releaseTerminal(record);
|
|
1652
|
+
default:
|
|
1653
|
+
throw new Error(`Unsupported ACP method: ${method}`);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
resolvePermission(params) {
|
|
1657
|
+
const options = Array.isArray(params?.options) ? params.options : [];
|
|
1658
|
+
const candidates = options.map((raw) => asRecord2(raw)).filter((raw) => raw !== null).map((raw) => ({
|
|
1659
|
+
optionId: asString(raw.optionId) ?? asString(raw.option_id) ?? "",
|
|
1660
|
+
kind: (asString(raw.kind) ?? "").toLowerCase()
|
|
1661
|
+
})).filter((raw) => raw.optionId !== "");
|
|
1662
|
+
const allow = candidates.find((option) => option.kind.startsWith("allow"));
|
|
1663
|
+
const reject = candidates.find((option) => option.kind.startsWith("reject"));
|
|
1664
|
+
const wantAllow = this.config.yolo !== false;
|
|
1665
|
+
if (!wantAllow && !reject) {
|
|
1666
|
+
return { outcome: { outcome: "cancelled" } };
|
|
1667
|
+
}
|
|
1668
|
+
const chosen = wantAllow ? allow ?? reject : reject;
|
|
1669
|
+
if (!chosen) {
|
|
1670
|
+
return { outcome: { outcome: "cancelled" } };
|
|
1671
|
+
}
|
|
1672
|
+
return { outcome: { outcome: "selected", optionId: chosen.optionId }, optionId: chosen.optionId };
|
|
1673
|
+
}
|
|
1674
|
+
realSandboxRoots() {
|
|
1675
|
+
const roots = [this.config.cwd || process.cwd(), ...this.config.addDirs ?? []];
|
|
1676
|
+
return roots.map((root) => {
|
|
1677
|
+
const absolute = resolve(root);
|
|
1678
|
+
try {
|
|
1679
|
+
return realpathSync(absolute);
|
|
1680
|
+
} catch {
|
|
1681
|
+
return absolute;
|
|
1682
|
+
}
|
|
1683
|
+
});
|
|
1684
|
+
}
|
|
1685
|
+
resolveSandboxPath(target, forWrite) {
|
|
1686
|
+
const absolute = resolve(target);
|
|
1687
|
+
const real = forWrite ? this.realpathForWrite(absolute) : realpathSync(absolute);
|
|
1688
|
+
const roots = this.realSandboxRoots();
|
|
1689
|
+
if (!roots.some((root) => isWithin(root, real))) {
|
|
1690
|
+
throw new Error(`agy ACP requested a path outside the allowed sandbox: ${absolute}`);
|
|
1691
|
+
}
|
|
1692
|
+
return real;
|
|
1693
|
+
}
|
|
1694
|
+
realpathForWrite(absolute) {
|
|
1695
|
+
let existing = absolute;
|
|
1696
|
+
const tail = [];
|
|
1697
|
+
while (!existsSync(existing)) {
|
|
1698
|
+
const parent = dirname(existing);
|
|
1699
|
+
if (parent === existing)
|
|
1700
|
+
break;
|
|
1701
|
+
tail.unshift(basename(existing));
|
|
1702
|
+
existing = parent;
|
|
1703
|
+
}
|
|
1704
|
+
if (tail.length > 0) {
|
|
1705
|
+
const firstMissing = resolve(existing, tail[0]);
|
|
1706
|
+
let stat = null;
|
|
1707
|
+
try {
|
|
1708
|
+
stat = lstatSync(firstMissing);
|
|
1709
|
+
} catch {
|
|
1710
|
+
stat = null;
|
|
1711
|
+
}
|
|
1712
|
+
if (stat?.isSymbolicLink()) {
|
|
1713
|
+
throw new Error(`agy ACP refuses to write through a symbolic link: ${firstMissing}`);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
const realExisting = realpathSync(existing);
|
|
1717
|
+
return tail.length > 0 ? resolve(realExisting, ...tail) : realExisting;
|
|
1718
|
+
}
|
|
1719
|
+
readTextFile(params) {
|
|
1720
|
+
const path = asString(params?.path);
|
|
1721
|
+
if (!path)
|
|
1722
|
+
throw new Error("fs/read_text_file requires a path");
|
|
1723
|
+
let content = readFileSync(this.resolveSandboxPath(path, false), "utf8");
|
|
1724
|
+
const line = asNumber(params?.line);
|
|
1725
|
+
const limit = asNumber(params?.limit);
|
|
1726
|
+
if (line !== undefined || limit !== undefined) {
|
|
1727
|
+
const lines = content.split(`
|
|
1728
|
+
`);
|
|
1729
|
+
const startIndex = Math.max(0, (line ?? 1) - 1);
|
|
1730
|
+
const endIndex = limit !== undefined ? startIndex + limit : lines.length;
|
|
1731
|
+
content = lines.slice(startIndex, endIndex).join(`
|
|
1732
|
+
`);
|
|
1733
|
+
}
|
|
1734
|
+
return { content };
|
|
1735
|
+
}
|
|
1736
|
+
writeTextFile(params) {
|
|
1737
|
+
const path = asString(params?.path);
|
|
1738
|
+
const content = asString(params?.content);
|
|
1739
|
+
if (!path || content === undefined)
|
|
1740
|
+
throw new Error("fs/write_text_file requires path and content");
|
|
1741
|
+
const realPath = this.resolveSandboxPath(path, true);
|
|
1742
|
+
mkdirSync(dirname(realPath), { recursive: true });
|
|
1743
|
+
writeFileSync(realPath, content, "utf8");
|
|
1744
|
+
return null;
|
|
1745
|
+
}
|
|
1746
|
+
createTerminal(params) {
|
|
1747
|
+
const command = asString(params?.command);
|
|
1748
|
+
if (!command)
|
|
1749
|
+
throw new Error("terminal/create requires a command");
|
|
1750
|
+
if (this.config.yolo === false) {
|
|
1751
|
+
throw new Error("terminal/create is denied in non-yolo agy ACP sessions");
|
|
1752
|
+
}
|
|
1753
|
+
const requestedCwd = asString(params?.cwd) ?? this.config.cwd ?? process.cwd();
|
|
1754
|
+
const realCwd = this.resolveSandboxPath(requestedCwd, false);
|
|
1755
|
+
const args = Array.isArray(params?.args) ? params.args.filter((value) => typeof value === "string") : [];
|
|
1756
|
+
const envRecord = asRecord2(params?.env);
|
|
1757
|
+
const env = { ...buildCliProcessEnv2(this.config.env) };
|
|
1758
|
+
if (envRecord) {
|
|
1759
|
+
for (const [key, value] of Object.entries(envRecord)) {
|
|
1760
|
+
const resolved = asString(value);
|
|
1761
|
+
if (resolved !== undefined)
|
|
1762
|
+
env[key] = resolved;
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
const child = spawn2(command, args, {
|
|
1766
|
+
cwd: realCwd,
|
|
1767
|
+
env,
|
|
1768
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1769
|
+
});
|
|
1770
|
+
const terminalId = `term_${this.terminals.size + 1}_${Date.now().toString(36)}`;
|
|
1771
|
+
const state = {
|
|
1772
|
+
child,
|
|
1773
|
+
output: "",
|
|
1774
|
+
truncated: false,
|
|
1775
|
+
exitCode: null,
|
|
1776
|
+
signal: null,
|
|
1777
|
+
exited: false,
|
|
1778
|
+
waiters: []
|
|
1779
|
+
};
|
|
1780
|
+
this.terminals.set(terminalId, state);
|
|
1781
|
+
const append = (chunk) => {
|
|
1782
|
+
state.output += chunk.toString("utf8");
|
|
1783
|
+
this.noteTurnActivity("terminal-output");
|
|
1784
|
+
if (state.output.length > MAX_TERMINAL_OUTPUT_CHARS) {
|
|
1785
|
+
state.output = state.output.slice(-MAX_TERMINAL_OUTPUT_CHARS);
|
|
1786
|
+
state.truncated = true;
|
|
1787
|
+
}
|
|
1788
|
+
};
|
|
1789
|
+
child.stdout?.on("data", append);
|
|
1790
|
+
child.stderr?.on("data", append);
|
|
1791
|
+
const finish = (code, signal) => {
|
|
1792
|
+
state.exited = true;
|
|
1793
|
+
state.exitCode = code;
|
|
1794
|
+
state.signal = signal;
|
|
1795
|
+
for (const waiter of state.waiters.splice(0))
|
|
1796
|
+
waiter();
|
|
1797
|
+
};
|
|
1798
|
+
child.on("exit", finish);
|
|
1799
|
+
child.on("error", (error) => {
|
|
1800
|
+
append(Buffer.from(`
|
|
1801
|
+
${error.message}`));
|
|
1802
|
+
finish(null, null);
|
|
1803
|
+
});
|
|
1804
|
+
return { terminalId };
|
|
1805
|
+
}
|
|
1806
|
+
readTerminalOutput(params) {
|
|
1807
|
+
const state = this.requireTerminal(params);
|
|
1808
|
+
return {
|
|
1809
|
+
output: state.output,
|
|
1810
|
+
truncated: state.truncated,
|
|
1811
|
+
...state.exited ? { exitStatus: { exitCode: state.exitCode, signal: state.signal } } : {}
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
async waitForTerminalExit(params) {
|
|
1815
|
+
const state = this.requireTerminal(params);
|
|
1816
|
+
if (!state.exited) {
|
|
1817
|
+
await new Promise((resolvePromise) => {
|
|
1818
|
+
const timer = setTimeout(resolvePromise, 120000);
|
|
1819
|
+
timer.unref?.();
|
|
1820
|
+
state.waiters.push(() => {
|
|
1821
|
+
clearTimeout(timer);
|
|
1822
|
+
resolvePromise();
|
|
1823
|
+
});
|
|
1824
|
+
});
|
|
1825
|
+
}
|
|
1826
|
+
return { exitCode: state.exitCode, signal: state.signal };
|
|
1827
|
+
}
|
|
1828
|
+
killTerminal(params) {
|
|
1829
|
+
const state = this.requireTerminal(params);
|
|
1830
|
+
if (!state.exited) {
|
|
1831
|
+
try {
|
|
1832
|
+
state.child.kill("SIGTERM");
|
|
1833
|
+
} catch {}
|
|
1834
|
+
}
|
|
1835
|
+
return null;
|
|
1836
|
+
}
|
|
1837
|
+
releaseTerminal(params) {
|
|
1838
|
+
const terminalId = asString(params?.terminalId);
|
|
1839
|
+
if (!terminalId)
|
|
1840
|
+
throw new Error("terminal/release requires terminalId");
|
|
1841
|
+
const state = this.terminals.get(terminalId);
|
|
1842
|
+
if (state) {
|
|
1843
|
+
if (!state.exited) {
|
|
1844
|
+
try {
|
|
1845
|
+
state.child.kill("SIGKILL");
|
|
1846
|
+
} catch {}
|
|
1847
|
+
}
|
|
1848
|
+
this.terminals.delete(terminalId);
|
|
1849
|
+
}
|
|
1850
|
+
return null;
|
|
1851
|
+
}
|
|
1852
|
+
requireTerminal(params) {
|
|
1853
|
+
const terminalId = asString(params?.terminalId);
|
|
1854
|
+
if (!terminalId)
|
|
1855
|
+
throw new Error("terminal request requires terminalId");
|
|
1856
|
+
const state = this.terminals.get(terminalId);
|
|
1857
|
+
if (!state)
|
|
1858
|
+
throw new Error(`Unknown terminal: ${terminalId}`);
|
|
1859
|
+
return state;
|
|
1860
|
+
}
|
|
1861
|
+
clearTerminals() {
|
|
1862
|
+
for (const [, state] of this.terminals) {
|
|
1863
|
+
if (state.exited)
|
|
1864
|
+
continue;
|
|
1865
|
+
try {
|
|
1866
|
+
state.child.kill("SIGTERM");
|
|
1867
|
+
} catch {}
|
|
1868
|
+
const escalate = setTimeout(() => {
|
|
1869
|
+
if (state.exited)
|
|
1870
|
+
return;
|
|
1871
|
+
try {
|
|
1872
|
+
state.child.kill("SIGKILL");
|
|
1873
|
+
} catch {}
|
|
1874
|
+
}, 100);
|
|
1875
|
+
escalate.unref?.();
|
|
1876
|
+
}
|
|
1877
|
+
this.terminals.clear();
|
|
1878
|
+
}
|
|
1879
|
+
touchIdleTimer() {
|
|
1880
|
+
this.clearIdleTimer();
|
|
1881
|
+
const idleMs = this.config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
|
|
1882
|
+
if (idleMs <= 0)
|
|
1883
|
+
return;
|
|
1884
|
+
this.idleTimer = setTimeout(() => {
|
|
1885
|
+
this.idleTimer = null;
|
|
1886
|
+
this.terminate("idle");
|
|
1887
|
+
}, idleMs);
|
|
1888
|
+
this.idleTimer.unref?.();
|
|
1889
|
+
}
|
|
1890
|
+
clearIdleTimer() {
|
|
1891
|
+
if (this.idleTimer) {
|
|
1892
|
+
clearTimeout(this.idleTimer);
|
|
1893
|
+
this.idleTimer = null;
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
async terminate(reason) {
|
|
1897
|
+
const inFlight = this.terminatePromise;
|
|
1898
|
+
if (inFlight)
|
|
1899
|
+
return inFlight;
|
|
1900
|
+
const running = this.doTerminate(reason).finally(() => {
|
|
1901
|
+
this.terminatePromise = null;
|
|
1902
|
+
});
|
|
1903
|
+
this.terminatePromise = running;
|
|
1904
|
+
return running;
|
|
1905
|
+
}
|
|
1906
|
+
async doTerminate(reason) {
|
|
1907
|
+
this.terminating = true;
|
|
1908
|
+
try {
|
|
1909
|
+
await this.terminateProcess(reason);
|
|
1910
|
+
} finally {
|
|
1911
|
+
this.terminating = false;
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
async terminateProcess(reason) {
|
|
1915
|
+
this.clearIdleTimer();
|
|
1916
|
+
this.clearTerminals();
|
|
1917
|
+
const proc = this.proc;
|
|
1918
|
+
const peer = this.peer;
|
|
1919
|
+
this.proc = null;
|
|
1920
|
+
this.peer = null;
|
|
1921
|
+
this.acpSessionId = null;
|
|
1922
|
+
this.state = "closed";
|
|
1923
|
+
this.needsContextReplay = this.history.length > 0;
|
|
1924
|
+
this.updateHandlers = null;
|
|
1925
|
+
peer?.dispose(new Error(`agy ACP session closed (${reason})`));
|
|
1926
|
+
if (proc) {
|
|
1927
|
+
proc.removeAllListeners("exit");
|
|
1928
|
+
proc.removeAllListeners("error");
|
|
1929
|
+
proc.stdout?.removeAllListeners("data");
|
|
1930
|
+
proc.stderr?.removeAllListeners("data");
|
|
1931
|
+
proc.on("error", () => {});
|
|
1932
|
+
const stopped = terminateCliProcessGroupEscalating2(proc).catch(() => {
|
|
1933
|
+
return;
|
|
1934
|
+
});
|
|
1935
|
+
await Promise.race([
|
|
1936
|
+
stopped,
|
|
1937
|
+
new Promise((resolvePromise) => {
|
|
1938
|
+
const timer = setTimeout(resolvePromise, 12000);
|
|
1939
|
+
timer.unref?.();
|
|
1940
|
+
})
|
|
1941
|
+
]);
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
var agyAcpSessions = new Map;
|
|
1946
|
+
var activeAgyPrintCount = 0;
|
|
1947
|
+
function isAgyAcpEnabled2(env = process.env) {
|
|
1948
|
+
const raw = (env.NOLO_AGY_ACP ?? "").trim().toLowerCase();
|
|
1949
|
+
return !(raw === "0" || raw === "false" || raw === "off" || raw === "no");
|
|
1950
|
+
}
|
|
1951
|
+
function isAgyAcpProcessPerSessionEnabled2(env = process.env) {
|
|
1952
|
+
const raw = (env?.NOLO_AGY_ACP_PROCESS_PER_SESSION ?? process.env.NOLO_AGY_ACP_PROCESS_PER_SESSION ?? "").trim().toLowerCase();
|
|
1953
|
+
return raw === "1" || raw === "true" || raw === "on" || raw === "yes";
|
|
1954
|
+
}
|
|
1955
|
+
function configUsesProcessPerSession(config) {
|
|
1956
|
+
if (config.processPerSession === true)
|
|
1957
|
+
return true;
|
|
1958
|
+
if (isAgyAcpProcessPerSessionEnabled2(config.env))
|
|
1959
|
+
return true;
|
|
1960
|
+
return (config.mcpServers ?? []).some((server) => ("type" in server) && (server.type === "http" || server.type === "sse"));
|
|
1961
|
+
}
|
|
1962
|
+
function liveSessionCount() {
|
|
1963
|
+
let count = 0;
|
|
1964
|
+
for (const session of agyAcpSessions.values()) {
|
|
1965
|
+
if (session.isOccupyingSlot())
|
|
1966
|
+
count += 1;
|
|
1967
|
+
}
|
|
1968
|
+
return count;
|
|
1969
|
+
}
|
|
1970
|
+
function liveNonIsolatedSessionCount() {
|
|
1971
|
+
let count = 0;
|
|
1972
|
+
for (const session of agyAcpSessions.values()) {
|
|
1973
|
+
if (session.isOccupyingSlot() && !session.usesProcessPerSession())
|
|
1974
|
+
count += 1;
|
|
1975
|
+
}
|
|
1976
|
+
return count;
|
|
1977
|
+
}
|
|
1978
|
+
function assertAgyPrintAllowed(label) {
|
|
1979
|
+
if (liveNonIsolatedSessionCount() <= 0)
|
|
1980
|
+
return;
|
|
1981
|
+
throw new CliProviderQuotaError2("agy", `${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.");
|
|
1982
|
+
}
|
|
1983
|
+
function assertAgyAcpAllowed() {
|
|
1984
|
+
if (activeAgyPrintCount <= 0)
|
|
1985
|
+
return;
|
|
1986
|
+
throw new CliProviderQuotaError2("agy", "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.");
|
|
1987
|
+
}
|
|
1988
|
+
function acquireAgyPrintSlot(label) {
|
|
1989
|
+
assertAgyPrintAllowed(label);
|
|
1990
|
+
activeAgyPrintCount += 1;
|
|
1991
|
+
let released = false;
|
|
1992
|
+
return () => {
|
|
1993
|
+
if (released)
|
|
1994
|
+
return;
|
|
1995
|
+
released = true;
|
|
1996
|
+
activeAgyPrintCount = Math.max(0, activeAgyPrintCount - 1);
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
function getAgyAcpSession2(key, config) {
|
|
2000
|
+
const isolated = configUsesProcessPerSession(config);
|
|
2001
|
+
const existing = agyAcpSessions.get(key);
|
|
2002
|
+
if (existing) {
|
|
2003
|
+
if (!isolated && !existing.isOccupyingSlot())
|
|
2004
|
+
assertAgyAcpAllowed();
|
|
2005
|
+
existing.updateConfig(config);
|
|
2006
|
+
return existing;
|
|
2007
|
+
}
|
|
2008
|
+
if (!isolated) {
|
|
2009
|
+
assertAgyAcpAllowed();
|
|
2010
|
+
if (liveSessionCount() > 0) {
|
|
2011
|
+
throw new CliProviderQuotaError2("agy", "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.");
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
const created = new AgyAcpSession(key, config);
|
|
2015
|
+
agyAcpSessions.set(key, created);
|
|
2016
|
+
return created;
|
|
2017
|
+
}
|
|
2018
|
+
async function prewarmAgyAcpSession2(key, config) {
|
|
2019
|
+
if (!isAgyAcpEnabled2(config.env)) {
|
|
2020
|
+
return { ok: false, error: "agy ACP is disabled" };
|
|
2021
|
+
}
|
|
2022
|
+
let session;
|
|
2023
|
+
try {
|
|
2024
|
+
session = getAgyAcpSession2(key, config);
|
|
2025
|
+
} catch (error) {
|
|
2026
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
2027
|
+
}
|
|
2028
|
+
if (session.isWarm()) {
|
|
2029
|
+
return { ok: true, warm: true };
|
|
2030
|
+
}
|
|
2031
|
+
try {
|
|
2032
|
+
await session.prewarm();
|
|
2033
|
+
return { ok: true, warm: session.isWarm() };
|
|
2034
|
+
} catch (error) {
|
|
2035
|
+
if (!session.isWarm()) {
|
|
2036
|
+
await closeAgyAcpSession2(key).catch(() => {});
|
|
2037
|
+
}
|
|
2038
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
function closeAgyAcpSession2(key) {
|
|
2042
|
+
const entries = key === undefined ? [...agyAcpSessions] : [[key, agyAcpSessions.get(key)]];
|
|
2043
|
+
const closing = [];
|
|
2044
|
+
for (const [sessionKey, session] of entries) {
|
|
2045
|
+
if (!session)
|
|
2046
|
+
continue;
|
|
2047
|
+
session.retire();
|
|
2048
|
+
closing.push(session.terminate(key === undefined ? "registry-close-all" : "registry-close").finally(() => {
|
|
2049
|
+
if (agyAcpSessions.get(sessionKey) === session)
|
|
2050
|
+
agyAcpSessions.delete(sessionKey);
|
|
2051
|
+
}));
|
|
2052
|
+
}
|
|
2053
|
+
return Promise.all(closing).then(() => {
|
|
2054
|
+
return;
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
2057
|
+
function adoptAgyAcpSession2(fromKey, toKey) {
|
|
2058
|
+
if (!fromKey || !toKey || fromKey === toKey)
|
|
2059
|
+
return false;
|
|
2060
|
+
if (agyAcpSessions.has(toKey))
|
|
2061
|
+
return false;
|
|
2062
|
+
const existing = agyAcpSessions.get(fromKey);
|
|
2063
|
+
if (!existing)
|
|
2064
|
+
return false;
|
|
2065
|
+
agyAcpSessions.delete(fromKey);
|
|
2066
|
+
agyAcpSessions.set(toKey, existing);
|
|
2067
|
+
return true;
|
|
2068
|
+
}
|
|
2069
|
+
// packages/ai/agent/executors/agyAcpMcpConfig.ts
|
|
2070
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
|
|
2071
|
+
function asRecord3(value) {
|
|
2072
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
2073
|
+
}
|
|
2074
|
+
function asNonEmptyString2(value) {
|
|
2075
|
+
if (typeof value !== "string")
|
|
2076
|
+
return;
|
|
2077
|
+
const trimmed = value.trim();
|
|
2078
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
2079
|
+
}
|
|
2080
|
+
function parseNameValueList(raw) {
|
|
2081
|
+
if (!Array.isArray(raw))
|
|
2082
|
+
return;
|
|
2083
|
+
const list = [];
|
|
2084
|
+
for (const item of raw) {
|
|
2085
|
+
const rec = asRecord3(item);
|
|
2086
|
+
if (!rec)
|
|
2087
|
+
continue;
|
|
2088
|
+
const name = asNonEmptyString2(rec.name);
|
|
2089
|
+
const value = typeof rec.value === "string" ? rec.value : undefined;
|
|
2090
|
+
if (name && value !== undefined)
|
|
2091
|
+
list.push({ name, value });
|
|
2092
|
+
}
|
|
2093
|
+
return list.length > 0 ? list : undefined;
|
|
2094
|
+
}
|
|
2095
|
+
function parseSingleMcpServer(raw) {
|
|
2096
|
+
const rec = asRecord3(raw);
|
|
2097
|
+
if (!rec)
|
|
2098
|
+
return null;
|
|
2099
|
+
const name = asNonEmptyString2(rec.name);
|
|
2100
|
+
if (!name)
|
|
2101
|
+
return null;
|
|
2102
|
+
const type = asNonEmptyString2(rec.type)?.toLowerCase();
|
|
2103
|
+
if (type === "http" || type === "sse") {
|
|
2104
|
+
const url = asNonEmptyString2(rec.url);
|
|
2105
|
+
if (!url)
|
|
2106
|
+
return null;
|
|
2107
|
+
const headers = parseNameValueList(rec.headers);
|
|
2108
|
+
return {
|
|
2109
|
+
type,
|
|
2110
|
+
name,
|
|
2111
|
+
url,
|
|
2112
|
+
...headers ? { headers } : {}
|
|
2113
|
+
};
|
|
2114
|
+
}
|
|
2115
|
+
const command = asNonEmptyString2(rec.command);
|
|
2116
|
+
if (!command)
|
|
2117
|
+
return null;
|
|
2118
|
+
const args = Array.isArray(rec.args) ? rec.args.filter((a) => typeof a === "string") : undefined;
|
|
2119
|
+
const env = parseNameValueList(rec.env);
|
|
2120
|
+
return {
|
|
2121
|
+
name,
|
|
2122
|
+
command,
|
|
2123
|
+
...args && args.length > 0 ? { args } : {},
|
|
2124
|
+
...env ? { env } : {}
|
|
2125
|
+
};
|
|
2126
|
+
}
|
|
2127
|
+
function resolveAgyAcpMcpServers(explicit, env = process.env) {
|
|
2128
|
+
const merged = new Map;
|
|
2129
|
+
const rawEnv = (env?.NOLO_AGY_ACP_MCP_SERVERS ?? process.env.NOLO_AGY_ACP_MCP_SERVERS ?? "").trim();
|
|
2130
|
+
if (rawEnv) {
|
|
2131
|
+
let jsonText = rawEnv;
|
|
2132
|
+
if (!rawEnv.startsWith("[") && !rawEnv.startsWith("{") && existsSync2(rawEnv)) {
|
|
2133
|
+
try {
|
|
2134
|
+
jsonText = readFileSync2(rawEnv, "utf8");
|
|
2135
|
+
} catch {
|
|
2136
|
+
jsonText = "";
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
if (jsonText) {
|
|
2140
|
+
try {
|
|
2141
|
+
const parsed = JSON.parse(jsonText);
|
|
2142
|
+
const list = Array.isArray(parsed) ? parsed : Array.isArray(asRecord3(parsed)?.mcpServers) ? asRecord3(parsed)?.mcpServers : [];
|
|
2143
|
+
for (const item of list) {
|
|
2144
|
+
const valid = parseSingleMcpServer(item);
|
|
2145
|
+
if (valid)
|
|
2146
|
+
merged.set(valid.name, valid);
|
|
2147
|
+
}
|
|
2148
|
+
} catch {}
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
for (const server of explicit ?? []) {
|
|
2152
|
+
const valid = parseSingleMcpServer(server);
|
|
2153
|
+
if (valid)
|
|
2154
|
+
merged.set(valid.name, valid);
|
|
2155
|
+
}
|
|
2156
|
+
return [...merged.values()];
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
// packages/ai/agent/executors/agyAcpSharedDaemon.ts
|
|
2160
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
2161
|
+
import { existsSync as existsSync3, lstatSync as lstatSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync as realpathSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
2162
|
+
import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2 } from "node:path";
|
|
2163
|
+
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
2164
|
+
var ACP_PROTOCOL_VERSION2 = 1;
|
|
2165
|
+
var HANDSHAKE_TIMEOUT_MS = 60000;
|
|
2166
|
+
var CANCEL_GRACE_MS2 = 800;
|
|
2167
|
+
var DEFAULT_DAEMON_IDLE_TIMEOUT_MS = 15 * 60000;
|
|
2168
|
+
var STDERR_TAIL_CHARS2 = 4000;
|
|
2169
|
+
function asRecord4(value) {
|
|
2170
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
2171
|
+
}
|
|
2172
|
+
function asString2(value) {
|
|
2173
|
+
return typeof value === "string" ? value : undefined;
|
|
2174
|
+
}
|
|
2175
|
+
function asNumber2(value) {
|
|
2176
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
2177
|
+
}
|
|
2178
|
+
function isWithin2(root, target) {
|
|
2179
|
+
const rel = relative2(resolve2(root), resolve2(target));
|
|
2180
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
|
|
2181
|
+
}
|
|
2182
|
+
function createAbortError2(message = "agy ACP execution aborted") {
|
|
2183
|
+
return new DOMException(message, "AbortError");
|
|
2184
|
+
}
|
|
2185
|
+
function normalizeUsage(value) {
|
|
2186
|
+
const record = asRecord4(value);
|
|
2187
|
+
if (!record)
|
|
2188
|
+
return;
|
|
2189
|
+
const pick = (...keys) => {
|
|
2190
|
+
for (const key of keys) {
|
|
2191
|
+
const n = asNumber2(record[key]);
|
|
2192
|
+
if (n !== undefined)
|
|
2193
|
+
return n;
|
|
2194
|
+
}
|
|
2195
|
+
return;
|
|
2196
|
+
};
|
|
2197
|
+
const inputTokens = pick("inputTokens", "input_tokens");
|
|
2198
|
+
const outputTokens = pick("outputTokens", "output_tokens");
|
|
2199
|
+
const totalTokens = pick("totalTokens", "total_tokens");
|
|
2200
|
+
const cachedReadTokens = pick("cachedReadTokens", "cache_read_input_tokens");
|
|
2201
|
+
if (inputTokens === undefined && outputTokens === undefined && totalTokens === undefined) {
|
|
2202
|
+
return;
|
|
2203
|
+
}
|
|
2204
|
+
return {
|
|
2205
|
+
...inputTokens !== undefined ? { input_tokens: inputTokens } : {},
|
|
2206
|
+
...outputTokens !== undefined ? { output_tokens: outputTokens } : {},
|
|
2207
|
+
...totalTokens !== undefined ? { total_tokens: totalTokens } : {},
|
|
2208
|
+
...cachedReadTokens !== undefined ? { cache_read_input_tokens: cachedReadTokens } : {}
|
|
2209
|
+
};
|
|
2210
|
+
}
|
|
2211
|
+
function parseConfigOptions2(result) {
|
|
2212
|
+
const record = asRecord4(result);
|
|
2213
|
+
if (!record)
|
|
2214
|
+
return [];
|
|
2215
|
+
const rawList = Array.isArray(record.configOptions) ? record.configOptions : [];
|
|
2216
|
+
const out = [];
|
|
2217
|
+
for (const item of rawList) {
|
|
2218
|
+
const rec = asRecord4(item);
|
|
2219
|
+
if (!rec)
|
|
2220
|
+
continue;
|
|
2221
|
+
const id = asString2(rec.id);
|
|
2222
|
+
if (!id)
|
|
2223
|
+
continue;
|
|
2224
|
+
const optionsRaw = Array.isArray(rec.options) ? rec.options : [];
|
|
2225
|
+
const options = optionsRaw.map((o) => asRecord4(o)).filter((o) => o !== null).map((o) => ({
|
|
2226
|
+
value: asString2(o.value) ?? "",
|
|
2227
|
+
name: asString2(o.name) ?? asString2(o.value) ?? "",
|
|
2228
|
+
description: asString2(o.description)
|
|
2229
|
+
})).filter((o) => o.value !== "");
|
|
2230
|
+
out.push({
|
|
2231
|
+
id,
|
|
2232
|
+
name: asString2(rec.name) ?? id,
|
|
2233
|
+
category: asString2(rec.category) ?? null,
|
|
2234
|
+
currentValue: asString2(rec.currentValue) ?? null,
|
|
2235
|
+
options
|
|
2236
|
+
});
|
|
2237
|
+
}
|
|
2238
|
+
return out;
|
|
2239
|
+
}
|
|
2240
|
+
function pickModelOption2(options) {
|
|
2241
|
+
return options.find((o) => o.category === "model") ?? options.find((o) => o.id === "model") ?? null;
|
|
2242
|
+
}
|
|
2243
|
+
function isAgyAcpSharedDaemonEnabled2(env = process.env) {
|
|
2244
|
+
if (!isAgyAcpEnabled2(env))
|
|
2245
|
+
return false;
|
|
2246
|
+
const raw = (env?.NOLO_AGY_ACP_SHARED_DAEMON ?? process.env.NOLO_AGY_ACP_SHARED_DAEMON ?? "").trim().toLowerCase();
|
|
2247
|
+
return !(raw === "0" || raw === "false" || raw === "off" || raw === "no");
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
class SharedAgyDaemon {
|
|
2251
|
+
proc = null;
|
|
2252
|
+
startPromise = null;
|
|
2253
|
+
initialized = false;
|
|
2254
|
+
nextId = 1;
|
|
2255
|
+
lineBuf = "";
|
|
2256
|
+
stderrTail = "";
|
|
2257
|
+
pending = new Map;
|
|
2258
|
+
sessions = new Map;
|
|
2259
|
+
sessionIdToKey = new Map;
|
|
2260
|
+
updateHandlers = new Map;
|
|
2261
|
+
activityTouchers = new Map;
|
|
2262
|
+
activeTurns = 0;
|
|
2263
|
+
idleTimer = null;
|
|
2264
|
+
daemonCwd = process.cwd();
|
|
2265
|
+
daemonYolo = true;
|
|
2266
|
+
daemonProcessPerSession = false;
|
|
2267
|
+
hasSessionHistory(key) {
|
|
2268
|
+
return (this.sessions.get(key)?.history.length ?? 0) > 0;
|
|
2269
|
+
}
|
|
2270
|
+
adoptSession(fromKey, toKey) {
|
|
2271
|
+
if (!fromKey || !toKey || fromKey === toKey)
|
|
2272
|
+
return false;
|
|
2273
|
+
if (this.sessions.has(toKey))
|
|
2274
|
+
return false;
|
|
2275
|
+
const entry = this.sessions.get(fromKey);
|
|
2276
|
+
if (!entry)
|
|
2277
|
+
return false;
|
|
2278
|
+
this.sessions.delete(fromKey);
|
|
2279
|
+
entry.key = toKey;
|
|
2280
|
+
this.sessions.set(toKey, entry);
|
|
2281
|
+
if (entry.acpSessionId) {
|
|
2282
|
+
this.sessionIdToKey.set(entry.acpSessionId, toKey);
|
|
2283
|
+
}
|
|
2284
|
+
return true;
|
|
2285
|
+
}
|
|
2286
|
+
isDaemonWarm() {
|
|
2287
|
+
return this.initialized && this.proc !== null;
|
|
2288
|
+
}
|
|
2289
|
+
clearIdleTimer() {
|
|
2290
|
+
if (this.idleTimer) {
|
|
2291
|
+
clearTimeout(this.idleTimer);
|
|
2292
|
+
this.idleTimer = null;
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
touchIdleTimer() {
|
|
2296
|
+
this.clearIdleTimer();
|
|
2297
|
+
if (this.activeTurns > 0)
|
|
2298
|
+
return;
|
|
2299
|
+
this.idleTimer = setTimeout(() => {
|
|
2300
|
+
this.idleTimer = null;
|
|
2301
|
+
if (this.activeTurns === 0)
|
|
2302
|
+
this.closeAll();
|
|
2303
|
+
}, DEFAULT_DAEMON_IDLE_TIMEOUT_MS);
|
|
2304
|
+
this.idleTimer.unref?.();
|
|
2305
|
+
}
|
|
2306
|
+
sendLine(payload) {
|
|
2307
|
+
if (!this.proc?.stdin || this.proc.stdin.destroyed) {
|
|
2308
|
+
throw new Error("shared agy ACP daemon stdin is closed");
|
|
2309
|
+
}
|
|
2310
|
+
this.proc.stdin.write(`${JSON.stringify(payload)}
|
|
2311
|
+
`);
|
|
2312
|
+
}
|
|
2313
|
+
requestWithId(method, params, timeoutMs = HANDSHAKE_TIMEOUT_MS) {
|
|
2314
|
+
const id = this.nextId++;
|
|
2315
|
+
const promise = new Promise((resolvePromise, rejectPromise) => {
|
|
2316
|
+
const entry = { resolve: resolvePromise, reject: rejectPromise };
|
|
2317
|
+
if (timeoutMs > 0) {
|
|
2318
|
+
entry.timer = setTimeout(() => {
|
|
2319
|
+
this.pending.delete(id);
|
|
2320
|
+
rejectPromise(new Error(`shared agy ACP request timed out: ${method}`));
|
|
2321
|
+
}, timeoutMs);
|
|
2322
|
+
entry.timer.unref?.();
|
|
2323
|
+
}
|
|
2324
|
+
this.pending.set(id, entry);
|
|
2325
|
+
try {
|
|
2326
|
+
this.sendLine({ jsonrpc: "2.0", id, method, params });
|
|
2327
|
+
} catch (err) {
|
|
2328
|
+
if (entry.timer)
|
|
2329
|
+
clearTimeout(entry.timer);
|
|
2330
|
+
this.pending.delete(id);
|
|
2331
|
+
rejectPromise(err instanceof Error ? err : new Error(String(err)));
|
|
2332
|
+
}
|
|
2333
|
+
});
|
|
2334
|
+
return { id, promise };
|
|
2335
|
+
}
|
|
2336
|
+
request(method, params, timeoutMs = HANDSHAKE_TIMEOUT_MS) {
|
|
2337
|
+
return this.requestWithId(method, params, timeoutMs).promise;
|
|
2338
|
+
}
|
|
2339
|
+
notify(method, params) {
|
|
2340
|
+
try {
|
|
2341
|
+
this.sendLine({ jsonrpc: "2.0", method, params });
|
|
2342
|
+
} catch {}
|
|
2343
|
+
}
|
|
2344
|
+
handleStdoutChunk(chunk) {
|
|
2345
|
+
this.lineBuf += chunk.toString("utf8");
|
|
2346
|
+
const lines = this.lineBuf.split(`
|
|
2347
|
+
`);
|
|
2348
|
+
this.lineBuf = lines.pop() ?? "";
|
|
2349
|
+
for (const line of lines) {
|
|
2350
|
+
if (!line.trim())
|
|
2351
|
+
continue;
|
|
2352
|
+
let frame = null;
|
|
2353
|
+
try {
|
|
2354
|
+
frame = asRecord4(JSON.parse(line));
|
|
2355
|
+
} catch {
|
|
2356
|
+
continue;
|
|
2357
|
+
}
|
|
2358
|
+
if (!frame)
|
|
2359
|
+
continue;
|
|
2360
|
+
const id = asNumber2(frame.id);
|
|
2361
|
+
const method = asString2(frame.method);
|
|
2362
|
+
if (id !== undefined && method === undefined) {
|
|
2363
|
+
const waiter = this.pending.get(id);
|
|
2364
|
+
if (!waiter)
|
|
2365
|
+
continue;
|
|
2366
|
+
this.pending.delete(id);
|
|
2367
|
+
if (waiter.timer)
|
|
2368
|
+
clearTimeout(waiter.timer);
|
|
2369
|
+
const errObj = asRecord4(frame.error);
|
|
2370
|
+
if (errObj) {
|
|
2371
|
+
const msg = asString2(errObj.message) ?? "JSON-RPC error";
|
|
2372
|
+
const code = asNumber2(errObj.code);
|
|
2373
|
+
waiter.reject(new Error(code !== undefined ? `${msg} (code ${code})` : msg));
|
|
2374
|
+
} else {
|
|
2375
|
+
waiter.resolve(frame.result);
|
|
2376
|
+
}
|
|
2377
|
+
continue;
|
|
2378
|
+
}
|
|
2379
|
+
if (method === "session/update" && id === undefined) {
|
|
2380
|
+
const params = asRecord4(frame.params);
|
|
2381
|
+
const sid = asString2(params?.sessionId);
|
|
2382
|
+
const update = asRecord4(params?.update) ?? params;
|
|
2383
|
+
if (sid && update) {
|
|
2384
|
+
const handler = this.updateHandlers.get(sid);
|
|
2385
|
+
try {
|
|
2386
|
+
handler?.(update);
|
|
2387
|
+
} catch {}
|
|
2388
|
+
}
|
|
2389
|
+
continue;
|
|
2390
|
+
}
|
|
2391
|
+
if (id !== undefined && method !== undefined) {
|
|
2392
|
+
const reqSid = asString2(asRecord4(frame.params)?.sessionId);
|
|
2393
|
+
if (reqSid) {
|
|
2394
|
+
this.activityTouchers.get(reqSid)?.();
|
|
2395
|
+
} else if (this.activityTouchers.size === 1) {
|
|
2396
|
+
for (const touch of this.activityTouchers.values())
|
|
2397
|
+
touch();
|
|
2398
|
+
}
|
|
2399
|
+
this.handleAgentRequest(method, frame.params).then((result) => {
|
|
2400
|
+
this.sendLine({ jsonrpc: "2.0", id, result });
|
|
2401
|
+
}).catch((error) => {
|
|
2402
|
+
this.sendLine({
|
|
2403
|
+
jsonrpc: "2.0",
|
|
2404
|
+
id,
|
|
2405
|
+
error: {
|
|
2406
|
+
code: -32000,
|
|
2407
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2408
|
+
}
|
|
2409
|
+
});
|
|
2410
|
+
});
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
resolveSessionForParams(params) {
|
|
2415
|
+
const sid = asString2(params?.sessionId);
|
|
2416
|
+
if (!sid)
|
|
2417
|
+
return;
|
|
2418
|
+
const key = this.sessionIdToKey.get(sid);
|
|
2419
|
+
return key ? this.sessions.get(key) : undefined;
|
|
2420
|
+
}
|
|
2421
|
+
resolveSandboxPath(target, rootDir, forWrite) {
|
|
2422
|
+
const absolute = resolve2(target);
|
|
2423
|
+
let realRoot = resolve2(rootDir);
|
|
2424
|
+
try {
|
|
2425
|
+
realRoot = realpathSync2(realRoot);
|
|
2426
|
+
} catch {}
|
|
2427
|
+
let realTarget;
|
|
2428
|
+
if (!forWrite) {
|
|
2429
|
+
realTarget = realpathSync2(absolute);
|
|
2430
|
+
} else {
|
|
2431
|
+
let existing = absolute;
|
|
2432
|
+
const tail = [];
|
|
2433
|
+
while (!existsSync3(existing)) {
|
|
2434
|
+
const parent = dirname2(existing);
|
|
2435
|
+
if (parent === existing)
|
|
2436
|
+
break;
|
|
2437
|
+
tail.unshift(basename2(existing));
|
|
2438
|
+
existing = parent;
|
|
2439
|
+
}
|
|
2440
|
+
if (tail.length > 0) {
|
|
2441
|
+
const firstMissing = resolve2(existing, tail[0]);
|
|
2442
|
+
let stat = null;
|
|
2443
|
+
try {
|
|
2444
|
+
stat = lstatSync2(firstMissing);
|
|
2445
|
+
} catch {
|
|
2446
|
+
stat = null;
|
|
2447
|
+
}
|
|
2448
|
+
if (stat?.isSymbolicLink()) {
|
|
2449
|
+
throw new Error(`agy ACP refuses to write through symlink: ${firstMissing}`);
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
const realExisting = realpathSync2(existing);
|
|
2453
|
+
realTarget = tail.length > 0 ? resolve2(realExisting, ...tail) : realExisting;
|
|
2454
|
+
}
|
|
2455
|
+
if (!isWithin2(realRoot, realTarget)) {
|
|
2456
|
+
throw new Error(`agy ACP path outside allowed sandbox: ${absolute}`);
|
|
2457
|
+
}
|
|
2458
|
+
return realTarget;
|
|
2459
|
+
}
|
|
2460
|
+
async handleAgentRequest(method, params) {
|
|
2461
|
+
const record = asRecord4(params);
|
|
2462
|
+
const session = this.resolveSessionForParams(record);
|
|
2463
|
+
const rootCwd = session?.cwd ?? this.daemonCwd;
|
|
2464
|
+
const yolo = session?.yolo ?? this.daemonYolo;
|
|
2465
|
+
if (method === "session/request_permission") {
|
|
2466
|
+
const options = Array.isArray(record?.options) ? record.options : [];
|
|
2467
|
+
const candidates = options.map((o) => asRecord4(o)).filter((o) => o !== null).map((o) => ({
|
|
2468
|
+
optionId: asString2(o.optionId) ?? asString2(o.option_id) ?? "",
|
|
2469
|
+
kind: (asString2(o.kind) ?? "").toLowerCase()
|
|
2470
|
+
})).filter((o) => o.optionId !== "");
|
|
2471
|
+
const allow = candidates.find((o) => o.kind.startsWith("allow"));
|
|
2472
|
+
const reject = candidates.find((o) => o.kind.startsWith("reject"));
|
|
2473
|
+
if (!yolo && !reject)
|
|
2474
|
+
return { outcome: { outcome: "cancelled" } };
|
|
2475
|
+
const chosen = yolo ? allow ?? reject : reject;
|
|
2476
|
+
if (!chosen)
|
|
2477
|
+
return { outcome: { outcome: "cancelled" } };
|
|
2478
|
+
return { outcome: { outcome: "selected", optionId: chosen.optionId }, optionId: chosen.optionId };
|
|
2479
|
+
}
|
|
2480
|
+
if (method === "fs/read_text_file") {
|
|
2481
|
+
const path = asString2(record?.path);
|
|
2482
|
+
if (!path)
|
|
2483
|
+
throw new Error("fs/read_text_file requires path");
|
|
2484
|
+
let content = readFileSync3(this.resolveSandboxPath(path, rootCwd, false), "utf8");
|
|
2485
|
+
const line = asNumber2(record?.line);
|
|
2486
|
+
const limit = asNumber2(record?.limit);
|
|
2487
|
+
if (line !== undefined || limit !== undefined) {
|
|
2488
|
+
const lines = content.split(`
|
|
2489
|
+
`);
|
|
2490
|
+
const startIndex = Math.max(0, (line ?? 1) - 1);
|
|
2491
|
+
const endIndex = limit !== undefined ? startIndex + limit : lines.length;
|
|
2492
|
+
content = lines.slice(startIndex, endIndex).join(`
|
|
2493
|
+
`);
|
|
2494
|
+
}
|
|
2495
|
+
return { content };
|
|
2496
|
+
}
|
|
2497
|
+
if (method === "fs/write_text_file") {
|
|
2498
|
+
const path = asString2(record?.path);
|
|
2499
|
+
const content = asString2(record?.content);
|
|
2500
|
+
if (!path || content === undefined)
|
|
2501
|
+
throw new Error("fs/write_text_file requires path and content");
|
|
2502
|
+
const realPath = this.resolveSandboxPath(path, rootCwd, true);
|
|
2503
|
+
mkdirSync2(dirname2(realPath), { recursive: true });
|
|
2504
|
+
writeFileSync2(realPath, content, "utf8");
|
|
2505
|
+
return null;
|
|
2506
|
+
}
|
|
2507
|
+
throw new Error(`Unsupported shared ACP method: ${method}`);
|
|
2508
|
+
}
|
|
2509
|
+
handleProcessExit(code, signal) {
|
|
2510
|
+
const err = new Error(`shared agy acp daemon exited (code=${code ?? "null"}, signal=${signal ?? "none"})` + (this.stderrTail.trim() ? `
|
|
2511
|
+
stderr: ${this.stderrTail.trim()}` : ""));
|
|
2512
|
+
for (const [, waiter] of this.pending) {
|
|
2513
|
+
if (waiter.timer)
|
|
2514
|
+
clearTimeout(waiter.timer);
|
|
2515
|
+
waiter.reject(err);
|
|
2516
|
+
}
|
|
2517
|
+
this.pending.clear();
|
|
2518
|
+
this.proc = null;
|
|
2519
|
+
this.initialized = false;
|
|
2520
|
+
this.startPromise = null;
|
|
2521
|
+
this.lineBuf = "";
|
|
2522
|
+
this.sessionIdToKey.clear();
|
|
2523
|
+
this.updateHandlers.clear();
|
|
2524
|
+
this.activityTouchers.clear();
|
|
2525
|
+
for (const entry of this.sessions.values()) {
|
|
2526
|
+
entry.acpSessionId = null;
|
|
2527
|
+
entry.appliedModel = null;
|
|
2528
|
+
entry.appliedThoughtLevel = null;
|
|
2529
|
+
entry.appliedMode = null;
|
|
2530
|
+
entry.systemPromptSent = false;
|
|
2531
|
+
if (entry.history.length > 0)
|
|
2532
|
+
entry.needsContextReplay = true;
|
|
2533
|
+
}
|
|
2534
|
+
this.clearIdleTimer();
|
|
2535
|
+
}
|
|
2536
|
+
invalidateSession(entry) {
|
|
2537
|
+
if (entry.acpSessionId) {
|
|
2538
|
+
this.sessionIdToKey.delete(entry.acpSessionId);
|
|
2539
|
+
this.updateHandlers.delete(entry.acpSessionId);
|
|
2540
|
+
this.activityTouchers.delete(entry.acpSessionId);
|
|
2541
|
+
}
|
|
2542
|
+
entry.acpSessionId = null;
|
|
2543
|
+
entry.appliedModel = null;
|
|
2544
|
+
entry.appliedThoughtLevel = null;
|
|
2545
|
+
entry.appliedMode = null;
|
|
2546
|
+
entry.systemPromptSent = false;
|
|
2547
|
+
if (entry.history.length > 0)
|
|
2548
|
+
entry.needsContextReplay = true;
|
|
2549
|
+
}
|
|
2550
|
+
async recycleDaemon() {
|
|
2551
|
+
this.clearIdleTimer();
|
|
2552
|
+
const proc = this.proc;
|
|
2553
|
+
this.proc = null;
|
|
2554
|
+
this.initialized = false;
|
|
2555
|
+
this.startPromise = null;
|
|
2556
|
+
this.lineBuf = "";
|
|
2557
|
+
this.sessionIdToKey.clear();
|
|
2558
|
+
this.updateHandlers.clear();
|
|
2559
|
+
this.activityTouchers.clear();
|
|
2560
|
+
for (const entry of this.sessions.values()) {
|
|
2561
|
+
this.invalidateSession(entry);
|
|
2562
|
+
}
|
|
2563
|
+
for (const [, waiter] of this.pending) {
|
|
2564
|
+
if (waiter.timer)
|
|
2565
|
+
clearTimeout(waiter.timer);
|
|
2566
|
+
waiter.reject(new Error("shared agy ACP daemon recycled after stall"));
|
|
2567
|
+
}
|
|
2568
|
+
this.pending.clear();
|
|
2569
|
+
if (proc) {
|
|
2570
|
+
proc.removeAllListeners("exit");
|
|
2571
|
+
proc.removeAllListeners("error");
|
|
2572
|
+
proc.stdout?.removeAllListeners("data");
|
|
2573
|
+
proc.stderr?.removeAllListeners("data");
|
|
2574
|
+
proc.on("error", () => {});
|
|
2575
|
+
await Promise.race([
|
|
2576
|
+
terminateCliProcessGroupEscalating2(proc).catch(() => {
|
|
2577
|
+
return;
|
|
2578
|
+
}),
|
|
2579
|
+
new Promise((r) => {
|
|
2580
|
+
const t = setTimeout(r, 5000);
|
|
2581
|
+
t.unref?.();
|
|
2582
|
+
})
|
|
2583
|
+
]);
|
|
2584
|
+
}
|
|
2585
|
+
}
|
|
2586
|
+
async ensureDaemon(config = {}) {
|
|
2587
|
+
if (this.initialized && this.proc)
|
|
2588
|
+
return;
|
|
2589
|
+
if (this.startPromise)
|
|
2590
|
+
return this.startPromise;
|
|
2591
|
+
const wantProcessPerSession = config.processPerSession === true || isAgyAcpProcessPerSessionEnabled2(config.env) || (config.mcpServers ?? []).some((s) => ("type" in s) && (s.type === "http" || s.type === "sse"));
|
|
2592
|
+
this.daemonCwd = config.cwd || process.cwd();
|
|
2593
|
+
this.daemonYolo = config.yolo !== false;
|
|
2594
|
+
this.daemonProcessPerSession = wantProcessPerSession;
|
|
2595
|
+
const start = (async () => {
|
|
2596
|
+
const binPath = config.binPath || process.env.AGY_BIN || "agy";
|
|
2597
|
+
const args = ["acp", "--disable-telemetry"];
|
|
2598
|
+
if (wantProcessPerSession)
|
|
2599
|
+
args.push("--process-per-session");
|
|
2600
|
+
if (config.yolo === false)
|
|
2601
|
+
args.push("--sandbox");
|
|
2602
|
+
const proc = spawn3(binPath, args, {
|
|
2603
|
+
cwd: this.daemonCwd,
|
|
2604
|
+
env: buildCliProcessEnv2(config.env),
|
|
2605
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
2606
|
+
detached: process.platform !== "win32"
|
|
2607
|
+
});
|
|
2608
|
+
this.proc = proc;
|
|
2609
|
+
this.stderrTail = "";
|
|
2610
|
+
const decoder = new StringDecoder2("utf8");
|
|
2611
|
+
let exited = false;
|
|
2612
|
+
const onExit = (code, signal) => {
|
|
2613
|
+
if (exited)
|
|
2614
|
+
return;
|
|
2615
|
+
exited = true;
|
|
2616
|
+
this.handleProcessExit(code, signal);
|
|
2617
|
+
};
|
|
2618
|
+
proc.on("exit", onExit);
|
|
2619
|
+
proc.on("error", (e) => {
|
|
2620
|
+
this.stderrTail += `
|
|
2621
|
+
${e.message}`;
|
|
2622
|
+
onExit(null, null);
|
|
2623
|
+
});
|
|
2624
|
+
proc.stdout?.on("data", (chunk) => this.handleStdoutChunk(chunk));
|
|
2625
|
+
proc.stderr?.on("data", (chunk) => {
|
|
2626
|
+
this.stderrTail = (this.stderrTail + decoder.write(chunk)).slice(-STDERR_TAIL_CHARS2);
|
|
2627
|
+
});
|
|
2628
|
+
await this.request("initialize", {
|
|
2629
|
+
protocolVersion: ACP_PROTOCOL_VERSION2,
|
|
2630
|
+
clientCapabilities: {
|
|
2631
|
+
fs: { readTextFile: true, writeTextFile: true },
|
|
2632
|
+
terminal: false
|
|
2633
|
+
}
|
|
2634
|
+
});
|
|
2635
|
+
this.initialized = true;
|
|
2636
|
+
this.touchIdleTimer();
|
|
2637
|
+
})();
|
|
2638
|
+
this.startPromise = start.catch((err) => {
|
|
2639
|
+
this.startPromise = null;
|
|
2640
|
+
throw err;
|
|
2641
|
+
});
|
|
2642
|
+
return this.startPromise;
|
|
2643
|
+
}
|
|
2644
|
+
async prewarmDaemon(config = {}) {
|
|
2645
|
+
try {
|
|
2646
|
+
await this.ensureDaemon(config);
|
|
2647
|
+
if (this.sessions.size === 0) {
|
|
2648
|
+
await this.ensureSession("__daemon_warmup__", config);
|
|
2649
|
+
}
|
|
2650
|
+
return { ok: true, warm: this.isDaemonWarm() };
|
|
2651
|
+
} catch (error) {
|
|
2652
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
async prewarmSession(key, config = {}) {
|
|
2656
|
+
try {
|
|
2657
|
+
const entry = await this.ensureSession(key, config);
|
|
2658
|
+
await this.applyModelAndThought(entry, config);
|
|
2659
|
+
return { ok: true, warm: Boolean(entry.acpSessionId) };
|
|
2660
|
+
} catch (error) {
|
|
2661
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
async ensureSession(key, config) {
|
|
2665
|
+
await this.ensureDaemon(config);
|
|
2666
|
+
let entry = this.sessions.get(key);
|
|
2667
|
+
if (!entry) {
|
|
2668
|
+
entry = {
|
|
2669
|
+
key,
|
|
2670
|
+
acpSessionId: null,
|
|
2671
|
+
cwd: config.cwd || process.cwd(),
|
|
2672
|
+
configOptions: [],
|
|
2673
|
+
appliedModel: null,
|
|
2674
|
+
appliedThoughtLevel: null,
|
|
2675
|
+
appliedMode: null,
|
|
2676
|
+
systemPromptSent: false,
|
|
2677
|
+
history: [],
|
|
2678
|
+
needsContextReplay: false,
|
|
2679
|
+
turnQueue: Promise.resolve(),
|
|
2680
|
+
mcpServers: config.mcpServers ?? [],
|
|
2681
|
+
yolo: config.yolo !== false
|
|
2682
|
+
};
|
|
2683
|
+
this.sessions.set(key, entry);
|
|
2684
|
+
} else {
|
|
2685
|
+
if (config.cwd)
|
|
2686
|
+
entry.cwd = config.cwd;
|
|
2687
|
+
if (config.mcpServers)
|
|
2688
|
+
entry.mcpServers = config.mcpServers;
|
|
2689
|
+
if (config.yolo !== undefined)
|
|
2690
|
+
entry.yolo = config.yolo;
|
|
2691
|
+
}
|
|
2692
|
+
if (!entry.acpSessionId) {
|
|
2693
|
+
const res = await this.request("session/new", {
|
|
2694
|
+
cwd: entry.cwd,
|
|
2695
|
+
mcpServers: entry.mcpServers
|
|
2696
|
+
});
|
|
2697
|
+
const rec = asRecord4(res);
|
|
2698
|
+
const sid = asString2(rec?.sessionId);
|
|
2699
|
+
if (!sid)
|
|
2700
|
+
throw new Error("shared agy ACP session/new returned no sessionId");
|
|
2701
|
+
entry.acpSessionId = sid;
|
|
2702
|
+
entry.configOptions = parseConfigOptions2(rec);
|
|
2703
|
+
entry.appliedModel = pickModelOption2(entry.configOptions)?.currentValue ?? null;
|
|
2704
|
+
const thoughtOpt = pickThoughtLevelOption(entry.configOptions);
|
|
2705
|
+
entry.appliedThoughtLevel = thoughtOpt?.currentValue ? `${thoughtOpt.id}=${thoughtOpt.currentValue}` : null;
|
|
2706
|
+
const modeOpt = entry.configOptions.find((o) => o.category === "mode" || o.id === "mode");
|
|
2707
|
+
entry.appliedMode = modeOpt?.currentValue ?? null;
|
|
2708
|
+
this.sessionIdToKey.set(sid, key);
|
|
2709
|
+
}
|
|
2710
|
+
return entry;
|
|
2711
|
+
}
|
|
2712
|
+
async applyModelAndThought(entry, config) {
|
|
2713
|
+
const warnings = [];
|
|
2714
|
+
const sid = entry.acpSessionId;
|
|
2715
|
+
if (!sid)
|
|
2716
|
+
return warnings;
|
|
2717
|
+
let derivedEffort;
|
|
2718
|
+
const requestedModel = config.model?.trim();
|
|
2719
|
+
if (requestedModel) {
|
|
2720
|
+
const modelOpt = pickModelOption2(entry.configOptions);
|
|
2721
|
+
if (modelOpt) {
|
|
2722
|
+
const resolved = resolveAcpModelAndEffort(modelOpt, requestedModel);
|
|
2723
|
+
derivedEffort = resolved.derivedEffort;
|
|
2724
|
+
if (!resolved.model) {
|
|
2725
|
+
warnings.push(`agy ACP model "${requestedModel}" is not in advertised model list; keeping current model.`);
|
|
2726
|
+
} else if (entry.appliedModel !== resolved.model) {
|
|
2727
|
+
const resp = await this.request("session/set_config_option", {
|
|
2728
|
+
sessionId: sid,
|
|
2729
|
+
configId: modelOpt.id,
|
|
2730
|
+
value: resolved.model
|
|
2731
|
+
});
|
|
2732
|
+
const updated = parseConfigOptions2(resp);
|
|
2733
|
+
if (updated.length > 0)
|
|
2734
|
+
entry.configOptions = updated;
|
|
2735
|
+
entry.appliedModel = resolved.model;
|
|
2736
|
+
const thoughtOpt = pickThoughtLevelOption(entry.configOptions);
|
|
2737
|
+
entry.appliedThoughtLevel = thoughtOpt?.currentValue ? `${thoughtOpt.id}=${thoughtOpt.currentValue}` : null;
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
const parallelConfigCalls = [];
|
|
2742
|
+
const explicitEffort = config.reasoningEffort?.trim();
|
|
2743
|
+
const requestedEffort = !derivedEffort && hasReasoningEffortSuffix(config.model) ? undefined : explicitEffort || derivedEffort;
|
|
2744
|
+
if (requestedEffort) {
|
|
2745
|
+
const resolution = resolveThoughtLevel(entry.configOptions, requestedEffort);
|
|
2746
|
+
if (resolution.kind === "exact" || resolution.kind === "clamped") {
|
|
2747
|
+
if (resolution.kind === "clamped") {
|
|
2748
|
+
warnings.push(`agy ACP thought_level clamped "${resolution.requested}" to "${resolution.value}"`);
|
|
2749
|
+
}
|
|
2750
|
+
const token = `${resolution.option.id}=${resolution.value}`;
|
|
2751
|
+
if (entry.appliedThoughtLevel !== token) {
|
|
2752
|
+
parallelConfigCalls.push(this.request("session/set_config_option", {
|
|
2753
|
+
sessionId: sid,
|
|
2754
|
+
configId: resolution.option.id,
|
|
2755
|
+
value: resolution.value
|
|
2756
|
+
}).then((resp) => {
|
|
2757
|
+
const updated = parseConfigOptions2(resp);
|
|
2758
|
+
if (updated.length > 0)
|
|
2759
|
+
entry.configOptions = updated;
|
|
2760
|
+
entry.appliedThoughtLevel = token;
|
|
2761
|
+
}));
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
if (config.yolo !== false) {
|
|
2766
|
+
const modeOpt = entry.configOptions.find((o) => o.category === "mode" || o.id === "mode");
|
|
2767
|
+
if (modeOpt && entry.appliedMode !== "auto" && modeOpt.options.some((o) => o.value === "auto")) {
|
|
2768
|
+
parallelConfigCalls.push(this.request("session/set_config_option", {
|
|
2769
|
+
sessionId: sid,
|
|
2770
|
+
configId: modeOpt.id,
|
|
2771
|
+
value: "auto"
|
|
2772
|
+
}).then(() => {
|
|
2773
|
+
entry.appliedMode = "auto";
|
|
2774
|
+
}).catch(() => {}));
|
|
2775
|
+
}
|
|
2776
|
+
}
|
|
2777
|
+
if (parallelConfigCalls.length > 0) {
|
|
2778
|
+
await Promise.all(parallelConfigCalls);
|
|
2779
|
+
}
|
|
2780
|
+
return warnings;
|
|
2781
|
+
}
|
|
2782
|
+
buildPromptText(entry, input, systemPrompt) {
|
|
2783
|
+
const parts = [];
|
|
2784
|
+
const sys = systemPrompt?.trim();
|
|
2785
|
+
let sentSystemPrompt = false;
|
|
2786
|
+
let replayedContext = false;
|
|
2787
|
+
if (sys && !entry.systemPromptSent) {
|
|
2788
|
+
parts.push(sys);
|
|
2789
|
+
sentSystemPrompt = true;
|
|
2790
|
+
}
|
|
2791
|
+
if (entry.needsContextReplay && entry.history.length > 0) {
|
|
2792
|
+
const transcript = entry.history.map((h, i) => `[${i + 1}] ${h.role === "user" ? "用户" : "助手"}
|
|
2793
|
+
${h.content.trim()}`).join(`
|
|
2794
|
+
|
|
2795
|
+
`);
|
|
2796
|
+
parts.push(`以下是同一会话此前已发生的对话(进程重启后重建上下文),请延续它继续回答最后一条用户消息。
|
|
2797
|
+
|
|
2798
|
+
${transcript}`);
|
|
2799
|
+
replayedContext = true;
|
|
2800
|
+
}
|
|
2801
|
+
parts.push(input);
|
|
2802
|
+
return { promptText: parts.join(`
|
|
2803
|
+
|
|
2804
|
+
`), sentSystemPrompt, replayedContext };
|
|
2805
|
+
}
|
|
2806
|
+
async promptSession(key, input, config, options = {}) {
|
|
2807
|
+
const entry = await this.ensureSession(key, config);
|
|
2808
|
+
const run = async () => {
|
|
2809
|
+
if (options.signal?.aborted)
|
|
2810
|
+
throw createAbortError2();
|
|
2811
|
+
const start = Date.now();
|
|
2812
|
+
this.activeTurns += 1;
|
|
2813
|
+
this.clearIdleTimer();
|
|
2814
|
+
try {
|
|
2815
|
+
const refreshed = await this.ensureSession(key, config);
|
|
2816
|
+
const sid = refreshed.acpSessionId;
|
|
2817
|
+
if (!sid)
|
|
2818
|
+
throw new Error("shared agy ACP session failed to initialize");
|
|
2819
|
+
const warnings = await this.applyModelAndThought(refreshed, config);
|
|
2820
|
+
const { promptText, sentSystemPrompt, replayedContext } = this.buildPromptText(refreshed, input, config.systemPrompt);
|
|
2821
|
+
const collected = [];
|
|
2822
|
+
const toolEvents = new AgyAcpToolEventTracker;
|
|
2823
|
+
let lastActivity = Date.now();
|
|
2824
|
+
const touchActivity = () => {
|
|
2825
|
+
lastActivity = Date.now();
|
|
2826
|
+
};
|
|
2827
|
+
this.activityTouchers.set(sid, touchActivity);
|
|
2828
|
+
this.updateHandlers.set(sid, (update) => {
|
|
2829
|
+
touchActivity();
|
|
2830
|
+
const kind = asString2(update.sessionUpdate) ?? asString2(update.type);
|
|
2831
|
+
if (kind === "agent_message_chunk") {
|
|
2832
|
+
const text = asString2(asRecord4(update.content)?.text);
|
|
2833
|
+
if (text) {
|
|
2834
|
+
collected.push(text);
|
|
2835
|
+
options.onChunk?.(text);
|
|
2836
|
+
}
|
|
2837
|
+
return;
|
|
2838
|
+
}
|
|
2839
|
+
if (kind === "agent_thought_chunk") {
|
|
2840
|
+
const text = asString2(asRecord4(update.content)?.text);
|
|
2841
|
+
if (text)
|
|
2842
|
+
options.onThoughtChunk?.(text);
|
|
2843
|
+
return;
|
|
2844
|
+
}
|
|
2845
|
+
if (kind === "tool_call" || kind === "tool_call_update") {
|
|
2846
|
+
const event = toolEvents.handleUpdate(update, options.toolEventRound ?? 1);
|
|
2847
|
+
if (event)
|
|
2848
|
+
options.onToolEvent?.(event);
|
|
2849
|
+
}
|
|
2850
|
+
});
|
|
2851
|
+
const totalMs = options.timeoutMs ?? 0;
|
|
2852
|
+
const noOutputMs = options.noOutputTimeoutMs ?? AGY_ACP_NO_OUTPUT_TIMEOUT_MS;
|
|
2853
|
+
let watchdogTimer = null;
|
|
2854
|
+
let abortHandler = null;
|
|
2855
|
+
const { id: promptReqId, promise: promptPromise } = this.requestWithId("session/prompt", { sessionId: sid, prompt: [{ type: "text", text: promptText }] }, 0);
|
|
2856
|
+
const racePromises = [promptPromise];
|
|
2857
|
+
if (options.signal) {
|
|
2858
|
+
racePromises.push(new Promise((_, rejectPromise) => {
|
|
2859
|
+
abortHandler = () => rejectPromise(createAbortError2());
|
|
2860
|
+
options.signal?.addEventListener("abort", abortHandler, { once: true });
|
|
2861
|
+
}));
|
|
2862
|
+
}
|
|
2863
|
+
if (totalMs > 0 || noOutputMs > 0) {
|
|
2864
|
+
const pollIntervalMs = Math.min(1000, Math.max(50, Math.floor((noOutputMs > 0 ? noOutputMs : totalMs) / 4)));
|
|
2865
|
+
racePromises.push(new Promise((_, rejectPromise) => {
|
|
2866
|
+
watchdogTimer = setInterval(() => {
|
|
2867
|
+
const now = Date.now();
|
|
2868
|
+
if (totalMs > 0 && now - start > totalMs) {
|
|
2869
|
+
rejectPromise(new Error(`agy ACP session/prompt total timeout after ${totalMs}ms`));
|
|
2870
|
+
} else if (noOutputMs > 0 && toolEvents.inFlightCount === 0 && now - lastActivity > noOutputMs) {
|
|
2871
|
+
rejectPromise(new Error(`agy ACP session/prompt stalled (no output for ${Math.round((now - lastActivity) / 1000)}s)`));
|
|
2872
|
+
}
|
|
2873
|
+
}, pollIntervalMs);
|
|
2874
|
+
watchdogTimer.unref?.();
|
|
2875
|
+
}));
|
|
2876
|
+
}
|
|
2877
|
+
let resultRaw;
|
|
2878
|
+
try {
|
|
2879
|
+
resultRaw = await Promise.race(racePromises);
|
|
2880
|
+
} catch (err) {
|
|
2881
|
+
let cancelAcked = false;
|
|
2882
|
+
try {
|
|
2883
|
+
this.notify("session/cancel", { sessionId: sid });
|
|
2884
|
+
} catch {}
|
|
2885
|
+
await Promise.race([
|
|
2886
|
+
promptPromise.then(() => {
|
|
2887
|
+
cancelAcked = true;
|
|
2888
|
+
}, () => {
|
|
2889
|
+
cancelAcked = true;
|
|
2890
|
+
}),
|
|
2891
|
+
new Promise((r) => {
|
|
2892
|
+
const t = setTimeout(r, CANCEL_GRACE_MS2);
|
|
2893
|
+
t.unref?.();
|
|
2894
|
+
})
|
|
2895
|
+
]);
|
|
2896
|
+
if (!cancelAcked) {
|
|
2897
|
+
this.pending.delete(promptReqId);
|
|
2898
|
+
this.invalidateSession(refreshed);
|
|
2899
|
+
if (this.activeTurns <= 1) {
|
|
2900
|
+
await this.recycleDaemon();
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2904
|
+
const quota = detectCliProviderQuotaLimit2("agy", "", `${msg}
|
|
2905
|
+
${this.stderrTail}`, null);
|
|
2906
|
+
if (quota.limited) {
|
|
2907
|
+
throw new CliProviderQuotaError2("agy", `${quota.message ?? "Agy quota limit"}: ${msg}`);
|
|
2908
|
+
}
|
|
2909
|
+
throw err;
|
|
2910
|
+
} finally {
|
|
2911
|
+
if (watchdogTimer)
|
|
2912
|
+
clearInterval(watchdogTimer);
|
|
2913
|
+
if (abortHandler && options.signal)
|
|
2914
|
+
options.signal.removeEventListener("abort", abortHandler);
|
|
2915
|
+
this.updateHandlers.delete(sid);
|
|
2916
|
+
this.activityTouchers.delete(sid);
|
|
2917
|
+
}
|
|
2918
|
+
const resRec = asRecord4(resultRaw);
|
|
2919
|
+
const stopReason = asString2(resRec?.stopReason) ?? "end_turn";
|
|
2920
|
+
const usage = normalizeUsage(resRec?.usage);
|
|
2921
|
+
const text = collected.join("");
|
|
2922
|
+
if (stopReason === "cancelled") {
|
|
2923
|
+
throw createAbortError2("agy ACP turn was cancelled by agent");
|
|
2924
|
+
}
|
|
2925
|
+
if (sentSystemPrompt)
|
|
2926
|
+
refreshed.systemPromptSent = true;
|
|
2927
|
+
if (replayedContext)
|
|
2928
|
+
refreshed.needsContextReplay = false;
|
|
2929
|
+
if (!options.ephemeral) {
|
|
2930
|
+
refreshed.history.push({ role: "user", content: input }, { role: "assistant", content: text });
|
|
2931
|
+
} else {
|
|
2932
|
+
this.sessions.delete(key);
|
|
2933
|
+
this.sessionIdToKey.delete(sid);
|
|
2934
|
+
}
|
|
2935
|
+
return {
|
|
2936
|
+
text,
|
|
2937
|
+
raw: text,
|
|
2938
|
+
elapsed: Date.now() - start,
|
|
2939
|
+
...usage ? { usage } : {},
|
|
2940
|
+
...warnings.length > 0 ? { warnings } : {}
|
|
2941
|
+
};
|
|
2942
|
+
} finally {
|
|
2943
|
+
this.activeTurns = Math.max(0, this.activeTurns - 1);
|
|
2944
|
+
this.touchIdleTimer();
|
|
2945
|
+
}
|
|
2946
|
+
};
|
|
2947
|
+
const next = entry.turnQueue.then(run, run);
|
|
2948
|
+
entry.turnQueue = next.then(() => {
|
|
2949
|
+
return;
|
|
2950
|
+
}, () => {
|
|
2951
|
+
return;
|
|
2952
|
+
});
|
|
2953
|
+
return next;
|
|
2954
|
+
}
|
|
2955
|
+
closeSession(key) {
|
|
2956
|
+
const entry = this.sessions.get(key);
|
|
2957
|
+
if (!entry)
|
|
2958
|
+
return;
|
|
2959
|
+
this.sessions.delete(key);
|
|
2960
|
+
if (entry.acpSessionId) {
|
|
2961
|
+
this.sessionIdToKey.delete(entry.acpSessionId);
|
|
2962
|
+
this.updateHandlers.delete(entry.acpSessionId);
|
|
2963
|
+
this.activityTouchers.delete(entry.acpSessionId);
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
async closeAll() {
|
|
2967
|
+
this.clearIdleTimer();
|
|
2968
|
+
const proc = this.proc;
|
|
2969
|
+
this.proc = null;
|
|
2970
|
+
this.initialized = false;
|
|
2971
|
+
this.startPromise = null;
|
|
2972
|
+
this.sessions.clear();
|
|
2973
|
+
this.sessionIdToKey.clear();
|
|
2974
|
+
this.updateHandlers.clear();
|
|
2975
|
+
this.activityTouchers.clear();
|
|
2976
|
+
for (const [, waiter] of this.pending) {
|
|
2977
|
+
if (waiter.timer)
|
|
2978
|
+
clearTimeout(waiter.timer);
|
|
2979
|
+
waiter.reject(new Error("shared agy ACP daemon closed"));
|
|
2980
|
+
}
|
|
2981
|
+
this.pending.clear();
|
|
2982
|
+
if (proc) {
|
|
2983
|
+
proc.removeAllListeners("exit");
|
|
2984
|
+
proc.removeAllListeners("error");
|
|
2985
|
+
proc.stdout?.removeAllListeners("data");
|
|
2986
|
+
proc.stderr?.removeAllListeners("data");
|
|
2987
|
+
proc.on("error", () => {});
|
|
2988
|
+
await Promise.race([
|
|
2989
|
+
terminateCliProcessGroupEscalating2(proc).catch(() => {
|
|
2990
|
+
return;
|
|
2991
|
+
}),
|
|
2992
|
+
new Promise((r) => {
|
|
2993
|
+
const t = setTimeout(r, 5000);
|
|
2994
|
+
t.unref?.();
|
|
2995
|
+
})
|
|
2996
|
+
]);
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
}
|
|
3000
|
+
var sharedDaemon = new SharedAgyDaemon;
|
|
3001
|
+
function prewarmSharedAgyDaemon2(config = {}) {
|
|
3002
|
+
return sharedDaemon.prewarmDaemon(config);
|
|
3003
|
+
}
|
|
3004
|
+
function prewarmSharedAgySession2(key, config = {}) {
|
|
3005
|
+
return sharedDaemon.prewarmSession(key, config);
|
|
3006
|
+
}
|
|
3007
|
+
function hasSharedAgySessionHistory2(key) {
|
|
3008
|
+
return sharedDaemon.hasSessionHistory(key);
|
|
3009
|
+
}
|
|
3010
|
+
function adoptSharedAgySession2(fromKey, toKey) {
|
|
3011
|
+
return sharedDaemon.adoptSession(fromKey, toKey);
|
|
3012
|
+
}
|
|
3013
|
+
function promptSharedAgySession(key, input, config, options = {}) {
|
|
3014
|
+
return sharedDaemon.promptSession(key, input, config, options);
|
|
3015
|
+
}
|
|
3016
|
+
function runOneShotSharedAgyPrompt(input, config, options = {}) {
|
|
3017
|
+
const ephemeralKey = `oneshot:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 8)}`;
|
|
3018
|
+
return sharedDaemon.promptSession(ephemeralKey, input, config, { ...options, ephemeral: true });
|
|
3019
|
+
}
|
|
3020
|
+
function closeSharedAgySession2(key) {
|
|
3021
|
+
if (key === undefined)
|
|
3022
|
+
return sharedDaemon.closeAll();
|
|
3023
|
+
sharedDaemon.closeSession(key);
|
|
3024
|
+
return Promise.resolve();
|
|
3025
|
+
}
|
|
3026
|
+
// packages/ai/agent/cliExecutor.ts
|
|
3027
|
+
class CliProviderQuotaError2 extends Error {
|
|
3028
|
+
provider;
|
|
3029
|
+
constructor(provider, message) {
|
|
3030
|
+
super(`[QUOTA_LIMITED:${provider}] ${message}`);
|
|
3031
|
+
this.name = "CliProviderQuotaError";
|
|
3032
|
+
this.provider = provider;
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
function detectCliProviderQuotaLimit2(provider, stdout, stderr, exitCode) {
|
|
3036
|
+
const stderrText = String(stderr || "");
|
|
3037
|
+
const stdoutText = String(stdout || "");
|
|
3038
|
+
const combined = stderrText + `
|
|
3039
|
+
` + stdoutText;
|
|
3040
|
+
const isQuotaText = (text) => {
|
|
3041
|
+
const t = text.toLowerCase();
|
|
3042
|
+
const strongPatterns = [
|
|
3043
|
+
/quota (exceeded|reached|limit|used up|insufficient|hit)/i,
|
|
3044
|
+
/usage limit (reached|exceeded|hit)/i,
|
|
3045
|
+
/weekly usage limit/i,
|
|
3046
|
+
/rate.?limit (exceeded|reached|hit)/i,
|
|
3047
|
+
/\b429\b.*(limit|quota|rate)/i,
|
|
3048
|
+
/too many request/i,
|
|
3049
|
+
/no (more|remaining) (credit|quota|usage)/i,
|
|
3050
|
+
/plan limit|membership limit/i,
|
|
3051
|
+
/daily limit|hourly limit reached/i,
|
|
3052
|
+
/limit reached.*reset/i,
|
|
3053
|
+
/resets in .* days/i
|
|
3054
|
+
];
|
|
3055
|
+
for (const re of strongPatterns) {
|
|
3056
|
+
if (re.test(t))
|
|
3057
|
+
return true;
|
|
3058
|
+
}
|
|
3059
|
+
return false;
|
|
3060
|
+
};
|
|
3061
|
+
if (isQuotaText(stderrText)) {
|
|
3062
|
+
return { limited: true, message: `quota/rate limit signal from ${provider} (stderr)` };
|
|
3063
|
+
}
|
|
3064
|
+
if (isQuotaText(combined)) {
|
|
3065
|
+
return { limited: true, message: `quota/rate limit signal from ${provider}` };
|
|
3066
|
+
}
|
|
3067
|
+
return { limited: false };
|
|
3068
|
+
}
|
|
3069
|
+
var DEFAULT_AGY_TIMEOUT_MS = 600000;
|
|
3070
|
+
var DEFAULT_AGY_ACP_TOTAL_TIMEOUT_MS = 0;
|
|
3071
|
+
var DEFAULT_OPENCODE_TIMEOUT_MS = 600000;
|
|
3072
|
+
var DEFAULT_GROK_TIMEOUT_MS = 600000;
|
|
3073
|
+
var BUFFERED_STREAMING_PROVIDERS = new Set([
|
|
3074
|
+
"codex",
|
|
3075
|
+
"claude",
|
|
3076
|
+
"qoder",
|
|
3077
|
+
"grok",
|
|
3078
|
+
"kimi"
|
|
3079
|
+
]);
|
|
3080
|
+
var cliSessions = new Map;
|
|
3081
|
+
function getCliProviderLabel(provider) {
|
|
3082
|
+
switch (provider) {
|
|
3083
|
+
case "claude":
|
|
3084
|
+
return "Claude CLI";
|
|
3085
|
+
case "codex":
|
|
3086
|
+
return "Codex CLI";
|
|
3087
|
+
case "copilot":
|
|
3088
|
+
return "Copilot CLI";
|
|
3089
|
+
case "agy":
|
|
3090
|
+
return "Antigravity CLI";
|
|
3091
|
+
case "qoder":
|
|
3092
|
+
return "Qoder CLI";
|
|
3093
|
+
case "gemini":
|
|
3094
|
+
return "Gemini CLI";
|
|
3095
|
+
case "opencode":
|
|
3096
|
+
return "OpenCode CLI";
|
|
3097
|
+
case "grok":
|
|
3098
|
+
return "Grok CLI";
|
|
3099
|
+
case "kimi":
|
|
3100
|
+
return "Kimi Code CLI";
|
|
3101
|
+
}
|
|
3102
|
+
}
|
|
3103
|
+
function supportsNativeSystemPrompt(provider) {
|
|
3104
|
+
return provider === "claude";
|
|
3105
|
+
}
|
|
3106
|
+
function supportsModel(provider) {
|
|
3107
|
+
return provider !== "codex";
|
|
3108
|
+
}
|
|
3109
|
+
function supportsReasoningEffort(provider) {
|
|
3110
|
+
return provider === "claude" || provider === "copilot" || provider === "qoder" || provider === "opencode" || provider === "grok" || provider === "agy";
|
|
3111
|
+
}
|
|
3112
|
+
function mapAgyEffort(effort) {
|
|
3113
|
+
return effort === "ultra" ? "max" : effort;
|
|
3114
|
+
}
|
|
3115
|
+
function pushAgyEffortArgs(args, model, effort) {
|
|
3116
|
+
if (!effort)
|
|
3117
|
+
return;
|
|
3118
|
+
if (hasReasoningEffortSuffix(model))
|
|
3119
|
+
return;
|
|
3120
|
+
args.push("--effort", mapAgyEffort(effort));
|
|
3121
|
+
}
|
|
3122
|
+
function normalizeAgyUsage(raw) {
|
|
3123
|
+
if (!raw || typeof raw !== "object")
|
|
3124
|
+
return;
|
|
3125
|
+
const u = raw;
|
|
3126
|
+
const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
3127
|
+
const input = num(u.input_tokens);
|
|
3128
|
+
const output = num(u.output_tokens);
|
|
3129
|
+
const total = num(u.total_tokens);
|
|
3130
|
+
const cacheRead = num(u.cache_read_tokens);
|
|
3131
|
+
if (input === undefined && output === undefined && total === undefined && cacheRead === undefined) {
|
|
3132
|
+
return;
|
|
3133
|
+
}
|
|
3134
|
+
return {
|
|
3135
|
+
...input !== undefined ? { input_tokens: input } : {},
|
|
3136
|
+
...output !== undefined ? { output_tokens: output } : {},
|
|
3137
|
+
...total !== undefined ? { total_tokens: total } : {},
|
|
3138
|
+
...cacheRead !== undefined ? { cache_read_input_tokens: cacheRead } : {}
|
|
3139
|
+
};
|
|
3140
|
+
}
|
|
3141
|
+
function parseAgyJsonResult(raw) {
|
|
3142
|
+
let last;
|
|
3143
|
+
for (const line of raw.split(`
|
|
3144
|
+
`)) {
|
|
3145
|
+
const trimmed = line.trim();
|
|
3146
|
+
if (!trimmed.startsWith("{"))
|
|
3147
|
+
continue;
|
|
3148
|
+
let parsed;
|
|
3149
|
+
try {
|
|
3150
|
+
parsed = JSON.parse(trimmed);
|
|
3151
|
+
} catch {
|
|
3152
|
+
continue;
|
|
3153
|
+
}
|
|
3154
|
+
if (!parsed || typeof parsed !== "object")
|
|
3155
|
+
continue;
|
|
3156
|
+
const obj = parsed;
|
|
3157
|
+
const response = typeof obj.response === "string" ? obj.response : undefined;
|
|
3158
|
+
const usage = normalizeAgyUsage(obj.usage);
|
|
3159
|
+
if (response === undefined && usage === undefined)
|
|
3160
|
+
continue;
|
|
3161
|
+
last = {
|
|
3162
|
+
...response !== undefined ? { response } : {},
|
|
3163
|
+
...usage ? { usage } : {}
|
|
3164
|
+
};
|
|
3165
|
+
}
|
|
3166
|
+
return last;
|
|
3167
|
+
}
|
|
3168
|
+
function shouldPassClaudeModel(options) {
|
|
3169
|
+
return (options.env?.NOLO_CLAUDE_CLI_ALLOW_MODEL ?? process.env.NOLO_CLAUDE_CLI_ALLOW_MODEL) === "1";
|
|
3170
|
+
}
|
|
3171
|
+
var DATA_URL_RE = /^data:image\/([\w.+-]+);base64,([A-Za-z0-9+/=]+)$/;
|
|
3172
|
+
var MIME_EXT = {
|
|
3173
|
+
png: ".png",
|
|
3174
|
+
jpeg: ".jpg",
|
|
3175
|
+
jpg: ".jpg",
|
|
3176
|
+
gif: ".gif",
|
|
3177
|
+
webp: ".webp",
|
|
3178
|
+
"svg+xml": ".svg",
|
|
3179
|
+
bmp: ".bmp",
|
|
3180
|
+
tiff: ".tiff",
|
|
3181
|
+
avif: ".avif"
|
|
3182
|
+
};
|
|
3183
|
+
function inferExtFromMime(extPart) {
|
|
3184
|
+
return MIME_EXT[extPart.toLowerCase().trim()] ?? ".bin";
|
|
3185
|
+
}
|
|
3186
|
+
var FILE_URL_RE = /^file:\/\/(.+)$/;
|
|
3187
|
+
function writeDataUrlToTempImage(dataUrl, tempDir, index) {
|
|
3188
|
+
const match = dataUrl.match(DATA_URL_RE);
|
|
3189
|
+
if (!match) {
|
|
3190
|
+
throw new Error(`Invalid data URL format for image #${index + 1}; expected data:image/<type>;base64,<data>`);
|
|
3191
|
+
}
|
|
3192
|
+
const [, mimeExt, b64] = match;
|
|
3193
|
+
const ext = inferExtFromMime(mimeExt);
|
|
3194
|
+
const filePath = join(tempDir, `image-${index + 1}${ext}`);
|
|
3195
|
+
writeFileSync3(filePath, Buffer.from(b64, "base64"));
|
|
3196
|
+
return filePath;
|
|
3197
|
+
}
|
|
3198
|
+
function materializeCliImageInputs(imageInputs, cwd) {
|
|
3199
|
+
let tempDir = null;
|
|
3200
|
+
const materialized = imageInputs.map((input, index) => {
|
|
3201
|
+
const src = input.source.trim();
|
|
3202
|
+
if (src.startsWith("http://") || src.startsWith("https://")) {
|
|
3203
|
+
return { ...input, materializedPath: undefined };
|
|
3204
|
+
}
|
|
3205
|
+
const fileUrlMatch = src.match(FILE_URL_RE);
|
|
3206
|
+
if (fileUrlMatch) {
|
|
3207
|
+
const localPath = fileUrlMatch[1];
|
|
3208
|
+
return {
|
|
3209
|
+
...input,
|
|
3210
|
+
materializedPath: isAbsolute3(localPath) ? localPath : resolve3(cwd, localPath)
|
|
3211
|
+
};
|
|
3212
|
+
}
|
|
3213
|
+
if (src.startsWith("data:")) {
|
|
3214
|
+
if (!tempDir) {
|
|
3215
|
+
tempDir = mkdtempSync(join(tmpdir(), "nolo-cli-assets-"));
|
|
3216
|
+
}
|
|
3217
|
+
const filePath = writeDataUrlToTempImage(src, tempDir, index);
|
|
3218
|
+
return { ...input, materializedPath: filePath };
|
|
3219
|
+
}
|
|
3220
|
+
return {
|
|
3221
|
+
...input,
|
|
3222
|
+
materializedPath: isAbsolute3(src) ? src : resolve3(cwd, src)
|
|
3223
|
+
};
|
|
3224
|
+
});
|
|
3225
|
+
return { materialized, tempDir };
|
|
3226
|
+
}
|
|
3227
|
+
function buildImageReferencePromptBlock(provider, materialized) {
|
|
3228
|
+
const label = getCliProviderLabel(provider);
|
|
3229
|
+
const localPaths = materialized.filter((img) => img.materializedPath).map((img) => img.materializedPath);
|
|
3230
|
+
const httpUrls = materialized.filter((img) => !img.materializedPath).map((img) => img.source);
|
|
3231
|
+
const lines = [];
|
|
3232
|
+
if (localPaths.length > 0) {
|
|
3233
|
+
lines.push(`[User attached image(s) - local file references (accessible at these paths):]`, ...localPaths.map((p) => ` - ${p}`), `Please read and analyze these image files as part of the user's request.`);
|
|
3234
|
+
}
|
|
3235
|
+
if (httpUrls.length > 0) {
|
|
3236
|
+
lines.push(`[User attached image(s) - remote URLs (content not available locally):]`, ...httpUrls.map((u) => ` - ${u}`), `These remote URLs could not be downloaded automatically. If you cannot access them, describe what you can infer from context.`);
|
|
3237
|
+
}
|
|
3238
|
+
const warning = materialized.length > 0 ? `${label} image input is passed as local file references; native image flags are not available in this wrapper.` : null;
|
|
3239
|
+
return {
|
|
3240
|
+
promptSuffix: lines.length > 0 ? lines.join(`
|
|
3241
|
+
`) + `
|
|
3242
|
+
|
|
3243
|
+
` : "",
|
|
3244
|
+
warning
|
|
3245
|
+
};
|
|
3246
|
+
}
|
|
3247
|
+
function collectCliCapabilityWarnings(provider, options) {
|
|
3248
|
+
const warnings = [];
|
|
3249
|
+
const label = getCliProviderLabel(provider);
|
|
3250
|
+
if (options.reasoningEffort !== undefined && !supportsReasoningEffort(provider)) {
|
|
3251
|
+
warnings.push(`${label} does not support reasoning_effort; ignored.`);
|
|
3252
|
+
}
|
|
3253
|
+
if (provider === "claude" && options.model !== undefined && !shouldPassClaudeModel(options)) {
|
|
3254
|
+
warnings.push("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.");
|
|
3255
|
+
} else if (options.model !== undefined && !supportsModel(provider)) {
|
|
3256
|
+
warnings.push(`${label} does not support model selection; ignored.`);
|
|
3257
|
+
}
|
|
3258
|
+
const unsupportedFields = [
|
|
3259
|
+
["temperature", options.temperature],
|
|
3260
|
+
["top_p", options.topP],
|
|
3261
|
+
["frequency_penalty", options.frequencyPenalty],
|
|
3262
|
+
["presence_penalty", options.presencePenalty],
|
|
3263
|
+
["max_tokens", options.maxTokens],
|
|
3264
|
+
["enableThinking", options.enableThinking ? true : undefined],
|
|
3265
|
+
["thinkingBudget", options.thinkingBudget]
|
|
3266
|
+
];
|
|
3267
|
+
for (const [field, value] of unsupportedFields) {
|
|
3268
|
+
if (value !== undefined) {
|
|
3269
|
+
warnings.push(`${label} does not support ${field}; ignored.`);
|
|
3270
|
+
}
|
|
3271
|
+
}
|
|
3272
|
+
return warnings;
|
|
3273
|
+
}
|
|
3274
|
+
function resolveCliExecution(provider, prompt, options) {
|
|
3275
|
+
const warnings = collectCliCapabilityWarnings(provider, options);
|
|
3276
|
+
const imageInputs = options.imageInputs ?? [];
|
|
3277
|
+
let resolvedPrompt = prompt;
|
|
3278
|
+
let resolvedOptions = options;
|
|
3279
|
+
let imageTempDir;
|
|
3280
|
+
if (imageInputs.length > 0) {
|
|
3281
|
+
const { materialized, tempDir } = materializeCliImageInputs(imageInputs, options.cwd ?? process.cwd());
|
|
3282
|
+
imageTempDir = tempDir ?? undefined;
|
|
3283
|
+
if (provider === "codex") {
|
|
3284
|
+
resolvedOptions = {
|
|
3285
|
+
...resolvedOptions,
|
|
3286
|
+
imageInputs: materialized
|
|
3287
|
+
};
|
|
3288
|
+
} else {
|
|
3289
|
+
const block = buildImageReferencePromptBlock(provider, materialized);
|
|
3290
|
+
if (block.promptSuffix) {
|
|
3291
|
+
resolvedPrompt = block.promptSuffix + resolvedPrompt;
|
|
3292
|
+
}
|
|
3293
|
+
if (block.warning) {
|
|
3294
|
+
warnings.push(block.warning);
|
|
3295
|
+
}
|
|
3296
|
+
}
|
|
3297
|
+
}
|
|
3298
|
+
if (supportsNativeSystemPrompt(provider) || !options.systemPrompt?.trim()) {
|
|
3299
|
+
return { prompt: resolvedPrompt, options: resolvedOptions, warnings, imageTempDir };
|
|
3300
|
+
}
|
|
3301
|
+
return {
|
|
3302
|
+
prompt: buildCliPrompt(options.systemPrompt, resolvedPrompt),
|
|
3303
|
+
options: {
|
|
3304
|
+
...resolvedOptions,
|
|
3305
|
+
systemPrompt: undefined
|
|
3306
|
+
},
|
|
3307
|
+
warnings,
|
|
3308
|
+
imageTempDir
|
|
3309
|
+
};
|
|
3310
|
+
}
|
|
3311
|
+
function executeCopilot(prompt, options) {
|
|
3312
|
+
const {
|
|
3313
|
+
model,
|
|
3314
|
+
reasoningEffort,
|
|
3315
|
+
timeout = 120000,
|
|
3316
|
+
cwd = process.cwd(),
|
|
3317
|
+
yolo = true
|
|
3318
|
+
} = options;
|
|
3319
|
+
return new Promise((resolve, reject) => {
|
|
3320
|
+
const args = [
|
|
3321
|
+
"copilot",
|
|
3322
|
+
"--",
|
|
3323
|
+
"-p",
|
|
3324
|
+
prompt,
|
|
3325
|
+
"--silent",
|
|
3326
|
+
"--disable-builtin-mcps",
|
|
3327
|
+
"--stream",
|
|
3328
|
+
"off",
|
|
3329
|
+
"--no-color"
|
|
3330
|
+
];
|
|
3331
|
+
if (model)
|
|
3332
|
+
args.push("--model", model);
|
|
3333
|
+
if (reasoningEffort)
|
|
3334
|
+
args.push("--reasoning-effort", reasoningEffort);
|
|
3335
|
+
if (yolo)
|
|
3336
|
+
args.push("--yolo");
|
|
3337
|
+
runBufferedCli("Copilot", "gh", args, cwd, { ...buildCliProcessEnv2(options.env), NO_COLOR: "1" }, timeout, options.signal, (stdout) => stdout.split(`
|
|
3338
|
+
`).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(`
|
|
3339
|
+
`).trim()).then(resolve, reject);
|
|
3340
|
+
});
|
|
3341
|
+
}
|
|
3342
|
+
function normalizeGeminiContent(content) {
|
|
3343
|
+
if (typeof content === "string")
|
|
3344
|
+
return content;
|
|
3345
|
+
if (Array.isArray(content)) {
|
|
3346
|
+
return content.map((part) => {
|
|
3347
|
+
if (typeof part === "string")
|
|
3348
|
+
return part;
|
|
3349
|
+
if (part && typeof part === "object" && typeof part.text === "string") {
|
|
3350
|
+
return part.text;
|
|
3351
|
+
}
|
|
3352
|
+
return "";
|
|
3353
|
+
}).join("");
|
|
3354
|
+
}
|
|
3355
|
+
if (content && typeof content === "object" && typeof content.text === "string") {
|
|
3356
|
+
return content.text;
|
|
3357
|
+
}
|
|
3358
|
+
return "";
|
|
3359
|
+
}
|
|
3360
|
+
function extractGeminiEventText(event) {
|
|
3361
|
+
if (event?.type === "message" && event.role === "assistant") {
|
|
3362
|
+
return normalizeGeminiContent(event.content);
|
|
3363
|
+
}
|
|
3364
|
+
if (event?.type === "result" && typeof event.result === "string") {
|
|
3365
|
+
return event.result;
|
|
3366
|
+
}
|
|
3367
|
+
return "";
|
|
3368
|
+
}
|
|
3369
|
+
function parseGeminiStreamJson(stdout) {
|
|
3370
|
+
const parts = [];
|
|
3371
|
+
for (const line of stdout.split(`
|
|
3372
|
+
`)) {
|
|
3373
|
+
const trimmed = line.trim();
|
|
3374
|
+
if (!trimmed)
|
|
3375
|
+
continue;
|
|
3376
|
+
try {
|
|
3377
|
+
const event = JSON.parse(trimmed);
|
|
3378
|
+
const text = extractGeminiEventText(event);
|
|
3379
|
+
if (text)
|
|
3380
|
+
parts.push(text);
|
|
3381
|
+
} catch {}
|
|
3382
|
+
}
|
|
3383
|
+
return parts.join("");
|
|
3384
|
+
}
|
|
3385
|
+
function resolveGeminiCommand(env, platform = process.platform) {
|
|
3386
|
+
if (platform !== "win32")
|
|
3387
|
+
return { command: "gemini", args: [] };
|
|
3388
|
+
const path = Object.entries(env).find(([key]) => key.toLowerCase() === "path")?.[1] ?? "";
|
|
3389
|
+
for (const directory of path.split(";")) {
|
|
3390
|
+
if (!directory || !isAbsolute3(directory))
|
|
3391
|
+
continue;
|
|
3392
|
+
if (existsSync4(join(directory, "gemini.exe"))) {
|
|
3393
|
+
return { command: join(directory, "gemini.exe"), args: [] };
|
|
3394
|
+
}
|
|
3395
|
+
if (!existsSync4(join(directory, "gemini.cmd")))
|
|
3396
|
+
continue;
|
|
3397
|
+
try {
|
|
3398
|
+
const root = realpathSync3(join(directory, "node_modules", "@google", "gemini-cli"));
|
|
3399
|
+
const manifest = JSON.parse(readFileSync4(join(root, "package.json"), "utf8"));
|
|
3400
|
+
const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.gemini;
|
|
3401
|
+
if (manifest.name !== "@google/gemini-cli" || typeof bin !== "string" || !bin) {
|
|
3402
|
+
throw new Error("missing package bin");
|
|
3403
|
+
}
|
|
3404
|
+
const entry = realpathSync3(resolve3(root, bin));
|
|
3405
|
+
const withinPackage = relative3(root, entry);
|
|
3406
|
+
if (withinPackage.startsWith("..") || isAbsolute3(withinPackage) || !/\.[cm]?js$/i.test(entry)) {
|
|
3407
|
+
throw new Error("package bin is not a contained JavaScript entry");
|
|
3408
|
+
}
|
|
3409
|
+
const node = join(directory, "node.exe");
|
|
3410
|
+
return { command: existsSync4(node) ? node : "node", args: [entry] };
|
|
3411
|
+
} catch (error) {
|
|
3412
|
+
throw new Error(`Gemini npm entry could not be resolved: ${String(error)}`);
|
|
3413
|
+
}
|
|
3414
|
+
}
|
|
3415
|
+
return { command: "gemini", args: [] };
|
|
3416
|
+
}
|
|
3417
|
+
function executeGemini(prompt, options) {
|
|
3418
|
+
const {
|
|
3419
|
+
model = "gemini-3.8-flash",
|
|
3420
|
+
timeout = 120000,
|
|
3421
|
+
cwd = process.cwd(),
|
|
3422
|
+
yolo = true
|
|
3423
|
+
} = options;
|
|
3424
|
+
return new Promise((resolve, reject) => {
|
|
3425
|
+
const args = [
|
|
3426
|
+
"-p",
|
|
3427
|
+
prompt,
|
|
3428
|
+
"--output-format",
|
|
3429
|
+
"stream-json",
|
|
3430
|
+
"-m",
|
|
3431
|
+
model
|
|
3432
|
+
];
|
|
3433
|
+
if (yolo)
|
|
3434
|
+
args.push("--yolo");
|
|
3435
|
+
args.push("-e", "none");
|
|
3436
|
+
const env = { ...buildCliProcessEnv2(options.env), NO_COLOR: "1", NODE_OPTIONS: "--no-deprecation" };
|
|
3437
|
+
const launcher = resolveGeminiCommand(env);
|
|
3438
|
+
runBufferedCli("Gemini", launcher.command, [...launcher.args, ...args], cwd, env, timeout, options.signal, parseGeminiStreamJson).then(resolve, reject);
|
|
3439
|
+
});
|
|
3440
|
+
}
|
|
3441
|
+
function executeCodex(prompt, options) {
|
|
3442
|
+
const {
|
|
3443
|
+
cwd = process.cwd(),
|
|
3444
|
+
yolo = true
|
|
3445
|
+
} = options;
|
|
3446
|
+
const imagePaths = (options.imageInputs ?? []).map((img) => img.materializedPath).filter((p) => Boolean(p));
|
|
3447
|
+
return new Promise((resolve, reject) => {
|
|
3448
|
+
const tempDir = mkdtempSync(join(tmpdir(), "codex-exec-"));
|
|
3449
|
+
const outputFile = join(tempDir, "last-message.txt");
|
|
3450
|
+
const executable = resolveLaunchableCodexCommand(options.env);
|
|
3451
|
+
const args = [
|
|
3452
|
+
"exec",
|
|
3453
|
+
"--skip-git-repo-check",
|
|
3454
|
+
"--ephemeral",
|
|
3455
|
+
"--color",
|
|
3456
|
+
"never",
|
|
3457
|
+
"--output-last-message",
|
|
3458
|
+
outputFile,
|
|
3459
|
+
"--cd",
|
|
3460
|
+
cwd
|
|
3461
|
+
];
|
|
3462
|
+
if (yolo) {
|
|
3463
|
+
args.push("--sandbox");
|
|
3464
|
+
args.push("danger-full-access");
|
|
3465
|
+
}
|
|
3466
|
+
for (const imgPath of imagePaths) {
|
|
3467
|
+
args.push("-i", imgPath);
|
|
3468
|
+
}
|
|
3469
|
+
const start = Date.now();
|
|
3470
|
+
const proc = spawnCliProcess(executable, [...args, prompt], {
|
|
3471
|
+
cwd,
|
|
3472
|
+
env: buildCliProcessEnv2(options.env),
|
|
3473
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3474
|
+
signal: options.signal
|
|
3475
|
+
}, reject);
|
|
3476
|
+
const stdout = createUtf8Collector();
|
|
3477
|
+
const stderr = createUtf8Collector();
|
|
3478
|
+
proc.stdout.on("data", (data) => {
|
|
3479
|
+
stdout.write(data);
|
|
3480
|
+
});
|
|
3481
|
+
proc.stderr.on("data", (data) => {
|
|
3482
|
+
stderr.write(data);
|
|
3483
|
+
});
|
|
3484
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
3485
|
+
const stdoutText = stdout.end();
|
|
3486
|
+
const stderrText = stderr.end();
|
|
3487
|
+
if (code !== 0 && code !== null) {
|
|
3488
|
+
rmSync(tempDir, { recursive: true, force: true });
|
|
3489
|
+
const quota = detectCliProviderQuotaLimit2("codex", stdoutText, stderrText, code);
|
|
3490
|
+
if (quota.limited) {
|
|
3491
|
+
reject(new CliProviderQuotaError2("codex", quota.message || "Codex reported quota/limit"));
|
|
3492
|
+
return;
|
|
3493
|
+
}
|
|
3494
|
+
reject(new Error(`Codex CLI exited with code ${code}
|
|
3495
|
+
stderr: ${stderrText}`));
|
|
3496
|
+
return;
|
|
3497
|
+
}
|
|
3498
|
+
let text = stdoutText.trim();
|
|
3499
|
+
try {
|
|
3500
|
+
const lastMessage = readFileSync4(outputFile, "utf8").trim();
|
|
3501
|
+
if (lastMessage)
|
|
3502
|
+
text = lastMessage;
|
|
3503
|
+
} catch {} finally {
|
|
3504
|
+
rmSync(tempDir, { recursive: true, force: true });
|
|
3505
|
+
}
|
|
3506
|
+
resolve({
|
|
3507
|
+
text,
|
|
3508
|
+
raw: stdoutText,
|
|
3509
|
+
elapsed: Date.now() - start
|
|
3510
|
+
});
|
|
3511
|
+
});
|
|
3512
|
+
proc.on("error", (err) => {
|
|
3513
|
+
rmSync(tempDir, { recursive: true, force: true });
|
|
3514
|
+
reject(proc.pid ? stoppingCliError(err, proc) : err);
|
|
3515
|
+
});
|
|
3516
|
+
});
|
|
3517
|
+
}
|
|
3518
|
+
function executeClaude(prompt, options) {
|
|
3519
|
+
const {
|
|
3520
|
+
model,
|
|
3521
|
+
systemPrompt,
|
|
3522
|
+
reasoningEffort,
|
|
3523
|
+
timeout = 120000,
|
|
3524
|
+
cwd = process.cwd(),
|
|
3525
|
+
yolo = true
|
|
3526
|
+
} = options;
|
|
3527
|
+
return new Promise((resolve, reject) => {
|
|
3528
|
+
const args = ["--add-dir", cwd, "-p", prompt];
|
|
3529
|
+
if (model && shouldPassClaudeModel(options)) {
|
|
3530
|
+
args.push("--model");
|
|
3531
|
+
args.push(model);
|
|
3532
|
+
}
|
|
3533
|
+
if (systemPrompt?.trim()) {
|
|
3534
|
+
args.push("--system-prompt");
|
|
3535
|
+
args.push(systemPrompt.trim());
|
|
3536
|
+
}
|
|
3537
|
+
if (reasoningEffort) {
|
|
3538
|
+
args.push("--effort");
|
|
3539
|
+
args.push(reasoningEffort);
|
|
3540
|
+
}
|
|
3541
|
+
if (yolo) {
|
|
3542
|
+
args.push("--permission-mode");
|
|
3543
|
+
args.push("bypassPermissions");
|
|
3544
|
+
}
|
|
3545
|
+
const start = Date.now();
|
|
3546
|
+
const proc = spawnCliProcess("claude", args, {
|
|
3547
|
+
cwd,
|
|
3548
|
+
env: buildCliProcessEnv2(options.env),
|
|
3549
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3550
|
+
signal: options.signal
|
|
3551
|
+
}, reject);
|
|
3552
|
+
const stdout = createUtf8Collector();
|
|
3553
|
+
const stderr = createUtf8Collector();
|
|
3554
|
+
let timer;
|
|
3555
|
+
if (timeout > 0) {
|
|
3556
|
+
timer = setTimeout(() => {
|
|
3557
|
+
reject(stoppingCliError(new Error(`Claude CLI timed out after ${timeout}ms`), proc));
|
|
3558
|
+
}, timeout);
|
|
3559
|
+
}
|
|
3560
|
+
proc.stdout.on("data", (data) => {
|
|
3561
|
+
stdout.write(data);
|
|
3562
|
+
});
|
|
3563
|
+
proc.stderr.on("data", (data) => {
|
|
3564
|
+
stderr.write(data);
|
|
3565
|
+
});
|
|
3566
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
3567
|
+
if (timer)
|
|
3568
|
+
clearTimeout(timer);
|
|
3569
|
+
const stdoutText = stdout.end();
|
|
3570
|
+
const stderrText = stderr.end();
|
|
3571
|
+
if (code !== 0 && code !== null) {
|
|
3572
|
+
const quota = detectCliProviderQuotaLimit2("claude", stdoutText, stderrText, code);
|
|
3573
|
+
if (quota.limited) {
|
|
3574
|
+
reject(new CliProviderQuotaError2("claude", quota.message || "Claude reported quota/limit"));
|
|
3575
|
+
return;
|
|
3576
|
+
}
|
|
3577
|
+
reject(new Error(`Claude CLI exited with code ${code}
|
|
3578
|
+
stderr: ${stderrText}`));
|
|
3579
|
+
return;
|
|
3580
|
+
}
|
|
3581
|
+
resolve({
|
|
3582
|
+
text: stdoutText.trim(),
|
|
3583
|
+
raw: stdoutText,
|
|
3584
|
+
elapsed: Date.now() - start
|
|
3585
|
+
});
|
|
3586
|
+
});
|
|
3587
|
+
proc.on("error", (err) => {
|
|
3588
|
+
if (timer)
|
|
3589
|
+
clearTimeout(timer);
|
|
3590
|
+
reject(proc.pid ? stoppingCliError(err, proc) : err);
|
|
3591
|
+
});
|
|
3592
|
+
});
|
|
3593
|
+
}
|
|
3594
|
+
function formatCliTimeout(timeoutMs) {
|
|
3595
|
+
return `${Math.max(1, Math.ceil(timeoutMs / 1000))}s`;
|
|
3596
|
+
}
|
|
3597
|
+
function tailText(value, maxChars = 1200) {
|
|
3598
|
+
if (value.length <= maxChars)
|
|
3599
|
+
return value;
|
|
3600
|
+
return value.slice(value.length - maxChars);
|
|
3601
|
+
}
|
|
3602
|
+
function createUtf8Collector() {
|
|
3603
|
+
const decoder = new StringDecoder3("utf8");
|
|
3604
|
+
let text = "";
|
|
3605
|
+
let ended = false;
|
|
3606
|
+
const finish = () => {
|
|
3607
|
+
if (ended)
|
|
3608
|
+
return "";
|
|
3609
|
+
ended = true;
|
|
3610
|
+
const chunk = decoder.end();
|
|
3611
|
+
if (chunk)
|
|
3612
|
+
text += chunk;
|
|
3613
|
+
return chunk;
|
|
3614
|
+
};
|
|
3615
|
+
return {
|
|
3616
|
+
write(data) {
|
|
3617
|
+
if (ended)
|
|
3618
|
+
return "";
|
|
3619
|
+
const chunk = decoder.write(data);
|
|
3620
|
+
text += chunk;
|
|
3621
|
+
return chunk;
|
|
3622
|
+
},
|
|
3623
|
+
finish,
|
|
3624
|
+
end() {
|
|
3625
|
+
finish();
|
|
3626
|
+
return text;
|
|
3627
|
+
},
|
|
3628
|
+
get text() {
|
|
3629
|
+
return text;
|
|
3630
|
+
}
|
|
3631
|
+
};
|
|
3632
|
+
}
|
|
3633
|
+
var CLI_ABORT_SIGKILL_GRACE_MS = 5000;
|
|
3634
|
+
function terminateCliProcessGroup(proc, signal, onWindowsTreeStopped) {
|
|
3635
|
+
const pid = typeof proc.pid === "number" ? proc.pid : 0;
|
|
3636
|
+
if (pid > 0 && process.platform !== "win32") {
|
|
3637
|
+
try {
|
|
3638
|
+
process.kill(-pid, signal);
|
|
3639
|
+
return;
|
|
3640
|
+
} catch {}
|
|
3641
|
+
}
|
|
3642
|
+
if (pid > 0 && process.platform === "win32") {
|
|
3643
|
+
try {
|
|
3644
|
+
const killer = spawn4("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
|
3645
|
+
stdio: "ignore",
|
|
3646
|
+
windowsHide: true
|
|
3647
|
+
});
|
|
3648
|
+
killer.on("error", () => {});
|
|
3649
|
+
killer.once("close", (code) => {
|
|
3650
|
+
if (code === 0)
|
|
3651
|
+
onWindowsTreeStopped();
|
|
3652
|
+
});
|
|
3653
|
+
return;
|
|
3654
|
+
} catch {}
|
|
3655
|
+
}
|
|
3656
|
+
try {
|
|
3657
|
+
proc.kill(signal);
|
|
3658
|
+
} catch {}
|
|
3659
|
+
}
|
|
3660
|
+
var executionStopped = Symbol.for("nolo.cli.executionStopped");
|
|
3661
|
+
function attachExecutionStoppedPromise2(error, stoppedPromise) {
|
|
3662
|
+
Object.defineProperty(error, executionStopped, { value: stoppedPromise, configurable: true, enumerable: true });
|
|
3663
|
+
return error;
|
|
3664
|
+
}
|
|
3665
|
+
function getExecutionStoppedPromise2(error) {
|
|
3666
|
+
const seen = new Set;
|
|
3667
|
+
const visit = (value) => {
|
|
3668
|
+
if (typeof value !== "object" || value === null || seen.has(value))
|
|
3669
|
+
return;
|
|
3670
|
+
seen.add(value);
|
|
3671
|
+
const entry = value;
|
|
3672
|
+
if (entry[executionStopped])
|
|
3673
|
+
return entry[executionStopped];
|
|
3674
|
+
const pending = [visit(entry.cause), ...value instanceof AggregateError ? value.errors.map(visit) : []].filter((promise) => promise !== undefined);
|
|
3675
|
+
return pending.length ? Promise.all(pending).then(() => {}) : undefined;
|
|
3676
|
+
};
|
|
3677
|
+
return visit(error);
|
|
3678
|
+
}
|
|
3679
|
+
var unconfirmedWindowsClose = new Promise(() => {});
|
|
3680
|
+
var stoppingProcesses = new WeakMap;
|
|
3681
|
+
function terminateCliProcessGroupEscalating2(proc) {
|
|
3682
|
+
const existing = stoppingProcesses.get(proc);
|
|
3683
|
+
if (existing)
|
|
3684
|
+
return existing;
|
|
3685
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
3686
|
+
stoppingProcesses.set(proc, promise);
|
|
3687
|
+
const pid = proc.pid;
|
|
3688
|
+
if (!pid) {
|
|
3689
|
+
terminateCliProcessGroup(proc, "SIGTERM", () => {});
|
|
3690
|
+
resolve();
|
|
3691
|
+
return promise;
|
|
3692
|
+
}
|
|
3693
|
+
const startedAt = performance.now();
|
|
3694
|
+
let escalated = false;
|
|
3695
|
+
let windowsTreeStopped = false;
|
|
3696
|
+
const markWindowsTreeStopped = () => {
|
|
3697
|
+
windowsTreeStopped = true;
|
|
3698
|
+
};
|
|
3699
|
+
let timer;
|
|
3700
|
+
const inspect = () => {
|
|
3701
|
+
let groupEmpty = windowsTreeStopped;
|
|
3702
|
+
if (process.platform !== "win32") {
|
|
3703
|
+
try {
|
|
3704
|
+
process.kill(-pid, 0);
|
|
3705
|
+
} catch (error) {
|
|
3706
|
+
groupEmpty = error.code === "ESRCH";
|
|
3707
|
+
}
|
|
3708
|
+
}
|
|
3709
|
+
if (groupEmpty && (proc.exitCode != null || proc.signalCode != null)) {
|
|
3710
|
+
clearInterval(timer);
|
|
3711
|
+
resolve();
|
|
3712
|
+
return;
|
|
3713
|
+
}
|
|
3714
|
+
const elapsed = performance.now() - startedAt;
|
|
3715
|
+
if (!escalated && elapsed >= CLI_ABORT_SIGKILL_GRACE_MS) {
|
|
3716
|
+
escalated = true;
|
|
3717
|
+
terminateCliProcessGroup(proc, "SIGKILL", markWindowsTreeStopped);
|
|
3718
|
+
}
|
|
3719
|
+
if (elapsed >= CLI_ABORT_SIGKILL_GRACE_MS + 1e4) {
|
|
3720
|
+
clearInterval(timer);
|
|
3721
|
+
console.warn("[cliExecutor] Could not confirm CLI process group shutdown", { pid });
|
|
3722
|
+
}
|
|
3723
|
+
};
|
|
3724
|
+
terminateCliProcessGroup(proc, "SIGTERM", markWindowsTreeStopped);
|
|
3725
|
+
timer = setInterval(inspect, 25);
|
|
3726
|
+
timer.unref?.();
|
|
3727
|
+
inspect();
|
|
3728
|
+
return promise;
|
|
3729
|
+
}
|
|
3730
|
+
function onCliClose(proc, resolve, reject, settle) {
|
|
3731
|
+
proc.on("close", (code, signal) => {
|
|
3732
|
+
let stopped = stoppingProcesses.get(proc);
|
|
3733
|
+
if (!stopped && proc.pid && process.platform === "win32") {
|
|
3734
|
+
stopped = unconfirmedWindowsClose;
|
|
3735
|
+
} else if (!stopped && proc.pid) {
|
|
3736
|
+
try {
|
|
3737
|
+
process.kill(-proc.pid, 0);
|
|
3738
|
+
stopped = terminateCliProcessGroupEscalating2(proc);
|
|
3739
|
+
} catch (error) {
|
|
3740
|
+
if (error.code !== "ESRCH")
|
|
3741
|
+
stopped = terminateCliProcessGroupEscalating2(proc);
|
|
3742
|
+
}
|
|
3743
|
+
}
|
|
3744
|
+
const annotate = (value) => stopped ? attachExecutionStoppedPromise2(value, stopped) : value;
|
|
3745
|
+
settle((value) => resolve(annotate(value)), (error) => reject(stopped ? annotate(error instanceof Error ? error : new Error(String(error))) : error), code, signal);
|
|
3746
|
+
});
|
|
3747
|
+
}
|
|
3748
|
+
function stoppingCliError(error, proc) {
|
|
3749
|
+
return attachExecutionStoppedPromise2(error instanceof Error ? error : new Error(String(error)), terminateCliProcessGroupEscalating2(proc));
|
|
3750
|
+
}
|
|
3751
|
+
function createCliAbortError(message = "CLI execution aborted") {
|
|
3752
|
+
return new DOMException(message, "AbortError");
|
|
3753
|
+
}
|
|
3754
|
+
function attachCliAbortSignal(proc, signal, onAbort) {
|
|
3755
|
+
if (!signal)
|
|
3756
|
+
return () => {};
|
|
3757
|
+
const handleAbort = () => onAbort(stoppingCliError(createCliAbortError(), proc));
|
|
3758
|
+
if (signal.aborted) {
|
|
3759
|
+
handleAbort();
|
|
3760
|
+
return () => {};
|
|
3761
|
+
}
|
|
3762
|
+
signal.addEventListener("abort", handleAbort, { once: true });
|
|
3763
|
+
return () => signal.removeEventListener("abort", handleAbort);
|
|
3764
|
+
}
|
|
3765
|
+
function spawnCliProcess(executable, args, options, onAbort) {
|
|
3766
|
+
const { signal, ...spawnOptions } = options;
|
|
3767
|
+
const proc = spawn4(executable, args, {
|
|
3768
|
+
...spawnOptions,
|
|
3769
|
+
detached: process.platform !== "win32"
|
|
3770
|
+
});
|
|
3771
|
+
if (signal) {
|
|
3772
|
+
const detachAbort = attachCliAbortSignal(proc, signal, onAbort ?? (() => {}));
|
|
3773
|
+
proc.once("exit", detachAbort);
|
|
3774
|
+
}
|
|
3775
|
+
return proc;
|
|
3776
|
+
}
|
|
3777
|
+
function runBufferedCli(label, executable, args, cwd, env, timeout, signal, parseText) {
|
|
3778
|
+
return new Promise((resolve, reject) => {
|
|
3779
|
+
const start = Date.now();
|
|
3780
|
+
const stdout = createUtf8Collector();
|
|
3781
|
+
const stderr = createUtf8Collector();
|
|
3782
|
+
let timer;
|
|
3783
|
+
const fail = (error) => {
|
|
3784
|
+
if (timer)
|
|
3785
|
+
clearTimeout(timer);
|
|
3786
|
+
reject(error);
|
|
3787
|
+
};
|
|
3788
|
+
const proc = spawnCliProcess(executable, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], signal }, fail);
|
|
3789
|
+
if (timeout > 0 && !signal?.aborted)
|
|
3790
|
+
timer = setTimeout(() => fail(stoppingCliError(new Error(`${label} CLI timed out after ${timeout}ms`), proc)), timeout);
|
|
3791
|
+
proc.stdout.on("data", (chunk) => stdout.write(chunk));
|
|
3792
|
+
proc.stderr.on("data", (chunk) => stderr.write(chunk));
|
|
3793
|
+
proc.on("error", (error) => fail(proc.pid ? stoppingCliError(error, proc) : error));
|
|
3794
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code, exitSignal) => {
|
|
3795
|
+
if (timer)
|
|
3796
|
+
clearTimeout(timer);
|
|
3797
|
+
if (code !== 0 || exitSignal) {
|
|
3798
|
+
reject(new Error(`${label} CLI failed: ${exitSignal ?? code}
|
|
3799
|
+
stderr: ${stderr.end()}`));
|
|
3800
|
+
return;
|
|
3801
|
+
}
|
|
3802
|
+
const raw = stdout.end();
|
|
3803
|
+
resolve({ text: parseText(raw), raw, elapsed: Date.now() - start });
|
|
3804
|
+
});
|
|
3805
|
+
});
|
|
3806
|
+
}
|
|
3807
|
+
function buildAgyTimeoutError(timeout, stdout, stderr) {
|
|
3808
|
+
const parts = [
|
|
3809
|
+
`Antigravity CLI timed out after ${timeout}ms.`,
|
|
3810
|
+
"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."
|
|
3811
|
+
];
|
|
3812
|
+
const stdoutTail = tailText(stdout).trim();
|
|
3813
|
+
const stderrTail = tailText(stderr).trim();
|
|
3814
|
+
if (stdoutTail)
|
|
3815
|
+
parts.push(`stdout tail:
|
|
3816
|
+
${stdoutTail}`);
|
|
3817
|
+
if (stderrTail)
|
|
3818
|
+
parts.push(`stderr tail:
|
|
3819
|
+
${stderrTail}`);
|
|
3820
|
+
return new Error(parts.join(`
|
|
3821
|
+
`));
|
|
3822
|
+
}
|
|
3823
|
+
function executeAgy(prompt, options) {
|
|
3824
|
+
const {
|
|
3825
|
+
timeout = DEFAULT_AGY_TIMEOUT_MS,
|
|
3826
|
+
cwd = process.cwd(),
|
|
3827
|
+
yolo = true,
|
|
3828
|
+
reasoningEffort
|
|
3829
|
+
} = options;
|
|
3830
|
+
const releasePrintSlot = acquireAgyPrintSlot("agy --print");
|
|
3831
|
+
let promise;
|
|
3832
|
+
try {
|
|
3833
|
+
promise = new Promise((resolve, reject) => {
|
|
3834
|
+
const args = [
|
|
3835
|
+
"--add-dir",
|
|
3836
|
+
cwd,
|
|
3837
|
+
"--print=" + prompt,
|
|
3838
|
+
"--output-format",
|
|
3839
|
+
"json",
|
|
3840
|
+
"--print-timeout",
|
|
3841
|
+
formatCliTimeout(timeout)
|
|
3842
|
+
];
|
|
3843
|
+
if (options.model)
|
|
3844
|
+
args.push("--model", options.model);
|
|
3845
|
+
pushAgyEffortArgs(args, options.model, reasoningEffort);
|
|
3846
|
+
if (yolo) {
|
|
3847
|
+
args.push("--dangerously-skip-permissions");
|
|
3848
|
+
}
|
|
3849
|
+
const start = Date.now();
|
|
3850
|
+
const proc = spawnCliProcess("agy", args, {
|
|
3851
|
+
cwd,
|
|
3852
|
+
env: buildCliProcessEnv2(options.env),
|
|
3853
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3854
|
+
detached: process.platform !== "win32",
|
|
3855
|
+
signal: options.signal
|
|
3856
|
+
}, reject);
|
|
3857
|
+
const stdout = createUtf8Collector();
|
|
3858
|
+
const stderr = createUtf8Collector();
|
|
3859
|
+
let timer;
|
|
3860
|
+
let settled = false;
|
|
3861
|
+
const clearTimers = () => {
|
|
3862
|
+
if (timer)
|
|
3863
|
+
clearTimeout(timer);
|
|
3864
|
+
};
|
|
3865
|
+
if (timeout > 0) {
|
|
3866
|
+
timer = setTimeout(() => {
|
|
3867
|
+
if (settled)
|
|
3868
|
+
return;
|
|
3869
|
+
settled = true;
|
|
3870
|
+
reject(stoppingCliError(buildAgyTimeoutError(timeout, stdout.end(), stderr.end()), proc));
|
|
3871
|
+
}, timeout + 1000);
|
|
3872
|
+
}
|
|
3873
|
+
proc.stdout.on("data", (data) => {
|
|
3874
|
+
stdout.write(data);
|
|
3875
|
+
});
|
|
3876
|
+
proc.stderr.on("data", (data) => {
|
|
3877
|
+
stderr.write(data);
|
|
3878
|
+
});
|
|
3879
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
3880
|
+
if (settled) {
|
|
3881
|
+
clearTimers();
|
|
3882
|
+
return;
|
|
3883
|
+
}
|
|
3884
|
+
settled = true;
|
|
3885
|
+
clearTimers();
|
|
3886
|
+
const stdoutText = stdout.end();
|
|
3887
|
+
const stderrText = stderr.end();
|
|
3888
|
+
if (code !== 0 && code !== null) {
|
|
3889
|
+
console.error("[cliExecutor] agy process exited with non-zero code:", code, "stderr:", stderrText);
|
|
3890
|
+
const quota = detectCliProviderQuotaLimit2("agy", stdoutText, stderrText, code);
|
|
3891
|
+
if (quota.limited) {
|
|
3892
|
+
reject(new CliProviderQuotaError2("agy", quota.message || "Agy reported quota/limit"));
|
|
3893
|
+
return;
|
|
3894
|
+
}
|
|
3895
|
+
reject(new Error(`Antigravity CLI exited with code ${code}
|
|
3896
|
+
stderr: ${stderrText}`));
|
|
3897
|
+
return;
|
|
3898
|
+
}
|
|
3899
|
+
const parsed = parseAgyJsonResult(stdoutText);
|
|
3900
|
+
resolve({
|
|
3901
|
+
text: (parsed?.response ?? stdoutText).trim(),
|
|
3902
|
+
raw: stdoutText,
|
|
3903
|
+
elapsed: Date.now() - start,
|
|
3904
|
+
...parsed?.usage ? { usage: parsed.usage } : {}
|
|
3905
|
+
});
|
|
3906
|
+
});
|
|
3907
|
+
proc.on("error", (err) => {
|
|
3908
|
+
if (settled)
|
|
3909
|
+
return;
|
|
3910
|
+
settled = true;
|
|
3911
|
+
clearTimers();
|
|
3912
|
+
console.error("[cliExecutor] agy process error event:", err);
|
|
3913
|
+
reject(proc.pid ? stoppingCliError(err, proc) : err);
|
|
3914
|
+
});
|
|
3915
|
+
});
|
|
3916
|
+
} catch (err) {
|
|
3917
|
+
releasePrintSlot();
|
|
3918
|
+
throw err;
|
|
3919
|
+
}
|
|
3920
|
+
return promise.finally(releasePrintSlot);
|
|
3921
|
+
}
|
|
3922
|
+
function executeAgyStreaming(prompt, options) {
|
|
3923
|
+
const {
|
|
3924
|
+
cwd = process.cwd(),
|
|
3925
|
+
timeout = DEFAULT_AGY_TIMEOUT_MS,
|
|
3926
|
+
yolo = true,
|
|
3927
|
+
model,
|
|
3928
|
+
reasoningEffort,
|
|
3929
|
+
onChunk
|
|
3930
|
+
} = options;
|
|
3931
|
+
const releasePrintSlot = acquireAgyPrintSlot("agy --print");
|
|
3932
|
+
let promise;
|
|
3933
|
+
try {
|
|
3934
|
+
promise = new Promise((resolve, reject) => {
|
|
3935
|
+
const args = [
|
|
3936
|
+
"--add-dir",
|
|
3937
|
+
cwd,
|
|
3938
|
+
"--print=" + prompt,
|
|
3939
|
+
"--output-format",
|
|
3940
|
+
"stream-json",
|
|
3941
|
+
"--print-timeout",
|
|
3942
|
+
formatCliTimeout(timeout)
|
|
3943
|
+
];
|
|
3944
|
+
if (model)
|
|
3945
|
+
args.push("--model", model);
|
|
3946
|
+
pushAgyEffortArgs(args, model, reasoningEffort);
|
|
3947
|
+
if (yolo)
|
|
3948
|
+
args.push("--dangerously-skip-permissions");
|
|
3949
|
+
const start = Date.now();
|
|
3950
|
+
const proc = spawnCliProcess("agy", args, {
|
|
3951
|
+
cwd,
|
|
3952
|
+
env: buildCliProcessEnv2(options.env),
|
|
3953
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3954
|
+
detached: process.platform !== "win32",
|
|
3955
|
+
signal: options.signal
|
|
3956
|
+
});
|
|
3957
|
+
const stdout = createUtf8Collector();
|
|
3958
|
+
const stderr = createUtf8Collector();
|
|
3959
|
+
let pending = "";
|
|
3960
|
+
let answer = "";
|
|
3961
|
+
let agyUsage;
|
|
3962
|
+
let settled = false;
|
|
3963
|
+
let timer;
|
|
3964
|
+
let detachAbort = () => {};
|
|
3965
|
+
const finish = (callback) => {
|
|
3966
|
+
if (settled)
|
|
3967
|
+
return;
|
|
3968
|
+
settled = true;
|
|
3969
|
+
if (timer)
|
|
3970
|
+
clearTimeout(timer);
|
|
3971
|
+
detachAbort();
|
|
3972
|
+
callback();
|
|
3973
|
+
};
|
|
3974
|
+
const fail = (error) => {
|
|
3975
|
+
if (settled)
|
|
3976
|
+
return;
|
|
3977
|
+
finish(() => reject(stoppingCliError(error, proc)));
|
|
3978
|
+
};
|
|
3979
|
+
detachAbort = attachCliAbortSignal(proc, options.signal, (error) => {
|
|
3980
|
+
finish(() => reject(error));
|
|
3981
|
+
});
|
|
3982
|
+
if (!settled && timeout > 0) {
|
|
3983
|
+
timer = setTimeout(() => {
|
|
3984
|
+
fail(buildAgyTimeoutError(timeout, stdout.end(), stderr.end()));
|
|
3985
|
+
}, timeout + 1000);
|
|
3986
|
+
}
|
|
3987
|
+
const consumeLine = (line) => {
|
|
3988
|
+
if (settled || !line.trim())
|
|
3989
|
+
return;
|
|
3990
|
+
let event;
|
|
3991
|
+
try {
|
|
3992
|
+
event = JSON.parse(line);
|
|
3993
|
+
} catch {
|
|
3994
|
+
return;
|
|
3995
|
+
}
|
|
3996
|
+
const usageSource = event?.event === "result" ? event.result?.usage : event?.event === "step_update" ? event.step_update?.usage : undefined;
|
|
3997
|
+
const normalizedUsage = normalizeAgyUsage(usageSource);
|
|
3998
|
+
if (normalizedUsage)
|
|
3999
|
+
agyUsage = normalizedUsage;
|
|
4000
|
+
if (event?.event !== "step_update" || event.step_update?.step_type !== "agent_response" || typeof event.step_update.text_delta !== "string")
|
|
4001
|
+
return;
|
|
4002
|
+
const delta = event.step_update.text_delta;
|
|
4003
|
+
if (!delta)
|
|
4004
|
+
return;
|
|
4005
|
+
answer += delta;
|
|
4006
|
+
try {
|
|
4007
|
+
onChunk(delta);
|
|
4008
|
+
} catch (error) {
|
|
4009
|
+
fail(error);
|
|
4010
|
+
}
|
|
4011
|
+
};
|
|
4012
|
+
proc.stdout.on("data", (data) => {
|
|
4013
|
+
if (settled)
|
|
4014
|
+
return;
|
|
4015
|
+
pending += stdout.write(data);
|
|
4016
|
+
const lines = pending.split(`
|
|
4017
|
+
`);
|
|
4018
|
+
pending = lines.pop() ?? "";
|
|
4019
|
+
for (const line of lines)
|
|
4020
|
+
consumeLine(line);
|
|
4021
|
+
});
|
|
4022
|
+
proc.stderr.on("data", (data) => {
|
|
4023
|
+
if (!settled)
|
|
4024
|
+
stderr.write(data);
|
|
4025
|
+
});
|
|
4026
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code, signal) => {
|
|
4027
|
+
if (settled)
|
|
4028
|
+
return;
|
|
4029
|
+
pending += stdout.finish();
|
|
4030
|
+
consumeLine(pending);
|
|
4031
|
+
if (settled)
|
|
4032
|
+
return;
|
|
4033
|
+
const raw = stdout.end();
|
|
4034
|
+
const stderrText = stderr.end();
|
|
4035
|
+
if (code !== 0 || signal) {
|
|
4036
|
+
const quota = detectCliProviderQuotaLimit2("agy", raw, stderrText, code);
|
|
4037
|
+
finish(() => reject(quota.limited ? new CliProviderQuotaError2("agy", quota.message || "Agy reported quota/limit") : new Error(`Antigravity CLI exited with ${signal ? `signal ${signal}` : `code ${code}`}
|
|
4038
|
+
stderr: ${stderrText}`)));
|
|
4039
|
+
return;
|
|
4040
|
+
}
|
|
4041
|
+
finish(() => resolve({
|
|
4042
|
+
text: answer.trim(),
|
|
4043
|
+
raw,
|
|
4044
|
+
elapsed: Date.now() - start,
|
|
4045
|
+
...agyUsage ? { usage: agyUsage } : {}
|
|
4046
|
+
}));
|
|
4047
|
+
});
|
|
4048
|
+
proc.on("error", (error) => fail(error));
|
|
4049
|
+
});
|
|
4050
|
+
} catch (err) {
|
|
4051
|
+
releasePrintSlot();
|
|
4052
|
+
throw err;
|
|
4053
|
+
}
|
|
4054
|
+
return promise.finally(releasePrintSlot);
|
|
4055
|
+
}
|
|
4056
|
+
function executeQoder(prompt, options) {
|
|
4057
|
+
const {
|
|
4058
|
+
model,
|
|
4059
|
+
reasoningEffort,
|
|
4060
|
+
timeout = 120000,
|
|
4061
|
+
cwd = process.cwd(),
|
|
4062
|
+
yolo = true
|
|
4063
|
+
} = options;
|
|
4064
|
+
return new Promise((resolve, reject) => {
|
|
4065
|
+
const args = ["-p", prompt, "--cwd", cwd];
|
|
4066
|
+
if (model) {
|
|
4067
|
+
args.push("--model");
|
|
4068
|
+
args.push(model);
|
|
4069
|
+
}
|
|
4070
|
+
if (reasoningEffort) {
|
|
4071
|
+
args.push("--reasoning-effort");
|
|
4072
|
+
args.push(reasoningEffort);
|
|
4073
|
+
}
|
|
4074
|
+
if (yolo) {
|
|
4075
|
+
args.push("--dangerously-skip-permissions");
|
|
4076
|
+
}
|
|
4077
|
+
const start = Date.now();
|
|
4078
|
+
const proc = spawnCliProcess("qoder", args, {
|
|
4079
|
+
cwd,
|
|
4080
|
+
env: buildCliProcessEnv2(options.env),
|
|
4081
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
4082
|
+
signal: options.signal
|
|
4083
|
+
}, reject);
|
|
4084
|
+
const stdout = createUtf8Collector();
|
|
4085
|
+
const stderr = createUtf8Collector();
|
|
4086
|
+
let timer;
|
|
4087
|
+
if (timeout > 0) {
|
|
4088
|
+
timer = setTimeout(() => {
|
|
4089
|
+
const partial = stdout.end() + `
|
|
4090
|
+
` + stderr.end();
|
|
4091
|
+
const q = detectCliProviderQuotaLimit2("qoder", "", partial, null);
|
|
4092
|
+
if (q.limited) {
|
|
4093
|
+
reject(stoppingCliError(new CliProviderQuotaError2("qoder", q.message || "Qoder quota signal seen before timeout"), proc));
|
|
4094
|
+
return;
|
|
4095
|
+
}
|
|
4096
|
+
reject(stoppingCliError(new Error(`Qoder CLI timed out after ${timeout}ms`), proc));
|
|
4097
|
+
}, timeout);
|
|
4098
|
+
}
|
|
4099
|
+
proc.stdout.on("data", (data) => {
|
|
4100
|
+
stdout.write(data);
|
|
4101
|
+
});
|
|
4102
|
+
proc.stderr.on("data", (data) => {
|
|
4103
|
+
stderr.write(data);
|
|
4104
|
+
const currentStderr = stderr.text;
|
|
4105
|
+
if (detectCliProviderQuotaLimit2("qoder", "", currentStderr, null).limited) {
|
|
4106
|
+
if (timer)
|
|
4107
|
+
clearTimeout(timer);
|
|
4108
|
+
reject(stoppingCliError(new CliProviderQuotaError2("qoder", "quota signal detected incrementally in stderr"), proc));
|
|
4109
|
+
return;
|
|
4110
|
+
}
|
|
4111
|
+
});
|
|
4112
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
4113
|
+
if (timer)
|
|
4114
|
+
clearTimeout(timer);
|
|
4115
|
+
const stdoutText = stdout.end();
|
|
4116
|
+
const stderrText = stderr.end();
|
|
4117
|
+
const quota = detectCliProviderQuotaLimit2("qoder", stdoutText, stderrText, code);
|
|
4118
|
+
const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
|
|
4119
|
+
if (quota.limited && hasRealErrorSignal) {
|
|
4120
|
+
reject(new CliProviderQuotaError2("qoder", quota.message || "Qoder reported quota/limit"));
|
|
4121
|
+
return;
|
|
4122
|
+
}
|
|
4123
|
+
if (code !== 0 && code !== null) {
|
|
4124
|
+
console.error("[cliExecutor] qoder process exited with non-zero code:", code, "stderr:", stderrText);
|
|
4125
|
+
reject(new Error(`Qoder CLI exited with code ${code}
|
|
4126
|
+
stderr: ${stderrText}`));
|
|
4127
|
+
return;
|
|
4128
|
+
}
|
|
4129
|
+
resolve({
|
|
4130
|
+
text: stdoutText.trim(),
|
|
4131
|
+
raw: stdoutText,
|
|
4132
|
+
elapsed: Date.now() - start
|
|
4133
|
+
});
|
|
4134
|
+
});
|
|
4135
|
+
proc.on("error", (err) => {
|
|
4136
|
+
if (timer)
|
|
4137
|
+
clearTimeout(timer);
|
|
4138
|
+
console.error("[cliExecutor] qoder process error event:", err);
|
|
4139
|
+
reject(proc.pid ? stoppingCliError(err, proc) : err);
|
|
4140
|
+
});
|
|
4141
|
+
});
|
|
4142
|
+
}
|
|
4143
|
+
function parseOpenCodeJsonlEvents(stdout) {
|
|
4144
|
+
const parts = [];
|
|
4145
|
+
for (const line of stdout.split(`
|
|
4146
|
+
`)) {
|
|
4147
|
+
const trimmed = line.trim();
|
|
4148
|
+
if (!trimmed)
|
|
4149
|
+
continue;
|
|
4150
|
+
try {
|
|
4151
|
+
const event = JSON.parse(trimmed);
|
|
4152
|
+
if (event.type === "text" && event.part?.type === "text" && typeof event.part.text === "string") {
|
|
4153
|
+
parts.push(event.part.text);
|
|
4154
|
+
}
|
|
4155
|
+
} catch {}
|
|
4156
|
+
}
|
|
4157
|
+
return parts.join("");
|
|
4158
|
+
}
|
|
4159
|
+
function executeOpenCode(prompt, options) {
|
|
4160
|
+
const {
|
|
4161
|
+
model,
|
|
4162
|
+
reasoningEffort,
|
|
4163
|
+
timeout = DEFAULT_OPENCODE_TIMEOUT_MS,
|
|
4164
|
+
cwd = process.cwd(),
|
|
4165
|
+
yolo = true
|
|
4166
|
+
} = options;
|
|
4167
|
+
return new Promise((resolve, reject) => {
|
|
4168
|
+
const args = [
|
|
4169
|
+
"run",
|
|
4170
|
+
"--format",
|
|
4171
|
+
"json",
|
|
4172
|
+
"--dir",
|
|
4173
|
+
cwd,
|
|
4174
|
+
"--print-logs"
|
|
4175
|
+
];
|
|
4176
|
+
if (model) {
|
|
4177
|
+
args.push("--model");
|
|
4178
|
+
args.push(model);
|
|
4179
|
+
}
|
|
4180
|
+
if (reasoningEffort) {
|
|
4181
|
+
args.push("--variant");
|
|
4182
|
+
args.push(reasoningEffort);
|
|
4183
|
+
}
|
|
4184
|
+
if (yolo) {
|
|
4185
|
+
args.push("--dangerously-skip-permissions");
|
|
4186
|
+
}
|
|
4187
|
+
args.push(prompt);
|
|
4188
|
+
const start = Date.now();
|
|
4189
|
+
const proc = spawnCliProcess("opencode", args, {
|
|
4190
|
+
cwd,
|
|
4191
|
+
env: buildCliProcessEnv2(options.env),
|
|
4192
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
4193
|
+
signal: options.signal
|
|
4194
|
+
}, reject);
|
|
4195
|
+
const stdout = createUtf8Collector();
|
|
4196
|
+
const stderr = createUtf8Collector();
|
|
4197
|
+
let timer;
|
|
4198
|
+
if (timeout > 0) {
|
|
4199
|
+
timer = setTimeout(() => {
|
|
4200
|
+
const stdoutPartial = stdout.end();
|
|
4201
|
+
const stderrPartial = stderr.end();
|
|
4202
|
+
const q = detectCliProviderQuotaLimit2("opencode", stdoutPartial, stderrPartial, null);
|
|
4203
|
+
if (q.limited) {
|
|
4204
|
+
reject(stoppingCliError(new CliProviderQuotaError2("opencode", q.message || "OpenCode quota signal seen before timeout"), proc));
|
|
4205
|
+
return;
|
|
4206
|
+
}
|
|
4207
|
+
reject(stoppingCliError(new Error(`OpenCode CLI timed out after ${timeout}ms`), proc));
|
|
4208
|
+
}, timeout);
|
|
4209
|
+
}
|
|
4210
|
+
proc.stdout.on("data", (data) => {
|
|
4211
|
+
stdout.write(data);
|
|
4212
|
+
});
|
|
4213
|
+
proc.stderr.on("data", (data) => {
|
|
4214
|
+
stderr.write(data);
|
|
4215
|
+
const currentStderr = stderr.text;
|
|
4216
|
+
if (detectCliProviderQuotaLimit2("opencode", "", currentStderr, null).limited) {
|
|
4217
|
+
if (timer)
|
|
4218
|
+
clearTimeout(timer);
|
|
4219
|
+
reject(stoppingCliError(new CliProviderQuotaError2("opencode", "quota signal detected incrementally in stderr"), proc));
|
|
4220
|
+
return;
|
|
4221
|
+
}
|
|
4222
|
+
});
|
|
4223
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
4224
|
+
if (timer)
|
|
4225
|
+
clearTimeout(timer);
|
|
4226
|
+
const stdoutText = stdout.end();
|
|
4227
|
+
const stderrText = stderr.end();
|
|
4228
|
+
const quota = detectCliProviderQuotaLimit2("opencode", stdoutText, stderrText, code);
|
|
4229
|
+
const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
|
|
4230
|
+
if (quota.limited && hasRealErrorSignal) {
|
|
4231
|
+
reject(new CliProviderQuotaError2("opencode", quota.message || "OpenCode reported quota/limit"));
|
|
4232
|
+
return;
|
|
4233
|
+
}
|
|
4234
|
+
if (code !== 0 && code !== null) {
|
|
4235
|
+
console.error("[cliExecutor] opencode process exited with non-zero code:", code, "stderr:", stderrText);
|
|
4236
|
+
reject(new Error(`OpenCode CLI exited with code ${code}
|
|
4237
|
+
stderr: ${stderrText}`));
|
|
4238
|
+
return;
|
|
4239
|
+
}
|
|
4240
|
+
resolve({
|
|
4241
|
+
text: parseOpenCodeJsonlEvents(stdoutText).trim(),
|
|
4242
|
+
raw: stdoutText,
|
|
4243
|
+
elapsed: Date.now() - start
|
|
4244
|
+
});
|
|
4245
|
+
});
|
|
4246
|
+
proc.on("error", (err) => {
|
|
4247
|
+
if (timer)
|
|
4248
|
+
clearTimeout(timer);
|
|
4249
|
+
console.error("[cliExecutor] opencode process error event:", err);
|
|
4250
|
+
reject(proc.pid ? stoppingCliError(err, proc) : err);
|
|
4251
|
+
});
|
|
4252
|
+
});
|
|
4253
|
+
}
|
|
4254
|
+
function parseGrokJsonOutput(stdout) {
|
|
4255
|
+
const trimmed = stdout.trim();
|
|
4256
|
+
if (!trimmed)
|
|
4257
|
+
return "";
|
|
4258
|
+
const parsed = JSON.parse(trimmed);
|
|
4259
|
+
if (parsed.type === "error") {
|
|
4260
|
+
throw new Error(typeof parsed.message === "string" ? parsed.message : "Grok CLI failed");
|
|
4261
|
+
}
|
|
4262
|
+
return typeof parsed.text === "string" ? parsed.text : "";
|
|
4263
|
+
}
|
|
4264
|
+
function buildGrokProcessEnv(extraEnv) {
|
|
4265
|
+
return buildCliProcessEnv2({
|
|
4266
|
+
GROK_TELEMETRY_TRACE_UPLOAD: "0",
|
|
4267
|
+
GROK_TELEMETRY_ENABLED: "0",
|
|
4268
|
+
GROK_FEEDBACK_ENABLED: "0",
|
|
4269
|
+
GROK_TELEMETRY_MIXPANEL_ENABLED: "0",
|
|
4270
|
+
...extraEnv
|
|
4271
|
+
});
|
|
4272
|
+
}
|
|
4273
|
+
function executeGrok(prompt, options) {
|
|
4274
|
+
const {
|
|
4275
|
+
model,
|
|
4276
|
+
reasoningEffort,
|
|
4277
|
+
timeout = DEFAULT_GROK_TIMEOUT_MS,
|
|
4278
|
+
cwd = process.cwd(),
|
|
4279
|
+
yolo = true
|
|
4280
|
+
} = options;
|
|
4281
|
+
return new Promise((resolve, reject) => {
|
|
4282
|
+
const args = ["-p", prompt, "--cwd", cwd, "--output-format", "json"];
|
|
4283
|
+
if (model) {
|
|
4284
|
+
args.push("-m", model);
|
|
4285
|
+
}
|
|
4286
|
+
if (reasoningEffort) {
|
|
4287
|
+
args.push("--effort", reasoningEffort);
|
|
4288
|
+
}
|
|
4289
|
+
if (yolo) {
|
|
4290
|
+
args.push("--yolo");
|
|
4291
|
+
}
|
|
4292
|
+
const start = Date.now();
|
|
4293
|
+
const proc = spawnCliProcess("grok", args, {
|
|
4294
|
+
cwd,
|
|
4295
|
+
env: buildGrokProcessEnv(options.env),
|
|
4296
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
4297
|
+
signal: options.signal
|
|
4298
|
+
}, reject);
|
|
4299
|
+
const stdout = createUtf8Collector();
|
|
4300
|
+
const stderr = createUtf8Collector();
|
|
4301
|
+
let timer;
|
|
4302
|
+
if (timeout > 0) {
|
|
4303
|
+
timer = setTimeout(() => {
|
|
4304
|
+
const partial = stdout.end() + `
|
|
4305
|
+
` + stderr.end();
|
|
4306
|
+
const q = detectCliProviderQuotaLimit2("grok", "", partial, null);
|
|
4307
|
+
if (q.limited) {
|
|
4308
|
+
reject(stoppingCliError(new CliProviderQuotaError2("grok", q.message || "Grok quota signal seen before timeout"), proc));
|
|
4309
|
+
return;
|
|
4310
|
+
}
|
|
4311
|
+
reject(stoppingCliError(new Error(`Grok CLI timed out after ${timeout}ms`), proc));
|
|
4312
|
+
}, timeout);
|
|
4313
|
+
}
|
|
4314
|
+
proc.stdout.on("data", (data) => {
|
|
4315
|
+
stdout.write(data);
|
|
4316
|
+
});
|
|
4317
|
+
proc.stderr.on("data", (data) => {
|
|
4318
|
+
stderr.write(data);
|
|
4319
|
+
const currentStderr = stderr.text;
|
|
4320
|
+
if (detectCliProviderQuotaLimit2("grok", "", currentStderr, null).limited) {
|
|
4321
|
+
if (timer)
|
|
4322
|
+
clearTimeout(timer);
|
|
4323
|
+
reject(stoppingCliError(new CliProviderQuotaError2("grok", "quota signal detected incrementally in stderr"), proc));
|
|
4324
|
+
return;
|
|
4325
|
+
}
|
|
4326
|
+
});
|
|
4327
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
4328
|
+
if (timer)
|
|
4329
|
+
clearTimeout(timer);
|
|
4330
|
+
const stdoutText = stdout.end();
|
|
4331
|
+
const stderrText = stderr.end();
|
|
4332
|
+
const quota = detectCliProviderQuotaLimit2("grok", stdoutText, stderrText, code);
|
|
4333
|
+
const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
|
|
4334
|
+
if (quota.limited && hasRealErrorSignal) {
|
|
4335
|
+
reject(new CliProviderQuotaError2("grok", quota.message || "Grok reported quota/limit"));
|
|
4336
|
+
return;
|
|
4337
|
+
}
|
|
4338
|
+
if (code !== 0 && code !== null) {
|
|
4339
|
+
console.error("[cliExecutor] grok process exited with non-zero code:", code, "stderr:", stderrText);
|
|
4340
|
+
reject(new Error(`Grok CLI exited with code ${code}
|
|
4341
|
+
stderr: ${stderrText}`));
|
|
4342
|
+
return;
|
|
4343
|
+
}
|
|
4344
|
+
try {
|
|
4345
|
+
resolve({
|
|
4346
|
+
text: parseGrokJsonOutput(stdoutText).trim(),
|
|
4347
|
+
raw: stdoutText,
|
|
4348
|
+
elapsed: Date.now() - start
|
|
4349
|
+
});
|
|
4350
|
+
} catch (error) {
|
|
4351
|
+
reject(error);
|
|
4352
|
+
}
|
|
4353
|
+
});
|
|
4354
|
+
proc.on("error", (err) => {
|
|
4355
|
+
if (timer)
|
|
4356
|
+
clearTimeout(timer);
|
|
4357
|
+
console.error("[cliExecutor] grok process error event:", err);
|
|
4358
|
+
reject(proc.pid ? stoppingCliError(err, proc) : err);
|
|
4359
|
+
});
|
|
4360
|
+
});
|
|
4361
|
+
}
|
|
4362
|
+
function parseKimiStreamJson(stdout) {
|
|
4363
|
+
const parts = [];
|
|
4364
|
+
for (const line of stdout.split(`
|
|
4365
|
+
`)) {
|
|
4366
|
+
const trimmed = line.trim();
|
|
4367
|
+
if (!trimmed)
|
|
4368
|
+
continue;
|
|
4369
|
+
try {
|
|
4370
|
+
const event = JSON.parse(trimmed);
|
|
4371
|
+
if (event.role === "assistant" && typeof event.content === "string" && event.content.length > 0) {
|
|
4372
|
+
parts.push(event.content);
|
|
4373
|
+
}
|
|
4374
|
+
} catch {}
|
|
4375
|
+
}
|
|
4376
|
+
return parts.join("");
|
|
4377
|
+
}
|
|
4378
|
+
function executeKimi(prompt, options) {
|
|
4379
|
+
const {
|
|
4380
|
+
model,
|
|
4381
|
+
timeout = 120000,
|
|
4382
|
+
cwd = process.cwd()
|
|
4383
|
+
} = options;
|
|
4384
|
+
return new Promise((resolve, reject) => {
|
|
4385
|
+
const args = ["-p", prompt, "--output-format", "stream-json"];
|
|
4386
|
+
if (model) {
|
|
4387
|
+
args.push("-m", model);
|
|
4388
|
+
}
|
|
4389
|
+
const start = Date.now();
|
|
4390
|
+
const proc = spawnCliProcess("kimi", args, {
|
|
4391
|
+
cwd,
|
|
4392
|
+
env: buildCliProcessEnv2(options.env),
|
|
4393
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
4394
|
+
signal: options.signal
|
|
4395
|
+
}, reject);
|
|
4396
|
+
const stdout = createUtf8Collector();
|
|
4397
|
+
const stderr = createUtf8Collector();
|
|
4398
|
+
let timer;
|
|
4399
|
+
if (timeout > 0) {
|
|
4400
|
+
timer = setTimeout(() => {
|
|
4401
|
+
const partial = stdout.end() + `
|
|
4402
|
+
` + stderr.end();
|
|
4403
|
+
const q = detectCliProviderQuotaLimit2("kimi", "", partial, null);
|
|
4404
|
+
if (q.limited) {
|
|
4405
|
+
reject(stoppingCliError(new CliProviderQuotaError2("kimi", q.message || "Kimi quota signal seen before timeout"), proc));
|
|
4406
|
+
return;
|
|
4407
|
+
}
|
|
4408
|
+
reject(stoppingCliError(new Error(`Kimi CLI timed out after ${timeout}ms`), proc));
|
|
4409
|
+
}, timeout);
|
|
4410
|
+
}
|
|
4411
|
+
proc.stdout.on("data", (data) => {
|
|
4412
|
+
stdout.write(data);
|
|
4413
|
+
});
|
|
4414
|
+
proc.stderr.on("data", (data) => {
|
|
4415
|
+
stderr.write(data);
|
|
4416
|
+
const currentStderr = stderr.text;
|
|
4417
|
+
if (detectCliProviderQuotaLimit2("kimi", "", currentStderr, null).limited) {
|
|
4418
|
+
if (timer)
|
|
4419
|
+
clearTimeout(timer);
|
|
4420
|
+
reject(stoppingCliError(new CliProviderQuotaError2("kimi", "quota signal detected incrementally in stderr"), proc));
|
|
4421
|
+
return;
|
|
4422
|
+
}
|
|
4423
|
+
});
|
|
4424
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
4425
|
+
if (timer)
|
|
4426
|
+
clearTimeout(timer);
|
|
4427
|
+
const stdoutText = stdout.end();
|
|
4428
|
+
const stderrText = stderr.end();
|
|
4429
|
+
const quota = detectCliProviderQuotaLimit2("kimi", stdoutText, stderrText, code);
|
|
4430
|
+
const hasRealErrorSignal = code !== 0 || /error|fail|quota|limit|429|rate limit|exceeded/i.test(stderrText);
|
|
4431
|
+
if (quota.limited && hasRealErrorSignal) {
|
|
4432
|
+
reject(new CliProviderQuotaError2("kimi", quota.message || "Kimi reported quota/limit"));
|
|
4433
|
+
return;
|
|
4434
|
+
}
|
|
4435
|
+
if (code !== 0 && code !== null) {
|
|
4436
|
+
console.error("[cliExecutor] kimi process exited with non-zero code:", code, "stderr:", stderrText);
|
|
4437
|
+
reject(new Error(`Kimi CLI exited with code ${code}
|
|
4438
|
+
stderr: ${stderrText}`));
|
|
4439
|
+
return;
|
|
4440
|
+
}
|
|
4441
|
+
resolve({
|
|
4442
|
+
text: parseKimiStreamJson(stdoutText).trim(),
|
|
4443
|
+
raw: stdoutText,
|
|
4444
|
+
elapsed: Date.now() - start
|
|
4445
|
+
});
|
|
4446
|
+
});
|
|
4447
|
+
proc.on("error", (err) => {
|
|
4448
|
+
if (timer)
|
|
4449
|
+
clearTimeout(timer);
|
|
4450
|
+
console.error("[cliExecutor] kimi process error event:", err);
|
|
4451
|
+
reject(proc.pid ? stoppingCliError(err, proc) : err);
|
|
4452
|
+
});
|
|
4453
|
+
});
|
|
4454
|
+
}
|
|
4455
|
+
var EXECUTORS = {
|
|
4456
|
+
copilot: executeCopilot,
|
|
4457
|
+
gemini: executeGemini,
|
|
4458
|
+
codex: executeCodex,
|
|
4459
|
+
claude: executeClaude,
|
|
4460
|
+
agy: executeAgy,
|
|
4461
|
+
qoder: executeQoder,
|
|
4462
|
+
opencode: executeOpenCode,
|
|
4463
|
+
grok: executeGrok,
|
|
4464
|
+
kimi: executeKimi
|
|
4465
|
+
};
|
|
4466
|
+
async function executeCli2(provider, prompt, options = {}) {
|
|
4467
|
+
const executor = EXECUTORS[provider];
|
|
4468
|
+
if (!executor) {
|
|
4469
|
+
throw new Error(`Unknown CLI provider: "${provider}". Supported: ${Object.keys(EXECUTORS).join(", ")}`);
|
|
4470
|
+
}
|
|
4471
|
+
const resolved = resolveCliExecution(provider, prompt, options);
|
|
4472
|
+
try {
|
|
4473
|
+
const result = await executor(resolved.prompt, resolved.options);
|
|
4474
|
+
return {
|
|
4475
|
+
...result,
|
|
4476
|
+
warnings: [...resolved.warnings, ...result.warnings ?? []]
|
|
4477
|
+
};
|
|
4478
|
+
} finally {
|
|
4479
|
+
if (resolved.imageTempDir) {
|
|
4480
|
+
rmSync(resolved.imageTempDir, { recursive: true, force: true });
|
|
4481
|
+
}
|
|
4482
|
+
}
|
|
4483
|
+
}
|
|
4484
|
+
function resolveAgyNoOutputTimeoutMs(env) {
|
|
4485
|
+
const raw = env?.NOLO_AGY_NO_OUTPUT_TIMEOUT_MS ?? process.env.NOLO_AGY_NO_OUTPUT_TIMEOUT_MS;
|
|
4486
|
+
if (raw === undefined)
|
|
4487
|
+
return;
|
|
4488
|
+
const trimmed = raw.trim();
|
|
4489
|
+
if (trimmed === "")
|
|
4490
|
+
return;
|
|
4491
|
+
if (!/^\d+$/.test(trimmed))
|
|
4492
|
+
return;
|
|
4493
|
+
const parsed = Number.parseInt(trimmed, 10);
|
|
4494
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
4495
|
+
}
|
|
4496
|
+
async function executeAgyAcpDirectTurn2(sessionKey, userInput, options = {}) {
|
|
4497
|
+
const { systemPrompt, onChunk, ...restOptions } = options;
|
|
4498
|
+
const resolved = resolveCliExecution("agy", userInput, restOptions);
|
|
4499
|
+
try {
|
|
4500
|
+
const mcpServers = resolveAgyAcpMcpServers(resolved.options.mcpServers, resolved.options.env);
|
|
4501
|
+
const noOutputTimeoutMs = resolveAgyNoOutputTimeoutMs(resolved.options.env);
|
|
4502
|
+
const useSharedDaemon = isAgyAcpSharedDaemonEnabled2(resolved.options.env);
|
|
4503
|
+
const result = useSharedDaemon ? await promptSharedAgySession(sessionKey, resolved.prompt, {
|
|
4504
|
+
cwd: resolved.options.cwd ?? process.cwd(),
|
|
4505
|
+
env: resolved.options.env,
|
|
4506
|
+
model: resolved.options.model,
|
|
4507
|
+
systemPrompt,
|
|
4508
|
+
yolo: resolved.options.yolo,
|
|
4509
|
+
reasoningEffort: resolved.options.reasoningEffort,
|
|
4510
|
+
...mcpServers.length > 0 ? { mcpServers } : {},
|
|
4511
|
+
...resolved.options.processPerSession !== undefined ? { processPerSession: resolved.options.processPerSession } : {}
|
|
4512
|
+
}, {
|
|
4513
|
+
signal: resolved.options.signal,
|
|
4514
|
+
timeoutMs: resolved.options.timeout ?? DEFAULT_AGY_ACP_TOTAL_TIMEOUT_MS,
|
|
4515
|
+
...noOutputTimeoutMs !== undefined ? { noOutputTimeoutMs } : {},
|
|
4516
|
+
...onChunk ? { onChunk } : {},
|
|
4517
|
+
...resolved.options.onThoughtChunk ? { onThoughtChunk: resolved.options.onThoughtChunk } : {},
|
|
4518
|
+
onToolEvent: resolved.options.onToolEvent,
|
|
4519
|
+
toolEventRound: resolved.options.toolEventRound
|
|
4520
|
+
}) : await getAgyAcpSession2(sessionKey, {
|
|
4521
|
+
cwd: resolved.options.cwd ?? process.cwd(),
|
|
4522
|
+
env: resolved.options.env,
|
|
4523
|
+
model: resolved.options.model,
|
|
4524
|
+
systemPrompt,
|
|
4525
|
+
yolo: resolved.options.yolo,
|
|
4526
|
+
reasoningEffort: resolved.options.reasoningEffort,
|
|
4527
|
+
...mcpServers.length > 0 ? { mcpServers } : {},
|
|
4528
|
+
...resolved.options.processPerSession !== undefined ? { processPerSession: resolved.options.processPerSession } : {}
|
|
4529
|
+
}).prompt(resolved.prompt, {
|
|
4530
|
+
signal: resolved.options.signal,
|
|
4531
|
+
timeoutMs: resolved.options.timeout ?? DEFAULT_AGY_ACP_TOTAL_TIMEOUT_MS,
|
|
4532
|
+
...noOutputTimeoutMs !== undefined ? { noOutputTimeoutMs } : {},
|
|
4533
|
+
...onChunk ? { onChunk } : {},
|
|
4534
|
+
...resolved.options.onThoughtChunk ? { onThoughtChunk: resolved.options.onThoughtChunk } : {},
|
|
4535
|
+
onToolEvent: resolved.options.onToolEvent,
|
|
4536
|
+
toolEventRound: resolved.options.toolEventRound
|
|
4537
|
+
});
|
|
4538
|
+
const warnings = [...resolved.warnings, ...result.warnings ?? []];
|
|
4539
|
+
return {
|
|
4540
|
+
text: result.text,
|
|
4541
|
+
raw: result.raw,
|
|
4542
|
+
elapsed: result.elapsed,
|
|
4543
|
+
...result.usage ? { usage: result.usage } : {},
|
|
4544
|
+
...warnings.length > 0 ? { warnings } : {}
|
|
4545
|
+
};
|
|
4546
|
+
} finally {
|
|
4547
|
+
if (resolved.imageTempDir) {
|
|
4548
|
+
rmSync(resolved.imageTempDir, { recursive: true, force: true });
|
|
4549
|
+
}
|
|
4550
|
+
}
|
|
4551
|
+
}
|
|
4552
|
+
async function executeAgyAcpOneShot2(userInput, options = {}) {
|
|
4553
|
+
const { systemPrompt, onChunk, ...restOptions } = options;
|
|
4554
|
+
const resolved = resolveCliExecution("agy", userInput, restOptions);
|
|
4555
|
+
try {
|
|
4556
|
+
const mcpServers = resolveAgyAcpMcpServers(resolved.options.mcpServers, resolved.options.env);
|
|
4557
|
+
const noOutputTimeoutMs = resolveAgyNoOutputTimeoutMs(resolved.options.env);
|
|
4558
|
+
const result = await runOneShotSharedAgyPrompt(resolved.prompt, {
|
|
4559
|
+
cwd: resolved.options.cwd ?? process.cwd(),
|
|
4560
|
+
env: resolved.options.env,
|
|
4561
|
+
model: resolved.options.model,
|
|
4562
|
+
systemPrompt,
|
|
4563
|
+
yolo: resolved.options.yolo,
|
|
4564
|
+
reasoningEffort: resolved.options.reasoningEffort,
|
|
4565
|
+
...mcpServers.length > 0 ? { mcpServers } : {},
|
|
4566
|
+
...resolved.options.processPerSession !== undefined ? { processPerSession: resolved.options.processPerSession } : {}
|
|
4567
|
+
}, {
|
|
4568
|
+
signal: resolved.options.signal,
|
|
4569
|
+
timeoutMs: resolved.options.timeout ?? DEFAULT_AGY_ACP_TOTAL_TIMEOUT_MS,
|
|
4570
|
+
...noOutputTimeoutMs !== undefined ? { noOutputTimeoutMs } : {},
|
|
4571
|
+
...onChunk ? { onChunk } : {},
|
|
4572
|
+
...resolved.options.onThoughtChunk ? { onThoughtChunk: resolved.options.onThoughtChunk } : {},
|
|
4573
|
+
onToolEvent: resolved.options.onToolEvent,
|
|
4574
|
+
toolEventRound: resolved.options.toolEventRound
|
|
4575
|
+
});
|
|
4576
|
+
const warnings = [...resolved.warnings, ...result.warnings ?? []];
|
|
4577
|
+
return {
|
|
4578
|
+
text: result.text,
|
|
4579
|
+
raw: result.raw,
|
|
4580
|
+
elapsed: result.elapsed,
|
|
4581
|
+
...result.usage ? { usage: result.usage } : {},
|
|
4582
|
+
...warnings.length > 0 ? { warnings } : {}
|
|
4583
|
+
};
|
|
4584
|
+
} finally {
|
|
4585
|
+
if (resolved.imageTempDir) {
|
|
4586
|
+
rmSync(resolved.imageTempDir, { recursive: true, force: true });
|
|
4587
|
+
}
|
|
4588
|
+
}
|
|
4589
|
+
}
|
|
4590
|
+
function filterNoiseLine(line) {
|
|
4591
|
+
return !line.includes("A new release of gh is available") && !line.includes("To upgrade, run:") && !line.includes("https://github.com/cli/cli/releases");
|
|
4592
|
+
}
|
|
4593
|
+
function executeCliStreaming2(provider, prompt, options) {
|
|
4594
|
+
const resolved = resolveCliExecution(provider, prompt, options);
|
|
4595
|
+
const executor = EXECUTORS[provider];
|
|
4596
|
+
const cleanupImageTempDir = () => {
|
|
4597
|
+
if (resolved.imageTempDir) {
|
|
4598
|
+
rmSync(resolved.imageTempDir, { recursive: true, force: true });
|
|
4599
|
+
}
|
|
4600
|
+
};
|
|
4601
|
+
const withCleanup = (promise) => promise.finally(cleanupImageTempDir);
|
|
4602
|
+
if (provider === "gemini") {
|
|
4603
|
+
return withCleanup(executeGeminiStreaming(resolved.prompt, resolved.options).then((result) => ({ ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] })));
|
|
4604
|
+
}
|
|
4605
|
+
if (provider === "codex") {
|
|
4606
|
+
return withCleanup(executor(resolved.prompt, resolved.options).then((result) => {
|
|
4607
|
+
const merged = { ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] };
|
|
4608
|
+
if (merged.text)
|
|
4609
|
+
options.onChunk(merged.text);
|
|
4610
|
+
return merged;
|
|
4611
|
+
}));
|
|
4612
|
+
}
|
|
4613
|
+
if (provider === "claude") {
|
|
4614
|
+
return withCleanup(executor(resolved.prompt, resolved.options).then((result) => {
|
|
4615
|
+
const merged = { ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] };
|
|
4616
|
+
if (merged.text)
|
|
4617
|
+
options.onChunk(merged.text);
|
|
4618
|
+
return merged;
|
|
4619
|
+
}));
|
|
4620
|
+
}
|
|
4621
|
+
if (provider === "agy") {
|
|
4622
|
+
return withCleanup(executeAgyStreaming(resolved.prompt, resolved.options).then((result) => ({ ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] })));
|
|
4623
|
+
}
|
|
4624
|
+
if (provider === "opencode") {
|
|
4625
|
+
return withCleanup(executeOpenCodeStreaming(resolved.prompt, resolved.options).then((result) => ({ ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] })));
|
|
4626
|
+
}
|
|
4627
|
+
if (provider === "qoder" || provider === "grok" || provider === "kimi") {
|
|
4628
|
+
return withCleanup(executor(resolved.prompt, resolved.options).then((result) => {
|
|
4629
|
+
const merged = { ...result, warnings: [...resolved.warnings, ...result.warnings ?? []] };
|
|
4630
|
+
if (merged.text)
|
|
4631
|
+
options.onChunk(merged.text);
|
|
4632
|
+
return merged;
|
|
4633
|
+
}));
|
|
4634
|
+
}
|
|
4635
|
+
if (provider !== "copilot") {
|
|
4636
|
+
return withCleanup(executor(resolved.prompt, resolved.options).then((result) => ({
|
|
4637
|
+
...result,
|
|
4638
|
+
warnings: [...resolved.warnings, ...result.warnings ?? []]
|
|
4639
|
+
})));
|
|
4640
|
+
}
|
|
4641
|
+
const {
|
|
4642
|
+
model,
|
|
4643
|
+
timeout = 120000,
|
|
4644
|
+
cwd = process.cwd(),
|
|
4645
|
+
yolo = true,
|
|
4646
|
+
onChunk
|
|
4647
|
+
} = resolved.options;
|
|
4648
|
+
return withCleanup(new Promise((resolve, reject) => {
|
|
4649
|
+
const args = [
|
|
4650
|
+
"copilot",
|
|
4651
|
+
"--",
|
|
4652
|
+
"-p",
|
|
4653
|
+
resolved.prompt,
|
|
4654
|
+
"--silent",
|
|
4655
|
+
"--disable-builtin-mcps"
|
|
4656
|
+
];
|
|
4657
|
+
if (model) {
|
|
4658
|
+
args.push("--model");
|
|
4659
|
+
args.push(model);
|
|
4660
|
+
}
|
|
4661
|
+
if (yolo)
|
|
4662
|
+
args.push("--yolo");
|
|
4663
|
+
const start = Date.now();
|
|
4664
|
+
const proc = spawn4("gh", args, {
|
|
4665
|
+
cwd,
|
|
4666
|
+
env: buildCliProcessEnv2(resolved.options.env),
|
|
4667
|
+
...resolved.options.signal ? { detached: true } : {}
|
|
4668
|
+
});
|
|
4669
|
+
const stdout = createUtf8Collector();
|
|
4670
|
+
let timer;
|
|
4671
|
+
let settled = false;
|
|
4672
|
+
const finish = (cb) => {
|
|
4673
|
+
if (settled)
|
|
4674
|
+
return;
|
|
4675
|
+
settled = true;
|
|
4676
|
+
if (timer)
|
|
4677
|
+
clearTimeout(timer);
|
|
4678
|
+
detachAbort();
|
|
4679
|
+
cb();
|
|
4680
|
+
};
|
|
4681
|
+
let detachAbort = () => {};
|
|
4682
|
+
detachAbort = attachCliAbortSignal(proc, resolved.options.signal, (error) => finish(() => reject(error)));
|
|
4683
|
+
if (timeout > 0) {
|
|
4684
|
+
timer = setTimeout(() => {
|
|
4685
|
+
finish(() => reject(stoppingCliError(new Error(`Copilot CLI timed out after ${timeout}ms`), proc)));
|
|
4686
|
+
}, timeout);
|
|
4687
|
+
}
|
|
4688
|
+
proc.stdout.on("data", (data) => {
|
|
4689
|
+
const chunk = stdout.write(data);
|
|
4690
|
+
const cleaned = chunk.split(`
|
|
4691
|
+
`).filter(filterNoiseLine).join(`
|
|
4692
|
+
`);
|
|
4693
|
+
if (cleaned && !settled) {
|
|
4694
|
+
try {
|
|
4695
|
+
onChunk(cleaned);
|
|
4696
|
+
} catch (error) {
|
|
4697
|
+
finish(() => reject(stoppingCliError(error, proc)));
|
|
4698
|
+
}
|
|
4699
|
+
}
|
|
4700
|
+
});
|
|
4701
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
4702
|
+
const raw = stdout.end();
|
|
4703
|
+
if (code !== 0 && code !== null) {
|
|
4704
|
+
finish(() => reject(new Error(`Copilot CLI exited with code ${code}`)));
|
|
4705
|
+
return;
|
|
4706
|
+
}
|
|
4707
|
+
const text = raw.split(`
|
|
4708
|
+
`).filter(filterNoiseLine).join(`
|
|
4709
|
+
`).trim();
|
|
4710
|
+
finish(() => resolve({
|
|
4711
|
+
text,
|
|
4712
|
+
raw,
|
|
4713
|
+
elapsed: Date.now() - start,
|
|
4714
|
+
warnings: [...resolved.warnings]
|
|
4715
|
+
}));
|
|
4716
|
+
});
|
|
4717
|
+
proc.on("error", (err) => {
|
|
4718
|
+
finish(() => reject(proc.pid ? stoppingCliError(err, proc) : err));
|
|
4719
|
+
});
|
|
4720
|
+
}));
|
|
4721
|
+
}
|
|
4722
|
+
function executeGeminiStreaming(prompt, options) {
|
|
4723
|
+
const {
|
|
4724
|
+
model = "gemini-3.8-flash",
|
|
4725
|
+
timeout = 120000,
|
|
4726
|
+
cwd = process.cwd(),
|
|
4727
|
+
yolo = true,
|
|
4728
|
+
onChunk
|
|
4729
|
+
} = options;
|
|
4730
|
+
return new Promise((resolve, reject) => {
|
|
4731
|
+
const args = ["-p", prompt, "--output-format", "stream-json", "-m", model];
|
|
4732
|
+
if (yolo)
|
|
4733
|
+
args.push("--yolo");
|
|
4734
|
+
args.push("-e", "none");
|
|
4735
|
+
const start = Date.now();
|
|
4736
|
+
const proc = spawn4("gemini", args, {
|
|
4737
|
+
cwd,
|
|
4738
|
+
env: buildCliProcessEnv2({
|
|
4739
|
+
...options.env,
|
|
4740
|
+
NODE_OPTIONS: "--no-deprecation"
|
|
4741
|
+
}),
|
|
4742
|
+
detached: process.platform !== "win32"
|
|
4743
|
+
});
|
|
4744
|
+
const stdout = createUtf8Collector();
|
|
4745
|
+
const stderr = createUtf8Collector();
|
|
4746
|
+
let lineBuffer = "";
|
|
4747
|
+
let timer;
|
|
4748
|
+
let settled = false;
|
|
4749
|
+
const finish = (cb) => {
|
|
4750
|
+
if (settled)
|
|
4751
|
+
return;
|
|
4752
|
+
settled = true;
|
|
4753
|
+
if (timer)
|
|
4754
|
+
clearTimeout(timer);
|
|
4755
|
+
detachAbort();
|
|
4756
|
+
cb();
|
|
4757
|
+
};
|
|
4758
|
+
let detachAbort = () => {};
|
|
4759
|
+
detachAbort = attachCliAbortSignal(proc, options.signal, (error) => finish(() => reject(error)));
|
|
4760
|
+
const flushLineBuffer = () => {
|
|
4761
|
+
if (settled)
|
|
4762
|
+
return;
|
|
4763
|
+
const trimmed = lineBuffer.trim();
|
|
4764
|
+
if (!trimmed)
|
|
4765
|
+
return;
|
|
4766
|
+
try {
|
|
4767
|
+
const event = JSON.parse(trimmed);
|
|
4768
|
+
const text = extractGeminiEventText(event);
|
|
4769
|
+
if (text)
|
|
4770
|
+
onChunk(text);
|
|
4771
|
+
} catch {}
|
|
4772
|
+
lineBuffer = "";
|
|
4773
|
+
};
|
|
4774
|
+
if (timeout > 0) {
|
|
4775
|
+
timer = setTimeout(() => {
|
|
4776
|
+
finish(() => reject(stoppingCliError(new Error(`Gemini CLI timed out after ${timeout}ms`), proc)));
|
|
4777
|
+
}, timeout);
|
|
4778
|
+
}
|
|
4779
|
+
proc.stdout.on("data", (data) => {
|
|
4780
|
+
const chunk = stdout.write(data);
|
|
4781
|
+
lineBuffer += chunk;
|
|
4782
|
+
let newlineIndex = lineBuffer.indexOf(`
|
|
4783
|
+
`);
|
|
4784
|
+
while (newlineIndex !== -1) {
|
|
4785
|
+
const line = lineBuffer.slice(0, newlineIndex).trim();
|
|
4786
|
+
lineBuffer = lineBuffer.slice(newlineIndex + 1);
|
|
4787
|
+
if (line) {
|
|
4788
|
+
try {
|
|
4789
|
+
const event = JSON.parse(line);
|
|
4790
|
+
const text = extractGeminiEventText(event);
|
|
4791
|
+
if (text && !settled) {
|
|
4792
|
+
try {
|
|
4793
|
+
onChunk(text);
|
|
4794
|
+
} catch (error) {
|
|
4795
|
+
finish(() => reject(stoppingCliError(error, proc)));
|
|
4796
|
+
}
|
|
4797
|
+
}
|
|
4798
|
+
} catch {}
|
|
4799
|
+
}
|
|
4800
|
+
newlineIndex = lineBuffer.indexOf(`
|
|
4801
|
+
`);
|
|
4802
|
+
}
|
|
4803
|
+
});
|
|
4804
|
+
proc.stderr.on("data", (data) => {
|
|
4805
|
+
stderr.write(data);
|
|
4806
|
+
});
|
|
4807
|
+
onCliClose(proc, resolve, reject, (resolve, reject, code) => {
|
|
4808
|
+
lineBuffer += stdout.finish();
|
|
4809
|
+
const raw = stdout.text;
|
|
4810
|
+
const stderrText = stderr.end();
|
|
4811
|
+
flushLineBuffer();
|
|
4812
|
+
if (code !== 0 && code !== null) {
|
|
4813
|
+
finish(() => reject(new Error(`Gemini CLI exited with code ${code}
|
|
4814
|
+
stderr: ${stderrText}`)));
|
|
4815
|
+
return;
|
|
4816
|
+
}
|
|
4817
|
+
finish(() => resolve({
|
|
4818
|
+
text: parseGeminiStreamJson(raw),
|
|
4819
|
+
raw,
|
|
4820
|
+
elapsed: Date.now() - start
|
|
4821
|
+
}));
|
|
4822
|
+
});
|
|
4823
|
+
proc.on("error", (err) => {
|
|
4824
|
+
finish(() => reject(proc.pid ? stoppingCliError(err, proc) : err));
|
|
4825
|
+
});
|
|
4826
|
+
});
|
|
4827
|
+
}
|
|
4828
|
+
|
|
4829
|
+
export { isAgyAcpEnabled2, isAgyAcpProcessPerSessionEnabled2, getAgyAcpSession2, prewarmAgyAcpSession2, closeAgyAcpSession2, adoptAgyAcpSession2, isAgyAcpSharedDaemonEnabled2, prewarmSharedAgyDaemon2, prewarmSharedAgySession2, hasSharedAgySessionHistory2, adoptSharedAgySession2, closeSharedAgySession2, CliProviderQuotaError2, detectCliProviderQuotaLimit2, attachExecutionStoppedPromise2, getExecutionStoppedPromise2, terminateCliProcessGroupEscalating2, executeCli2, executeAgyAcpDirectTurn2, executeAgyAcpOneShot2, executeCliStreaming2 };
|