@jayjiang/open-cc 0.2.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/LICENSE +8 -0
- package/README.md +107 -0
- package/dist/chunk-00dxqxqj.js +227 -0
- package/dist/chunk-01p8hhsp.js +154 -0
- package/dist/chunk-02wy0m47.js +152 -0
- package/dist/chunk-0465tnzh.js +110 -0
- package/dist/chunk-054mjk62.js +678 -0
- package/dist/chunk-06saje2v.js +39 -0
- package/dist/chunk-0731m51q.js +8 -0
- package/dist/chunk-09y0jvtm.js +165 -0
- package/dist/chunk-0fkqze0v.js +113 -0
- package/dist/chunk-0hn525br.js +1920 -0
- package/dist/chunk-0hneh9ha.js +123 -0
- package/dist/chunk-0paqc2yw.js +15 -0
- package/dist/chunk-0rkbrabt.js +32 -0
- package/dist/chunk-0scs4rpx.js +96 -0
- package/dist/chunk-0vkfrmqm.js +690 -0
- package/dist/chunk-0w2byc95.js +38 -0
- package/dist/chunk-0xjaqda8.js +1124 -0
- package/dist/chunk-0y3vcsv4.js +92 -0
- package/dist/chunk-0yb4dz9c.js +26840 -0
- package/dist/chunk-10fdxge0.js +121 -0
- package/dist/chunk-1141xmr4.js +8 -0
- package/dist/chunk-14vffdmg.js +38 -0
- package/dist/chunk-178ykx7k.js +1493 -0
- package/dist/chunk-1bhva2z9.js +128 -0
- package/dist/chunk-1c8z1b5v.js +16 -0
- package/dist/chunk-1cbn5kxf.js +7 -0
- package/dist/chunk-1che51a5.js +1585 -0
- package/dist/chunk-1h2famwb.js +49 -0
- package/dist/chunk-1jrkpnbn.js +71 -0
- package/dist/chunk-1k4j1xcf.js +154 -0
- package/dist/chunk-1mm9d8p4.js +70 -0
- package/dist/chunk-1n3gnn2t.js +41 -0
- package/dist/chunk-1nqaq1rs.js +654 -0
- package/dist/chunk-1p2j9g3w.js +998 -0
- package/dist/chunk-1p7jfcee.js +533 -0
- package/dist/chunk-1pg8s12r.js +338 -0
- package/dist/chunk-1qjb22fx.js +109 -0
- package/dist/chunk-1yzc16qa.js +39 -0
- package/dist/chunk-20gm89wf.js +208 -0
- package/dist/chunk-238g70xa.js +36 -0
- package/dist/chunk-26k0324b.js +751 -0
- package/dist/chunk-27xc1csx.js +104 -0
- package/dist/chunk-2a42s11t.js +412 -0
- package/dist/chunk-2bhq4emw.js +10476 -0
- package/dist/chunk-2eykm0j0.js +20 -0
- package/dist/chunk-2gzv8nrw.js +205 -0
- package/dist/chunk-2k995y2x.js +880 -0
- package/dist/chunk-2kpzaa7w.js +401 -0
- package/dist/chunk-2nayx6q1.js +63 -0
- package/dist/chunk-2qhs9n36.js +151 -0
- package/dist/chunk-2s5f2nnw.js +603 -0
- package/dist/chunk-2y54j9ew.js +174394 -0
- package/dist/chunk-2zcaw1jd.js +2343 -0
- package/dist/chunk-30chpfyc.js +15275 -0
- package/dist/chunk-30k39xd2.js +28 -0
- package/dist/chunk-30rst83v.js +168 -0
- package/dist/chunk-36z5enc4.js +160 -0
- package/dist/chunk-3c25bcsw.js +17 -0
- package/dist/chunk-3c4qja3e.js +63 -0
- package/dist/chunk-3ccx8k84.js +102 -0
- package/dist/chunk-3envnthj.js +157 -0
- package/dist/chunk-3h8a89gy.js +46 -0
- package/dist/chunk-3kadbep2.js +6956 -0
- package/dist/chunk-3kd79cnk.js +15 -0
- package/dist/chunk-3m45xtza.js +1188 -0
- package/dist/chunk-3q50xe1j.js +17 -0
- package/dist/chunk-3w6s9m5w.js +16 -0
- package/dist/chunk-3x0408tc.js +42 -0
- package/dist/chunk-3z7ae04g.js +372 -0
- package/dist/chunk-40tedt0y.js +275 -0
- package/dist/chunk-44q8kegv.js +811 -0
- package/dist/chunk-47gy6qkp.js +328 -0
- package/dist/chunk-495d85x1.js +8066 -0
- package/dist/chunk-4axcksrv.js +129 -0
- package/dist/chunk-4e1271a8.js +106 -0
- package/dist/chunk-4g3v8y12.js +23 -0
- package/dist/chunk-4g5mrzm0.js +220 -0
- package/dist/chunk-4jm600zv.js +13 -0
- package/dist/chunk-4n989n6h.js +153 -0
- package/dist/chunk-4qedx22a.js +44 -0
- package/dist/chunk-4rze71rx.js +116 -0
- package/dist/chunk-4wbhvcag.js +91 -0
- package/dist/chunk-4zfkzkt6.js +37 -0
- package/dist/chunk-55wgxwa9.js +13877 -0
- package/dist/chunk-56ta4h0b.js +154 -0
- package/dist/chunk-58a0x39g.js +89 -0
- package/dist/chunk-5dbk24zg.js +890 -0
- package/dist/chunk-5gzg4q1k.js +99 -0
- package/dist/chunk-5k2gdxnr.js +336 -0
- package/dist/chunk-5kp252z6.js +202 -0
- package/dist/chunk-5p2ssw3d.js +825 -0
- package/dist/chunk-5w33j8gy.js +1580 -0
- package/dist/chunk-5ywjzvm8.js +61 -0
- package/dist/chunk-5ztxx8gd.js +80 -0
- package/dist/chunk-62vwr0y5.js +117 -0
- package/dist/chunk-6b8ksqmf.js +1153 -0
- package/dist/chunk-6bd8brc4.js +48 -0
- package/dist/chunk-6cpqmd4r.js +132 -0
- package/dist/chunk-6dj5t602.js +341 -0
- package/dist/chunk-6g62sjpf.js +328 -0
- package/dist/chunk-6gr3c3w9.js +378 -0
- package/dist/chunk-6h9n8qbr.js +1170 -0
- package/dist/chunk-6kpbgc5w.js +23 -0
- package/dist/chunk-6n2qgm9v.js +8 -0
- package/dist/chunk-6n6jfmce.js +2833 -0
- package/dist/chunk-6q2x8zeg.js +802 -0
- package/dist/chunk-6tnekwtp.js +849 -0
- package/dist/chunk-6tq2v3rk.js +186 -0
- package/dist/chunk-6vphqqd1.js +27 -0
- package/dist/chunk-6wkdqk81.js +444 -0
- package/dist/chunk-7226mgjt.js +195 -0
- package/dist/chunk-72fey14y.js +565 -0
- package/dist/chunk-73fgm72g.js +698 -0
- package/dist/chunk-73fhat5j.js +212 -0
- package/dist/chunk-73rpbt04.js +1947 -0
- package/dist/chunk-743znc5c.js +56 -0
- package/dist/chunk-760252na.js +101 -0
- package/dist/chunk-76t2h5v2.js +495 -0
- package/dist/chunk-7739pg2c.js +4261 -0
- package/dist/chunk-789khc7a.js +96 -0
- package/dist/chunk-78mma1s7.js +88 -0
- package/dist/chunk-7aw745vx.js +40175 -0
- package/dist/chunk-7azp8c8y.js +584 -0
- package/dist/chunk-7m2nd8da.js +110 -0
- package/dist/chunk-7pemewz2.js +726 -0
- package/dist/chunk-7rjyn5d3.js +125 -0
- package/dist/chunk-7v0wq9nk.js +93 -0
- package/dist/chunk-7wm5s02e.js +216 -0
- package/dist/chunk-83hfzbx3.js +10 -0
- package/dist/chunk-84k64e4a.js +1646 -0
- package/dist/chunk-87jfpcm7.js +438 -0
- package/dist/chunk-8btm871b.js +42 -0
- package/dist/chunk-8hbbzet5.js +34 -0
- package/dist/chunk-8hq5kk3y.js +44 -0
- package/dist/chunk-8j6vs75t.js +256 -0
- package/dist/chunk-8ngxagxq.js +18 -0
- package/dist/chunk-8nsem424.js +110 -0
- package/dist/chunk-8pf73pc8.js +169 -0
- package/dist/chunk-8tnsngw2.js +31 -0
- package/dist/chunk-8y12jxg8.js +10 -0
- package/dist/chunk-8ymf4e6z.js +48 -0
- package/dist/chunk-90wp6wez.js +10510 -0
- package/dist/chunk-95dt8mpg.js +603 -0
- package/dist/chunk-95rj8m4e.js +130 -0
- package/dist/chunk-9ebygqen.js +89 -0
- package/dist/chunk-9gbamk79.js +93 -0
- package/dist/chunk-9tkq3g56.js +642 -0
- package/dist/chunk-a05hje2h.js +105 -0
- package/dist/chunk-a2krhf3c.js +90 -0
- package/dist/chunk-a6q9rehn.js +182 -0
- package/dist/chunk-a78b3pvt.js +71 -0
- package/dist/chunk-a8ejc632.js +3094 -0
- package/dist/chunk-a9vdeb6y.js +258 -0
- package/dist/chunk-a9zh40sj.js +48 -0
- package/dist/chunk-ab59azrr.js +480 -0
- package/dist/chunk-accxhkm6.js +88 -0
- package/dist/chunk-adzd8pzb.js +1095 -0
- package/dist/chunk-ae76ded0.js +30 -0
- package/dist/chunk-aftppv3p.js +691 -0
- package/dist/chunk-agmw1vmf.js +725 -0
- package/dist/chunk-an5cb1vx.js +16 -0
- package/dist/chunk-b1s11z4y.js +63 -0
- package/dist/chunk-b2rkh01x.js +443 -0
- package/dist/chunk-b4w4argn.js +1551 -0
- package/dist/chunk-b4wg70y1.js +54 -0
- package/dist/chunk-b5b7h81y.js +7189 -0
- package/dist/chunk-b9k5cs09.js +50 -0
- package/dist/chunk-bapy5rc8.js +40 -0
- package/dist/chunk-bda3gxxz.js +246 -0
- package/dist/chunk-bhdt6k7w.js +15 -0
- package/dist/chunk-bm1qb16p.js +17 -0
- package/dist/chunk-bp0dnrwg.js +281 -0
- package/dist/chunk-bqfnp99q.js +477 -0
- package/dist/chunk-bs6keys0.js +158 -0
- package/dist/chunk-bsbmmfyt.js +17 -0
- package/dist/chunk-btkettbr.js +166 -0
- package/dist/chunk-bwgde7nf.js +37 -0
- package/dist/chunk-c1zc58pw.js +280 -0
- package/dist/chunk-c2g96ga2.js +184 -0
- package/dist/chunk-c3z7ptb2.js +21933 -0
- package/dist/chunk-c8vn3ynx.js +349 -0
- package/dist/chunk-cdm0k2n0.js +115 -0
- package/dist/chunk-cdz5yb0r.js +57 -0
- package/dist/chunk-cfv996bs.js +22 -0
- package/dist/chunk-cg788ab0.js +100 -0
- package/dist/chunk-cgfdkzhb.js +12 -0
- package/dist/chunk-cp76dsdp.js +386 -0
- package/dist/chunk-cr6t6rth.js +306 -0
- package/dist/chunk-cvp5vayb.js +31 -0
- package/dist/chunk-cwehsmj5.js +114 -0
- package/dist/chunk-cy2hswr1.js +15 -0
- package/dist/chunk-d2rzy2p0.js +42 -0
- package/dist/chunk-d3v2fbay.js +106 -0
- package/dist/chunk-dc4eha8a.js +243 -0
- package/dist/chunk-dcz167d6.js +73 -0
- package/dist/chunk-de55jjre.js +106 -0
- package/dist/chunk-dfx733j3.js +650 -0
- package/dist/chunk-dgqrcy74.js +48 -0
- package/dist/chunk-dj6dk19k.js +55 -0
- package/dist/chunk-dn2xcmc4.js +173 -0
- package/dist/chunk-dndehvfr.js +57 -0
- package/dist/chunk-dnh7jtpb.js +37 -0
- package/dist/chunk-dnwzz9f7.js +88 -0
- package/dist/chunk-dv1wfr85.js +6373 -0
- package/dist/chunk-dwq5rs3q.js +62 -0
- package/dist/chunk-dz8exe78.js +91 -0
- package/dist/chunk-e4rzw1sd.js +606 -0
- package/dist/chunk-e6rrwzv0.js +463 -0
- package/dist/chunk-e6t9kpzq.js +145 -0
- package/dist/chunk-e7c8ypwc.js +287 -0
- package/dist/chunk-e9nkfs4e.js +738 -0
- package/dist/chunk-eaf7c8ck.js +537 -0
- package/dist/chunk-ebyr6p77.js +115 -0
- package/dist/chunk-edfv7pme.js +104 -0
- package/dist/chunk-eh474zhj.js +59 -0
- package/dist/chunk-er8ckwzt.js +140 -0
- package/dist/chunk-ev5p07yh.js +144 -0
- package/dist/chunk-ewadzrm8.js +103 -0
- package/dist/chunk-f2mhrmww.js +62 -0
- package/dist/chunk-f2zhqnb6.js +69 -0
- package/dist/chunk-f5ma3nh5.js +3436 -0
- package/dist/chunk-f63q7vx7.js +756 -0
- package/dist/chunk-fbv4apne.js +51 -0
- package/dist/chunk-fcna95wg.js +113 -0
- package/dist/chunk-fdvcpaz3.js +163 -0
- package/dist/chunk-fgc0q2b2.js +3354 -0
- package/dist/chunk-fm2jvsk7.js +87 -0
- package/dist/chunk-ft7fs35e.js +282 -0
- package/dist/chunk-fyc5fepv.js +10 -0
- package/dist/chunk-g0j0t6qk.js +26 -0
- package/dist/chunk-g0nbec9m.js +32 -0
- package/dist/chunk-g1fdv1kb.js +86 -0
- package/dist/chunk-g338npwr.js +1061 -0
- package/dist/chunk-g3t0act8.js +8 -0
- package/dist/chunk-g6qddbvf.js +1391 -0
- package/dist/chunk-ga5faygf.js +61 -0
- package/dist/chunk-gac6nzhc.js +90 -0
- package/dist/chunk-gck2cswd.js +862 -0
- package/dist/chunk-gntr3b25.js +40683 -0
- package/dist/chunk-gq5bbtme.js +456 -0
- package/dist/chunk-gyj242zr.js +20 -0
- package/dist/chunk-h0qngp9w.js +157 -0
- package/dist/chunk-h1xnvnye.js +524 -0
- package/dist/chunk-h3mhfamg.js +60 -0
- package/dist/chunk-h6s1tx0e.js +250 -0
- package/dist/chunk-h7qb4hyj.js +70 -0
- package/dist/chunk-h8qd1gw2.js +106 -0
- package/dist/chunk-hakdhagh.js +16606 -0
- package/dist/chunk-hcdt34n4.js +143 -0
- package/dist/chunk-hh7cmy4k.js +20 -0
- package/dist/chunk-hk9xz7gk.js +118 -0
- package/dist/chunk-hqmz36b3.js +552 -0
- package/dist/chunk-hs8ph4p8.js +8 -0
- package/dist/chunk-hsq4vtjy.js +92 -0
- package/dist/chunk-hzhd0p1y.js +104 -0
- package/dist/chunk-hzhe8ygc.js +547 -0
- package/dist/chunk-j0tqbsh7.js +176 -0
- package/dist/chunk-j1s1jvad.js +346 -0
- package/dist/chunk-j2k4p94p.js +55 -0
- package/dist/chunk-j3a4p81y.js +184 -0
- package/dist/chunk-j595yd4h.js +439 -0
- package/dist/chunk-j64ga6ta.js +8035 -0
- package/dist/chunk-j7qwxra8.js +2335 -0
- package/dist/chunk-j98f65zv.js +789 -0
- package/dist/chunk-jd32zbps.js +15 -0
- package/dist/chunk-jdgeec04.js +4249 -0
- package/dist/chunk-jdt5s5k7.js +62 -0
- package/dist/chunk-jeaek018.js +97 -0
- package/dist/chunk-jkhvm8yk.js +104 -0
- package/dist/chunk-jmxaze30.js +780 -0
- package/dist/chunk-jne71s1f.js +104 -0
- package/dist/chunk-jnhkref0.js +30 -0
- package/dist/chunk-jpgr7zfs.js +95 -0
- package/dist/chunk-jqp0q5nk.js +339 -0
- package/dist/chunk-jtqgnyaq.js +1317 -0
- package/dist/chunk-jx817w05.js +11 -0
- package/dist/chunk-jynzr5w9.js +71 -0
- package/dist/chunk-jzmz18nn.js +65 -0
- package/dist/chunk-k0p9w03v.js +4957 -0
- package/dist/chunk-k1jnpyj9.js +155 -0
- package/dist/chunk-k445en8h.js +102 -0
- package/dist/chunk-k62k13ya.js +81 -0
- package/dist/chunk-kf8kjmfv.js +821 -0
- package/dist/chunk-kgn1nfg9.js +468 -0
- package/dist/chunk-khmz14d4.js +38 -0
- package/dist/chunk-kjhmt6ba.js +100 -0
- package/dist/chunk-kkrz2zw2.js +122 -0
- package/dist/chunk-kv1ryvtm.js +176 -0
- package/dist/chunk-kwekc97v.js +18 -0
- package/dist/chunk-kyvwf342.js +65 -0
- package/dist/chunk-m0g3xv72.js +266 -0
- package/dist/chunk-m26twd8m.js +277 -0
- package/dist/chunk-m4bc15mz.js +229 -0
- package/dist/chunk-m9t8j37k.js +253 -0
- package/dist/chunk-mb2gpwwf.js +432 -0
- package/dist/chunk-mezwt1bt.js +306 -0
- package/dist/chunk-mfm83xn5.js +84 -0
- package/dist/chunk-mn7870fh.js +4389 -0
- package/dist/chunk-mr9df5v8.js +722 -0
- package/dist/chunk-mt25echc.js +6157 -0
- package/dist/chunk-mwrr6zbb.js +55 -0
- package/dist/chunk-mywpbwad.js +198 -0
- package/dist/chunk-mzdtkccs.js +125 -0
- package/dist/chunk-mzn0z9d3.js +691 -0
- package/dist/chunk-n0qaeaa5.js +256 -0
- package/dist/chunk-n128bzxs.js +2739 -0
- package/dist/chunk-n1erf6kh.js +22820 -0
- package/dist/chunk-n4nbgkvd.js +520 -0
- package/dist/chunk-n5gkdn9v.js +120 -0
- package/dist/chunk-n7ttdtk0.js +641 -0
- package/dist/chunk-n8b1njwb.js +208 -0
- package/dist/chunk-nek12gtk.js +94 -0
- package/dist/chunk-nerv0jvx.js +74 -0
- package/dist/chunk-nka1g8f4.js +773 -0
- package/dist/chunk-nm2cncrq.js +336 -0
- package/dist/chunk-nq0fxyxh.js +752 -0
- package/dist/chunk-nrnkshv2.js +192 -0
- package/dist/chunk-nsqma629.js +128 -0
- package/dist/chunk-nt837qt9.js +21 -0
- package/dist/chunk-nttf3k0r.js +2643 -0
- package/dist/chunk-nx638j6h.js +268 -0
- package/dist/chunk-nx7s0zn5.js +375 -0
- package/dist/chunk-p0hff8zy.js +8871 -0
- package/dist/chunk-p2816w9z.js +1486 -0
- package/dist/chunk-p2d5nh3g.js +342 -0
- package/dist/chunk-p57bz7nv.js +55 -0
- package/dist/chunk-p5z8t6r3.js +130 -0
- package/dist/chunk-pd6653na.js +5394 -0
- package/dist/chunk-pjnzf3cg.js +61 -0
- package/dist/chunk-ps49ymvj.js +43 -0
- package/dist/chunk-pthzapbx.js +348 -0
- package/dist/chunk-pwwa7s62.js +11 -0
- package/dist/chunk-pyx135a5.js +20 -0
- package/dist/chunk-q132dkwr.js +195 -0
- package/dist/chunk-q16y18s1.js +120 -0
- package/dist/chunk-q25bjaev.js +15 -0
- package/dist/chunk-q3jxs36m.js +716 -0
- package/dist/chunk-q5by3da6.js +8 -0
- package/dist/chunk-q663msp4.js +908 -0
- package/dist/chunk-qezgfppb.js +4521 -0
- package/dist/chunk-qgjgqmy5.js +5796 -0
- package/dist/chunk-qj7h3xc3.js +40 -0
- package/dist/chunk-qjcxkbv6.js +644 -0
- package/dist/chunk-qnfx3qtx.js +617 -0
- package/dist/chunk-qnmyzsam.js +84 -0
- package/dist/chunk-qp2qdcda.js +100 -0
- package/dist/chunk-qvrq1sby.js +6107 -0
- package/dist/chunk-qz2x630m.js +49145 -0
- package/dist/chunk-qz3fe4fj.js +469 -0
- package/dist/chunk-r0af6bw0.js +173 -0
- package/dist/chunk-r1v8d6da.js +1299 -0
- package/dist/chunk-r6b58y3x.js +17 -0
- package/dist/chunk-r6e45bzh.js +118 -0
- package/dist/chunk-r843jezp.js +28 -0
- package/dist/chunk-rbgjkg3v.js +90 -0
- package/dist/chunk-rc5bbzx4.js +655 -0
- package/dist/chunk-rca5xtnd.js +267 -0
- package/dist/chunk-rfdbzyjh.js +1865 -0
- package/dist/chunk-rh7q28df.js +93 -0
- package/dist/chunk-rn0v1hk8.js +34 -0
- package/dist/chunk-rvxs7x7j.js +542 -0
- package/dist/chunk-rw6fwk2s.js +98 -0
- package/dist/chunk-rwagvxh5.js +1711 -0
- package/dist/chunk-s10vyjz4.js +224 -0
- package/dist/chunk-s274nv8k.js +8 -0
- package/dist/chunk-s3pzvdss.js +50 -0
- package/dist/chunk-s4w01jsb.js +969 -0
- package/dist/chunk-s56j2d6g.js +500 -0
- package/dist/chunk-sbs1r0h4.js +317 -0
- package/dist/chunk-sd36yzx8.js +954 -0
- package/dist/chunk-sd6env07.js +19 -0
- package/dist/chunk-sdj9b9wh.js +782 -0
- package/dist/chunk-sfht9xvd.js +24 -0
- package/dist/chunk-sk3gpkdt.js +89 -0
- package/dist/chunk-sp5cjcjh.js +526 -0
- package/dist/chunk-sq847dr5.js +1528 -0
- package/dist/chunk-sskngwam.js +89 -0
- package/dist/chunk-svar8pp2.js +276 -0
- package/dist/chunk-szj5wvdy.js +28 -0
- package/dist/chunk-t175chdd.js +714 -0
- package/dist/chunk-t4k75hqs.js +4987 -0
- package/dist/chunk-t7z7vg91.js +225 -0
- package/dist/chunk-tanfpxm1.js +419 -0
- package/dist/chunk-tf9h0cyj.js +3037 -0
- package/dist/chunk-tm1wwvm1.js +99 -0
- package/dist/chunk-trtgjd28.js +9300 -0
- package/dist/chunk-ts2p6bv1.js +224 -0
- package/dist/chunk-ttk5dzz8.js +25 -0
- package/dist/chunk-tvg352rv.js +391 -0
- package/dist/chunk-tww14j0s.js +86 -0
- package/dist/chunk-tz03j2da.js +66 -0
- package/dist/chunk-v1kzp02e.js +785 -0
- package/dist/chunk-v2sm9w6h.js +220 -0
- package/dist/chunk-v3gm2day.js +8 -0
- package/dist/chunk-v4qn3g0d.js +286 -0
- package/dist/chunk-v66tbnn6.js +476 -0
- package/dist/chunk-v78fj8by.js +145 -0
- package/dist/chunk-v9smspw2.js +4301 -0
- package/dist/chunk-v9ybze94.js +713 -0
- package/dist/chunk-vest0y6x.js +3830 -0
- package/dist/chunk-vf5sd1nq.js +12 -0
- package/dist/chunk-vht4mzgb.js +298 -0
- package/dist/chunk-vjwgf4qh.js +41 -0
- package/dist/chunk-vkrhafhf.js +248 -0
- package/dist/chunk-vn56q87z.js +2058 -0
- package/dist/chunk-vscz82fv.js +27 -0
- package/dist/chunk-vvn4gkak.js +642 -0
- package/dist/chunk-vxj5rbg5.js +84 -0
- package/dist/chunk-vyjeh50y.js +2149 -0
- package/dist/chunk-w44nvpvt.js +22 -0
- package/dist/chunk-waambva2.js +2430 -0
- package/dist/chunk-wbhsqc2a.js +275 -0
- package/dist/chunk-wbsnpxzh.js +471 -0
- package/dist/chunk-wfz0qffj.js +3939 -0
- package/dist/chunk-wpqbrv0f.js +83 -0
- package/dist/chunk-wzpdet3m.js +843 -0
- package/dist/chunk-x6tb96y2.js +264 -0
- package/dist/chunk-x8b7vft8.js +132 -0
- package/dist/chunk-x8eg216f.js +99 -0
- package/dist/chunk-xc9khn0r.js +490 -0
- package/dist/chunk-xch406a3.js +673 -0
- package/dist/chunk-xdw5dv00.js +8 -0
- package/dist/chunk-xe0bpcbr.js +3444 -0
- package/dist/chunk-xm3ed3zn.js +300 -0
- package/dist/chunk-xpm4ebhz.js +87 -0
- package/dist/chunk-xr6yfttj.js +43 -0
- package/dist/chunk-xsq9ae7x.js +90 -0
- package/dist/chunk-xszk7n10.js +14358 -0
- package/dist/chunk-xzmkekfb.js +259 -0
- package/dist/chunk-y1784krc.js +19 -0
- package/dist/chunk-y3py9g5d.js +213 -0
- package/dist/chunk-y9nnmev5.js +687 -0
- package/dist/chunk-ya6jq0hf.js +29 -0
- package/dist/chunk-ycc3xnx0.js +374 -0
- package/dist/chunk-yfa54ssn.js +87 -0
- package/dist/chunk-ymy4xrr8.js +101 -0
- package/dist/chunk-yqfz2k9z.js +48 -0
- package/dist/chunk-ywxd4qw4.js +22 -0
- package/dist/chunk-yxmz5k16.js +122 -0
- package/dist/chunk-yxvy4jt4.js +1014 -0
- package/dist/chunk-z2dp53wn.js +17 -0
- package/dist/chunk-z2xxx2sz.js +294 -0
- package/dist/chunk-z31an09g.js +67 -0
- package/dist/chunk-z95xqvr0.js +75 -0
- package/dist/chunk-zbmxxxz8.js +161 -0
- package/dist/chunk-zk2wsm7d.js +15 -0
- package/dist/chunk-zmg1pcp3.js +71 -0
- package/dist/chunk-znrwmznk.js +272 -0
- package/dist/chunk-zq9r43cb.js +26 -0
- package/dist/chunk-zsfxha74.js +17655 -0
- package/dist/chunk-ztpr96av.js +229 -0
- package/dist/chunk-zv7qrz04.js +58 -0
- package/dist/chunk-zxa7st21.js +32 -0
- package/dist/chunk-zxhezavg.js +216 -0
- package/dist/chunk-zz0qcq2n.js +434 -0
- package/dist/cli.js +194 -0
- package/package.json +164 -0
|
@@ -0,0 +1,4987 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
HybridTransport,
|
|
4
|
+
WebSocketTransport
|
|
5
|
+
} from "./chunk-y9nnmev5.js";
|
|
6
|
+
import {
|
|
7
|
+
CCRClient,
|
|
8
|
+
CCRInitError,
|
|
9
|
+
SSETransport
|
|
10
|
+
} from "./chunk-3m45xtza.js";
|
|
11
|
+
import {
|
|
12
|
+
StructuredIO,
|
|
13
|
+
buildSystemInitMessage,
|
|
14
|
+
exports_MessageSelector,
|
|
15
|
+
extractInboundMessageFields,
|
|
16
|
+
init_MessageSelector,
|
|
17
|
+
ndjsonSafeStringify,
|
|
18
|
+
outputSchema,
|
|
19
|
+
permissionPromptToolResultToPermissionDecision,
|
|
20
|
+
processUserInput,
|
|
21
|
+
reconcileMarketplaces,
|
|
22
|
+
sdkCompatToolName
|
|
23
|
+
} from "./chunk-n128bzxs.js";
|
|
24
|
+
import {
|
|
25
|
+
detectAndUninstallDelistedPlugins
|
|
26
|
+
} from "./chunk-yfa54ssn.js";
|
|
27
|
+
import {
|
|
28
|
+
restoreAgentFromSession,
|
|
29
|
+
restoreSessionStateFromLog,
|
|
30
|
+
skillChangeDetector
|
|
31
|
+
} from "./chunk-gq5bbtme.js";
|
|
32
|
+
import"./chunk-nt837qt9.js";
|
|
33
|
+
import"./chunk-a6q9rehn.js";
|
|
34
|
+
import {
|
|
35
|
+
externalMetadataToAppState
|
|
36
|
+
} from "./chunk-00dxqxqj.js";
|
|
37
|
+
import"./chunk-x8b7vft8.js";
|
|
38
|
+
import {
|
|
39
|
+
getSessionState,
|
|
40
|
+
notifySessionMetadataChanged,
|
|
41
|
+
notifySessionStateChanged,
|
|
42
|
+
setPermissionModeChangedListener,
|
|
43
|
+
setSessionMetadataChangedListener,
|
|
44
|
+
setSessionStateChangedListener
|
|
45
|
+
} from "./chunk-5ywjzvm8.js";
|
|
46
|
+
import {
|
|
47
|
+
getPollIntervalConfig
|
|
48
|
+
} from "./chunk-pjnzf3cg.js";
|
|
49
|
+
import"./chunk-02wy0m47.js";
|
|
50
|
+
import {
|
|
51
|
+
init_settingsSync
|
|
52
|
+
} from "./chunk-tww14j0s.js";
|
|
53
|
+
import {
|
|
54
|
+
init_refresh,
|
|
55
|
+
refreshActivePlugins
|
|
56
|
+
} from "./chunk-er8ckwzt.js";
|
|
57
|
+
import {
|
|
58
|
+
init_toolPool,
|
|
59
|
+
mergeAndFilterTools
|
|
60
|
+
} from "./chunk-g0nbec9m.js";
|
|
61
|
+
import"./chunk-jynzr5w9.js";
|
|
62
|
+
import {
|
|
63
|
+
init_mappers,
|
|
64
|
+
localCommandOutputToSDKAssistantMessage,
|
|
65
|
+
toInternalMessages,
|
|
66
|
+
toSDKCompactMetadata,
|
|
67
|
+
toSDKRateLimitInfo
|
|
68
|
+
} from "./chunk-ztpr96av.js";
|
|
69
|
+
import {
|
|
70
|
+
generateSessionTitle,
|
|
71
|
+
init_sessionTitle
|
|
72
|
+
} from "./chunk-p5z8t6r3.js";
|
|
73
|
+
import {
|
|
74
|
+
getBridgeAccessToken,
|
|
75
|
+
getBridgeBaseUrl,
|
|
76
|
+
init_bridgeConfig
|
|
77
|
+
} from "./chunk-zxa7st21.js";
|
|
78
|
+
import {
|
|
79
|
+
ChannelMessageNotificationSchema,
|
|
80
|
+
findChannelEntry,
|
|
81
|
+
gateChannelServer,
|
|
82
|
+
init_channelAllowlist,
|
|
83
|
+
init_channelNotification,
|
|
84
|
+
init_omit,
|
|
85
|
+
omit_default,
|
|
86
|
+
wrapChannelMessage
|
|
87
|
+
} from "./chunk-s56j2d6g.js";
|
|
88
|
+
import"./chunk-qjcxkbv6.js";
|
|
89
|
+
import"./chunk-20gm89wf.js";
|
|
90
|
+
import {
|
|
91
|
+
collectContextData,
|
|
92
|
+
init_context_noninteractive
|
|
93
|
+
} from "./chunk-bp0dnrwg.js";
|
|
94
|
+
import {
|
|
95
|
+
init_sideQuestion,
|
|
96
|
+
runSideQuestion
|
|
97
|
+
} from "./chunk-rw6fwk2s.js";
|
|
98
|
+
import"./chunk-rn0v1hk8.js";
|
|
99
|
+
import {
|
|
100
|
+
DEFAULT_OUTPUT_STYLE_NAME,
|
|
101
|
+
EFFORT_LEVELS,
|
|
102
|
+
OAuthService,
|
|
103
|
+
SHELL_TOOL_NAMES,
|
|
104
|
+
SYNTHETIC_MESSAGES,
|
|
105
|
+
SYNTHETIC_OUTPUT_TOOL_NAME,
|
|
106
|
+
SandboxManager,
|
|
107
|
+
accumulateUsage,
|
|
108
|
+
applySettingsChange,
|
|
109
|
+
areMcpConfigsEqual,
|
|
110
|
+
asSessionId,
|
|
111
|
+
asSystemPrompt,
|
|
112
|
+
assembleToolPool,
|
|
113
|
+
atomicWriteToZipCache,
|
|
114
|
+
buildBridgeConnectUrl,
|
|
115
|
+
categorizeRetryableAPIError,
|
|
116
|
+
checkGroveForNonInteractive,
|
|
117
|
+
cleanupSessionPluginCache,
|
|
118
|
+
clearCommandsCache,
|
|
119
|
+
clearMarketplacesCache,
|
|
120
|
+
clearPluginCache,
|
|
121
|
+
clearServerCache,
|
|
122
|
+
commandBelongsToServer,
|
|
123
|
+
connectToServer,
|
|
124
|
+
countToolCalls,
|
|
125
|
+
createAbortController,
|
|
126
|
+
createCombinedAbortSignal,
|
|
127
|
+
createModelSwitchBreadcrumbs,
|
|
128
|
+
createSyntheticOutputTool,
|
|
129
|
+
dequeue,
|
|
130
|
+
dequeueAllMatching,
|
|
131
|
+
doesMessageExistInSession,
|
|
132
|
+
drainSdkEvents,
|
|
133
|
+
enqueue,
|
|
134
|
+
executeNotificationHooks,
|
|
135
|
+
extractReadFilesFromMessages,
|
|
136
|
+
fetchToolsForClient,
|
|
137
|
+
fileHistoryCanRestore,
|
|
138
|
+
fileHistoryEnabled,
|
|
139
|
+
fileHistoryGetDiffStats,
|
|
140
|
+
fileHistoryMakeSnapshot,
|
|
141
|
+
fileHistoryRewind,
|
|
142
|
+
filterMcpServersByPolicy,
|
|
143
|
+
filterToolsByDenyRules,
|
|
144
|
+
filterToolsByServer,
|
|
145
|
+
finalizePendingAsyncHooks,
|
|
146
|
+
findUnresolvedToolUse,
|
|
147
|
+
flushSessionStorage,
|
|
148
|
+
formatDescriptionWithSource,
|
|
149
|
+
fromArray,
|
|
150
|
+
getAllMcpConfigs,
|
|
151
|
+
getAllOutputStyles,
|
|
152
|
+
getCommandName,
|
|
153
|
+
getCommands,
|
|
154
|
+
getCommandsByMaxPriority,
|
|
155
|
+
getDeclaredMarketplaces,
|
|
156
|
+
getLastCacheSafeParams,
|
|
157
|
+
getMarketplaceJsonRelativePath,
|
|
158
|
+
getMcpConfigByName,
|
|
159
|
+
getModelOptions,
|
|
160
|
+
getPluginZipCachePath,
|
|
161
|
+
getRemoteSessionUrl,
|
|
162
|
+
getRunningTasks,
|
|
163
|
+
getScratchpadDir,
|
|
164
|
+
getSlashCommandToolSkills,
|
|
165
|
+
getSystemContext,
|
|
166
|
+
getSystemPrompt,
|
|
167
|
+
getUserContext,
|
|
168
|
+
getZipCacheKnownMarketplacesPath,
|
|
169
|
+
getZipCacheMarketplacesDir,
|
|
170
|
+
getZipCachePluginsDir,
|
|
171
|
+
gracefulShutdown,
|
|
172
|
+
gracefulShutdownSync,
|
|
173
|
+
handleOrphanedPermission,
|
|
174
|
+
hasCommandsInQueue,
|
|
175
|
+
hasPermissionsToUseTool,
|
|
176
|
+
headlessProfilerCheckpoint,
|
|
177
|
+
headlessProfilerStartTurn,
|
|
178
|
+
hydrateFromCCRv2InternalEvents,
|
|
179
|
+
hydrateRemoteSession,
|
|
180
|
+
init_AsyncHookRegistry,
|
|
181
|
+
init_Shell,
|
|
182
|
+
init_SyntheticOutputTool,
|
|
183
|
+
init_Tool,
|
|
184
|
+
init_abortController,
|
|
185
|
+
init_applySettingsChange,
|
|
186
|
+
init_auth as init_auth2,
|
|
187
|
+
init_auth1 as init_auth3,
|
|
188
|
+
init_bridgeStatusUtil,
|
|
189
|
+
init_changeDetector,
|
|
190
|
+
init_claude,
|
|
191
|
+
init_claudeAiLimits,
|
|
192
|
+
init_client,
|
|
193
|
+
init_combinedAbortSignal,
|
|
194
|
+
init_commandLifecycle,
|
|
195
|
+
init_commands1 as init_commands,
|
|
196
|
+
init_config as init_config2,
|
|
197
|
+
init_constants,
|
|
198
|
+
init_constants1 as init_constants2,
|
|
199
|
+
init_context,
|
|
200
|
+
init_conversationRecovery,
|
|
201
|
+
init_cost_tracker,
|
|
202
|
+
init_effort,
|
|
203
|
+
init_elicitationHandler,
|
|
204
|
+
init_errors as init_errors2,
|
|
205
|
+
init_fileHistory,
|
|
206
|
+
init_filesApi,
|
|
207
|
+
init_filesystem,
|
|
208
|
+
init_forkedAgent,
|
|
209
|
+
init_framework,
|
|
210
|
+
init_generators,
|
|
211
|
+
init_gracefulShutdown,
|
|
212
|
+
init_grove,
|
|
213
|
+
init_headlessProfiler,
|
|
214
|
+
init_hookEvents,
|
|
215
|
+
init_hookHelpers,
|
|
216
|
+
init_hooks1 as init_hooks,
|
|
217
|
+
init_ids,
|
|
218
|
+
init_last,
|
|
219
|
+
init_loadAgentsDir,
|
|
220
|
+
init_logging,
|
|
221
|
+
init_marketplaceManager,
|
|
222
|
+
init_memdir,
|
|
223
|
+
init_messageQueueManager,
|
|
224
|
+
init_messages1 as init_messages,
|
|
225
|
+
init_modelOptions,
|
|
226
|
+
init_oauth,
|
|
227
|
+
init_outputStyles,
|
|
228
|
+
init_outputsScanner,
|
|
229
|
+
init_permissionSetup,
|
|
230
|
+
init_permissions,
|
|
231
|
+
init_pluginIdentifier,
|
|
232
|
+
init_pluginLoader,
|
|
233
|
+
init_policyLimits,
|
|
234
|
+
init_product,
|
|
235
|
+
init_prompt as init_prompt2,
|
|
236
|
+
init_prompt1 as init_prompt3,
|
|
237
|
+
init_prompt10 as init_prompt7,
|
|
238
|
+
init_prompt11 as init_prompt8,
|
|
239
|
+
init_prompt2 as init_prompt4,
|
|
240
|
+
init_prompt3 as init_prompt5,
|
|
241
|
+
init_prompt5 as init_prompt6,
|
|
242
|
+
init_promptSuggestion,
|
|
243
|
+
init_prompts1 as init_prompts,
|
|
244
|
+
init_query,
|
|
245
|
+
init_queryHelpers,
|
|
246
|
+
init_queryProfiler,
|
|
247
|
+
init_reject,
|
|
248
|
+
init_remoteManagedSettings,
|
|
249
|
+
init_sandbox_adapter,
|
|
250
|
+
init_sdkEventQueue,
|
|
251
|
+
init_sessionStart,
|
|
252
|
+
init_sessionStorage,
|
|
253
|
+
init_shellToolUtils,
|
|
254
|
+
init_stopTask,
|
|
255
|
+
init_systemPromptType,
|
|
256
|
+
init_teammateMailbox,
|
|
257
|
+
init_thinking,
|
|
258
|
+
init_tools1 as init_tools,
|
|
259
|
+
init_types2,
|
|
260
|
+
init_uniqBy,
|
|
261
|
+
init_utils,
|
|
262
|
+
init_uuid,
|
|
263
|
+
init_vscodeSdkMcp,
|
|
264
|
+
init_zipCache,
|
|
265
|
+
installOAuthTokens,
|
|
266
|
+
isBackgroundTask,
|
|
267
|
+
isBuiltInAgent,
|
|
268
|
+
isBypassPermissionsModeDisabled,
|
|
269
|
+
isMarketplaceSourceSupportedByZipCache,
|
|
270
|
+
isMcpServerDisabled,
|
|
271
|
+
isPluginZipCacheEnabled,
|
|
272
|
+
isPolicyAllowed,
|
|
273
|
+
isQualifiedForGrove,
|
|
274
|
+
isResultSuccessful,
|
|
275
|
+
isScratchpadEnabled,
|
|
276
|
+
isShutdownApproved,
|
|
277
|
+
isShuttingDown,
|
|
278
|
+
last_default,
|
|
279
|
+
loadAllPluginsCacheOnly,
|
|
280
|
+
loadConversationForResume,
|
|
281
|
+
loadKnownMarketplacesConfigSafe,
|
|
282
|
+
loadMemoryPrompt,
|
|
283
|
+
logHeadlessProfilerTurn,
|
|
284
|
+
logQueryProfileReport,
|
|
285
|
+
logSuggestionOutcome,
|
|
286
|
+
logSuggestionSuppressed,
|
|
287
|
+
markMessagesAsRead,
|
|
288
|
+
modelSupportsAdaptiveThinking,
|
|
289
|
+
modelSupportsEffort,
|
|
290
|
+
modelSupportsMaxEffort,
|
|
291
|
+
normalizeMessage,
|
|
292
|
+
notifyCommandLifecycle,
|
|
293
|
+
parseAgentsFromJson,
|
|
294
|
+
parsePluginIdentifier,
|
|
295
|
+
peek,
|
|
296
|
+
performMCPOAuthFlow,
|
|
297
|
+
processSessionStartHooks,
|
|
298
|
+
processSetupHooks,
|
|
299
|
+
query,
|
|
300
|
+
readUnreadMessages,
|
|
301
|
+
reconnectMcpServerImpl,
|
|
302
|
+
recordTranscript,
|
|
303
|
+
registerHookEventHandler,
|
|
304
|
+
registerSeedMarketplaces,
|
|
305
|
+
registerStructuredOutputEnforcement,
|
|
306
|
+
reject_default,
|
|
307
|
+
resetSessionFilePointer,
|
|
308
|
+
resolveAppliedEffort,
|
|
309
|
+
restoreSessionMetadata,
|
|
310
|
+
revokeServerTokens,
|
|
311
|
+
runElicitationHooks,
|
|
312
|
+
runElicitationResultHooks,
|
|
313
|
+
saveAgentSetting,
|
|
314
|
+
saveAiGeneratedTitle,
|
|
315
|
+
setCommandLifecycleListener,
|
|
316
|
+
setCwd,
|
|
317
|
+
setInternalEventReader,
|
|
318
|
+
setInternalEventWriter,
|
|
319
|
+
setMcpServerEnabled,
|
|
320
|
+
settingsChangeDetector,
|
|
321
|
+
setupSdkMcpClients,
|
|
322
|
+
setupVscodeSdkMcp,
|
|
323
|
+
shouldEnableThinkingByDefault,
|
|
324
|
+
startQueryProfile,
|
|
325
|
+
statusListeners,
|
|
326
|
+
stopTask,
|
|
327
|
+
subscribeToCommandQueue,
|
|
328
|
+
takeInitialUserMessage,
|
|
329
|
+
toolMatchesName,
|
|
330
|
+
transitionPermissionMode,
|
|
331
|
+
tryGenerateSuggestion,
|
|
332
|
+
uniqBy_default,
|
|
333
|
+
updateUsage,
|
|
334
|
+
validateUuid,
|
|
335
|
+
waitForRemoteManagedSettingsToLoad
|
|
336
|
+
} from "./chunk-2y54j9ew.js";
|
|
337
|
+
import"./chunk-1yzc16qa.js";
|
|
338
|
+
import {
|
|
339
|
+
EMPTY_USAGE,
|
|
340
|
+
getSessionIngressAuthToken,
|
|
341
|
+
init_sessionIngressAuth
|
|
342
|
+
} from "./chunk-s10vyjz4.js";
|
|
343
|
+
import"./chunk-1k4j1xcf.js";
|
|
344
|
+
import"./chunk-3c4qja3e.js";
|
|
345
|
+
import {
|
|
346
|
+
init_commitAttribution
|
|
347
|
+
} from "./chunk-rc5bbzx4.js";
|
|
348
|
+
import"./chunk-e6rrwzv0.js";
|
|
349
|
+
import"./chunk-2gzv8nrw.js";
|
|
350
|
+
import"./chunk-743znc5c.js";
|
|
351
|
+
import {
|
|
352
|
+
init_tasks,
|
|
353
|
+
init_teamHelpers,
|
|
354
|
+
removeTeammateFromTeamFile,
|
|
355
|
+
unassignTeammateTasks
|
|
356
|
+
} from "./chunk-5p2ssw3d.js";
|
|
357
|
+
import"./chunk-cgfdkzhb.js";
|
|
358
|
+
import"./chunk-bhdt6k7w.js";
|
|
359
|
+
import"./chunk-6wkdqk81.js";
|
|
360
|
+
import {
|
|
361
|
+
ElicitRequestSchema,
|
|
362
|
+
ElicitationCompleteNotificationSchema,
|
|
363
|
+
init_types
|
|
364
|
+
} from "./chunk-5dbk24zg.js";
|
|
365
|
+
import"./chunk-bda3gxxz.js";
|
|
366
|
+
import"./chunk-zxhezavg.js";
|
|
367
|
+
import"./chunk-x8eg216f.js";
|
|
368
|
+
import {
|
|
369
|
+
READ_FILE_STATE_CACHE_SIZE,
|
|
370
|
+
cloneFileStateCache,
|
|
371
|
+
createFileStateCacheWithSizeLimit,
|
|
372
|
+
init_fileStateCache,
|
|
373
|
+
mergeFileStateCaches
|
|
374
|
+
} from "./chunk-9gbamk79.js";
|
|
375
|
+
import"./chunk-t175chdd.js";
|
|
376
|
+
import"./chunk-7rjyn5d3.js";
|
|
377
|
+
import"./chunk-6q2x8zeg.js";
|
|
378
|
+
import {
|
|
379
|
+
init_systemTheme,
|
|
380
|
+
resolveThemeSetting
|
|
381
|
+
} from "./chunk-0yb4dz9c.js";
|
|
382
|
+
import"./chunk-7m2nd8da.js";
|
|
383
|
+
import"./chunk-ps49ymvj.js";
|
|
384
|
+
import"./chunk-g338npwr.js";
|
|
385
|
+
import"./chunk-zk2wsm7d.js";
|
|
386
|
+
import"./chunk-eh474zhj.js";
|
|
387
|
+
import"./chunk-ga5faygf.js";
|
|
388
|
+
import"./chunk-e7c8ypwc.js";
|
|
389
|
+
import"./chunk-g6qddbvf.js";
|
|
390
|
+
import"./chunk-b1s11z4y.js";
|
|
391
|
+
import"./chunk-4jm600zv.js";
|
|
392
|
+
import"./chunk-yxmz5k16.js";
|
|
393
|
+
import"./chunk-v9smspw2.js";
|
|
394
|
+
import"./chunk-qz2x630m.js";
|
|
395
|
+
import {
|
|
396
|
+
AwsAuthStatusManager,
|
|
397
|
+
KnownMarketplacesFileSchema,
|
|
398
|
+
TASK_STOP_TOOL_NAME,
|
|
399
|
+
ensureModelStringsInitialized,
|
|
400
|
+
getAPIProvider,
|
|
401
|
+
getAccountInformation,
|
|
402
|
+
getDefaultMainLoopModel,
|
|
403
|
+
getFastModeState,
|
|
404
|
+
getFeatureValue_CACHED_MAY_BE_STALE,
|
|
405
|
+
getGlobalConfig,
|
|
406
|
+
getMainLoopModel,
|
|
407
|
+
getMcpPrefix,
|
|
408
|
+
getSettingsWithSources,
|
|
409
|
+
getSettings_DEPRECATED,
|
|
410
|
+
hasAutoMemPathOverride,
|
|
411
|
+
init_auth,
|
|
412
|
+
init_awsAuthStatusManager,
|
|
413
|
+
init_betas1 as init_betas,
|
|
414
|
+
init_config1 as init_config,
|
|
415
|
+
init_fastMode,
|
|
416
|
+
init_growthbook,
|
|
417
|
+
init_mcpStringUtils,
|
|
418
|
+
init_model,
|
|
419
|
+
init_modelStrings,
|
|
420
|
+
init_paths,
|
|
421
|
+
init_prompt,
|
|
422
|
+
init_providers,
|
|
423
|
+
init_schemas,
|
|
424
|
+
init_settings1 as init_settings,
|
|
425
|
+
init_sleep,
|
|
426
|
+
init_stringUtils,
|
|
427
|
+
init_workloadContext,
|
|
428
|
+
initializeGrowthBook,
|
|
429
|
+
isFastModeAvailable,
|
|
430
|
+
isFastModeEnabled,
|
|
431
|
+
isFastModeSupportedByModel,
|
|
432
|
+
modelDisplayString,
|
|
433
|
+
modelSupportsAutoMode,
|
|
434
|
+
parseUserSpecifiedModel,
|
|
435
|
+
runWithWorkload,
|
|
436
|
+
sleep
|
|
437
|
+
} from "./chunk-30chpfyc.js";
|
|
438
|
+
import {
|
|
439
|
+
init_json,
|
|
440
|
+
safeParseJSON
|
|
441
|
+
} from "./chunk-84k64e4a.js";
|
|
442
|
+
import {
|
|
443
|
+
expandPath,
|
|
444
|
+
init_path
|
|
445
|
+
} from "./chunk-y3py9g5d.js";
|
|
446
|
+
import"./chunk-7pemewz2.js";
|
|
447
|
+
import {
|
|
448
|
+
hasActiveInProcessTeammates,
|
|
449
|
+
hasWorkingInProcessTeammates,
|
|
450
|
+
init_array,
|
|
451
|
+
init_teammate,
|
|
452
|
+
isTeamLead,
|
|
453
|
+
uniq,
|
|
454
|
+
waitForTeammatesToBecomeIdle
|
|
455
|
+
} from "./chunk-s4w01jsb.js";
|
|
456
|
+
import"./chunk-c8vn3ynx.js";
|
|
457
|
+
import {
|
|
458
|
+
init_v4
|
|
459
|
+
} from "./chunk-g0j0t6qk.js";
|
|
460
|
+
import"./chunk-6kpbgc5w.js";
|
|
461
|
+
import"./chunk-3c25bcsw.js";
|
|
462
|
+
import"./chunk-mzdtkccs.js";
|
|
463
|
+
import {
|
|
464
|
+
exports_external,
|
|
465
|
+
init_lazySchema,
|
|
466
|
+
lazySchema
|
|
467
|
+
} from "./chunk-55wgxwa9.js";
|
|
468
|
+
import"./chunk-5k2gdxnr.js";
|
|
469
|
+
import"./chunk-2qhs9n36.js";
|
|
470
|
+
import"./chunk-f5ma3nh5.js";
|
|
471
|
+
import"./chunk-v1kzp02e.js";
|
|
472
|
+
import"./chunk-p2816w9z.js";
|
|
473
|
+
import"./chunk-0vkfrmqm.js";
|
|
474
|
+
import"./chunk-0xjaqda8.js";
|
|
475
|
+
import {
|
|
476
|
+
init_strip_ansi,
|
|
477
|
+
stripAnsi
|
|
478
|
+
} from "./chunk-mr9df5v8.js";
|
|
479
|
+
import"./chunk-cdz5yb0r.js";
|
|
480
|
+
import {
|
|
481
|
+
init_analytics,
|
|
482
|
+
logEvent
|
|
483
|
+
} from "./chunk-f2mhrmww.js";
|
|
484
|
+
import"./chunk-10fdxge0.js";
|
|
485
|
+
import {
|
|
486
|
+
init_diagLogs,
|
|
487
|
+
logForDiagnosticsNoPII,
|
|
488
|
+
withDiagnosticsTiming
|
|
489
|
+
} from "./chunk-r1v8d6da.js";
|
|
490
|
+
import"./chunk-d3v2fbay.js";
|
|
491
|
+
import"./chunk-qnfx3qtx.js";
|
|
492
|
+
import"./chunk-f2zhqnb6.js";
|
|
493
|
+
import"./chunk-cvp5vayb.js";
|
|
494
|
+
import"./chunk-b5b7h81y.js";
|
|
495
|
+
import {
|
|
496
|
+
LOCAL_COMMAND_STDERR_TAG,
|
|
497
|
+
LOCAL_COMMAND_STDOUT_TAG,
|
|
498
|
+
TEAMMATE_MESSAGE_TAG,
|
|
499
|
+
getInMemoryErrors,
|
|
500
|
+
init_log,
|
|
501
|
+
init_xml,
|
|
502
|
+
logError,
|
|
503
|
+
logMCPDebug
|
|
504
|
+
} from "./chunk-nm2cncrq.js";
|
|
505
|
+
import"./chunk-8tnsngw2.js";
|
|
506
|
+
import {
|
|
507
|
+
getCwd,
|
|
508
|
+
init_cwd
|
|
509
|
+
} from "./chunk-0rkbrabt.js";
|
|
510
|
+
import"./chunk-7wm5s02e.js";
|
|
511
|
+
import {
|
|
512
|
+
errorMessage,
|
|
513
|
+
getFsImplementation,
|
|
514
|
+
init_cleanupRegistry,
|
|
515
|
+
init_debug,
|
|
516
|
+
init_errors,
|
|
517
|
+
init_fsOperations,
|
|
518
|
+
init_slowOperations,
|
|
519
|
+
isDebugMode,
|
|
520
|
+
jsonParse,
|
|
521
|
+
jsonStringify,
|
|
522
|
+
logForDebugging,
|
|
523
|
+
registerCleanup,
|
|
524
|
+
toError
|
|
525
|
+
} from "./chunk-rwagvxh5.js";
|
|
526
|
+
import {
|
|
527
|
+
init_process,
|
|
528
|
+
registerProcessOutputErrorHandlers,
|
|
529
|
+
writeToStdout
|
|
530
|
+
} from "./chunk-fbv4apne.js";
|
|
531
|
+
import {
|
|
532
|
+
getConfigHomeDir,
|
|
533
|
+
init_envUtils,
|
|
534
|
+
isBareMode,
|
|
535
|
+
isEnvDefinedFalsy,
|
|
536
|
+
isEnvTruthy
|
|
537
|
+
} from "./chunk-0fkqze0v.js";
|
|
538
|
+
import {
|
|
539
|
+
getAllowedChannels,
|
|
540
|
+
getFlagSettingsInline,
|
|
541
|
+
getInitJsonSchema,
|
|
542
|
+
getMainThreadAgentType,
|
|
543
|
+
getModelUsage,
|
|
544
|
+
getSessionId,
|
|
545
|
+
getTotalAPIDuration,
|
|
546
|
+
getTotalCostUSD,
|
|
547
|
+
init_state,
|
|
548
|
+
isSessionPersistenceDisabled,
|
|
549
|
+
registerHookCallbacks,
|
|
550
|
+
setAllowedChannels,
|
|
551
|
+
setFlagSettingsInline,
|
|
552
|
+
setInitJsonSchema,
|
|
553
|
+
setMainLoopModelOverride,
|
|
554
|
+
setMainThreadAgentType,
|
|
555
|
+
setSdkAgentProgressSummariesEnabled,
|
|
556
|
+
switchSession
|
|
557
|
+
} from "./chunk-2zcaw1jd.js";
|
|
558
|
+
import"./chunk-hqmz36b3.js";
|
|
559
|
+
import"./chunk-4g3v8y12.js";
|
|
560
|
+
import"./chunk-7739pg2c.js";
|
|
561
|
+
import {
|
|
562
|
+
axios_default,
|
|
563
|
+
init_axios
|
|
564
|
+
} from "./chunk-xszk7n10.js";
|
|
565
|
+
import"./chunk-sdj9b9wh.js";
|
|
566
|
+
import {
|
|
567
|
+
__require,
|
|
568
|
+
__toCommonJS
|
|
569
|
+
} from "./chunk-qp2qdcda.js";
|
|
570
|
+
|
|
571
|
+
// src/cli/print.ts
|
|
572
|
+
init_settingsSync();
|
|
573
|
+
init_remoteManagedSettings();
|
|
574
|
+
import { readFile as readFile2, stat } from "fs/promises";
|
|
575
|
+
import { dirname } from "path";
|
|
576
|
+
|
|
577
|
+
// src/cli/remoteIO.ts
|
|
578
|
+
init_state();
|
|
579
|
+
import { PassThrough } from "stream";
|
|
580
|
+
import { URL as URL3 } from "url";
|
|
581
|
+
init_cleanupRegistry();
|
|
582
|
+
init_commandLifecycle();
|
|
583
|
+
init_debug();
|
|
584
|
+
init_diagLogs();
|
|
585
|
+
init_envUtils();
|
|
586
|
+
init_errors();
|
|
587
|
+
init_gracefulShutdown();
|
|
588
|
+
init_log();
|
|
589
|
+
init_process();
|
|
590
|
+
init_sessionIngressAuth();
|
|
591
|
+
init_sessionStorage();
|
|
592
|
+
|
|
593
|
+
// src/cli/transports/transportUtils.ts
|
|
594
|
+
init_envUtils();
|
|
595
|
+
import { URL as URL2 } from "url";
|
|
596
|
+
function getTransportForUrl(url, headers = {}, sessionId, refreshHeaders) {
|
|
597
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
|
|
598
|
+
const sseUrl = new URL2(url.href);
|
|
599
|
+
if (sseUrl.protocol === "wss:") {
|
|
600
|
+
sseUrl.protocol = "https:";
|
|
601
|
+
} else if (sseUrl.protocol === "ws:") {
|
|
602
|
+
sseUrl.protocol = "http:";
|
|
603
|
+
}
|
|
604
|
+
sseUrl.pathname = sseUrl.pathname.replace(/\/$/, "") + "/worker/events/stream";
|
|
605
|
+
return new SSETransport(sseUrl, headers, sessionId, refreshHeaders);
|
|
606
|
+
}
|
|
607
|
+
if (url.protocol === "ws:" || url.protocol === "wss:") {
|
|
608
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)) {
|
|
609
|
+
return new HybridTransport(url, headers, sessionId, refreshHeaders);
|
|
610
|
+
}
|
|
611
|
+
return new WebSocketTransport(url, headers, sessionId, refreshHeaders);
|
|
612
|
+
} else {
|
|
613
|
+
throw new Error(`Unsupported protocol: ${url.protocol}`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/cli/remoteIO.ts
|
|
618
|
+
class RemoteIO extends StructuredIO {
|
|
619
|
+
url;
|
|
620
|
+
transport;
|
|
621
|
+
inputStream;
|
|
622
|
+
isBridge = false;
|
|
623
|
+
isDebug = false;
|
|
624
|
+
ccrClient = null;
|
|
625
|
+
keepAliveTimer = null;
|
|
626
|
+
constructor(streamUrl, initialPrompt, replayUserMessages) {
|
|
627
|
+
const inputStream = new PassThrough({ encoding: "utf8" });
|
|
628
|
+
super(inputStream, replayUserMessages);
|
|
629
|
+
this.inputStream = inputStream;
|
|
630
|
+
this.url = new URL3(streamUrl);
|
|
631
|
+
const headers = {};
|
|
632
|
+
const sessionToken = getSessionIngressAuthToken();
|
|
633
|
+
if (sessionToken) {
|
|
634
|
+
headers["Authorization"] = `Bearer ${sessionToken}`;
|
|
635
|
+
} else {
|
|
636
|
+
logForDebugging("[remote-io] No session ingress token available", {
|
|
637
|
+
level: "error"
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
const erVersion = process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;
|
|
641
|
+
if (erVersion) {
|
|
642
|
+
headers["x-environment-runner-version"] = erVersion;
|
|
643
|
+
}
|
|
644
|
+
const refreshHeaders = () => {
|
|
645
|
+
const h = {};
|
|
646
|
+
const freshToken = getSessionIngressAuthToken();
|
|
647
|
+
if (freshToken) {
|
|
648
|
+
h["Authorization"] = `Bearer ${freshToken}`;
|
|
649
|
+
}
|
|
650
|
+
const freshErVersion = process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;
|
|
651
|
+
if (freshErVersion) {
|
|
652
|
+
h["x-environment-runner-version"] = freshErVersion;
|
|
653
|
+
}
|
|
654
|
+
return h;
|
|
655
|
+
};
|
|
656
|
+
this.transport = getTransportForUrl(this.url, headers, getSessionId(), refreshHeaders);
|
|
657
|
+
this.isBridge = process.env.CLAUDE_CODE_ENVIRONMENT_KIND === "bridge";
|
|
658
|
+
this.isDebug = isDebugMode();
|
|
659
|
+
this.transport.setOnData((data) => {
|
|
660
|
+
this.inputStream.write(data);
|
|
661
|
+
if (this.isBridge && this.isDebug) {
|
|
662
|
+
writeToStdout(data.endsWith(`
|
|
663
|
+
`) ? data : data + `
|
|
664
|
+
`);
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
this.transport.setOnClose(() => {
|
|
668
|
+
this.inputStream.end();
|
|
669
|
+
});
|
|
670
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
|
|
671
|
+
if (!(this.transport instanceof SSETransport)) {
|
|
672
|
+
throw new Error("CCR v2 requires SSETransport; check getTransportForUrl");
|
|
673
|
+
}
|
|
674
|
+
this.ccrClient = new CCRClient(this.transport, this.url);
|
|
675
|
+
const init = this.ccrClient.initialize();
|
|
676
|
+
this.restoredWorkerState = init.catch(() => null);
|
|
677
|
+
init.catch((error) => {
|
|
678
|
+
logForDiagnosticsNoPII("error", "cli_worker_lifecycle_init_failed", {
|
|
679
|
+
reason: error instanceof CCRInitError ? error.reason : "unknown"
|
|
680
|
+
});
|
|
681
|
+
logError(new Error(`CCRClient initialization failed: ${errorMessage(error)}`));
|
|
682
|
+
gracefulShutdown(1, "other");
|
|
683
|
+
});
|
|
684
|
+
registerCleanup(async () => this.ccrClient?.close());
|
|
685
|
+
setInternalEventWriter((eventType, payload, options) => this.ccrClient.writeInternalEvent(eventType, payload, options));
|
|
686
|
+
setInternalEventReader(() => this.ccrClient.readInternalEvents(), () => this.ccrClient.readSubagentInternalEvents());
|
|
687
|
+
const LIFECYCLE_TO_DELIVERY = {
|
|
688
|
+
started: "processing",
|
|
689
|
+
completed: "processed"
|
|
690
|
+
};
|
|
691
|
+
setCommandLifecycleListener((uuid, state) => {
|
|
692
|
+
this.ccrClient?.reportDelivery(uuid, LIFECYCLE_TO_DELIVERY[state]);
|
|
693
|
+
});
|
|
694
|
+
setSessionStateChangedListener((state, details) => {
|
|
695
|
+
this.ccrClient?.reportState(state, details);
|
|
696
|
+
});
|
|
697
|
+
setSessionMetadataChangedListener((metadata) => {
|
|
698
|
+
this.ccrClient?.reportMetadata(metadata);
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
this.transport.connect();
|
|
702
|
+
const keepAliveIntervalMs = getPollIntervalConfig().session_keepalive_interval_v2_ms;
|
|
703
|
+
if (this.isBridge && keepAliveIntervalMs > 0) {
|
|
704
|
+
this.keepAliveTimer = setInterval(() => {
|
|
705
|
+
logForDebugging("[remote-io] keep_alive sent");
|
|
706
|
+
this.write({ type: "keep_alive" }).catch((err) => {
|
|
707
|
+
logForDebugging(`[remote-io] keep_alive write failed: ${errorMessage(err)}`);
|
|
708
|
+
});
|
|
709
|
+
}, keepAliveIntervalMs);
|
|
710
|
+
this.keepAliveTimer.unref?.();
|
|
711
|
+
}
|
|
712
|
+
registerCleanup(async () => this.close());
|
|
713
|
+
if (initialPrompt) {
|
|
714
|
+
const stream = this.inputStream;
|
|
715
|
+
(async () => {
|
|
716
|
+
for await (const chunk of initialPrompt) {
|
|
717
|
+
stream.write(String(chunk).replace(/\n$/, "") + `
|
|
718
|
+
`);
|
|
719
|
+
}
|
|
720
|
+
})();
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
flushInternalEvents() {
|
|
724
|
+
return this.ccrClient?.flushInternalEvents() ?? Promise.resolve();
|
|
725
|
+
}
|
|
726
|
+
get internalEventsPending() {
|
|
727
|
+
return this.ccrClient?.internalEventsPending ?? 0;
|
|
728
|
+
}
|
|
729
|
+
async write(message) {
|
|
730
|
+
if (this.ccrClient) {
|
|
731
|
+
await this.ccrClient.writeEvent(message);
|
|
732
|
+
} else {
|
|
733
|
+
await this.transport.write(message);
|
|
734
|
+
}
|
|
735
|
+
if (this.isBridge) {
|
|
736
|
+
if (message.type === "control_request" || this.isDebug) {
|
|
737
|
+
writeToStdout(ndjsonSafeStringify(message) + `
|
|
738
|
+
`);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
close() {
|
|
743
|
+
if (this.keepAliveTimer) {
|
|
744
|
+
clearInterval(this.keepAliveTimer);
|
|
745
|
+
this.keepAliveTimer = null;
|
|
746
|
+
}
|
|
747
|
+
this.transport.close();
|
|
748
|
+
this.inputStream.end();
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// src/cli/print.ts
|
|
753
|
+
init_commands();
|
|
754
|
+
|
|
755
|
+
// src/utils/streamlinedTransform.ts
|
|
756
|
+
init_constants();
|
|
757
|
+
init_prompt3();
|
|
758
|
+
init_prompt4();
|
|
759
|
+
init_prompt5();
|
|
760
|
+
init_prompt2();
|
|
761
|
+
init_prompt8();
|
|
762
|
+
init_prompt7();
|
|
763
|
+
init_constants2();
|
|
764
|
+
init_prompt();
|
|
765
|
+
init_prompt6();
|
|
766
|
+
init_messages();
|
|
767
|
+
init_shellToolUtils();
|
|
768
|
+
init_stringUtils();
|
|
769
|
+
var COMMAND_TOOLS = [...SHELL_TOOL_NAMES, "Tmux", TASK_STOP_TOOL_NAME];
|
|
770
|
+
|
|
771
|
+
// src/utils/streamJsonStdoutGuard.ts
|
|
772
|
+
init_cleanupRegistry();
|
|
773
|
+
init_debug();
|
|
774
|
+
var STDOUT_GUARD_MARKER = "[stdout-guard]";
|
|
775
|
+
var installed = false;
|
|
776
|
+
var buffer = "";
|
|
777
|
+
var originalWrite = null;
|
|
778
|
+
function isJsonLine(line) {
|
|
779
|
+
if (line.length === 0) {
|
|
780
|
+
return true;
|
|
781
|
+
}
|
|
782
|
+
try {
|
|
783
|
+
JSON.parse(line);
|
|
784
|
+
return true;
|
|
785
|
+
} catch {
|
|
786
|
+
return false;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
function installStreamJsonStdoutGuard() {
|
|
790
|
+
if (installed) {
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
installed = true;
|
|
794
|
+
originalWrite = process.stdout.write.bind(process.stdout);
|
|
795
|
+
process.stdout.write = function(chunk, encodingOrCb, cb) {
|
|
796
|
+
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf-8");
|
|
797
|
+
buffer += text;
|
|
798
|
+
let newlineIdx;
|
|
799
|
+
let wrote = true;
|
|
800
|
+
while ((newlineIdx = buffer.indexOf(`
|
|
801
|
+
`)) !== -1) {
|
|
802
|
+
const line = buffer.slice(0, newlineIdx);
|
|
803
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
804
|
+
if (isJsonLine(line)) {
|
|
805
|
+
wrote = originalWrite(line + `
|
|
806
|
+
`);
|
|
807
|
+
} else {
|
|
808
|
+
process.stderr.write(`${STDOUT_GUARD_MARKER} ${line}
|
|
809
|
+
`);
|
|
810
|
+
logForDebugging(`streamJsonStdoutGuard diverted non-JSON stdout line: ${line.slice(0, 200)}`);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
const callback = typeof encodingOrCb === "function" ? encodingOrCb : cb;
|
|
814
|
+
if (callback) {
|
|
815
|
+
queueMicrotask(() => callback());
|
|
816
|
+
}
|
|
817
|
+
return wrote;
|
|
818
|
+
};
|
|
819
|
+
registerCleanup(async () => {
|
|
820
|
+
if (buffer.length > 0) {
|
|
821
|
+
if (originalWrite && isJsonLine(buffer)) {
|
|
822
|
+
originalWrite(buffer + `
|
|
823
|
+
`);
|
|
824
|
+
} else {
|
|
825
|
+
process.stderr.write(`${STDOUT_GUARD_MARKER} ${buffer}
|
|
826
|
+
`);
|
|
827
|
+
}
|
|
828
|
+
buffer = "";
|
|
829
|
+
}
|
|
830
|
+
if (originalWrite) {
|
|
831
|
+
process.stdout.write = originalWrite;
|
|
832
|
+
originalWrite = null;
|
|
833
|
+
}
|
|
834
|
+
installed = false;
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// src/cli/print.ts
|
|
839
|
+
init_tools();
|
|
840
|
+
init_uniqBy();
|
|
841
|
+
init_array();
|
|
842
|
+
init_toolPool();
|
|
843
|
+
init_analytics();
|
|
844
|
+
init_growthbook();
|
|
845
|
+
init_debug();
|
|
846
|
+
init_diagLogs();
|
|
847
|
+
init_Tool();
|
|
848
|
+
init_loadAgentsDir();
|
|
849
|
+
init_messageQueueManager();
|
|
850
|
+
init_commandLifecycle();
|
|
851
|
+
init_log();
|
|
852
|
+
init_process();
|
|
853
|
+
init_logging();
|
|
854
|
+
init_conversationRecovery();
|
|
855
|
+
init_channelNotification();
|
|
856
|
+
init_channelAllowlist();
|
|
857
|
+
init_pluginIdentifier();
|
|
858
|
+
init_uuid();
|
|
859
|
+
init_generators();
|
|
860
|
+
|
|
861
|
+
// src/QueryEngine.ts
|
|
862
|
+
init_last();
|
|
863
|
+
init_state();
|
|
864
|
+
init_claude();
|
|
865
|
+
init_logging();
|
|
866
|
+
init_strip_ansi();
|
|
867
|
+
init_commands();
|
|
868
|
+
init_xml();
|
|
869
|
+
init_cost_tracker();
|
|
870
|
+
init_memdir();
|
|
871
|
+
init_paths();
|
|
872
|
+
init_query();
|
|
873
|
+
init_errors2();
|
|
874
|
+
init_Tool();
|
|
875
|
+
init_SyntheticOutputTool();
|
|
876
|
+
init_abortController();
|
|
877
|
+
init_config();
|
|
878
|
+
init_cwd();
|
|
879
|
+
init_envUtils();
|
|
880
|
+
init_fastMode();
|
|
881
|
+
init_fileHistory();
|
|
882
|
+
init_fileStateCache();
|
|
883
|
+
init_headlessProfiler();
|
|
884
|
+
init_hookHelpers();
|
|
885
|
+
init_log();
|
|
886
|
+
init_messages();
|
|
887
|
+
init_model();
|
|
888
|
+
init_pluginLoader();
|
|
889
|
+
import { randomUUID } from "crypto";
|
|
890
|
+
|
|
891
|
+
// src/utils/queryContext.ts
|
|
892
|
+
init_prompts();
|
|
893
|
+
init_context();
|
|
894
|
+
init_abortController();
|
|
895
|
+
init_model();
|
|
896
|
+
init_systemPromptType();
|
|
897
|
+
init_thinking();
|
|
898
|
+
async function fetchSystemPromptParts({
|
|
899
|
+
tools,
|
|
900
|
+
mainLoopModel,
|
|
901
|
+
additionalWorkingDirectories,
|
|
902
|
+
mcpClients,
|
|
903
|
+
customSystemPrompt
|
|
904
|
+
}) {
|
|
905
|
+
const [defaultSystemPrompt, userContext, systemContext] = await Promise.all([
|
|
906
|
+
customSystemPrompt !== undefined ? Promise.resolve([]) : getSystemPrompt(tools, mainLoopModel, additionalWorkingDirectories, mcpClients),
|
|
907
|
+
getUserContext(),
|
|
908
|
+
customSystemPrompt !== undefined ? Promise.resolve({}) : getSystemContext()
|
|
909
|
+
]);
|
|
910
|
+
return { defaultSystemPrompt, userContext, systemContext };
|
|
911
|
+
}
|
|
912
|
+
async function buildSideQuestionFallbackParams({
|
|
913
|
+
tools,
|
|
914
|
+
commands,
|
|
915
|
+
mcpClients,
|
|
916
|
+
messages,
|
|
917
|
+
readFileState,
|
|
918
|
+
getAppState,
|
|
919
|
+
setAppState,
|
|
920
|
+
customSystemPrompt,
|
|
921
|
+
appendSystemPrompt,
|
|
922
|
+
thinkingConfig,
|
|
923
|
+
agents
|
|
924
|
+
}) {
|
|
925
|
+
const mainLoopModel = getMainLoopModel();
|
|
926
|
+
const appState = getAppState();
|
|
927
|
+
const { defaultSystemPrompt, userContext, systemContext } = await fetchSystemPromptParts({
|
|
928
|
+
tools,
|
|
929
|
+
mainLoopModel,
|
|
930
|
+
additionalWorkingDirectories: Array.from(appState.toolPermissionContext.additionalWorkingDirectories.keys()),
|
|
931
|
+
mcpClients,
|
|
932
|
+
customSystemPrompt
|
|
933
|
+
});
|
|
934
|
+
const systemPrompt = asSystemPrompt([
|
|
935
|
+
...customSystemPrompt !== undefined ? [customSystemPrompt] : defaultSystemPrompt,
|
|
936
|
+
...appendSystemPrompt ? [appendSystemPrompt] : []
|
|
937
|
+
]);
|
|
938
|
+
const last = messages.at(-1);
|
|
939
|
+
const forkContextMessages = last?.type === "assistant" && last.message.stop_reason === null ? messages.slice(0, -1) : messages;
|
|
940
|
+
const toolUseContext = {
|
|
941
|
+
options: {
|
|
942
|
+
commands,
|
|
943
|
+
debug: false,
|
|
944
|
+
mainLoopModel,
|
|
945
|
+
tools,
|
|
946
|
+
verbose: false,
|
|
947
|
+
thinkingConfig: thinkingConfig ?? (shouldEnableThinkingByDefault() !== false ? { type: "adaptive" } : { type: "disabled" }),
|
|
948
|
+
mcpClients,
|
|
949
|
+
mcpResources: {},
|
|
950
|
+
isNonInteractiveSession: true,
|
|
951
|
+
agentDefinitions: { activeAgents: agents, allAgents: [] },
|
|
952
|
+
customSystemPrompt,
|
|
953
|
+
appendSystemPrompt
|
|
954
|
+
},
|
|
955
|
+
abortController: createAbortController(),
|
|
956
|
+
readFileState,
|
|
957
|
+
getAppState,
|
|
958
|
+
setAppState,
|
|
959
|
+
messages: forkContextMessages,
|
|
960
|
+
setInProgressToolUseIDs: () => {},
|
|
961
|
+
setResponseLength: () => {},
|
|
962
|
+
updateFileHistoryState: () => {},
|
|
963
|
+
updateAttributionState: () => {}
|
|
964
|
+
};
|
|
965
|
+
return {
|
|
966
|
+
systemPrompt,
|
|
967
|
+
userContext,
|
|
968
|
+
systemContext,
|
|
969
|
+
toolUseContext,
|
|
970
|
+
forkContextMessages
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// src/QueryEngine.ts
|
|
975
|
+
init_Shell();
|
|
976
|
+
init_sessionStorage();
|
|
977
|
+
init_systemPromptType();
|
|
978
|
+
init_systemTheme();
|
|
979
|
+
init_thinking();
|
|
980
|
+
init_mappers();
|
|
981
|
+
init_filesystem();
|
|
982
|
+
init_queryHelpers();
|
|
983
|
+
var messageSelector = () => (init_MessageSelector(), __toCommonJS(exports_MessageSelector));
|
|
984
|
+
var getCoordinatorUserContext = () => ({});
|
|
985
|
+
class QueryEngine {
|
|
986
|
+
config;
|
|
987
|
+
mutableMessages;
|
|
988
|
+
abortController;
|
|
989
|
+
permissionDenials;
|
|
990
|
+
totalUsage;
|
|
991
|
+
hasHandledOrphanedPermission = false;
|
|
992
|
+
readFileState;
|
|
993
|
+
discoveredSkillNames = new Set;
|
|
994
|
+
loadedNestedMemoryPaths = new Set;
|
|
995
|
+
constructor(config) {
|
|
996
|
+
this.config = config;
|
|
997
|
+
this.mutableMessages = config.initialMessages ?? [];
|
|
998
|
+
this.abortController = config.abortController ?? createAbortController();
|
|
999
|
+
this.permissionDenials = [];
|
|
1000
|
+
this.readFileState = config.readFileCache;
|
|
1001
|
+
this.totalUsage = EMPTY_USAGE;
|
|
1002
|
+
}
|
|
1003
|
+
async* submitMessage(prompt, options) {
|
|
1004
|
+
const {
|
|
1005
|
+
cwd,
|
|
1006
|
+
commands,
|
|
1007
|
+
tools,
|
|
1008
|
+
mcpClients,
|
|
1009
|
+
verbose = false,
|
|
1010
|
+
thinkingConfig,
|
|
1011
|
+
maxTurns,
|
|
1012
|
+
maxBudgetUsd,
|
|
1013
|
+
taskBudget,
|
|
1014
|
+
canUseTool,
|
|
1015
|
+
customSystemPrompt,
|
|
1016
|
+
appendSystemPrompt,
|
|
1017
|
+
userSpecifiedModel,
|
|
1018
|
+
fallbackModel,
|
|
1019
|
+
jsonSchema,
|
|
1020
|
+
getAppState,
|
|
1021
|
+
setAppState,
|
|
1022
|
+
replayUserMessages = false,
|
|
1023
|
+
includePartialMessages = false,
|
|
1024
|
+
agents = [],
|
|
1025
|
+
setSDKStatus,
|
|
1026
|
+
orphanedPermission
|
|
1027
|
+
} = this.config;
|
|
1028
|
+
this.discoveredSkillNames.clear();
|
|
1029
|
+
setCwd(cwd);
|
|
1030
|
+
const persistSession = !isSessionPersistenceDisabled();
|
|
1031
|
+
const startTime = Date.now();
|
|
1032
|
+
const wrappedCanUseTool = async (tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision) => {
|
|
1033
|
+
const result2 = await canUseTool(tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision);
|
|
1034
|
+
if (result2.behavior !== "allow") {
|
|
1035
|
+
this.permissionDenials.push({
|
|
1036
|
+
type: "permission_denial",
|
|
1037
|
+
tool_name: sdkCompatToolName(tool.name),
|
|
1038
|
+
tool_use_id: toolUseID,
|
|
1039
|
+
tool_input: input
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
return result2;
|
|
1043
|
+
};
|
|
1044
|
+
const initialAppState = getAppState();
|
|
1045
|
+
const initialMainLoopModel = userSpecifiedModel ? parseUserSpecifiedModel(userSpecifiedModel) : getMainLoopModel();
|
|
1046
|
+
const initialThinkingConfig = thinkingConfig ? thinkingConfig : shouldEnableThinkingByDefault() !== false ? { type: "adaptive" } : { type: "disabled" };
|
|
1047
|
+
headlessProfilerCheckpoint("before_getSystemPrompt");
|
|
1048
|
+
const customPrompt = typeof customSystemPrompt === "string" ? customSystemPrompt : undefined;
|
|
1049
|
+
const {
|
|
1050
|
+
defaultSystemPrompt,
|
|
1051
|
+
userContext: baseUserContext,
|
|
1052
|
+
systemContext
|
|
1053
|
+
} = await fetchSystemPromptParts({
|
|
1054
|
+
tools,
|
|
1055
|
+
mainLoopModel: initialMainLoopModel,
|
|
1056
|
+
additionalWorkingDirectories: Array.from(initialAppState.toolPermissionContext.additionalWorkingDirectories.keys()),
|
|
1057
|
+
mcpClients,
|
|
1058
|
+
customSystemPrompt: customPrompt
|
|
1059
|
+
});
|
|
1060
|
+
headlessProfilerCheckpoint("after_getSystemPrompt");
|
|
1061
|
+
const userContext = {
|
|
1062
|
+
...baseUserContext,
|
|
1063
|
+
...getCoordinatorUserContext(mcpClients, isScratchpadEnabled() ? getScratchpadDir() : undefined)
|
|
1064
|
+
};
|
|
1065
|
+
const memoryMechanicsPrompt = customPrompt !== undefined && hasAutoMemPathOverride() ? await loadMemoryPrompt() : null;
|
|
1066
|
+
const systemPrompt = asSystemPrompt([
|
|
1067
|
+
...customPrompt !== undefined ? [customPrompt] : defaultSystemPrompt,
|
|
1068
|
+
...memoryMechanicsPrompt ? [memoryMechanicsPrompt] : [],
|
|
1069
|
+
...appendSystemPrompt ? [appendSystemPrompt] : []
|
|
1070
|
+
]);
|
|
1071
|
+
const hasStructuredOutputTool = tools.some((t) => toolMatchesName(t, SYNTHETIC_OUTPUT_TOOL_NAME));
|
|
1072
|
+
if (jsonSchema && hasStructuredOutputTool) {
|
|
1073
|
+
registerStructuredOutputEnforcement(setAppState, getSessionId());
|
|
1074
|
+
}
|
|
1075
|
+
let processUserInputContext = {
|
|
1076
|
+
messages: this.mutableMessages,
|
|
1077
|
+
setMessages: (fn) => {
|
|
1078
|
+
this.mutableMessages = fn(this.mutableMessages);
|
|
1079
|
+
},
|
|
1080
|
+
onChangeAPIKey: () => {},
|
|
1081
|
+
handleElicitation: this.config.handleElicitation,
|
|
1082
|
+
options: {
|
|
1083
|
+
commands,
|
|
1084
|
+
debug: false,
|
|
1085
|
+
tools,
|
|
1086
|
+
verbose,
|
|
1087
|
+
mainLoopModel: initialMainLoopModel,
|
|
1088
|
+
thinkingConfig: initialThinkingConfig,
|
|
1089
|
+
mcpClients,
|
|
1090
|
+
mcpResources: {},
|
|
1091
|
+
ideInstallationStatus: null,
|
|
1092
|
+
isNonInteractiveSession: true,
|
|
1093
|
+
customSystemPrompt,
|
|
1094
|
+
appendSystemPrompt,
|
|
1095
|
+
agentDefinitions: { activeAgents: agents, allAgents: [] },
|
|
1096
|
+
theme: resolveThemeSetting(getGlobalConfig().theme),
|
|
1097
|
+
maxBudgetUsd
|
|
1098
|
+
},
|
|
1099
|
+
getAppState,
|
|
1100
|
+
setAppState,
|
|
1101
|
+
abortController: this.abortController,
|
|
1102
|
+
readFileState: this.readFileState,
|
|
1103
|
+
nestedMemoryAttachmentTriggers: new Set,
|
|
1104
|
+
loadedNestedMemoryPaths: this.loadedNestedMemoryPaths,
|
|
1105
|
+
dynamicSkillDirTriggers: new Set,
|
|
1106
|
+
discoveredSkillNames: this.discoveredSkillNames,
|
|
1107
|
+
setInProgressToolUseIDs: () => {},
|
|
1108
|
+
setResponseLength: () => {},
|
|
1109
|
+
updateFileHistoryState: (updater) => {
|
|
1110
|
+
setAppState((prev) => {
|
|
1111
|
+
const updated = updater(prev.fileHistory);
|
|
1112
|
+
if (updated === prev.fileHistory)
|
|
1113
|
+
return prev;
|
|
1114
|
+
return { ...prev, fileHistory: updated };
|
|
1115
|
+
});
|
|
1116
|
+
},
|
|
1117
|
+
updateAttributionState: (updater) => {
|
|
1118
|
+
setAppState((prev) => {
|
|
1119
|
+
const updated = updater(prev.attribution);
|
|
1120
|
+
if (updated === prev.attribution)
|
|
1121
|
+
return prev;
|
|
1122
|
+
return { ...prev, attribution: updated };
|
|
1123
|
+
});
|
|
1124
|
+
},
|
|
1125
|
+
setSDKStatus
|
|
1126
|
+
};
|
|
1127
|
+
if (orphanedPermission && !this.hasHandledOrphanedPermission) {
|
|
1128
|
+
this.hasHandledOrphanedPermission = true;
|
|
1129
|
+
for await (const message of handleOrphanedPermission(orphanedPermission, tools, this.mutableMessages, processUserInputContext)) {
|
|
1130
|
+
yield message;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
const {
|
|
1134
|
+
messages: messagesFromUserInput,
|
|
1135
|
+
shouldQuery,
|
|
1136
|
+
allowedTools,
|
|
1137
|
+
model: modelFromUserInput,
|
|
1138
|
+
resultText
|
|
1139
|
+
} = await processUserInput({
|
|
1140
|
+
input: prompt,
|
|
1141
|
+
mode: "prompt",
|
|
1142
|
+
setToolJSX: () => {},
|
|
1143
|
+
context: {
|
|
1144
|
+
...processUserInputContext,
|
|
1145
|
+
messages: this.mutableMessages
|
|
1146
|
+
},
|
|
1147
|
+
messages: this.mutableMessages,
|
|
1148
|
+
uuid: options?.uuid,
|
|
1149
|
+
isMeta: options?.isMeta,
|
|
1150
|
+
querySource: "sdk"
|
|
1151
|
+
});
|
|
1152
|
+
this.mutableMessages.push(...messagesFromUserInput);
|
|
1153
|
+
const messages = [...this.mutableMessages];
|
|
1154
|
+
if (persistSession && messagesFromUserInput.length > 0) {
|
|
1155
|
+
const transcriptPromise = recordTranscript(messages);
|
|
1156
|
+
if (isBareMode()) {} else {
|
|
1157
|
+
await transcriptPromise;
|
|
1158
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
|
|
1159
|
+
await flushSessionStorage();
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
const replayableMessages = messagesFromUserInput.filter((msg) => msg.type === "user" && !msg.isMeta && !msg.toolUseResult && messageSelector().selectableUserMessagesFilter(msg) || msg.type === "system" && msg.subtype === "compact_boundary");
|
|
1164
|
+
const messagesToAck = replayUserMessages ? replayableMessages : [];
|
|
1165
|
+
setAppState((prev) => ({
|
|
1166
|
+
...prev,
|
|
1167
|
+
toolPermissionContext: {
|
|
1168
|
+
...prev.toolPermissionContext,
|
|
1169
|
+
alwaysAllowRules: {
|
|
1170
|
+
...prev.toolPermissionContext.alwaysAllowRules,
|
|
1171
|
+
command: allowedTools
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}));
|
|
1175
|
+
const mainLoopModel = modelFromUserInput ?? initialMainLoopModel;
|
|
1176
|
+
processUserInputContext = {
|
|
1177
|
+
messages,
|
|
1178
|
+
setMessages: () => {},
|
|
1179
|
+
onChangeAPIKey: () => {},
|
|
1180
|
+
handleElicitation: this.config.handleElicitation,
|
|
1181
|
+
options: {
|
|
1182
|
+
commands,
|
|
1183
|
+
debug: false,
|
|
1184
|
+
tools,
|
|
1185
|
+
verbose,
|
|
1186
|
+
mainLoopModel,
|
|
1187
|
+
thinkingConfig: initialThinkingConfig,
|
|
1188
|
+
mcpClients,
|
|
1189
|
+
mcpResources: {},
|
|
1190
|
+
ideInstallationStatus: null,
|
|
1191
|
+
isNonInteractiveSession: true,
|
|
1192
|
+
customSystemPrompt,
|
|
1193
|
+
appendSystemPrompt,
|
|
1194
|
+
theme: resolveThemeSetting(getGlobalConfig().theme),
|
|
1195
|
+
agentDefinitions: { activeAgents: agents, allAgents: [] },
|
|
1196
|
+
maxBudgetUsd
|
|
1197
|
+
},
|
|
1198
|
+
getAppState,
|
|
1199
|
+
setAppState,
|
|
1200
|
+
abortController: this.abortController,
|
|
1201
|
+
readFileState: this.readFileState,
|
|
1202
|
+
nestedMemoryAttachmentTriggers: new Set,
|
|
1203
|
+
loadedNestedMemoryPaths: this.loadedNestedMemoryPaths,
|
|
1204
|
+
dynamicSkillDirTriggers: new Set,
|
|
1205
|
+
discoveredSkillNames: this.discoveredSkillNames,
|
|
1206
|
+
setInProgressToolUseIDs: () => {},
|
|
1207
|
+
setResponseLength: () => {},
|
|
1208
|
+
updateFileHistoryState: processUserInputContext.updateFileHistoryState,
|
|
1209
|
+
updateAttributionState: processUserInputContext.updateAttributionState,
|
|
1210
|
+
setSDKStatus
|
|
1211
|
+
};
|
|
1212
|
+
headlessProfilerCheckpoint("before_skills_plugins");
|
|
1213
|
+
const [skills, { enabled: enabledPlugins }] = await Promise.all([
|
|
1214
|
+
getSlashCommandToolSkills(getCwd()),
|
|
1215
|
+
loadAllPluginsCacheOnly()
|
|
1216
|
+
]);
|
|
1217
|
+
headlessProfilerCheckpoint("after_skills_plugins");
|
|
1218
|
+
yield buildSystemInitMessage({
|
|
1219
|
+
tools,
|
|
1220
|
+
mcpClients,
|
|
1221
|
+
model: mainLoopModel,
|
|
1222
|
+
permissionMode: initialAppState.toolPermissionContext.mode,
|
|
1223
|
+
commands,
|
|
1224
|
+
agents,
|
|
1225
|
+
skills,
|
|
1226
|
+
plugins: enabledPlugins,
|
|
1227
|
+
fastMode: initialAppState.fastMode
|
|
1228
|
+
});
|
|
1229
|
+
headlessProfilerCheckpoint("system_message_yielded");
|
|
1230
|
+
if (!shouldQuery) {
|
|
1231
|
+
for (const msg of messagesFromUserInput) {
|
|
1232
|
+
if (msg.type === "user" && typeof msg.message.content === "string" && (msg.message.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`) || msg.message.content.includes(`<${LOCAL_COMMAND_STDERR_TAG}>`) || msg.isCompactSummary)) {
|
|
1233
|
+
yield {
|
|
1234
|
+
type: "user",
|
|
1235
|
+
message: {
|
|
1236
|
+
...msg.message,
|
|
1237
|
+
content: stripAnsi(msg.message.content)
|
|
1238
|
+
},
|
|
1239
|
+
session_id: getSessionId(),
|
|
1240
|
+
parent_tool_use_id: null,
|
|
1241
|
+
uuid: msg.uuid,
|
|
1242
|
+
timestamp: msg.timestamp,
|
|
1243
|
+
isReplay: !msg.isCompactSummary,
|
|
1244
|
+
isSynthetic: msg.isMeta || msg.isVisibleInTranscriptOnly
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
if (msg.type === "system" && msg.subtype === "local_command" && typeof msg.content === "string" && (msg.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`) || msg.content.includes(`<${LOCAL_COMMAND_STDERR_TAG}>`))) {
|
|
1248
|
+
yield localCommandOutputToSDKAssistantMessage(msg.content, msg.uuid);
|
|
1249
|
+
}
|
|
1250
|
+
if (msg.type === "system" && msg.subtype === "compact_boundary") {
|
|
1251
|
+
const compactMsg = msg;
|
|
1252
|
+
yield {
|
|
1253
|
+
type: "system",
|
|
1254
|
+
subtype: "compact_boundary",
|
|
1255
|
+
session_id: getSessionId(),
|
|
1256
|
+
uuid: msg.uuid,
|
|
1257
|
+
compact_metadata: toSDKCompactMetadata(compactMsg.compactMetadata)
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
if (persistSession) {
|
|
1262
|
+
await recordTranscript(messages);
|
|
1263
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
|
|
1264
|
+
await flushSessionStorage();
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
yield {
|
|
1268
|
+
type: "result",
|
|
1269
|
+
subtype: "success",
|
|
1270
|
+
is_error: false,
|
|
1271
|
+
duration_ms: Date.now() - startTime,
|
|
1272
|
+
duration_api_ms: getTotalAPIDuration(),
|
|
1273
|
+
num_turns: messages.length - 1,
|
|
1274
|
+
result: resultText ?? "",
|
|
1275
|
+
stop_reason: null,
|
|
1276
|
+
session_id: getSessionId(),
|
|
1277
|
+
total_cost_usd: getTotalCostUSD(),
|
|
1278
|
+
usage: this.totalUsage,
|
|
1279
|
+
modelUsage: getModelUsage(),
|
|
1280
|
+
permission_denials: this.permissionDenials,
|
|
1281
|
+
fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
|
|
1282
|
+
uuid: randomUUID()
|
|
1283
|
+
};
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
if (fileHistoryEnabled() && persistSession) {
|
|
1287
|
+
messagesFromUserInput.filter(messageSelector().selectableUserMessagesFilter).forEach((message) => {
|
|
1288
|
+
fileHistoryMakeSnapshot((updater) => {
|
|
1289
|
+
setAppState((prev) => ({
|
|
1290
|
+
...prev,
|
|
1291
|
+
fileHistory: updater(prev.fileHistory)
|
|
1292
|
+
}));
|
|
1293
|
+
}, message.uuid);
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1296
|
+
let currentMessageUsage = EMPTY_USAGE;
|
|
1297
|
+
let turnCount = 1;
|
|
1298
|
+
let hasAcknowledgedInitialMessages = false;
|
|
1299
|
+
let structuredOutputFromTool;
|
|
1300
|
+
let lastStopReason = null;
|
|
1301
|
+
const errorLogWatermark = getInMemoryErrors().at(-1);
|
|
1302
|
+
const initialStructuredOutputCalls = jsonSchema ? countToolCalls(this.mutableMessages, SYNTHETIC_OUTPUT_TOOL_NAME) : 0;
|
|
1303
|
+
for await (const message of query({
|
|
1304
|
+
messages,
|
|
1305
|
+
systemPrompt,
|
|
1306
|
+
userContext,
|
|
1307
|
+
systemContext,
|
|
1308
|
+
canUseTool: wrappedCanUseTool,
|
|
1309
|
+
toolUseContext: processUserInputContext,
|
|
1310
|
+
fallbackModel,
|
|
1311
|
+
querySource: "sdk",
|
|
1312
|
+
maxTurns,
|
|
1313
|
+
taskBudget
|
|
1314
|
+
})) {
|
|
1315
|
+
if (message.type === "assistant" || message.type === "user" || message.type === "system" && message.subtype === "compact_boundary") {
|
|
1316
|
+
if (persistSession && message.type === "system" && message.subtype === "compact_boundary") {
|
|
1317
|
+
const compactMsg = message;
|
|
1318
|
+
const tailUuid = compactMsg.compactMetadata?.preservedSegment?.tailUuid;
|
|
1319
|
+
if (tailUuid) {
|
|
1320
|
+
const tailIdx = this.mutableMessages.findLastIndex((m) => m.uuid === tailUuid);
|
|
1321
|
+
if (tailIdx !== -1) {
|
|
1322
|
+
await recordTranscript(this.mutableMessages.slice(0, tailIdx + 1));
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
messages.push(message);
|
|
1327
|
+
if (persistSession) {
|
|
1328
|
+
if (message.type === "assistant") {
|
|
1329
|
+
recordTranscript(messages);
|
|
1330
|
+
} else {
|
|
1331
|
+
await recordTranscript(messages);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
if (!hasAcknowledgedInitialMessages && messagesToAck.length > 0) {
|
|
1335
|
+
hasAcknowledgedInitialMessages = true;
|
|
1336
|
+
for (const msgToAck of messagesToAck) {
|
|
1337
|
+
if (msgToAck.type === "user") {
|
|
1338
|
+
yield {
|
|
1339
|
+
type: "user",
|
|
1340
|
+
message: msgToAck.message,
|
|
1341
|
+
session_id: getSessionId(),
|
|
1342
|
+
parent_tool_use_id: null,
|
|
1343
|
+
uuid: msgToAck.uuid,
|
|
1344
|
+
timestamp: msgToAck.timestamp,
|
|
1345
|
+
isReplay: true
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
if (message.type === "user") {
|
|
1352
|
+
turnCount++;
|
|
1353
|
+
}
|
|
1354
|
+
switch (message.type) {
|
|
1355
|
+
case "tombstone":
|
|
1356
|
+
break;
|
|
1357
|
+
case "assistant": {
|
|
1358
|
+
const msg = message;
|
|
1359
|
+
const stopReason = msg.message?.stop_reason;
|
|
1360
|
+
if (stopReason != null) {
|
|
1361
|
+
lastStopReason = stopReason;
|
|
1362
|
+
}
|
|
1363
|
+
this.mutableMessages.push(msg);
|
|
1364
|
+
yield* normalizeMessage(msg);
|
|
1365
|
+
break;
|
|
1366
|
+
}
|
|
1367
|
+
case "progress": {
|
|
1368
|
+
const msg = message;
|
|
1369
|
+
this.mutableMessages.push(msg);
|
|
1370
|
+
if (persistSession) {
|
|
1371
|
+
messages.push(msg);
|
|
1372
|
+
recordTranscript(messages);
|
|
1373
|
+
}
|
|
1374
|
+
yield* normalizeMessage(msg);
|
|
1375
|
+
break;
|
|
1376
|
+
}
|
|
1377
|
+
case "user": {
|
|
1378
|
+
const msg = message;
|
|
1379
|
+
this.mutableMessages.push(msg);
|
|
1380
|
+
yield* normalizeMessage(msg);
|
|
1381
|
+
break;
|
|
1382
|
+
}
|
|
1383
|
+
case "stream_event": {
|
|
1384
|
+
const event = message.event;
|
|
1385
|
+
if (event.type === "message_start") {
|
|
1386
|
+
currentMessageUsage = EMPTY_USAGE;
|
|
1387
|
+
const eventMessage = event.message;
|
|
1388
|
+
currentMessageUsage = updateUsage(currentMessageUsage, eventMessage.usage);
|
|
1389
|
+
}
|
|
1390
|
+
if (event.type === "message_delta") {
|
|
1391
|
+
currentMessageUsage = updateUsage(currentMessageUsage, event.usage);
|
|
1392
|
+
const delta = event.delta;
|
|
1393
|
+
if (delta.stop_reason != null) {
|
|
1394
|
+
lastStopReason = delta.stop_reason;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
if (event.type === "message_stop") {
|
|
1398
|
+
this.totalUsage = accumulateUsage(this.totalUsage, currentMessageUsage);
|
|
1399
|
+
}
|
|
1400
|
+
if (includePartialMessages) {
|
|
1401
|
+
yield {
|
|
1402
|
+
type: "stream_event",
|
|
1403
|
+
event,
|
|
1404
|
+
session_id: getSessionId(),
|
|
1405
|
+
parent_tool_use_id: null,
|
|
1406
|
+
uuid: randomUUID()
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
break;
|
|
1410
|
+
}
|
|
1411
|
+
case "attachment": {
|
|
1412
|
+
const msg = message;
|
|
1413
|
+
this.mutableMessages.push(msg);
|
|
1414
|
+
if (persistSession) {
|
|
1415
|
+
messages.push(msg);
|
|
1416
|
+
recordTranscript(messages);
|
|
1417
|
+
}
|
|
1418
|
+
const attachment = msg.attachment;
|
|
1419
|
+
if (attachment.type === "structured_output") {
|
|
1420
|
+
structuredOutputFromTool = attachment.data;
|
|
1421
|
+
} else if (attachment.type === "max_turns_reached") {
|
|
1422
|
+
if (persistSession) {
|
|
1423
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
|
|
1424
|
+
await flushSessionStorage();
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
yield {
|
|
1428
|
+
type: "result",
|
|
1429
|
+
subtype: "error_max_turns",
|
|
1430
|
+
duration_ms: Date.now() - startTime,
|
|
1431
|
+
duration_api_ms: getTotalAPIDuration(),
|
|
1432
|
+
is_error: true,
|
|
1433
|
+
num_turns: attachment.turnCount,
|
|
1434
|
+
stop_reason: lastStopReason,
|
|
1435
|
+
session_id: getSessionId(),
|
|
1436
|
+
total_cost_usd: getTotalCostUSD(),
|
|
1437
|
+
usage: this.totalUsage,
|
|
1438
|
+
modelUsage: getModelUsage(),
|
|
1439
|
+
permission_denials: this.permissionDenials,
|
|
1440
|
+
fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
|
|
1441
|
+
uuid: randomUUID(),
|
|
1442
|
+
errors: [
|
|
1443
|
+
`Reached maximum number of turns (${attachment.maxTurns})`
|
|
1444
|
+
]
|
|
1445
|
+
};
|
|
1446
|
+
return;
|
|
1447
|
+
} else if (replayUserMessages && attachment.type === "queued_command") {
|
|
1448
|
+
yield {
|
|
1449
|
+
type: "user",
|
|
1450
|
+
message: {
|
|
1451
|
+
role: "user",
|
|
1452
|
+
content: attachment.prompt
|
|
1453
|
+
},
|
|
1454
|
+
session_id: getSessionId(),
|
|
1455
|
+
parent_tool_use_id: null,
|
|
1456
|
+
uuid: attachment.source_uuid || msg.uuid,
|
|
1457
|
+
timestamp: msg.timestamp,
|
|
1458
|
+
isReplay: true
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
break;
|
|
1462
|
+
}
|
|
1463
|
+
case "stream_request_start":
|
|
1464
|
+
break;
|
|
1465
|
+
case "system": {
|
|
1466
|
+
const msg = message;
|
|
1467
|
+
const snipResult = this.config.snipReplay?.(msg, this.mutableMessages);
|
|
1468
|
+
if (snipResult !== undefined) {
|
|
1469
|
+
if (snipResult.executed) {
|
|
1470
|
+
this.mutableMessages.length = 0;
|
|
1471
|
+
this.mutableMessages.push(...snipResult.messages);
|
|
1472
|
+
}
|
|
1473
|
+
break;
|
|
1474
|
+
}
|
|
1475
|
+
this.mutableMessages.push(msg);
|
|
1476
|
+
if (msg.subtype === "compact_boundary" && msg.compactMetadata) {
|
|
1477
|
+
const compactMsg = msg;
|
|
1478
|
+
const mutableBoundaryIdx = this.mutableMessages.length - 1;
|
|
1479
|
+
if (mutableBoundaryIdx > 0) {
|
|
1480
|
+
this.mutableMessages.splice(0, mutableBoundaryIdx);
|
|
1481
|
+
}
|
|
1482
|
+
const localBoundaryIdx = messages.length - 1;
|
|
1483
|
+
if (localBoundaryIdx > 0) {
|
|
1484
|
+
messages.splice(0, localBoundaryIdx);
|
|
1485
|
+
}
|
|
1486
|
+
yield {
|
|
1487
|
+
type: "system",
|
|
1488
|
+
subtype: "compact_boundary",
|
|
1489
|
+
session_id: getSessionId(),
|
|
1490
|
+
uuid: msg.uuid,
|
|
1491
|
+
compact_metadata: toSDKCompactMetadata(compactMsg.compactMetadata)
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
if (msg.subtype === "api_error") {
|
|
1495
|
+
const apiErrorMsg = msg;
|
|
1496
|
+
yield {
|
|
1497
|
+
type: "system",
|
|
1498
|
+
subtype: "api_retry",
|
|
1499
|
+
attempt: apiErrorMsg.retryAttempt,
|
|
1500
|
+
max_retries: apiErrorMsg.maxRetries,
|
|
1501
|
+
retry_delay_ms: apiErrorMsg.retryInMs,
|
|
1502
|
+
error_status: apiErrorMsg.error.status ?? null,
|
|
1503
|
+
error: categorizeRetryableAPIError(apiErrorMsg.error),
|
|
1504
|
+
session_id: getSessionId(),
|
|
1505
|
+
uuid: msg.uuid
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
break;
|
|
1509
|
+
}
|
|
1510
|
+
case "tool_use_summary": {
|
|
1511
|
+
const msg = message;
|
|
1512
|
+
yield {
|
|
1513
|
+
type: "tool_use_summary",
|
|
1514
|
+
summary: msg.summary,
|
|
1515
|
+
preceding_tool_use_ids: msg.precedingToolUseIds,
|
|
1516
|
+
session_id: getSessionId(),
|
|
1517
|
+
uuid: msg.uuid
|
|
1518
|
+
};
|
|
1519
|
+
break;
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
if (maxBudgetUsd !== undefined && getTotalCostUSD() >= maxBudgetUsd) {
|
|
1523
|
+
if (persistSession) {
|
|
1524
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
|
|
1525
|
+
await flushSessionStorage();
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
yield {
|
|
1529
|
+
type: "result",
|
|
1530
|
+
subtype: "error_max_budget_usd",
|
|
1531
|
+
duration_ms: Date.now() - startTime,
|
|
1532
|
+
duration_api_ms: getTotalAPIDuration(),
|
|
1533
|
+
is_error: true,
|
|
1534
|
+
num_turns: turnCount,
|
|
1535
|
+
stop_reason: lastStopReason,
|
|
1536
|
+
session_id: getSessionId(),
|
|
1537
|
+
total_cost_usd: getTotalCostUSD(),
|
|
1538
|
+
usage: this.totalUsage,
|
|
1539
|
+
modelUsage: getModelUsage(),
|
|
1540
|
+
permission_denials: this.permissionDenials,
|
|
1541
|
+
fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
|
|
1542
|
+
uuid: randomUUID(),
|
|
1543
|
+
errors: [`Reached maximum budget ($${maxBudgetUsd})`]
|
|
1544
|
+
};
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
if (message.type === "user" && jsonSchema) {
|
|
1548
|
+
const currentCalls = countToolCalls(this.mutableMessages, SYNTHETIC_OUTPUT_TOOL_NAME);
|
|
1549
|
+
const callsThisQuery = currentCalls - initialStructuredOutputCalls;
|
|
1550
|
+
const maxRetries = parseInt(process.env.MAX_STRUCTURED_OUTPUT_RETRIES || "5", 10);
|
|
1551
|
+
if (callsThisQuery >= maxRetries) {
|
|
1552
|
+
if (persistSession) {
|
|
1553
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
|
|
1554
|
+
await flushSessionStorage();
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
yield {
|
|
1558
|
+
type: "result",
|
|
1559
|
+
subtype: "error_max_structured_output_retries",
|
|
1560
|
+
duration_ms: Date.now() - startTime,
|
|
1561
|
+
duration_api_ms: getTotalAPIDuration(),
|
|
1562
|
+
is_error: true,
|
|
1563
|
+
num_turns: turnCount,
|
|
1564
|
+
stop_reason: lastStopReason,
|
|
1565
|
+
session_id: getSessionId(),
|
|
1566
|
+
total_cost_usd: getTotalCostUSD(),
|
|
1567
|
+
usage: this.totalUsage,
|
|
1568
|
+
modelUsage: getModelUsage(),
|
|
1569
|
+
permission_denials: this.permissionDenials,
|
|
1570
|
+
fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
|
|
1571
|
+
uuid: randomUUID(),
|
|
1572
|
+
errors: [
|
|
1573
|
+
`Failed to provide valid structured output after ${maxRetries} attempts`
|
|
1574
|
+
]
|
|
1575
|
+
};
|
|
1576
|
+
return;
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
const result = messages.findLast((m) => m.type === "assistant" || m.type === "user");
|
|
1581
|
+
const edeResultType = result?.type ?? "undefined";
|
|
1582
|
+
const edeLastContentType = result?.type === "assistant" ? last_default(result.message.content)?.type ?? "none" : "n/a";
|
|
1583
|
+
if (persistSession) {
|
|
1584
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
|
|
1585
|
+
await flushSessionStorage();
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
if (!isResultSuccessful(result, lastStopReason)) {
|
|
1589
|
+
yield {
|
|
1590
|
+
type: "result",
|
|
1591
|
+
subtype: "error_during_execution",
|
|
1592
|
+
duration_ms: Date.now() - startTime,
|
|
1593
|
+
duration_api_ms: getTotalAPIDuration(),
|
|
1594
|
+
is_error: true,
|
|
1595
|
+
num_turns: turnCount,
|
|
1596
|
+
stop_reason: lastStopReason,
|
|
1597
|
+
session_id: getSessionId(),
|
|
1598
|
+
total_cost_usd: getTotalCostUSD(),
|
|
1599
|
+
usage: this.totalUsage,
|
|
1600
|
+
modelUsage: getModelUsage(),
|
|
1601
|
+
permission_denials: this.permissionDenials,
|
|
1602
|
+
fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
|
|
1603
|
+
uuid: randomUUID(),
|
|
1604
|
+
errors: (() => {
|
|
1605
|
+
const all = getInMemoryErrors();
|
|
1606
|
+
const start = errorLogWatermark ? all.lastIndexOf(errorLogWatermark) + 1 : 0;
|
|
1607
|
+
return [
|
|
1608
|
+
`[ede_diagnostic] result_type=${edeResultType} last_content_type=${edeLastContentType} stop_reason=${lastStopReason}`,
|
|
1609
|
+
...all.slice(start).map((_) => _.error)
|
|
1610
|
+
];
|
|
1611
|
+
})()
|
|
1612
|
+
};
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
let textResult = "";
|
|
1616
|
+
let isApiError = false;
|
|
1617
|
+
if (result.type === "assistant") {
|
|
1618
|
+
const lastContent = last_default(result.message.content);
|
|
1619
|
+
if (lastContent?.type === "text" && !SYNTHETIC_MESSAGES.has(lastContent.text)) {
|
|
1620
|
+
textResult = lastContent.text;
|
|
1621
|
+
}
|
|
1622
|
+
isApiError = Boolean(result.isApiErrorMessage);
|
|
1623
|
+
}
|
|
1624
|
+
yield {
|
|
1625
|
+
type: "result",
|
|
1626
|
+
subtype: "success",
|
|
1627
|
+
is_error: isApiError,
|
|
1628
|
+
duration_ms: Date.now() - startTime,
|
|
1629
|
+
duration_api_ms: getTotalAPIDuration(),
|
|
1630
|
+
num_turns: turnCount,
|
|
1631
|
+
result: textResult,
|
|
1632
|
+
stop_reason: lastStopReason,
|
|
1633
|
+
session_id: getSessionId(),
|
|
1634
|
+
total_cost_usd: getTotalCostUSD(),
|
|
1635
|
+
usage: this.totalUsage,
|
|
1636
|
+
modelUsage: getModelUsage(),
|
|
1637
|
+
permission_denials: this.permissionDenials,
|
|
1638
|
+
structured_output: structuredOutputFromTool,
|
|
1639
|
+
fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
|
|
1640
|
+
uuid: randomUUID()
|
|
1641
|
+
};
|
|
1642
|
+
}
|
|
1643
|
+
interrupt() {
|
|
1644
|
+
this.abortController.abort();
|
|
1645
|
+
}
|
|
1646
|
+
getMessages() {
|
|
1647
|
+
return this.mutableMessages;
|
|
1648
|
+
}
|
|
1649
|
+
getReadFileState() {
|
|
1650
|
+
return this.readFileState;
|
|
1651
|
+
}
|
|
1652
|
+
getSessionId() {
|
|
1653
|
+
return getSessionId();
|
|
1654
|
+
}
|
|
1655
|
+
setModel(model) {
|
|
1656
|
+
this.config.userSpecifiedModel = model;
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
async function* ask({
|
|
1660
|
+
commands,
|
|
1661
|
+
prompt,
|
|
1662
|
+
promptUuid,
|
|
1663
|
+
isMeta,
|
|
1664
|
+
cwd,
|
|
1665
|
+
tools,
|
|
1666
|
+
mcpClients,
|
|
1667
|
+
verbose = false,
|
|
1668
|
+
thinkingConfig,
|
|
1669
|
+
maxTurns,
|
|
1670
|
+
maxBudgetUsd,
|
|
1671
|
+
taskBudget,
|
|
1672
|
+
canUseTool,
|
|
1673
|
+
mutableMessages = [],
|
|
1674
|
+
getReadFileCache,
|
|
1675
|
+
setReadFileCache,
|
|
1676
|
+
customSystemPrompt,
|
|
1677
|
+
appendSystemPrompt,
|
|
1678
|
+
userSpecifiedModel,
|
|
1679
|
+
fallbackModel,
|
|
1680
|
+
jsonSchema,
|
|
1681
|
+
getAppState,
|
|
1682
|
+
setAppState,
|
|
1683
|
+
abortController,
|
|
1684
|
+
replayUserMessages = false,
|
|
1685
|
+
includePartialMessages = false,
|
|
1686
|
+
handleElicitation,
|
|
1687
|
+
agents = [],
|
|
1688
|
+
setSDKStatus,
|
|
1689
|
+
orphanedPermission
|
|
1690
|
+
}) {
|
|
1691
|
+
const engine = new QueryEngine({
|
|
1692
|
+
cwd,
|
|
1693
|
+
tools,
|
|
1694
|
+
commands,
|
|
1695
|
+
mcpClients,
|
|
1696
|
+
agents: agents ?? [],
|
|
1697
|
+
canUseTool,
|
|
1698
|
+
getAppState,
|
|
1699
|
+
setAppState,
|
|
1700
|
+
initialMessages: mutableMessages,
|
|
1701
|
+
readFileCache: cloneFileStateCache(getReadFileCache()),
|
|
1702
|
+
customSystemPrompt,
|
|
1703
|
+
appendSystemPrompt,
|
|
1704
|
+
userSpecifiedModel,
|
|
1705
|
+
fallbackModel,
|
|
1706
|
+
thinkingConfig,
|
|
1707
|
+
maxTurns,
|
|
1708
|
+
maxBudgetUsd,
|
|
1709
|
+
taskBudget,
|
|
1710
|
+
jsonSchema,
|
|
1711
|
+
verbose,
|
|
1712
|
+
handleElicitation,
|
|
1713
|
+
replayUserMessages,
|
|
1714
|
+
includePartialMessages,
|
|
1715
|
+
setSDKStatus,
|
|
1716
|
+
abortController,
|
|
1717
|
+
orphanedPermission,
|
|
1718
|
+
...{}
|
|
1719
|
+
});
|
|
1720
|
+
try {
|
|
1721
|
+
yield* engine.submitMessage(prompt, {
|
|
1722
|
+
uuid: promptUuid,
|
|
1723
|
+
isMeta
|
|
1724
|
+
});
|
|
1725
|
+
} finally {
|
|
1726
|
+
setReadFileCache(engine.getReadFileState());
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
// src/cli/print.ts
|
|
1731
|
+
init_fileStateCache();
|
|
1732
|
+
init_path();
|
|
1733
|
+
init_queryHelpers();
|
|
1734
|
+
init_hookEvents();
|
|
1735
|
+
|
|
1736
|
+
// src/utils/filePersistence/filePersistence.ts
|
|
1737
|
+
init_analytics();
|
|
1738
|
+
init_filesApi();
|
|
1739
|
+
init_cwd();
|
|
1740
|
+
init_errors();
|
|
1741
|
+
init_log();
|
|
1742
|
+
init_sessionIngressAuth();
|
|
1743
|
+
init_outputsScanner();
|
|
1744
|
+
|
|
1745
|
+
// src/cli/print.ts
|
|
1746
|
+
init_AsyncHookRegistry();
|
|
1747
|
+
init_gracefulShutdown();
|
|
1748
|
+
init_cleanupRegistry();
|
|
1749
|
+
|
|
1750
|
+
// src/utils/idleTimeout.ts
|
|
1751
|
+
init_debug();
|
|
1752
|
+
init_gracefulShutdown();
|
|
1753
|
+
function createIdleTimeoutManager(isIdle) {
|
|
1754
|
+
const exitAfterStopDelay = process.env.CLAUDE_CODE_EXIT_AFTER_STOP_DELAY;
|
|
1755
|
+
const delayMs = exitAfterStopDelay ? parseInt(exitAfterStopDelay, 10) : null;
|
|
1756
|
+
const isValidDelay = delayMs && !isNaN(delayMs) && delayMs > 0;
|
|
1757
|
+
let timer = null;
|
|
1758
|
+
let lastIdleTime = 0;
|
|
1759
|
+
return {
|
|
1760
|
+
start() {
|
|
1761
|
+
if (timer) {
|
|
1762
|
+
clearTimeout(timer);
|
|
1763
|
+
timer = null;
|
|
1764
|
+
}
|
|
1765
|
+
if (isValidDelay) {
|
|
1766
|
+
lastIdleTime = Date.now();
|
|
1767
|
+
timer = setTimeout(() => {
|
|
1768
|
+
const idleDuration = Date.now() - lastIdleTime;
|
|
1769
|
+
if (isIdle() && idleDuration >= delayMs) {
|
|
1770
|
+
logForDebugging(`Exiting after ${delayMs}ms of idle time`);
|
|
1771
|
+
gracefulShutdownSync();
|
|
1772
|
+
}
|
|
1773
|
+
}, delayMs);
|
|
1774
|
+
}
|
|
1775
|
+
},
|
|
1776
|
+
stop() {
|
|
1777
|
+
if (timer) {
|
|
1778
|
+
clearTimeout(timer);
|
|
1779
|
+
timer = null;
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
};
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
// src/cli/print.ts
|
|
1786
|
+
init_cwd();
|
|
1787
|
+
init_omit();
|
|
1788
|
+
init_reject();
|
|
1789
|
+
init_policyLimits();
|
|
1790
|
+
init_product();
|
|
1791
|
+
init_bridgeStatusUtil();
|
|
1792
|
+
import { cwd } from "process";
|
|
1793
|
+
|
|
1794
|
+
// src/bridge/inboundAttachments.ts
|
|
1795
|
+
init_axios();
|
|
1796
|
+
init_v4();
|
|
1797
|
+
init_state();
|
|
1798
|
+
init_debug();
|
|
1799
|
+
init_envUtils();
|
|
1800
|
+
init_lazySchema();
|
|
1801
|
+
init_bridgeConfig();
|
|
1802
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1803
|
+
import { mkdir, writeFile } from "fs/promises";
|
|
1804
|
+
import { basename, join } from "path";
|
|
1805
|
+
var DOWNLOAD_TIMEOUT_MS = 30000;
|
|
1806
|
+
function debug(msg) {
|
|
1807
|
+
logForDebugging(`[bridge:inbound-attach] ${msg}`);
|
|
1808
|
+
}
|
|
1809
|
+
var attachmentSchema = lazySchema(() => exports_external.object({
|
|
1810
|
+
file_uuid: exports_external.string(),
|
|
1811
|
+
file_name: exports_external.string()
|
|
1812
|
+
}));
|
|
1813
|
+
var attachmentsArraySchema = lazySchema(() => exports_external.array(attachmentSchema()));
|
|
1814
|
+
function extractInboundAttachments(msg) {
|
|
1815
|
+
if (typeof msg !== "object" || msg === null || !("file_attachments" in msg)) {
|
|
1816
|
+
return [];
|
|
1817
|
+
}
|
|
1818
|
+
const parsed = attachmentsArraySchema().safeParse(msg.file_attachments);
|
|
1819
|
+
return parsed.success ? parsed.data : [];
|
|
1820
|
+
}
|
|
1821
|
+
function sanitizeFileName(name) {
|
|
1822
|
+
const base = basename(name).replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
1823
|
+
return base || "attachment";
|
|
1824
|
+
}
|
|
1825
|
+
function uploadsDir() {
|
|
1826
|
+
return join(getConfigHomeDir(), "uploads", getSessionId());
|
|
1827
|
+
}
|
|
1828
|
+
async function resolveOne(att) {
|
|
1829
|
+
const token = getBridgeAccessToken();
|
|
1830
|
+
if (!token) {
|
|
1831
|
+
debug("skip: no oauth token");
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
let data;
|
|
1835
|
+
try {
|
|
1836
|
+
const url = `${getBridgeBaseUrl()}/api/oauth/files/${encodeURIComponent(att.file_uuid)}/content`;
|
|
1837
|
+
const response = await axios_default.get(url, {
|
|
1838
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1839
|
+
responseType: "arraybuffer",
|
|
1840
|
+
timeout: DOWNLOAD_TIMEOUT_MS,
|
|
1841
|
+
validateStatus: () => true
|
|
1842
|
+
});
|
|
1843
|
+
if (response.status !== 200) {
|
|
1844
|
+
debug(`fetch ${att.file_uuid} failed: status=${response.status}`);
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
data = Buffer.from(response.data);
|
|
1848
|
+
} catch (e) {
|
|
1849
|
+
debug(`fetch ${att.file_uuid} threw: ${e}`);
|
|
1850
|
+
return;
|
|
1851
|
+
}
|
|
1852
|
+
const safeName = sanitizeFileName(att.file_name);
|
|
1853
|
+
const prefix = (att.file_uuid.slice(0, 8) || randomUUID2().slice(0, 8)).replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1854
|
+
const dir = uploadsDir();
|
|
1855
|
+
const outPath = join(dir, `${prefix}-${safeName}`);
|
|
1856
|
+
try {
|
|
1857
|
+
await mkdir(dir, { recursive: true });
|
|
1858
|
+
await writeFile(outPath, data);
|
|
1859
|
+
} catch (e) {
|
|
1860
|
+
debug(`write ${outPath} failed: ${e}`);
|
|
1861
|
+
return;
|
|
1862
|
+
}
|
|
1863
|
+
debug(`resolved ${att.file_uuid} \u2192 ${outPath} (${data.length} bytes)`);
|
|
1864
|
+
return outPath;
|
|
1865
|
+
}
|
|
1866
|
+
async function resolveInboundAttachments(attachments) {
|
|
1867
|
+
if (attachments.length === 0)
|
|
1868
|
+
return "";
|
|
1869
|
+
debug(`resolving ${attachments.length} attachment(s)`);
|
|
1870
|
+
const paths = await Promise.all(attachments.map(resolveOne));
|
|
1871
|
+
const ok = paths.filter((p) => p !== undefined);
|
|
1872
|
+
if (ok.length === 0)
|
|
1873
|
+
return "";
|
|
1874
|
+
return ok.map((p) => `@"${p}"`).join(" ") + " ";
|
|
1875
|
+
}
|
|
1876
|
+
function prependPathRefs(content, prefix) {
|
|
1877
|
+
if (!prefix)
|
|
1878
|
+
return content;
|
|
1879
|
+
if (typeof content === "string")
|
|
1880
|
+
return prefix + content;
|
|
1881
|
+
const i = content.findLastIndex((b) => b.type === "text");
|
|
1882
|
+
if (i !== -1) {
|
|
1883
|
+
const b = content[i];
|
|
1884
|
+
if (b.type === "text") {
|
|
1885
|
+
return [
|
|
1886
|
+
...content.slice(0, i),
|
|
1887
|
+
{ ...b, text: prefix + b.text },
|
|
1888
|
+
...content.slice(i + 1)
|
|
1889
|
+
];
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
return [...content, { type: "text", text: prefix.trimEnd() }];
|
|
1893
|
+
}
|
|
1894
|
+
async function resolveAndPrepend(msg, content) {
|
|
1895
|
+
const attachments = extractInboundAttachments(msg);
|
|
1896
|
+
if (attachments.length === 0)
|
|
1897
|
+
return content;
|
|
1898
|
+
const prefix = await resolveInboundAttachments(attachments);
|
|
1899
|
+
return prependPathRefs(content, prefix);
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
// src/cli/print.ts
|
|
1903
|
+
init_permissions();
|
|
1904
|
+
init_json();
|
|
1905
|
+
init_abortController();
|
|
1906
|
+
init_combinedAbortSignal();
|
|
1907
|
+
init_sessionTitle();
|
|
1908
|
+
init_sideQuestion();
|
|
1909
|
+
init_sessionStart();
|
|
1910
|
+
init_outputStyles();
|
|
1911
|
+
init_xml();
|
|
1912
|
+
init_settings();
|
|
1913
|
+
init_changeDetector();
|
|
1914
|
+
init_applySettingsChange();
|
|
1915
|
+
init_fastMode();
|
|
1916
|
+
init_permissionSetup();
|
|
1917
|
+
init_promptSuggestion();
|
|
1918
|
+
init_forkedAgent();
|
|
1919
|
+
init_auth();
|
|
1920
|
+
init_oauth();
|
|
1921
|
+
init_auth2();
|
|
1922
|
+
init_providers();
|
|
1923
|
+
init_awsAuthStatusManager();
|
|
1924
|
+
init_state();
|
|
1925
|
+
init_SyntheticOutputTool();
|
|
1926
|
+
|
|
1927
|
+
// src/utils/sessionUrl.ts
|
|
1928
|
+
init_uuid();
|
|
1929
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
1930
|
+
function parseSessionIdentifier(resumeIdentifier) {
|
|
1931
|
+
if (resumeIdentifier.toLowerCase().endsWith(".jsonl")) {
|
|
1932
|
+
return {
|
|
1933
|
+
sessionId: randomUUID3(),
|
|
1934
|
+
ingressUrl: null,
|
|
1935
|
+
isUrl: false,
|
|
1936
|
+
jsonlFile: resumeIdentifier,
|
|
1937
|
+
isJsonlFile: true
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
if (validateUuid(resumeIdentifier)) {
|
|
1941
|
+
return {
|
|
1942
|
+
sessionId: resumeIdentifier,
|
|
1943
|
+
ingressUrl: null,
|
|
1944
|
+
isUrl: false,
|
|
1945
|
+
jsonlFile: null,
|
|
1946
|
+
isJsonlFile: false
|
|
1947
|
+
};
|
|
1948
|
+
}
|
|
1949
|
+
try {
|
|
1950
|
+
const url = new URL(resumeIdentifier);
|
|
1951
|
+
return {
|
|
1952
|
+
sessionId: randomUUID3(),
|
|
1953
|
+
ingressUrl: url.href,
|
|
1954
|
+
isUrl: true,
|
|
1955
|
+
jsonlFile: null,
|
|
1956
|
+
isJsonlFile: false
|
|
1957
|
+
};
|
|
1958
|
+
} catch {}
|
|
1959
|
+
return null;
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
// src/cli/print.ts
|
|
1963
|
+
init_sessionStorage();
|
|
1964
|
+
init_commitAttribution();
|
|
1965
|
+
init_client();
|
|
1966
|
+
init_config2();
|
|
1967
|
+
init_auth3();
|
|
1968
|
+
init_elicitationHandler();
|
|
1969
|
+
init_hooks();
|
|
1970
|
+
init_types();
|
|
1971
|
+
init_mcpStringUtils();
|
|
1972
|
+
init_utils();
|
|
1973
|
+
init_vscodeSdkMcp();
|
|
1974
|
+
init_config2();
|
|
1975
|
+
init_grove();
|
|
1976
|
+
init_mappers();
|
|
1977
|
+
init_messages();
|
|
1978
|
+
init_context_noninteractive();
|
|
1979
|
+
init_xml();
|
|
1980
|
+
init_claudeAiLimits();
|
|
1981
|
+
init_model();
|
|
1982
|
+
init_modelOptions();
|
|
1983
|
+
init_effort();
|
|
1984
|
+
init_thinking();
|
|
1985
|
+
init_betas();
|
|
1986
|
+
init_modelStrings();
|
|
1987
|
+
init_state();
|
|
1988
|
+
init_workloadContext();
|
|
1989
|
+
init_fileHistory();
|
|
1990
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
1991
|
+
init_sandbox_adapter();
|
|
1992
|
+
init_headlessProfiler();
|
|
1993
|
+
init_queryProfiler();
|
|
1994
|
+
init_ids();
|
|
1995
|
+
init_slowOperations();
|
|
1996
|
+
init_commands();
|
|
1997
|
+
init_envUtils();
|
|
1998
|
+
|
|
1999
|
+
// src/utils/plugins/headlessPluginInstall.ts
|
|
2000
|
+
init_analytics();
|
|
2001
|
+
init_cleanupRegistry();
|
|
2002
|
+
init_debug();
|
|
2003
|
+
init_diagLogs();
|
|
2004
|
+
init_fsOperations();
|
|
2005
|
+
init_log();
|
|
2006
|
+
init_marketplaceManager();
|
|
2007
|
+
init_pluginLoader();
|
|
2008
|
+
init_zipCache();
|
|
2009
|
+
|
|
2010
|
+
// src/utils/plugins/zipCacheAdapters.ts
|
|
2011
|
+
init_debug();
|
|
2012
|
+
init_slowOperations();
|
|
2013
|
+
init_marketplaceManager();
|
|
2014
|
+
init_schemas();
|
|
2015
|
+
init_zipCache();
|
|
2016
|
+
import { readFile } from "fs/promises";
|
|
2017
|
+
import { join as join2 } from "path";
|
|
2018
|
+
async function readZipCacheKnownMarketplaces() {
|
|
2019
|
+
try {
|
|
2020
|
+
const content = await readFile(getZipCacheKnownMarketplacesPath(), "utf-8");
|
|
2021
|
+
const parsed = KnownMarketplacesFileSchema().safeParse(jsonParse(content));
|
|
2022
|
+
if (!parsed.success) {
|
|
2023
|
+
logForDebugging(`Invalid known_marketplaces.json in zip cache: ${parsed.error.message}`, { level: "error" });
|
|
2024
|
+
return {};
|
|
2025
|
+
}
|
|
2026
|
+
return parsed.data;
|
|
2027
|
+
} catch {
|
|
2028
|
+
return {};
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
async function writeZipCacheKnownMarketplaces(data) {
|
|
2032
|
+
await atomicWriteToZipCache(getZipCacheKnownMarketplacesPath(), jsonStringify(data, null, 2));
|
|
2033
|
+
}
|
|
2034
|
+
async function saveMarketplaceJsonToZipCache(marketplaceName, installLocation) {
|
|
2035
|
+
const zipCachePath = getPluginZipCachePath();
|
|
2036
|
+
if (!zipCachePath) {
|
|
2037
|
+
return;
|
|
2038
|
+
}
|
|
2039
|
+
const content = await readMarketplaceJsonContent(installLocation);
|
|
2040
|
+
if (content !== null) {
|
|
2041
|
+
const relPath = getMarketplaceJsonRelativePath(marketplaceName);
|
|
2042
|
+
await atomicWriteToZipCache(join2(zipCachePath, relPath), content);
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
async function readMarketplaceJsonContent(dir) {
|
|
2046
|
+
const candidates = [
|
|
2047
|
+
join2(dir, ".claude-plugin", "marketplace.json"),
|
|
2048
|
+
join2(dir, "marketplace.json"),
|
|
2049
|
+
dir
|
|
2050
|
+
];
|
|
2051
|
+
for (const candidate of candidates) {
|
|
2052
|
+
try {
|
|
2053
|
+
return await readFile(candidate, "utf-8");
|
|
2054
|
+
} catch {}
|
|
2055
|
+
}
|
|
2056
|
+
return null;
|
|
2057
|
+
}
|
|
2058
|
+
async function syncMarketplacesToZipCache() {
|
|
2059
|
+
const knownMarketplaces = await loadKnownMarketplacesConfigSafe();
|
|
2060
|
+
for (const [name, entry] of Object.entries(knownMarketplaces)) {
|
|
2061
|
+
if (!entry.installLocation)
|
|
2062
|
+
continue;
|
|
2063
|
+
try {
|
|
2064
|
+
await saveMarketplaceJsonToZipCache(name, entry.installLocation);
|
|
2065
|
+
} catch (error) {
|
|
2066
|
+
logForDebugging(`Failed to save marketplace JSON for ${name}: ${error}`);
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
const zipCacheKnownMarketplaces = await readZipCacheKnownMarketplaces();
|
|
2070
|
+
const mergedKnownMarketplaces = {
|
|
2071
|
+
...zipCacheKnownMarketplaces,
|
|
2072
|
+
...knownMarketplaces
|
|
2073
|
+
};
|
|
2074
|
+
await writeZipCacheKnownMarketplaces(mergedKnownMarketplaces);
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
// src/utils/plugins/headlessPluginInstall.ts
|
|
2078
|
+
async function installPluginsForHeadless() {
|
|
2079
|
+
const zipCacheMode = isPluginZipCacheEnabled();
|
|
2080
|
+
logForDebugging(`installPluginsForHeadless: starting${zipCacheMode ? " (zip cache mode)" : ""}`);
|
|
2081
|
+
const seedChanged = await registerSeedMarketplaces();
|
|
2082
|
+
if (seedChanged) {
|
|
2083
|
+
clearMarketplacesCache();
|
|
2084
|
+
clearPluginCache("headlessPluginInstall: seed marketplaces registered");
|
|
2085
|
+
}
|
|
2086
|
+
if (zipCacheMode) {
|
|
2087
|
+
await getFsImplementation().mkdir(getZipCacheMarketplacesDir());
|
|
2088
|
+
await getFsImplementation().mkdir(getZipCachePluginsDir());
|
|
2089
|
+
}
|
|
2090
|
+
const declaredCount = Object.keys(getDeclaredMarketplaces()).length;
|
|
2091
|
+
const metrics = {
|
|
2092
|
+
marketplaces_installed: 0,
|
|
2093
|
+
delisted_count: 0
|
|
2094
|
+
};
|
|
2095
|
+
let pluginsChanged = seedChanged;
|
|
2096
|
+
try {
|
|
2097
|
+
if (declaredCount === 0) {
|
|
2098
|
+
logForDebugging("installPluginsForHeadless: no marketplaces declared");
|
|
2099
|
+
} else {
|
|
2100
|
+
const reconcileResult = await withDiagnosticsTiming("headless_marketplace_reconcile", () => reconcileMarketplaces({
|
|
2101
|
+
skip: zipCacheMode ? (_name, source) => !isMarketplaceSourceSupportedByZipCache(source) : undefined,
|
|
2102
|
+
onProgress: (event) => {
|
|
2103
|
+
if (event.type === "installed") {
|
|
2104
|
+
logForDebugging(`installPluginsForHeadless: installed marketplace ${event.name}`);
|
|
2105
|
+
} else if (event.type === "failed") {
|
|
2106
|
+
logForDebugging(`installPluginsForHeadless: failed to install marketplace ${event.name}: ${event.error}`);
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
}), (r) => ({
|
|
2110
|
+
installed_count: r.installed.length,
|
|
2111
|
+
updated_count: r.updated.length,
|
|
2112
|
+
failed_count: r.failed.length,
|
|
2113
|
+
skipped_count: r.skipped.length
|
|
2114
|
+
}));
|
|
2115
|
+
if (reconcileResult.skipped.length > 0) {
|
|
2116
|
+
logForDebugging(`installPluginsForHeadless: skipped ${reconcileResult.skipped.length} marketplace(s) unsupported by zip cache: ${reconcileResult.skipped.join(", ")}`);
|
|
2117
|
+
}
|
|
2118
|
+
const marketplacesChanged = reconcileResult.installed.length + reconcileResult.updated.length;
|
|
2119
|
+
if (marketplacesChanged > 0) {
|
|
2120
|
+
clearMarketplacesCache();
|
|
2121
|
+
clearPluginCache("headlessPluginInstall: marketplaces reconciled");
|
|
2122
|
+
pluginsChanged = true;
|
|
2123
|
+
}
|
|
2124
|
+
metrics.marketplaces_installed = marketplacesChanged;
|
|
2125
|
+
}
|
|
2126
|
+
if (zipCacheMode) {
|
|
2127
|
+
await syncMarketplacesToZipCache();
|
|
2128
|
+
}
|
|
2129
|
+
const newlyDelisted = await detectAndUninstallDelistedPlugins();
|
|
2130
|
+
metrics.delisted_count = newlyDelisted.length;
|
|
2131
|
+
if (newlyDelisted.length > 0) {
|
|
2132
|
+
pluginsChanged = true;
|
|
2133
|
+
}
|
|
2134
|
+
if (pluginsChanged) {
|
|
2135
|
+
clearPluginCache("headlessPluginInstall: plugins changed");
|
|
2136
|
+
}
|
|
2137
|
+
if (zipCacheMode) {
|
|
2138
|
+
registerCleanup(cleanupSessionPluginCache);
|
|
2139
|
+
}
|
|
2140
|
+
return pluginsChanged;
|
|
2141
|
+
} catch (error) {
|
|
2142
|
+
logError(error);
|
|
2143
|
+
return false;
|
|
2144
|
+
} finally {
|
|
2145
|
+
logEvent("tengu_headless_plugin_install", metrics);
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
// src/cli/print.ts
|
|
2150
|
+
init_refresh();
|
|
2151
|
+
init_pluginLoader();
|
|
2152
|
+
init_teammate();
|
|
2153
|
+
init_teammateMailbox();
|
|
2154
|
+
init_teamHelpers();
|
|
2155
|
+
init_tasks();
|
|
2156
|
+
init_framework();
|
|
2157
|
+
init_types2();
|
|
2158
|
+
init_stopTask();
|
|
2159
|
+
init_sdkEventQueue();
|
|
2160
|
+
init_growthbook();
|
|
2161
|
+
init_errors();
|
|
2162
|
+
init_sleep();
|
|
2163
|
+
init_paths();
|
|
2164
|
+
var SHUTDOWN_TEAM_PROMPT = `<system-reminder>
|
|
2165
|
+
You are running in non-interactive mode and cannot return a response to the user until your team is shut down.
|
|
2166
|
+
|
|
2167
|
+
You MUST shut down your team before preparing your final response:
|
|
2168
|
+
1. Use requestShutdown to ask each team member to shut down gracefully
|
|
2169
|
+
2. Wait for shutdown approvals
|
|
2170
|
+
3. Use the cleanup operation to clean up the team
|
|
2171
|
+
4. Only then provide your final response to the user
|
|
2172
|
+
|
|
2173
|
+
The user cannot receive your response until the team is completely shut down.
|
|
2174
|
+
</system-reminder>
|
|
2175
|
+
|
|
2176
|
+
Shut down your team and prepare your final response for the user.`;
|
|
2177
|
+
var MAX_RECEIVED_UUIDS = 1e4;
|
|
2178
|
+
var receivedMessageUuids = new Set;
|
|
2179
|
+
var receivedMessageUuidsOrder = [];
|
|
2180
|
+
function trackReceivedMessageUuid(uuid) {
|
|
2181
|
+
if (receivedMessageUuids.has(uuid)) {
|
|
2182
|
+
return false;
|
|
2183
|
+
}
|
|
2184
|
+
receivedMessageUuids.add(uuid);
|
|
2185
|
+
receivedMessageUuidsOrder.push(uuid);
|
|
2186
|
+
if (receivedMessageUuidsOrder.length > MAX_RECEIVED_UUIDS) {
|
|
2187
|
+
const toEvict = receivedMessageUuidsOrder.splice(0, receivedMessageUuidsOrder.length - MAX_RECEIVED_UUIDS);
|
|
2188
|
+
for (const old of toEvict) {
|
|
2189
|
+
receivedMessageUuids.delete(old);
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
return true;
|
|
2193
|
+
}
|
|
2194
|
+
function toBlocks(v) {
|
|
2195
|
+
return typeof v === "string" ? [{ type: "text", text: v }] : v;
|
|
2196
|
+
}
|
|
2197
|
+
function joinPromptValues(values) {
|
|
2198
|
+
if (values.length === 1)
|
|
2199
|
+
return values[0];
|
|
2200
|
+
if (values.every((v) => typeof v === "string")) {
|
|
2201
|
+
return values.join(`
|
|
2202
|
+
`);
|
|
2203
|
+
}
|
|
2204
|
+
return values.flatMap(toBlocks);
|
|
2205
|
+
}
|
|
2206
|
+
function canBatchWith(head, next) {
|
|
2207
|
+
return next !== undefined && next.mode === "prompt" && next.workload === head.workload && next.isMeta === head.isMeta;
|
|
2208
|
+
}
|
|
2209
|
+
async function runHeadless(inputPrompt, getAppState, setAppState, commands, tools, sdkMcpConfigs, agents, options) {
|
|
2210
|
+
if (process.env.USER_TYPE === "ant" && isEnvTruthy(process.env.CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER)) {
|
|
2211
|
+
process.stderr.write(`
|
|
2212
|
+
Startup time: ${Math.round(process.uptime() * 1000)}ms
|
|
2213
|
+
`);
|
|
2214
|
+
process.exit(0);
|
|
2215
|
+
}
|
|
2216
|
+
if (false) {}
|
|
2217
|
+
settingsChangeDetector.subscribe((source) => {
|
|
2218
|
+
applySettingsChange(source, setAppState);
|
|
2219
|
+
if (isFastModeEnabled()) {
|
|
2220
|
+
setAppState((prev) => {
|
|
2221
|
+
const s = prev.settings;
|
|
2222
|
+
const fastMode = s.fastMode === true && !s.fastModePerSessionOptIn;
|
|
2223
|
+
return { ...prev, fastMode };
|
|
2224
|
+
});
|
|
2225
|
+
}
|
|
2226
|
+
});
|
|
2227
|
+
if (false) {}
|
|
2228
|
+
if (typeof Bun !== "undefined") {
|
|
2229
|
+
const gcTimer = setInterval(Bun.gc, 1000);
|
|
2230
|
+
gcTimer.unref();
|
|
2231
|
+
}
|
|
2232
|
+
headlessProfilerStartTurn();
|
|
2233
|
+
headlessProfilerCheckpoint("runHeadless_entry");
|
|
2234
|
+
if (await isQualifiedForGrove()) {
|
|
2235
|
+
await checkGroveForNonInteractive();
|
|
2236
|
+
}
|
|
2237
|
+
headlessProfilerCheckpoint("after_grove_check");
|
|
2238
|
+
initializeGrowthBook();
|
|
2239
|
+
if (options.resumeSessionAt && !options.resume) {
|
|
2240
|
+
process.stderr.write(`Error: --resume-session-at requires --resume
|
|
2241
|
+
`);
|
|
2242
|
+
gracefulShutdownSync(1);
|
|
2243
|
+
return;
|
|
2244
|
+
}
|
|
2245
|
+
if (options.rewindFiles && !options.resume) {
|
|
2246
|
+
process.stderr.write(`Error: --rewind-files requires --resume
|
|
2247
|
+
`);
|
|
2248
|
+
gracefulShutdownSync(1);
|
|
2249
|
+
return;
|
|
2250
|
+
}
|
|
2251
|
+
if (options.rewindFiles && inputPrompt) {
|
|
2252
|
+
process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt
|
|
2253
|
+
`);
|
|
2254
|
+
gracefulShutdownSync(1);
|
|
2255
|
+
return;
|
|
2256
|
+
}
|
|
2257
|
+
const structuredIO = getStructuredIO(inputPrompt, options);
|
|
2258
|
+
if (options.outputFormat === "stream-json") {
|
|
2259
|
+
installStreamJsonStdoutGuard();
|
|
2260
|
+
}
|
|
2261
|
+
const sandboxUnavailableReason = SandboxManager.getSandboxUnavailableReason();
|
|
2262
|
+
if (sandboxUnavailableReason) {
|
|
2263
|
+
if (SandboxManager.isSandboxRequired()) {
|
|
2264
|
+
process.stderr.write(`
|
|
2265
|
+
Error: sandbox required but unavailable: ${sandboxUnavailableReason}
|
|
2266
|
+
` + ` sandbox.failIfUnavailable is set \u2014 refusing to start without a working sandbox.
|
|
2267
|
+
|
|
2268
|
+
`);
|
|
2269
|
+
gracefulShutdownSync(1);
|
|
2270
|
+
return;
|
|
2271
|
+
}
|
|
2272
|
+
process.stderr.write(`
|
|
2273
|
+
\u26A0 Sandbox disabled: ${sandboxUnavailableReason}
|
|
2274
|
+
` + ` Commands will run WITHOUT sandboxing. Network and filesystem restrictions will NOT be enforced.
|
|
2275
|
+
|
|
2276
|
+
`);
|
|
2277
|
+
} else if (SandboxManager.isSandboxingEnabled()) {
|
|
2278
|
+
try {
|
|
2279
|
+
await SandboxManager.initialize(structuredIO.createSandboxAskCallback());
|
|
2280
|
+
} catch (err) {
|
|
2281
|
+
process.stderr.write(`
|
|
2282
|
+
\u274C Sandbox Error: ${errorMessage(err)}
|
|
2283
|
+
`);
|
|
2284
|
+
gracefulShutdownSync(1, "other");
|
|
2285
|
+
return;
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
if (options.outputFormat === "stream-json" && options.verbose) {
|
|
2289
|
+
registerHookEventHandler((event) => {
|
|
2290
|
+
const message = (() => {
|
|
2291
|
+
switch (event.type) {
|
|
2292
|
+
case "started":
|
|
2293
|
+
return {
|
|
2294
|
+
type: "system",
|
|
2295
|
+
subtype: "hook_started",
|
|
2296
|
+
hook_id: event.hookId,
|
|
2297
|
+
hook_name: event.hookName,
|
|
2298
|
+
hook_event: event.hookEvent,
|
|
2299
|
+
uuid: randomUUID4(),
|
|
2300
|
+
session_id: getSessionId()
|
|
2301
|
+
};
|
|
2302
|
+
case "progress":
|
|
2303
|
+
return {
|
|
2304
|
+
type: "system",
|
|
2305
|
+
subtype: "hook_progress",
|
|
2306
|
+
hook_id: event.hookId,
|
|
2307
|
+
hook_name: event.hookName,
|
|
2308
|
+
hook_event: event.hookEvent,
|
|
2309
|
+
stdout: event.stdout,
|
|
2310
|
+
stderr: event.stderr,
|
|
2311
|
+
output: event.output,
|
|
2312
|
+
uuid: randomUUID4(),
|
|
2313
|
+
session_id: getSessionId()
|
|
2314
|
+
};
|
|
2315
|
+
case "response":
|
|
2316
|
+
return {
|
|
2317
|
+
type: "system",
|
|
2318
|
+
subtype: "hook_response",
|
|
2319
|
+
hook_id: event.hookId,
|
|
2320
|
+
hook_name: event.hookName,
|
|
2321
|
+
hook_event: event.hookEvent,
|
|
2322
|
+
output: event.output,
|
|
2323
|
+
stdout: event.stdout,
|
|
2324
|
+
stderr: event.stderr,
|
|
2325
|
+
exit_code: event.exitCode,
|
|
2326
|
+
outcome: event.outcome,
|
|
2327
|
+
uuid: randomUUID4(),
|
|
2328
|
+
session_id: getSessionId()
|
|
2329
|
+
};
|
|
2330
|
+
}
|
|
2331
|
+
})();
|
|
2332
|
+
structuredIO.write(message);
|
|
2333
|
+
});
|
|
2334
|
+
}
|
|
2335
|
+
if (options.setupTrigger) {
|
|
2336
|
+
await processSetupHooks(options.setupTrigger);
|
|
2337
|
+
}
|
|
2338
|
+
headlessProfilerCheckpoint("before_loadInitialMessages");
|
|
2339
|
+
const appState = getAppState();
|
|
2340
|
+
const {
|
|
2341
|
+
messages: initialMessages,
|
|
2342
|
+
turnInterruptionState,
|
|
2343
|
+
agentSetting: resumedAgentSetting
|
|
2344
|
+
} = await loadInitialMessages(setAppState, {
|
|
2345
|
+
continue: options.continue,
|
|
2346
|
+
teleport: options.teleport,
|
|
2347
|
+
resume: options.resume,
|
|
2348
|
+
resumeSessionAt: options.resumeSessionAt,
|
|
2349
|
+
forkSession: options.forkSession,
|
|
2350
|
+
outputFormat: options.outputFormat,
|
|
2351
|
+
sessionStartHooksPromise: options.sessionStartHooksPromise,
|
|
2352
|
+
restoredWorkerState: structuredIO.restoredWorkerState
|
|
2353
|
+
});
|
|
2354
|
+
const hookInitialUserMessage = takeInitialUserMessage();
|
|
2355
|
+
if (hookInitialUserMessage) {
|
|
2356
|
+
structuredIO.prependUserMessage(hookInitialUserMessage);
|
|
2357
|
+
}
|
|
2358
|
+
if (!options.agent && !getMainThreadAgentType() && resumedAgentSetting) {
|
|
2359
|
+
const { agentDefinition: restoredAgent } = restoreAgentFromSession(resumedAgentSetting, undefined, { activeAgents: agents, allAgents: agents });
|
|
2360
|
+
if (restoredAgent) {
|
|
2361
|
+
setAppState((prev) => ({ ...prev, agent: restoredAgent.agentType }));
|
|
2362
|
+
if (!options.systemPrompt && !isBuiltInAgent(restoredAgent)) {
|
|
2363
|
+
const agentSystemPrompt = restoredAgent.getSystemPrompt();
|
|
2364
|
+
if (agentSystemPrompt) {
|
|
2365
|
+
options.systemPrompt = agentSystemPrompt;
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
saveAgentSetting(restoredAgent.agentType);
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
if (initialMessages.length === 0 && process.exitCode !== undefined) {
|
|
2372
|
+
return;
|
|
2373
|
+
}
|
|
2374
|
+
if (options.rewindFiles) {
|
|
2375
|
+
const targetMessage = initialMessages.find((m) => m.uuid === options.rewindFiles);
|
|
2376
|
+
if (!targetMessage || targetMessage.type !== "user") {
|
|
2377
|
+
process.stderr.write(`Error: --rewind-files requires a user message UUID, but ${options.rewindFiles} is not a user message in this session
|
|
2378
|
+
`);
|
|
2379
|
+
gracefulShutdownSync(1);
|
|
2380
|
+
return;
|
|
2381
|
+
}
|
|
2382
|
+
const currentAppState = getAppState();
|
|
2383
|
+
const result = await handleRewindFiles(options.rewindFiles, currentAppState, setAppState, false);
|
|
2384
|
+
if (!result.canRewind) {
|
|
2385
|
+
process.stderr.write(`Error: ${result.error || "Unexpected error"}
|
|
2386
|
+
`);
|
|
2387
|
+
gracefulShutdownSync(1);
|
|
2388
|
+
return;
|
|
2389
|
+
}
|
|
2390
|
+
process.stdout.write(`Files rewound to state at message ${options.rewindFiles}
|
|
2391
|
+
`);
|
|
2392
|
+
gracefulShutdownSync(0);
|
|
2393
|
+
return;
|
|
2394
|
+
}
|
|
2395
|
+
const hasValidResumeSessionId = typeof options.resume === "string" && (Boolean(validateUuid(options.resume)) || options.resume.endsWith(".jsonl"));
|
|
2396
|
+
const isUsingSdkUrl = Boolean(options.sdkUrl);
|
|
2397
|
+
if (!inputPrompt && !hasValidResumeSessionId && !isUsingSdkUrl) {
|
|
2398
|
+
process.stderr.write(`Error: Input must be provided either through stdin or as a prompt argument when using --print
|
|
2399
|
+
`);
|
|
2400
|
+
gracefulShutdownSync(1);
|
|
2401
|
+
return;
|
|
2402
|
+
}
|
|
2403
|
+
if (options.outputFormat === "stream-json" && !options.verbose) {
|
|
2404
|
+
process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
|
|
2405
|
+
`);
|
|
2406
|
+
gracefulShutdownSync(1);
|
|
2407
|
+
return;
|
|
2408
|
+
}
|
|
2409
|
+
const allowedMcpTools = filterToolsByDenyRules(appState.mcp.tools, appState.toolPermissionContext);
|
|
2410
|
+
let filteredTools = [...tools, ...allowedMcpTools];
|
|
2411
|
+
const effectivePermissionPromptToolName = options.sdkUrl ? "stdio" : options.permissionPromptToolName;
|
|
2412
|
+
const onPermissionPrompt = (details) => {
|
|
2413
|
+
if (false) {}
|
|
2414
|
+
notifySessionStateChanged("requires_action", details);
|
|
2415
|
+
};
|
|
2416
|
+
const canUseTool = getCanUseToolFn(effectivePermissionPromptToolName, structuredIO, () => getAppState().mcp.tools, onPermissionPrompt);
|
|
2417
|
+
if (options.permissionPromptToolName) {
|
|
2418
|
+
filteredTools = filteredTools.filter((tool) => !toolMatchesName(tool, options.permissionPromptToolName));
|
|
2419
|
+
}
|
|
2420
|
+
registerProcessOutputErrorHandlers();
|
|
2421
|
+
headlessProfilerCheckpoint("after_loadInitialMessages");
|
|
2422
|
+
await ensureModelStringsInitialized();
|
|
2423
|
+
headlessProfilerCheckpoint("after_modelStrings");
|
|
2424
|
+
const needsFullArray = options.outputFormat === "json" && options.verbose;
|
|
2425
|
+
const messages = [];
|
|
2426
|
+
let lastMessage;
|
|
2427
|
+
const transformToStreamlined = null;
|
|
2428
|
+
headlessProfilerCheckpoint("before_runHeadlessStreaming");
|
|
2429
|
+
for await (const message of runHeadlessStreaming(structuredIO, appState.mcp.clients, [...commands, ...appState.mcp.commands], filteredTools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents, options, turnInterruptionState)) {
|
|
2430
|
+
if (transformToStreamlined) {
|
|
2431
|
+
const transformed = transformToStreamlined(message);
|
|
2432
|
+
if (transformed) {
|
|
2433
|
+
await structuredIO.write(transformed);
|
|
2434
|
+
}
|
|
2435
|
+
} else if (options.outputFormat === "stream-json" && options.verbose) {
|
|
2436
|
+
await structuredIO.write(message);
|
|
2437
|
+
}
|
|
2438
|
+
if (message.type !== "control_response" && message.type !== "control_request" && message.type !== "control_cancel_request" && !(message.type === "system" && (message.subtype === "session_state_changed" || message.subtype === "task_notification" || message.subtype === "task_started" || message.subtype === "task_progress" || message.subtype === "post_turn_summary")) && message.type !== "stream_event" && message.type !== "keep_alive" && message.type !== "streamlined_text" && message.type !== "streamlined_tool_use_summary" && message.type !== "prompt_suggestion") {
|
|
2439
|
+
if (needsFullArray) {
|
|
2440
|
+
messages.push(message);
|
|
2441
|
+
}
|
|
2442
|
+
lastMessage = message;
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
switch (options.outputFormat) {
|
|
2446
|
+
case "json":
|
|
2447
|
+
if (!lastMessage || lastMessage.type !== "result") {
|
|
2448
|
+
throw new Error("No messages returned");
|
|
2449
|
+
}
|
|
2450
|
+
if (options.verbose) {
|
|
2451
|
+
writeToStdout(jsonStringify(messages) + `
|
|
2452
|
+
`);
|
|
2453
|
+
break;
|
|
2454
|
+
}
|
|
2455
|
+
writeToStdout(jsonStringify(lastMessage) + `
|
|
2456
|
+
`);
|
|
2457
|
+
break;
|
|
2458
|
+
case "stream-json":
|
|
2459
|
+
break;
|
|
2460
|
+
default:
|
|
2461
|
+
if (!lastMessage || lastMessage.type !== "result") {
|
|
2462
|
+
throw new Error("No messages returned");
|
|
2463
|
+
}
|
|
2464
|
+
switch (lastMessage.subtype) {
|
|
2465
|
+
case "success":
|
|
2466
|
+
writeToStdout(lastMessage.result.endsWith(`
|
|
2467
|
+
`) ? lastMessage.result : lastMessage.result + `
|
|
2468
|
+
`);
|
|
2469
|
+
break;
|
|
2470
|
+
case "error_during_execution":
|
|
2471
|
+
writeToStdout(`Execution error`);
|
|
2472
|
+
break;
|
|
2473
|
+
case "error_max_turns":
|
|
2474
|
+
writeToStdout(`Error: Reached max turns (${options.maxTurns})`);
|
|
2475
|
+
break;
|
|
2476
|
+
case "error_max_budget_usd":
|
|
2477
|
+
writeToStdout(`Error: Exceeded USD budget (${options.maxBudgetUsd})`);
|
|
2478
|
+
break;
|
|
2479
|
+
case "error_max_structured_output_retries":
|
|
2480
|
+
writeToStdout(`Error: Failed to provide valid structured output after maximum retries`);
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
logHeadlessProfilerTurn();
|
|
2484
|
+
if (false) {}
|
|
2485
|
+
gracefulShutdownSync(lastMessage?.type === "result" && lastMessage?.is_error ? 1 : 0);
|
|
2486
|
+
}
|
|
2487
|
+
function runHeadlessStreaming(structuredIO, mcpClients, commands, tools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents, options, turnInterruptionState) {
|
|
2488
|
+
let running = false;
|
|
2489
|
+
let runPhase;
|
|
2490
|
+
let inputClosed = false;
|
|
2491
|
+
let shutdownPromptInjected = false;
|
|
2492
|
+
let heldBackResult = null;
|
|
2493
|
+
let abortController;
|
|
2494
|
+
const output = structuredIO.outbound;
|
|
2495
|
+
const sigintHandler = () => {
|
|
2496
|
+
logForDiagnosticsNoPII("info", "shutdown_signal", { signal: "SIGINT" });
|
|
2497
|
+
if (abortController && !abortController.signal.aborted) {
|
|
2498
|
+
abortController.abort();
|
|
2499
|
+
}
|
|
2500
|
+
gracefulShutdown(0);
|
|
2501
|
+
};
|
|
2502
|
+
process.on("SIGINT", sigintHandler);
|
|
2503
|
+
registerCleanup(async () => {
|
|
2504
|
+
const bg = {};
|
|
2505
|
+
for (const t of getRunningTasks(getAppState())) {
|
|
2506
|
+
if (isBackgroundTask(t))
|
|
2507
|
+
bg[t.type] = (bg[t.type] ?? 0) + 1;
|
|
2508
|
+
}
|
|
2509
|
+
logForDiagnosticsNoPII("info", "run_state_at_shutdown", {
|
|
2510
|
+
run_active: running,
|
|
2511
|
+
run_phase: runPhase,
|
|
2512
|
+
worker_status: getSessionState(),
|
|
2513
|
+
internal_events_pending: structuredIO.internalEventsPending,
|
|
2514
|
+
bg_tasks: bg
|
|
2515
|
+
});
|
|
2516
|
+
});
|
|
2517
|
+
setPermissionModeChangedListener((newMode) => {
|
|
2518
|
+
if (newMode === "default" || newMode === "acceptEdits" || newMode === "bypassPermissions" || newMode === "plan" || newMode === false || newMode === "dontAsk") {
|
|
2519
|
+
output.enqueue({
|
|
2520
|
+
type: "system",
|
|
2521
|
+
subtype: "status",
|
|
2522
|
+
status: null,
|
|
2523
|
+
permissionMode: newMode,
|
|
2524
|
+
uuid: randomUUID4(),
|
|
2525
|
+
session_id: getSessionId()
|
|
2526
|
+
});
|
|
2527
|
+
}
|
|
2528
|
+
});
|
|
2529
|
+
const suggestionState = {
|
|
2530
|
+
abortController: null,
|
|
2531
|
+
inflightPromise: null,
|
|
2532
|
+
lastEmitted: null,
|
|
2533
|
+
pendingSuggestion: null,
|
|
2534
|
+
pendingLastEmittedEntry: null
|
|
2535
|
+
};
|
|
2536
|
+
let unsubscribeAuthStatus;
|
|
2537
|
+
if (options.enableAuthStatus) {
|
|
2538
|
+
const authStatusManager = AwsAuthStatusManager.getInstance();
|
|
2539
|
+
unsubscribeAuthStatus = authStatusManager.subscribe((status) => {
|
|
2540
|
+
output.enqueue({
|
|
2541
|
+
type: "auth_status",
|
|
2542
|
+
isAuthenticating: status.isAuthenticating,
|
|
2543
|
+
output: status.output,
|
|
2544
|
+
error: status.error,
|
|
2545
|
+
uuid: randomUUID4(),
|
|
2546
|
+
session_id: getSessionId()
|
|
2547
|
+
});
|
|
2548
|
+
});
|
|
2549
|
+
}
|
|
2550
|
+
const rateLimitListener = (limits) => {
|
|
2551
|
+
const rateLimitInfo = toSDKRateLimitInfo(limits);
|
|
2552
|
+
if (rateLimitInfo) {
|
|
2553
|
+
output.enqueue({
|
|
2554
|
+
type: "rate_limit_event",
|
|
2555
|
+
rate_limit_info: rateLimitInfo,
|
|
2556
|
+
uuid: randomUUID4(),
|
|
2557
|
+
session_id: getSessionId()
|
|
2558
|
+
});
|
|
2559
|
+
}
|
|
2560
|
+
};
|
|
2561
|
+
statusListeners.add(rateLimitListener);
|
|
2562
|
+
const mutableMessages = initialMessages;
|
|
2563
|
+
let readFileState = extractReadFilesFromMessages(initialMessages, cwd(), READ_FILE_STATE_CACHE_SIZE);
|
|
2564
|
+
const pendingSeeds = createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE);
|
|
2565
|
+
const resumeInterruptedTurnEnv = process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;
|
|
2566
|
+
if (turnInterruptionState && turnInterruptionState.kind !== "none" && resumeInterruptedTurnEnv) {
|
|
2567
|
+
logForDebugging(`[print.ts] Auto-resuming interrupted turn (kind: ${turnInterruptionState.kind})`);
|
|
2568
|
+
removeInterruptedMessage(mutableMessages, turnInterruptionState.message);
|
|
2569
|
+
enqueue({
|
|
2570
|
+
mode: "prompt",
|
|
2571
|
+
value: turnInterruptionState.message.message.content,
|
|
2572
|
+
uuid: randomUUID4()
|
|
2573
|
+
});
|
|
2574
|
+
}
|
|
2575
|
+
const modelOptions = getModelOptions();
|
|
2576
|
+
const modelInfos = modelOptions.map((option) => {
|
|
2577
|
+
const modelId = option.value === null ? "default" : option.value;
|
|
2578
|
+
const resolvedModel = modelId === "default" ? getDefaultMainLoopModel() : parseUserSpecifiedModel(modelId);
|
|
2579
|
+
const hasEffort = modelSupportsEffort(resolvedModel);
|
|
2580
|
+
const hasAdaptiveThinking = modelSupportsAdaptiveThinking(resolvedModel);
|
|
2581
|
+
const hasFastMode = isFastModeSupportedByModel(option.value);
|
|
2582
|
+
const hasAutoMode = modelSupportsAutoMode(resolvedModel);
|
|
2583
|
+
return {
|
|
2584
|
+
name: modelId,
|
|
2585
|
+
value: modelId,
|
|
2586
|
+
displayName: option.label,
|
|
2587
|
+
description: option.description,
|
|
2588
|
+
...hasEffort && {
|
|
2589
|
+
supportsEffort: true,
|
|
2590
|
+
supportedEffortLevels: modelSupportsMaxEffort(resolvedModel) ? [...EFFORT_LEVELS] : EFFORT_LEVELS.filter((l) => l !== "max")
|
|
2591
|
+
},
|
|
2592
|
+
...hasAdaptiveThinking && { supportsAdaptiveThinking: true },
|
|
2593
|
+
...hasFastMode && { supportsFastMode: true },
|
|
2594
|
+
...hasAutoMode && { supportsAutoMode: true }
|
|
2595
|
+
};
|
|
2596
|
+
});
|
|
2597
|
+
let activeUserSpecifiedModel = options.userSpecifiedModel;
|
|
2598
|
+
function injectModelSwitchBreadcrumbs(modelArg, resolvedModel) {
|
|
2599
|
+
const breadcrumbs = createModelSwitchBreadcrumbs(modelArg, modelDisplayString(resolvedModel));
|
|
2600
|
+
mutableMessages.push(...breadcrumbs);
|
|
2601
|
+
for (const crumb of breadcrumbs) {
|
|
2602
|
+
if (typeof crumb.message.content === "string" && crumb.message.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`)) {
|
|
2603
|
+
output.enqueue({
|
|
2604
|
+
type: "user",
|
|
2605
|
+
content: crumb.message.content,
|
|
2606
|
+
message: crumb.message,
|
|
2607
|
+
session_id: getSessionId(),
|
|
2608
|
+
parent_tool_use_id: null,
|
|
2609
|
+
uuid: crumb.uuid,
|
|
2610
|
+
timestamp: crumb.timestamp,
|
|
2611
|
+
isReplay: true
|
|
2612
|
+
});
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
}
|
|
2616
|
+
let sdkClients = [];
|
|
2617
|
+
let sdkTools = [];
|
|
2618
|
+
const elicitationRegistered = new Set;
|
|
2619
|
+
function registerElicitationHandlers(clients) {
|
|
2620
|
+
for (const connection of clients) {
|
|
2621
|
+
if (connection.type !== "connected" || elicitationRegistered.has(connection.name)) {
|
|
2622
|
+
continue;
|
|
2623
|
+
}
|
|
2624
|
+
if (connection.config.type === "sdk") {
|
|
2625
|
+
continue;
|
|
2626
|
+
}
|
|
2627
|
+
const serverName = connection.name;
|
|
2628
|
+
try {
|
|
2629
|
+
connection.client.setRequestHandler(ElicitRequestSchema, async (request, extra) => {
|
|
2630
|
+
logMCPDebug(serverName, `Elicitation request received in print mode: ${jsonStringify(request)}`);
|
|
2631
|
+
const mode = request.params.mode === "url" ? "url" : "form";
|
|
2632
|
+
logEvent("tengu_mcp_elicitation_shown", {
|
|
2633
|
+
mode
|
|
2634
|
+
});
|
|
2635
|
+
const hookResponse = await runElicitationHooks(serverName, request.params, extra.signal);
|
|
2636
|
+
if (hookResponse) {
|
|
2637
|
+
logMCPDebug(serverName, `Elicitation resolved by hook: ${jsonStringify(hookResponse)}`);
|
|
2638
|
+
logEvent("tengu_mcp_elicitation_response", {
|
|
2639
|
+
mode,
|
|
2640
|
+
action: hookResponse.action
|
|
2641
|
+
});
|
|
2642
|
+
return hookResponse;
|
|
2643
|
+
}
|
|
2644
|
+
const url = "url" in request.params ? request.params.url : undefined;
|
|
2645
|
+
const requestedSchema = "requestedSchema" in request.params ? request.params.requestedSchema : undefined;
|
|
2646
|
+
const elicitationId = "elicitationId" in request.params ? request.params.elicitationId : undefined;
|
|
2647
|
+
const rawResult = await structuredIO.handleElicitation(serverName, request.params.message, requestedSchema, extra.signal, mode, url, elicitationId);
|
|
2648
|
+
const result = await runElicitationResultHooks(serverName, rawResult, extra.signal, mode, elicitationId);
|
|
2649
|
+
logEvent("tengu_mcp_elicitation_response", {
|
|
2650
|
+
mode,
|
|
2651
|
+
action: result.action
|
|
2652
|
+
});
|
|
2653
|
+
return result;
|
|
2654
|
+
});
|
|
2655
|
+
connection.client.setNotificationHandler(ElicitationCompleteNotificationSchema, (notification) => {
|
|
2656
|
+
const { elicitationId } = notification.params;
|
|
2657
|
+
logMCPDebug(serverName, `Elicitation completion notification: ${elicitationId}`);
|
|
2658
|
+
executeNotificationHooks({
|
|
2659
|
+
message: `MCP server "${serverName}" confirmed elicitation ${elicitationId} complete`,
|
|
2660
|
+
notificationType: "elicitation_complete"
|
|
2661
|
+
});
|
|
2662
|
+
output.enqueue({
|
|
2663
|
+
type: "system",
|
|
2664
|
+
subtype: "elicitation_complete",
|
|
2665
|
+
mcp_server_name: serverName,
|
|
2666
|
+
elicitation_id: elicitationId,
|
|
2667
|
+
uuid: randomUUID4(),
|
|
2668
|
+
session_id: getSessionId()
|
|
2669
|
+
});
|
|
2670
|
+
});
|
|
2671
|
+
elicitationRegistered.add(serverName);
|
|
2672
|
+
} catch {}
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
async function updateSdkMcp() {
|
|
2676
|
+
const currentServerNames = new Set(Object.keys(sdkMcpConfigs));
|
|
2677
|
+
const connectedServerNames = new Set(sdkClients.map((c) => c.name));
|
|
2678
|
+
const hasNewServers = Array.from(currentServerNames).some((name) => !connectedServerNames.has(name));
|
|
2679
|
+
const hasRemovedServers = Array.from(connectedServerNames).some((name) => !currentServerNames.has(name));
|
|
2680
|
+
const hasPendingSdkClients = sdkClients.some((c) => c.type === "pending");
|
|
2681
|
+
const hasFailedSdkClients = sdkClients.some((c) => c.type === "failed");
|
|
2682
|
+
const haveServersChanged = hasNewServers || hasRemovedServers || hasPendingSdkClients || hasFailedSdkClients;
|
|
2683
|
+
if (haveServersChanged) {
|
|
2684
|
+
for (const client of sdkClients) {
|
|
2685
|
+
if (!currentServerNames.has(client.name)) {
|
|
2686
|
+
if (client.type === "connected") {
|
|
2687
|
+
await client.cleanup();
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
const sdkSetup = await setupSdkMcpClients(sdkMcpConfigs, (serverName, message) => structuredIO.sendMcpMessage(serverName, message));
|
|
2692
|
+
sdkClients = sdkSetup.clients;
|
|
2693
|
+
sdkTools = sdkSetup.tools;
|
|
2694
|
+
const allSdkNames = uniq([...connectedServerNames, ...currentServerNames]);
|
|
2695
|
+
setAppState((prev) => ({
|
|
2696
|
+
...prev,
|
|
2697
|
+
mcp: {
|
|
2698
|
+
...prev.mcp,
|
|
2699
|
+
tools: [
|
|
2700
|
+
...prev.mcp.tools.filter((t) => !allSdkNames.some((name) => t.name.startsWith(getMcpPrefix(name)))),
|
|
2701
|
+
...sdkTools
|
|
2702
|
+
]
|
|
2703
|
+
}
|
|
2704
|
+
}));
|
|
2705
|
+
setupVscodeSdkMcp(sdkClients);
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
updateSdkMcp();
|
|
2709
|
+
let dynamicMcpState = {
|
|
2710
|
+
clients: [],
|
|
2711
|
+
tools: [],
|
|
2712
|
+
configs: {}
|
|
2713
|
+
};
|
|
2714
|
+
const buildAllTools = (appState) => {
|
|
2715
|
+
const assembledTools = assembleToolPool(appState.toolPermissionContext, appState.mcp.tools);
|
|
2716
|
+
let allTools = uniqBy_default(mergeAndFilterTools([...tools, ...sdkTools, ...dynamicMcpState.tools], assembledTools, appState.toolPermissionContext.mode), "name");
|
|
2717
|
+
if (options.permissionPromptToolName) {
|
|
2718
|
+
allTools = allTools.filter((tool) => !toolMatchesName(tool, options.permissionPromptToolName));
|
|
2719
|
+
}
|
|
2720
|
+
const initJsonSchema = getInitJsonSchema();
|
|
2721
|
+
if (initJsonSchema && !options.jsonSchema) {
|
|
2722
|
+
const syntheticOutputResult = createSyntheticOutputTool(initJsonSchema);
|
|
2723
|
+
if ("tool" in syntheticOutputResult) {
|
|
2724
|
+
allTools = [...allTools, syntheticOutputResult.tool];
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
return allTools;
|
|
2728
|
+
};
|
|
2729
|
+
let bridgeHandle = null;
|
|
2730
|
+
let bridgeLastForwardedIndex = 0;
|
|
2731
|
+
function forwardMessagesToBridge() {
|
|
2732
|
+
if (!bridgeHandle)
|
|
2733
|
+
return;
|
|
2734
|
+
const startIndex = Math.min(bridgeLastForwardedIndex, mutableMessages.length);
|
|
2735
|
+
const newMessages = mutableMessages.slice(startIndex).filter((m) => m.type === "user" || m.type === "assistant");
|
|
2736
|
+
bridgeLastForwardedIndex = mutableMessages.length;
|
|
2737
|
+
if (newMessages.length > 0) {
|
|
2738
|
+
bridgeHandle.writeMessages(newMessages);
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
let mcpChangesPromise = Promise.resolve({
|
|
2742
|
+
response: {
|
|
2743
|
+
added: [],
|
|
2744
|
+
removed: [],
|
|
2745
|
+
errors: {}
|
|
2746
|
+
},
|
|
2747
|
+
sdkServersChanged: false
|
|
2748
|
+
});
|
|
2749
|
+
function applyMcpServerChanges(servers) {
|
|
2750
|
+
const doWork = async () => {
|
|
2751
|
+
const oldSdkClientNames = new Set(sdkClients.map((c) => c.name));
|
|
2752
|
+
const result = await handleMcpSetServers(servers, { configs: sdkMcpConfigs, clients: sdkClients, tools: sdkTools }, dynamicMcpState, setAppState);
|
|
2753
|
+
for (const key of Object.keys(sdkMcpConfigs)) {
|
|
2754
|
+
delete sdkMcpConfigs[key];
|
|
2755
|
+
}
|
|
2756
|
+
Object.assign(sdkMcpConfigs, result.newSdkState.configs);
|
|
2757
|
+
sdkClients = result.newSdkState.clients;
|
|
2758
|
+
sdkTools = result.newSdkState.tools;
|
|
2759
|
+
dynamicMcpState = result.newDynamicState;
|
|
2760
|
+
if (result.sdkServersChanged) {
|
|
2761
|
+
const newSdkClientNames = new Set(sdkClients.map((c) => c.name));
|
|
2762
|
+
const allSdkNames = uniq([...oldSdkClientNames, ...newSdkClientNames]);
|
|
2763
|
+
setAppState((prev) => ({
|
|
2764
|
+
...prev,
|
|
2765
|
+
mcp: {
|
|
2766
|
+
...prev.mcp,
|
|
2767
|
+
tools: [
|
|
2768
|
+
...prev.mcp.tools.filter((t) => !allSdkNames.some((name) => t.name.startsWith(getMcpPrefix(name)))),
|
|
2769
|
+
...sdkTools
|
|
2770
|
+
]
|
|
2771
|
+
}
|
|
2772
|
+
}));
|
|
2773
|
+
}
|
|
2774
|
+
return {
|
|
2775
|
+
response: result.response,
|
|
2776
|
+
sdkServersChanged: result.sdkServersChanged
|
|
2777
|
+
};
|
|
2778
|
+
};
|
|
2779
|
+
mcpChangesPromise = mcpChangesPromise.then(doWork, doWork);
|
|
2780
|
+
return mcpChangesPromise;
|
|
2781
|
+
}
|
|
2782
|
+
function buildMcpServerStatuses() {
|
|
2783
|
+
const currentAppState = getAppState();
|
|
2784
|
+
const currentMcpClients = currentAppState.mcp.clients;
|
|
2785
|
+
const allMcpTools = uniqBy_default([...currentAppState.mcp.tools, ...dynamicMcpState.tools], "name");
|
|
2786
|
+
const existingNames = new Set([
|
|
2787
|
+
...currentMcpClients.map((c) => c.name),
|
|
2788
|
+
...sdkClients.map((c) => c.name)
|
|
2789
|
+
]);
|
|
2790
|
+
return [
|
|
2791
|
+
...currentMcpClients,
|
|
2792
|
+
...sdkClients,
|
|
2793
|
+
...dynamicMcpState.clients.filter((c) => !existingNames.has(c.name))
|
|
2794
|
+
].map((connection) => {
|
|
2795
|
+
let config;
|
|
2796
|
+
if (connection.config.type === "sse" || connection.config.type === "http") {
|
|
2797
|
+
config = {
|
|
2798
|
+
type: connection.config.type,
|
|
2799
|
+
url: connection.config.url,
|
|
2800
|
+
headers: connection.config.headers,
|
|
2801
|
+
oauth: connection.config.oauth
|
|
2802
|
+
};
|
|
2803
|
+
} else if (connection.config.type === "claudeai-proxy") {
|
|
2804
|
+
config = {
|
|
2805
|
+
type: "claudeai-proxy",
|
|
2806
|
+
url: connection.config.url,
|
|
2807
|
+
id: connection.config.id
|
|
2808
|
+
};
|
|
2809
|
+
} else if (connection.config.type === "stdio" || connection.config.type === undefined) {
|
|
2810
|
+
const stdioConfig = connection.config;
|
|
2811
|
+
config = {
|
|
2812
|
+
type: "stdio",
|
|
2813
|
+
command: stdioConfig.command,
|
|
2814
|
+
args: stdioConfig.args
|
|
2815
|
+
};
|
|
2816
|
+
}
|
|
2817
|
+
const serverTools = connection.type === "connected" ? filterToolsByServer(allMcpTools, connection.name).map((tool) => ({
|
|
2818
|
+
name: tool.mcpInfo?.toolName ?? tool.name,
|
|
2819
|
+
annotations: {
|
|
2820
|
+
readOnly: tool.isReadOnly({}) || undefined,
|
|
2821
|
+
destructive: tool.isDestructive?.({}) || undefined,
|
|
2822
|
+
openWorld: tool.isOpenWorld?.({}) || undefined
|
|
2823
|
+
}
|
|
2824
|
+
})) : undefined;
|
|
2825
|
+
let capabilities;
|
|
2826
|
+
if (false) {}
|
|
2827
|
+
return {
|
|
2828
|
+
name: connection.name,
|
|
2829
|
+
status: connection.type,
|
|
2830
|
+
serverInfo: connection.type === "connected" ? connection.serverInfo : undefined,
|
|
2831
|
+
error: connection.type === "failed" ? connection.error : undefined,
|
|
2832
|
+
config,
|
|
2833
|
+
scope: connection.config.scope,
|
|
2834
|
+
tools: serverTools,
|
|
2835
|
+
capabilities
|
|
2836
|
+
};
|
|
2837
|
+
});
|
|
2838
|
+
}
|
|
2839
|
+
async function installPluginsAndApplyMcpInBackground() {
|
|
2840
|
+
try {
|
|
2841
|
+
await Promise.all([
|
|
2842
|
+
Promise.resolve(),
|
|
2843
|
+
withDiagnosticsTiming("headless_managed_settings_wait", () => waitForRemoteManagedSettingsToLoad())
|
|
2844
|
+
]);
|
|
2845
|
+
const pluginsInstalled = await installPluginsForHeadless();
|
|
2846
|
+
if (pluginsInstalled) {
|
|
2847
|
+
await applyPluginMcpDiff();
|
|
2848
|
+
}
|
|
2849
|
+
} catch (error) {
|
|
2850
|
+
logError(error);
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
let pluginInstallPromise = null;
|
|
2854
|
+
if (!isBareMode()) {
|
|
2855
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)) {
|
|
2856
|
+
pluginInstallPromise = installPluginsAndApplyMcpInBackground();
|
|
2857
|
+
} else {
|
|
2858
|
+
installPluginsAndApplyMcpInBackground();
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
const idleTimeout = createIdleTimeoutManager(() => !running);
|
|
2862
|
+
let currentCommands = commands;
|
|
2863
|
+
let currentAgents = agents;
|
|
2864
|
+
async function refreshPluginState() {
|
|
2865
|
+
const { agentDefinitions: freshAgentDefs } = await refreshActivePlugins(setAppState);
|
|
2866
|
+
currentCommands = await getCommands(cwd());
|
|
2867
|
+
const sdkAgents = currentAgents.filter((a) => a.source === "flagSettings");
|
|
2868
|
+
currentAgents = [...freshAgentDefs.allAgents, ...sdkAgents];
|
|
2869
|
+
}
|
|
2870
|
+
async function applyPluginMcpDiff() {
|
|
2871
|
+
const { servers: newConfigs } = await getAllMcpConfigs();
|
|
2872
|
+
const supportedConfigs = {};
|
|
2873
|
+
for (const [name, config] of Object.entries(newConfigs)) {
|
|
2874
|
+
const type = config.type;
|
|
2875
|
+
if (type === undefined || type === "stdio" || type === "sse" || type === "http" || type === "sdk") {
|
|
2876
|
+
supportedConfigs[name] = config;
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
for (const [name, config] of Object.entries(sdkMcpConfigs)) {
|
|
2880
|
+
if (config.type === "sdk" && !(name in supportedConfigs)) {
|
|
2881
|
+
supportedConfigs[name] = config;
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
const { response, sdkServersChanged } = await applyMcpServerChanges(supportedConfigs);
|
|
2885
|
+
if (sdkServersChanged) {
|
|
2886
|
+
updateSdkMcp();
|
|
2887
|
+
}
|
|
2888
|
+
logForDebugging(`Headless MCP refresh: added=${response.added.length}, removed=${response.removed.length}`);
|
|
2889
|
+
}
|
|
2890
|
+
const unsubscribeSkillChanges = skillChangeDetector.subscribe(() => {
|
|
2891
|
+
clearCommandsCache();
|
|
2892
|
+
getCommands(cwd()).then((newCommands) => {
|
|
2893
|
+
currentCommands = newCommands;
|
|
2894
|
+
});
|
|
2895
|
+
});
|
|
2896
|
+
const scheduleProactiveTick = undefined;
|
|
2897
|
+
subscribeToCommandQueue(() => {
|
|
2898
|
+
if (abortController && getCommandsByMaxPriority("now").length > 0) {
|
|
2899
|
+
abortController.abort("interrupt");
|
|
2900
|
+
}
|
|
2901
|
+
});
|
|
2902
|
+
const run = async () => {
|
|
2903
|
+
if (running) {
|
|
2904
|
+
return;
|
|
2905
|
+
}
|
|
2906
|
+
running = true;
|
|
2907
|
+
runPhase = undefined;
|
|
2908
|
+
notifySessionStateChanged("running");
|
|
2909
|
+
idleTimeout.stop();
|
|
2910
|
+
headlessProfilerCheckpoint("run_entry");
|
|
2911
|
+
await updateSdkMcp();
|
|
2912
|
+
headlessProfilerCheckpoint("after_updateSdkMcp");
|
|
2913
|
+
if (pluginInstallPromise) {
|
|
2914
|
+
const timeoutMs = parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS || "", 10);
|
|
2915
|
+
if (timeoutMs > 0) {
|
|
2916
|
+
const timeout = sleep(timeoutMs).then(() => "timeout");
|
|
2917
|
+
const result = await Promise.race([pluginInstallPromise, timeout]);
|
|
2918
|
+
if (result === "timeout") {
|
|
2919
|
+
logError(new Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${timeoutMs}ms`));
|
|
2920
|
+
logEvent("tengu_sync_plugin_install_timeout", {
|
|
2921
|
+
timeout_ms: timeoutMs
|
|
2922
|
+
});
|
|
2923
|
+
}
|
|
2924
|
+
} else {
|
|
2925
|
+
await pluginInstallPromise;
|
|
2926
|
+
}
|
|
2927
|
+
pluginInstallPromise = null;
|
|
2928
|
+
await refreshPluginState();
|
|
2929
|
+
const { setupPluginHookHotReload } = await import("./chunk-0scs4rpx.js");
|
|
2930
|
+
setupPluginHookHotReload();
|
|
2931
|
+
}
|
|
2932
|
+
const isMainThread = (cmd) => cmd.agentId === undefined;
|
|
2933
|
+
try {
|
|
2934
|
+
let command;
|
|
2935
|
+
let waitingForAgents = false;
|
|
2936
|
+
const drainCommandQueue = async () => {
|
|
2937
|
+
while (command = dequeue(isMainThread)) {
|
|
2938
|
+
if (command.mode !== "prompt" && command.mode !== "orphaned-permission" && command.mode !== "task-notification") {
|
|
2939
|
+
throw new Error("only prompt commands are supported in streaming mode");
|
|
2940
|
+
}
|
|
2941
|
+
const batch = [command];
|
|
2942
|
+
if (command.mode === "prompt") {
|
|
2943
|
+
while (canBatchWith(command, peek(isMainThread))) {
|
|
2944
|
+
batch.push(dequeue(isMainThread));
|
|
2945
|
+
}
|
|
2946
|
+
if (batch.length > 1) {
|
|
2947
|
+
command = {
|
|
2948
|
+
...command,
|
|
2949
|
+
value: joinPromptValues(batch.map((c) => c.value)),
|
|
2950
|
+
uuid: batch.findLast((c) => c.uuid)?.uuid ?? command.uuid
|
|
2951
|
+
};
|
|
2952
|
+
}
|
|
2953
|
+
}
|
|
2954
|
+
const batchUuids = batch.map((c) => c.uuid).filter((u) => u !== undefined);
|
|
2955
|
+
if (options.replayUserMessages && batch.length > 1) {
|
|
2956
|
+
for (const c of batch) {
|
|
2957
|
+
if (c.uuid && c.uuid !== command.uuid) {
|
|
2958
|
+
output.enqueue({
|
|
2959
|
+
type: "user",
|
|
2960
|
+
content: c.value,
|
|
2961
|
+
message: { role: "user", content: c.value },
|
|
2962
|
+
session_id: getSessionId(),
|
|
2963
|
+
parent_tool_use_id: null,
|
|
2964
|
+
uuid: c.uuid,
|
|
2965
|
+
isReplay: true
|
|
2966
|
+
});
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
}
|
|
2970
|
+
const appState = getAppState();
|
|
2971
|
+
const allMcpClients = [
|
|
2972
|
+
...appState.mcp.clients,
|
|
2973
|
+
...sdkClients,
|
|
2974
|
+
...dynamicMcpState.clients
|
|
2975
|
+
];
|
|
2976
|
+
registerElicitationHandlers(allMcpClients);
|
|
2977
|
+
for (const client of allMcpClients) {
|
|
2978
|
+
reregisterChannelHandlerAfterReconnect(client);
|
|
2979
|
+
}
|
|
2980
|
+
const allTools = buildAllTools(appState);
|
|
2981
|
+
for (const uuid of batchUuids) {
|
|
2982
|
+
notifyCommandLifecycle(uuid, "started");
|
|
2983
|
+
}
|
|
2984
|
+
if (command.mode === "task-notification") {
|
|
2985
|
+
const notificationText = typeof command.value === "string" ? command.value : "";
|
|
2986
|
+
const taskIdMatch = notificationText.match(/<task-id>([^<]+)<\/task-id>/);
|
|
2987
|
+
const toolUseIdMatch = notificationText.match(/<tool-use-id>([^<]+)<\/tool-use-id>/);
|
|
2988
|
+
const outputFileMatch = notificationText.match(/<output-file>([^<]+)<\/output-file>/);
|
|
2989
|
+
const statusMatch = notificationText.match(/<status>([^<]+)<\/status>/);
|
|
2990
|
+
const summaryMatch = notificationText.match(/<summary>([^<]+)<\/summary>/);
|
|
2991
|
+
const isValidStatus = (s) => s === "completed" || s === "failed" || s === "stopped" || s === "killed";
|
|
2992
|
+
const rawStatus = statusMatch?.[1];
|
|
2993
|
+
const status = isValidStatus(rawStatus) ? rawStatus === "killed" ? "stopped" : rawStatus : "completed";
|
|
2994
|
+
const usageMatch = notificationText.match(/<usage>([\s\S]*?)<\/usage>/);
|
|
2995
|
+
const usageContent = usageMatch?.[1] ?? "";
|
|
2996
|
+
const totalTokensMatch = usageContent.match(/<total_tokens>(\d+)<\/total_tokens>/);
|
|
2997
|
+
const toolUsesMatch = usageContent.match(/<tool_uses>(\d+)<\/tool_uses>/);
|
|
2998
|
+
const durationMsMatch = usageContent.match(/<duration_ms>(\d+)<\/duration_ms>/);
|
|
2999
|
+
if (statusMatch) {
|
|
3000
|
+
output.enqueue({
|
|
3001
|
+
type: "system",
|
|
3002
|
+
subtype: "task_notification",
|
|
3003
|
+
task_id: taskIdMatch?.[1] ?? "",
|
|
3004
|
+
tool_use_id: toolUseIdMatch?.[1],
|
|
3005
|
+
status,
|
|
3006
|
+
output_file: outputFileMatch?.[1] ?? "",
|
|
3007
|
+
summary: summaryMatch?.[1] ?? "",
|
|
3008
|
+
usage: totalTokensMatch && toolUsesMatch ? {
|
|
3009
|
+
total_tokens: parseInt(totalTokensMatch[1], 10),
|
|
3010
|
+
tool_uses: parseInt(toolUsesMatch[1], 10),
|
|
3011
|
+
duration_ms: durationMsMatch ? parseInt(durationMsMatch[1], 10) : 0
|
|
3012
|
+
} : undefined,
|
|
3013
|
+
session_id: getSessionId(),
|
|
3014
|
+
uuid: randomUUID4()
|
|
3015
|
+
});
|
|
3016
|
+
}
|
|
3017
|
+
}
|
|
3018
|
+
const input = command.value;
|
|
3019
|
+
if (structuredIO instanceof RemoteIO && command.mode === "prompt") {
|
|
3020
|
+
logEvent("tengu_bridge_message_received", {
|
|
3021
|
+
is_repl: false
|
|
3022
|
+
});
|
|
3023
|
+
}
|
|
3024
|
+
suggestionState.abortController?.abort();
|
|
3025
|
+
suggestionState.abortController = null;
|
|
3026
|
+
suggestionState.pendingSuggestion = null;
|
|
3027
|
+
suggestionState.pendingLastEmittedEntry = null;
|
|
3028
|
+
if (suggestionState.lastEmitted) {
|
|
3029
|
+
if (command.mode === "prompt") {
|
|
3030
|
+
const inputText = typeof input === "string" ? input : input.find((b) => b.type === "text")?.text;
|
|
3031
|
+
if (typeof inputText === "string") {
|
|
3032
|
+
logSuggestionOutcome(suggestionState.lastEmitted.text, inputText, suggestionState.lastEmitted.emittedAt, suggestionState.lastEmitted.promptId, suggestionState.lastEmitted.generationRequestId);
|
|
3033
|
+
}
|
|
3034
|
+
suggestionState.lastEmitted = null;
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
3037
|
+
abortController = createAbortController();
|
|
3038
|
+
const turnStartTime = undefined;
|
|
3039
|
+
headlessProfilerCheckpoint("before_ask");
|
|
3040
|
+
startQueryProfile();
|
|
3041
|
+
const cmd = command;
|
|
3042
|
+
await runWithWorkload(cmd.workload ?? options.workload, async () => {
|
|
3043
|
+
for await (const message of ask({
|
|
3044
|
+
commands: uniqBy_default([...currentCommands, ...appState.mcp.commands], "name"),
|
|
3045
|
+
prompt: input,
|
|
3046
|
+
promptUuid: cmd.uuid,
|
|
3047
|
+
isMeta: cmd.isMeta,
|
|
3048
|
+
cwd: cwd(),
|
|
3049
|
+
tools: allTools,
|
|
3050
|
+
verbose: options.verbose,
|
|
3051
|
+
mcpClients: allMcpClients,
|
|
3052
|
+
thinkingConfig: options.thinkingConfig,
|
|
3053
|
+
maxTurns: options.maxTurns,
|
|
3054
|
+
maxBudgetUsd: options.maxBudgetUsd,
|
|
3055
|
+
taskBudget: options.taskBudget,
|
|
3056
|
+
canUseTool,
|
|
3057
|
+
userSpecifiedModel: activeUserSpecifiedModel,
|
|
3058
|
+
fallbackModel: options.fallbackModel,
|
|
3059
|
+
jsonSchema: getInitJsonSchema() ?? options.jsonSchema,
|
|
3060
|
+
mutableMessages,
|
|
3061
|
+
getReadFileCache: () => pendingSeeds.size === 0 ? readFileState : mergeFileStateCaches(readFileState, pendingSeeds),
|
|
3062
|
+
setReadFileCache: (cache) => {
|
|
3063
|
+
readFileState = cache;
|
|
3064
|
+
for (const [path, seed] of pendingSeeds.entries()) {
|
|
3065
|
+
const existing = readFileState.get(path);
|
|
3066
|
+
if (!existing || seed.timestamp > existing.timestamp) {
|
|
3067
|
+
readFileState.set(path, seed);
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
pendingSeeds.clear();
|
|
3071
|
+
},
|
|
3072
|
+
customSystemPrompt: options.systemPrompt,
|
|
3073
|
+
appendSystemPrompt: options.appendSystemPrompt,
|
|
3074
|
+
getAppState,
|
|
3075
|
+
setAppState,
|
|
3076
|
+
abortController,
|
|
3077
|
+
replayUserMessages: options.replayUserMessages,
|
|
3078
|
+
includePartialMessages: options.includePartialMessages,
|
|
3079
|
+
handleElicitation: (serverName, params, elicitSignal) => structuredIO.handleElicitation(serverName, params.message, undefined, elicitSignal, params.mode, params.url, "elicitationId" in params ? params.elicitationId : undefined),
|
|
3080
|
+
agents: currentAgents,
|
|
3081
|
+
orphanedPermission: cmd.orphanedPermission,
|
|
3082
|
+
setSDKStatus: (status) => {
|
|
3083
|
+
output.enqueue({
|
|
3084
|
+
type: "system",
|
|
3085
|
+
subtype: "status",
|
|
3086
|
+
status,
|
|
3087
|
+
session_id: getSessionId(),
|
|
3088
|
+
uuid: randomUUID4()
|
|
3089
|
+
});
|
|
3090
|
+
}
|
|
3091
|
+
})) {
|
|
3092
|
+
forwardMessagesToBridge();
|
|
3093
|
+
if (message.type === "result") {
|
|
3094
|
+
for (const event of drainSdkEvents()) {
|
|
3095
|
+
output.enqueue(event);
|
|
3096
|
+
}
|
|
3097
|
+
const currentState = getAppState();
|
|
3098
|
+
if (getRunningTasks(currentState).some((t) => (t.type === "local_agent" || t.type === "local_workflow") && isBackgroundTask(t))) {
|
|
3099
|
+
heldBackResult = message;
|
|
3100
|
+
} else {
|
|
3101
|
+
heldBackResult = null;
|
|
3102
|
+
output.enqueue(message);
|
|
3103
|
+
}
|
|
3104
|
+
} else {
|
|
3105
|
+
for (const event of drainSdkEvents()) {
|
|
3106
|
+
output.enqueue(event);
|
|
3107
|
+
}
|
|
3108
|
+
output.enqueue(message);
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
});
|
|
3112
|
+
for (const uuid of batchUuids) {
|
|
3113
|
+
notifyCommandLifecycle(uuid, "completed");
|
|
3114
|
+
}
|
|
3115
|
+
forwardMessagesToBridge();
|
|
3116
|
+
bridgeHandle?.sendResult();
|
|
3117
|
+
if (false) {}
|
|
3118
|
+
if (options.promptSuggestions && !isEnvDefinedFalsy(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)) {
|
|
3119
|
+
const state = suggestionState;
|
|
3120
|
+
state.abortController?.abort();
|
|
3121
|
+
const localAbort = new AbortController;
|
|
3122
|
+
suggestionState.abortController = localAbort;
|
|
3123
|
+
const cacheSafeParams = getLastCacheSafeParams();
|
|
3124
|
+
if (!cacheSafeParams) {
|
|
3125
|
+
logSuggestionSuppressed("sdk_no_params", undefined, undefined, "sdk");
|
|
3126
|
+
} else {
|
|
3127
|
+
const ref = { promise: null };
|
|
3128
|
+
ref.promise = (async () => {
|
|
3129
|
+
try {
|
|
3130
|
+
const result = await tryGenerateSuggestion(localAbort, mutableMessages, getAppState, cacheSafeParams, "sdk");
|
|
3131
|
+
if (!result || localAbort.signal.aborted)
|
|
3132
|
+
return;
|
|
3133
|
+
const suggestionMsg = {
|
|
3134
|
+
type: "prompt_suggestion",
|
|
3135
|
+
suggestion: result.suggestion,
|
|
3136
|
+
uuid: randomUUID4(),
|
|
3137
|
+
session_id: getSessionId()
|
|
3138
|
+
};
|
|
3139
|
+
const lastEmittedEntry = {
|
|
3140
|
+
text: result.suggestion,
|
|
3141
|
+
emittedAt: Date.now(),
|
|
3142
|
+
promptId: result.promptId,
|
|
3143
|
+
generationRequestId: result.generationRequestId
|
|
3144
|
+
};
|
|
3145
|
+
if (heldBackResult) {
|
|
3146
|
+
suggestionState.pendingSuggestion = suggestionMsg;
|
|
3147
|
+
suggestionState.pendingLastEmittedEntry = {
|
|
3148
|
+
text: lastEmittedEntry.text,
|
|
3149
|
+
promptId: lastEmittedEntry.promptId,
|
|
3150
|
+
generationRequestId: lastEmittedEntry.generationRequestId
|
|
3151
|
+
};
|
|
3152
|
+
} else {
|
|
3153
|
+
suggestionState.lastEmitted = lastEmittedEntry;
|
|
3154
|
+
output.enqueue(suggestionMsg);
|
|
3155
|
+
}
|
|
3156
|
+
} catch (error) {
|
|
3157
|
+
if (error instanceof Error && (error.name === "AbortError" || error.name === "APIUserAbortError")) {
|
|
3158
|
+
logSuggestionSuppressed("aborted", undefined, undefined, "sdk");
|
|
3159
|
+
return;
|
|
3160
|
+
}
|
|
3161
|
+
logError(toError(error));
|
|
3162
|
+
} finally {
|
|
3163
|
+
if (suggestionState.inflightPromise === ref.promise) {
|
|
3164
|
+
suggestionState.inflightPromise = null;
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
})();
|
|
3168
|
+
suggestionState.inflightPromise = ref.promise;
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
logHeadlessProfilerTurn();
|
|
3172
|
+
logQueryProfileReport();
|
|
3173
|
+
headlessProfilerStartTurn();
|
|
3174
|
+
}
|
|
3175
|
+
};
|
|
3176
|
+
do {
|
|
3177
|
+
for (const event of drainSdkEvents()) {
|
|
3178
|
+
output.enqueue(event);
|
|
3179
|
+
}
|
|
3180
|
+
runPhase = "draining_commands";
|
|
3181
|
+
await drainCommandQueue();
|
|
3182
|
+
waitingForAgents = false;
|
|
3183
|
+
{
|
|
3184
|
+
const state = getAppState();
|
|
3185
|
+
const hasRunningBg = getRunningTasks(state).some((t) => isBackgroundTask(t) && t.type !== "in_process_teammate");
|
|
3186
|
+
const hasMainThreadQueued = peek(isMainThread) !== undefined;
|
|
3187
|
+
if (hasRunningBg || hasMainThreadQueued) {
|
|
3188
|
+
waitingForAgents = true;
|
|
3189
|
+
if (!hasMainThreadQueued) {
|
|
3190
|
+
runPhase = "waiting_for_agents";
|
|
3191
|
+
await sleep(100);
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
} while (waitingForAgents);
|
|
3196
|
+
if (heldBackResult) {
|
|
3197
|
+
output.enqueue(heldBackResult);
|
|
3198
|
+
heldBackResult = null;
|
|
3199
|
+
if (suggestionState.pendingSuggestion) {
|
|
3200
|
+
output.enqueue(suggestionState.pendingSuggestion);
|
|
3201
|
+
if (suggestionState.pendingLastEmittedEntry) {
|
|
3202
|
+
suggestionState.lastEmitted = {
|
|
3203
|
+
...suggestionState.pendingLastEmittedEntry,
|
|
3204
|
+
emittedAt: Date.now()
|
|
3205
|
+
};
|
|
3206
|
+
suggestionState.pendingLastEmittedEntry = null;
|
|
3207
|
+
}
|
|
3208
|
+
suggestionState.pendingSuggestion = null;
|
|
3209
|
+
}
|
|
3210
|
+
}
|
|
3211
|
+
} catch (error) {
|
|
3212
|
+
try {
|
|
3213
|
+
await structuredIO.write({
|
|
3214
|
+
type: "result",
|
|
3215
|
+
subtype: "error_during_execution",
|
|
3216
|
+
duration_ms: 0,
|
|
3217
|
+
duration_api_ms: 0,
|
|
3218
|
+
is_error: true,
|
|
3219
|
+
num_turns: 0,
|
|
3220
|
+
stop_reason: null,
|
|
3221
|
+
session_id: getSessionId(),
|
|
3222
|
+
total_cost_usd: 0,
|
|
3223
|
+
usage: EMPTY_USAGE,
|
|
3224
|
+
modelUsage: {},
|
|
3225
|
+
permission_denials: [],
|
|
3226
|
+
uuid: randomUUID4(),
|
|
3227
|
+
errors: [
|
|
3228
|
+
errorMessage(error),
|
|
3229
|
+
...getInMemoryErrors().map((_) => _.error)
|
|
3230
|
+
]
|
|
3231
|
+
});
|
|
3232
|
+
} catch {}
|
|
3233
|
+
suggestionState.abortController?.abort();
|
|
3234
|
+
gracefulShutdownSync(1);
|
|
3235
|
+
return;
|
|
3236
|
+
} finally {
|
|
3237
|
+
runPhase = "finally_flush";
|
|
3238
|
+
await structuredIO.flushInternalEvents();
|
|
3239
|
+
runPhase = "finally_post_flush";
|
|
3240
|
+
if (!isShuttingDown()) {
|
|
3241
|
+
notifySessionStateChanged("idle");
|
|
3242
|
+
for (const event of drainSdkEvents()) {
|
|
3243
|
+
output.enqueue(event);
|
|
3244
|
+
}
|
|
3245
|
+
}
|
|
3246
|
+
running = false;
|
|
3247
|
+
idleTimeout.start();
|
|
3248
|
+
}
|
|
3249
|
+
if (false) {}
|
|
3250
|
+
if (peek(isMainThread) !== undefined) {
|
|
3251
|
+
run();
|
|
3252
|
+
return;
|
|
3253
|
+
}
|
|
3254
|
+
{
|
|
3255
|
+
const currentAppState = getAppState();
|
|
3256
|
+
const teamContext = currentAppState.teamContext;
|
|
3257
|
+
if (teamContext && isTeamLead(teamContext)) {
|
|
3258
|
+
const agentName = "team-lead";
|
|
3259
|
+
const POLL_INTERVAL_MS = 500;
|
|
3260
|
+
while (true) {
|
|
3261
|
+
const refreshedState = getAppState();
|
|
3262
|
+
const hasActiveTeammates = hasActiveInProcessTeammates(refreshedState) || refreshedState.teamContext && Object.keys(refreshedState.teamContext.teammates).length > 0;
|
|
3263
|
+
if (!hasActiveTeammates) {
|
|
3264
|
+
logForDebugging("[print.ts] No more active teammates, stopping poll");
|
|
3265
|
+
break;
|
|
3266
|
+
}
|
|
3267
|
+
const unread = await readUnreadMessages(agentName, refreshedState.teamContext?.teamName);
|
|
3268
|
+
if (unread.length > 0) {
|
|
3269
|
+
logForDebugging(`[print.ts] Team-lead found ${unread.length} unread messages`);
|
|
3270
|
+
await markMessagesAsRead(agentName, refreshedState.teamContext?.teamName);
|
|
3271
|
+
const teamName = refreshedState.teamContext?.teamName;
|
|
3272
|
+
for (const m of unread) {
|
|
3273
|
+
const shutdownApproval = isShutdownApproved(m.text);
|
|
3274
|
+
if (shutdownApproval && teamName) {
|
|
3275
|
+
const teammateToRemove = shutdownApproval.from;
|
|
3276
|
+
logForDebugging(`[print.ts] Processing shutdown_approved from ${teammateToRemove}`);
|
|
3277
|
+
const teammateId = refreshedState.teamContext?.teammates ? Object.entries(refreshedState.teamContext.teammates).find(([, t]) => t.name === teammateToRemove)?.[0] : undefined;
|
|
3278
|
+
if (teammateId) {
|
|
3279
|
+
removeTeammateFromTeamFile(teamName, {
|
|
3280
|
+
agentId: teammateId,
|
|
3281
|
+
name: teammateToRemove
|
|
3282
|
+
});
|
|
3283
|
+
logForDebugging(`[print.ts] Removed ${teammateToRemove} from team file`);
|
|
3284
|
+
await unassignTeammateTasks(teamName, teammateId, teammateToRemove, "shutdown");
|
|
3285
|
+
setAppState((prev) => {
|
|
3286
|
+
if (!prev.teamContext?.teammates)
|
|
3287
|
+
return prev;
|
|
3288
|
+
if (!(teammateId in prev.teamContext.teammates))
|
|
3289
|
+
return prev;
|
|
3290
|
+
const { [teammateId]: _, ...remainingTeammates } = prev.teamContext.teammates;
|
|
3291
|
+
return {
|
|
3292
|
+
...prev,
|
|
3293
|
+
teamContext: {
|
|
3294
|
+
...prev.teamContext,
|
|
3295
|
+
teammates: remainingTeammates
|
|
3296
|
+
}
|
|
3297
|
+
};
|
|
3298
|
+
});
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
}
|
|
3302
|
+
const formatted = unread.map((m) => `<${TEAMMATE_MESSAGE_TAG} teammate_id="${m.from}"${m.color ? ` color="${m.color}"` : ""}>
|
|
3303
|
+
${m.text}
|
|
3304
|
+
</${TEAMMATE_MESSAGE_TAG}>`).join(`
|
|
3305
|
+
|
|
3306
|
+
`);
|
|
3307
|
+
enqueue({
|
|
3308
|
+
mode: "prompt",
|
|
3309
|
+
value: formatted,
|
|
3310
|
+
uuid: randomUUID4()
|
|
3311
|
+
});
|
|
3312
|
+
run();
|
|
3313
|
+
return;
|
|
3314
|
+
}
|
|
3315
|
+
if (inputClosed && !shutdownPromptInjected) {
|
|
3316
|
+
shutdownPromptInjected = true;
|
|
3317
|
+
logForDebugging("[print.ts] Input closed with active teammates, injecting shutdown prompt");
|
|
3318
|
+
enqueue({
|
|
3319
|
+
mode: "prompt",
|
|
3320
|
+
value: SHUTDOWN_TEAM_PROMPT,
|
|
3321
|
+
uuid: randomUUID4()
|
|
3322
|
+
});
|
|
3323
|
+
run();
|
|
3324
|
+
return;
|
|
3325
|
+
}
|
|
3326
|
+
await sleep(POLL_INTERVAL_MS);
|
|
3327
|
+
}
|
|
3328
|
+
}
|
|
3329
|
+
}
|
|
3330
|
+
if (inputClosed) {
|
|
3331
|
+
const hasActiveSwarm = await (async () => {
|
|
3332
|
+
const currentAppState = getAppState();
|
|
3333
|
+
if (hasWorkingInProcessTeammates(currentAppState)) {
|
|
3334
|
+
await waitForTeammatesToBecomeIdle(setAppState, currentAppState);
|
|
3335
|
+
}
|
|
3336
|
+
const refreshedAppState = getAppState();
|
|
3337
|
+
const refreshedTeamContext = refreshedAppState.teamContext;
|
|
3338
|
+
const hasTeamMembersNotCleanedUp = refreshedTeamContext && Object.keys(refreshedTeamContext.teammates).length > 0;
|
|
3339
|
+
return hasTeamMembersNotCleanedUp || hasActiveInProcessTeammates(refreshedAppState);
|
|
3340
|
+
})();
|
|
3341
|
+
if (hasActiveSwarm) {
|
|
3342
|
+
enqueue({
|
|
3343
|
+
mode: "prompt",
|
|
3344
|
+
value: SHUTDOWN_TEAM_PROMPT,
|
|
3345
|
+
uuid: randomUUID4()
|
|
3346
|
+
});
|
|
3347
|
+
run();
|
|
3348
|
+
} else {
|
|
3349
|
+
if (suggestionState.inflightPromise) {
|
|
3350
|
+
await Promise.race([suggestionState.inflightPromise, sleep(5000)]);
|
|
3351
|
+
}
|
|
3352
|
+
suggestionState.abortController?.abort();
|
|
3353
|
+
suggestionState.abortController = null;
|
|
3354
|
+
await finalizePendingAsyncHooks();
|
|
3355
|
+
unsubscribeSkillChanges();
|
|
3356
|
+
unsubscribeAuthStatus?.();
|
|
3357
|
+
statusListeners.delete(rateLimitListener);
|
|
3358
|
+
output.done();
|
|
3359
|
+
}
|
|
3360
|
+
}
|
|
3361
|
+
};
|
|
3362
|
+
if (false) {}
|
|
3363
|
+
let cronScheduler = null;
|
|
3364
|
+
if (false) {}
|
|
3365
|
+
const sendControlResponseSuccess = function(message, response) {
|
|
3366
|
+
output.enqueue({
|
|
3367
|
+
type: "control_response",
|
|
3368
|
+
response: {
|
|
3369
|
+
subtype: "success",
|
|
3370
|
+
request_id: message.request_id,
|
|
3371
|
+
response
|
|
3372
|
+
}
|
|
3373
|
+
});
|
|
3374
|
+
};
|
|
3375
|
+
const sendControlResponseError = function(message, errorMessage2) {
|
|
3376
|
+
output.enqueue({
|
|
3377
|
+
type: "control_response",
|
|
3378
|
+
response: {
|
|
3379
|
+
subtype: "error",
|
|
3380
|
+
request_id: message.request_id,
|
|
3381
|
+
error: errorMessage2
|
|
3382
|
+
}
|
|
3383
|
+
});
|
|
3384
|
+
};
|
|
3385
|
+
const handledOrphanedToolUseIds = new Set;
|
|
3386
|
+
structuredIO.setUnexpectedResponseCallback(async (message) => {
|
|
3387
|
+
await handleOrphanedPermissionResponse({
|
|
3388
|
+
message,
|
|
3389
|
+
setAppState,
|
|
3390
|
+
handledToolUseIds: handledOrphanedToolUseIds,
|
|
3391
|
+
onEnqueued: () => {
|
|
3392
|
+
run();
|
|
3393
|
+
}
|
|
3394
|
+
});
|
|
3395
|
+
});
|
|
3396
|
+
const activeOAuthFlows = new Map;
|
|
3397
|
+
const oauthCallbackSubmitters = new Map;
|
|
3398
|
+
const oauthManualCallbackUsed = new Set;
|
|
3399
|
+
const oauthAuthPromises = new Map;
|
|
3400
|
+
let claudeOAuth = null;
|
|
3401
|
+
(async () => {
|
|
3402
|
+
let initialized = false;
|
|
3403
|
+
logForDiagnosticsNoPII("info", "cli_message_loop_started");
|
|
3404
|
+
for await (const message of structuredIO.structuredInput) {
|
|
3405
|
+
const eventId = "uuid" in message ? message.uuid : undefined;
|
|
3406
|
+
if (eventId && message.type !== "user" && message.type !== "control_response") {
|
|
3407
|
+
notifyCommandLifecycle(eventId, "completed");
|
|
3408
|
+
}
|
|
3409
|
+
if (message.type === "control_request") {
|
|
3410
|
+
if (message.request.subtype === "interrupt") {
|
|
3411
|
+
if (false) {}
|
|
3412
|
+
if (abortController) {
|
|
3413
|
+
abortController.abort();
|
|
3414
|
+
}
|
|
3415
|
+
suggestionState.abortController?.abort();
|
|
3416
|
+
suggestionState.abortController = null;
|
|
3417
|
+
suggestionState.lastEmitted = null;
|
|
3418
|
+
suggestionState.pendingSuggestion = null;
|
|
3419
|
+
sendControlResponseSuccess(message);
|
|
3420
|
+
} else if (message.request.subtype === "end_session") {
|
|
3421
|
+
logForDebugging(`[print.ts] end_session received, reason=${message.request.reason ?? "unspecified"}`);
|
|
3422
|
+
if (abortController) {
|
|
3423
|
+
abortController.abort();
|
|
3424
|
+
}
|
|
3425
|
+
suggestionState.abortController?.abort();
|
|
3426
|
+
suggestionState.abortController = null;
|
|
3427
|
+
suggestionState.lastEmitted = null;
|
|
3428
|
+
suggestionState.pendingSuggestion = null;
|
|
3429
|
+
sendControlResponseSuccess(message);
|
|
3430
|
+
break;
|
|
3431
|
+
} else if (message.request.subtype === "initialize") {
|
|
3432
|
+
if (message.request.sdkMcpServers && message.request.sdkMcpServers.length > 0) {
|
|
3433
|
+
for (const serverName of message.request.sdkMcpServers) {
|
|
3434
|
+
sdkMcpConfigs[serverName] = {
|
|
3435
|
+
type: "sdk",
|
|
3436
|
+
name: serverName
|
|
3437
|
+
};
|
|
3438
|
+
}
|
|
3439
|
+
}
|
|
3440
|
+
await handleInitializeRequest(message.request, message.request_id, initialized, output, commands, modelInfos, structuredIO, !!options.enableAuthStatus, options, agents, getAppState);
|
|
3441
|
+
if (message.request.promptSuggestions) {
|
|
3442
|
+
setAppState((prev) => {
|
|
3443
|
+
if (prev.promptSuggestionEnabled)
|
|
3444
|
+
return prev;
|
|
3445
|
+
return { ...prev, promptSuggestionEnabled: true };
|
|
3446
|
+
});
|
|
3447
|
+
}
|
|
3448
|
+
if (message.request.agentProgressSummaries && getFeatureValue_CACHED_MAY_BE_STALE("tengu_slate_prism", true)) {
|
|
3449
|
+
setSdkAgentProgressSummariesEnabled(true);
|
|
3450
|
+
}
|
|
3451
|
+
initialized = true;
|
|
3452
|
+
if (hasCommandsInQueue()) {
|
|
3453
|
+
run();
|
|
3454
|
+
}
|
|
3455
|
+
} else if (message.request.subtype === "set_permission_mode") {
|
|
3456
|
+
const m = message.request;
|
|
3457
|
+
setAppState((prev) => ({
|
|
3458
|
+
...prev,
|
|
3459
|
+
toolPermissionContext: handleSetPermissionMode(m, message.request_id, prev.toolPermissionContext, output),
|
|
3460
|
+
isUltraplanMode: m.ultraplan ?? prev.isUltraplanMode
|
|
3461
|
+
}));
|
|
3462
|
+
} else if (message.request.subtype === "set_model") {
|
|
3463
|
+
const requestedModel = message.request.model ?? "default";
|
|
3464
|
+
const model = requestedModel === "default" ? getDefaultMainLoopModel() : requestedModel;
|
|
3465
|
+
activeUserSpecifiedModel = model;
|
|
3466
|
+
setMainLoopModelOverride(model);
|
|
3467
|
+
notifySessionMetadataChanged({ model });
|
|
3468
|
+
injectModelSwitchBreadcrumbs(requestedModel, model);
|
|
3469
|
+
sendControlResponseSuccess(message);
|
|
3470
|
+
} else if (message.request.subtype === "set_max_thinking_tokens") {
|
|
3471
|
+
if (message.request.max_thinking_tokens === null) {
|
|
3472
|
+
options.thinkingConfig = undefined;
|
|
3473
|
+
} else if (message.request.max_thinking_tokens === 0) {
|
|
3474
|
+
options.thinkingConfig = { type: "disabled" };
|
|
3475
|
+
} else {
|
|
3476
|
+
options.thinkingConfig = {
|
|
3477
|
+
type: "enabled",
|
|
3478
|
+
budgetTokens: message.request.max_thinking_tokens
|
|
3479
|
+
};
|
|
3480
|
+
}
|
|
3481
|
+
sendControlResponseSuccess(message);
|
|
3482
|
+
} else if (message.request.subtype === "mcp_status") {
|
|
3483
|
+
sendControlResponseSuccess(message, {
|
|
3484
|
+
mcpServers: buildMcpServerStatuses()
|
|
3485
|
+
});
|
|
3486
|
+
} else if (message.request.subtype === "get_context_usage") {
|
|
3487
|
+
try {
|
|
3488
|
+
const appState = getAppState();
|
|
3489
|
+
const data = await collectContextData({
|
|
3490
|
+
messages: mutableMessages,
|
|
3491
|
+
getAppState,
|
|
3492
|
+
options: {
|
|
3493
|
+
mainLoopModel: getMainLoopModel(),
|
|
3494
|
+
tools: buildAllTools(appState),
|
|
3495
|
+
agentDefinitions: appState.agentDefinitions,
|
|
3496
|
+
customSystemPrompt: options.systemPrompt,
|
|
3497
|
+
appendSystemPrompt: options.appendSystemPrompt
|
|
3498
|
+
}
|
|
3499
|
+
});
|
|
3500
|
+
sendControlResponseSuccess(message, { ...data });
|
|
3501
|
+
} catch (error) {
|
|
3502
|
+
sendControlResponseError(message, errorMessage(error));
|
|
3503
|
+
}
|
|
3504
|
+
} else if (message.request.subtype === "mcp_message") {
|
|
3505
|
+
const mcpRequest = message.request;
|
|
3506
|
+
const sdkClient = sdkClients.find((client) => client.name === mcpRequest.server_name);
|
|
3507
|
+
if (sdkClient && sdkClient.type === "connected" && sdkClient.client?.transport?.onmessage) {
|
|
3508
|
+
sdkClient.client.transport.onmessage(mcpRequest.message);
|
|
3509
|
+
}
|
|
3510
|
+
sendControlResponseSuccess(message);
|
|
3511
|
+
} else if (message.request.subtype === "rewind_files") {
|
|
3512
|
+
const appState = getAppState();
|
|
3513
|
+
const result = await handleRewindFiles(message.request.user_message_id, appState, setAppState, message.request.dry_run ?? false);
|
|
3514
|
+
if (result.canRewind || message.request.dry_run) {
|
|
3515
|
+
sendControlResponseSuccess(message, result);
|
|
3516
|
+
} else {
|
|
3517
|
+
sendControlResponseError(message, result.error ?? "Unexpected error");
|
|
3518
|
+
}
|
|
3519
|
+
} else if (message.request.subtype === "cancel_async_message") {
|
|
3520
|
+
const targetUuid = message.request.message_uuid;
|
|
3521
|
+
const removed = dequeueAllMatching((cmd) => cmd.uuid === targetUuid);
|
|
3522
|
+
sendControlResponseSuccess(message, {
|
|
3523
|
+
cancelled: removed.length > 0
|
|
3524
|
+
});
|
|
3525
|
+
} else if (message.request.subtype === "seed_read_state") {
|
|
3526
|
+
try {
|
|
3527
|
+
const normalizedPath = expandPath(message.request.path);
|
|
3528
|
+
const diskMtime = Math.floor((await stat(normalizedPath)).mtimeMs);
|
|
3529
|
+
if (diskMtime <= message.request.mtime) {
|
|
3530
|
+
const raw = await readFile2(normalizedPath, "utf-8");
|
|
3531
|
+
const content = (raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw).replaceAll(`\r
|
|
3532
|
+
`, `
|
|
3533
|
+
`);
|
|
3534
|
+
pendingSeeds.set(normalizedPath, {
|
|
3535
|
+
content,
|
|
3536
|
+
timestamp: diskMtime,
|
|
3537
|
+
offset: undefined,
|
|
3538
|
+
limit: undefined
|
|
3539
|
+
});
|
|
3540
|
+
}
|
|
3541
|
+
} catch {}
|
|
3542
|
+
sendControlResponseSuccess(message);
|
|
3543
|
+
} else if (message.request.subtype === "mcp_set_servers") {
|
|
3544
|
+
const { response, sdkServersChanged } = await applyMcpServerChanges(message.request.servers);
|
|
3545
|
+
sendControlResponseSuccess(message, response);
|
|
3546
|
+
if (sdkServersChanged) {
|
|
3547
|
+
updateSdkMcp();
|
|
3548
|
+
}
|
|
3549
|
+
} else if (message.request.subtype === "reload_plugins") {
|
|
3550
|
+
try {
|
|
3551
|
+
if (false) {}
|
|
3552
|
+
const r = await refreshActivePlugins(setAppState);
|
|
3553
|
+
const sdkAgents = currentAgents.filter((a) => a.source === "flagSettings");
|
|
3554
|
+
currentAgents = [...r.agentDefinitions.allAgents, ...sdkAgents];
|
|
3555
|
+
let plugins = [];
|
|
3556
|
+
const [cmdsR, mcpR, pluginsR] = await Promise.allSettled([
|
|
3557
|
+
getCommands(cwd()),
|
|
3558
|
+
applyPluginMcpDiff(),
|
|
3559
|
+
loadAllPluginsCacheOnly()
|
|
3560
|
+
]);
|
|
3561
|
+
if (cmdsR.status === "fulfilled") {
|
|
3562
|
+
currentCommands = cmdsR.value;
|
|
3563
|
+
} else {
|
|
3564
|
+
logError(cmdsR.reason);
|
|
3565
|
+
}
|
|
3566
|
+
if (mcpR.status === "rejected") {
|
|
3567
|
+
logError(mcpR.reason);
|
|
3568
|
+
}
|
|
3569
|
+
if (pluginsR.status === "fulfilled") {
|
|
3570
|
+
plugins = pluginsR.value.enabled.map((p) => ({
|
|
3571
|
+
name: p.name,
|
|
3572
|
+
path: p.path,
|
|
3573
|
+
source: p.source
|
|
3574
|
+
}));
|
|
3575
|
+
} else {
|
|
3576
|
+
logError(pluginsR.reason);
|
|
3577
|
+
}
|
|
3578
|
+
sendControlResponseSuccess(message, {
|
|
3579
|
+
commands: currentCommands.filter((cmd) => cmd.userInvocable !== false).map((cmd) => ({
|
|
3580
|
+
name: getCommandName(cmd),
|
|
3581
|
+
description: formatDescriptionWithSource(cmd),
|
|
3582
|
+
argumentHint: cmd.argumentHint || ""
|
|
3583
|
+
})),
|
|
3584
|
+
agents: currentAgents.map((a) => ({
|
|
3585
|
+
name: a.agentType,
|
|
3586
|
+
description: a.whenToUse,
|
|
3587
|
+
model: a.model === "inherit" ? undefined : a.model
|
|
3588
|
+
})),
|
|
3589
|
+
plugins,
|
|
3590
|
+
mcpServers: buildMcpServerStatuses(),
|
|
3591
|
+
error_count: r.error_count
|
|
3592
|
+
});
|
|
3593
|
+
} catch (error) {
|
|
3594
|
+
sendControlResponseError(message, errorMessage(error));
|
|
3595
|
+
}
|
|
3596
|
+
} else if (message.request.subtype === "mcp_reconnect") {
|
|
3597
|
+
const currentAppState = getAppState();
|
|
3598
|
+
const { serverName } = message.request;
|
|
3599
|
+
elicitationRegistered.delete(serverName);
|
|
3600
|
+
const config = getMcpConfigByName(serverName) ?? mcpClients.find((c) => c.name === serverName)?.config ?? sdkClients.find((c) => c.name === serverName)?.config ?? dynamicMcpState.clients.find((c) => c.name === serverName)?.config ?? currentAppState.mcp.clients.find((c) => c.name === serverName)?.config ?? null;
|
|
3601
|
+
if (!config) {
|
|
3602
|
+
sendControlResponseError(message, `Server not found: ${serverName}`);
|
|
3603
|
+
} else {
|
|
3604
|
+
const result = await reconnectMcpServerImpl(serverName, config);
|
|
3605
|
+
const prefix = getMcpPrefix(serverName);
|
|
3606
|
+
setAppState((prev) => ({
|
|
3607
|
+
...prev,
|
|
3608
|
+
mcp: {
|
|
3609
|
+
...prev.mcp,
|
|
3610
|
+
clients: prev.mcp.clients.map((c) => c.name === serverName ? result.client : c),
|
|
3611
|
+
tools: [
|
|
3612
|
+
...reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
|
|
3613
|
+
...result.tools
|
|
3614
|
+
],
|
|
3615
|
+
commands: [
|
|
3616
|
+
...reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
|
|
3617
|
+
...result.commands
|
|
3618
|
+
],
|
|
3619
|
+
resources: result.resources && result.resources.length > 0 ? { ...prev.mcp.resources, [serverName]: result.resources } : omit_default(prev.mcp.resources, serverName)
|
|
3620
|
+
}
|
|
3621
|
+
}));
|
|
3622
|
+
dynamicMcpState = {
|
|
3623
|
+
...dynamicMcpState,
|
|
3624
|
+
clients: [
|
|
3625
|
+
...dynamicMcpState.clients.filter((c) => c.name !== serverName),
|
|
3626
|
+
result.client
|
|
3627
|
+
],
|
|
3628
|
+
tools: [
|
|
3629
|
+
...dynamicMcpState.tools.filter((t) => !t.name?.startsWith(prefix)),
|
|
3630
|
+
...result.tools
|
|
3631
|
+
]
|
|
3632
|
+
};
|
|
3633
|
+
if (result.client.type === "connected") {
|
|
3634
|
+
registerElicitationHandlers([result.client]);
|
|
3635
|
+
reregisterChannelHandlerAfterReconnect(result.client);
|
|
3636
|
+
sendControlResponseSuccess(message);
|
|
3637
|
+
} else {
|
|
3638
|
+
const errorMessage2 = result.client.type === "failed" ? result.client.error ?? "Connection failed" : `Server status: ${result.client.type}`;
|
|
3639
|
+
sendControlResponseError(message, errorMessage2);
|
|
3640
|
+
}
|
|
3641
|
+
}
|
|
3642
|
+
} else if (message.request.subtype === "mcp_toggle") {
|
|
3643
|
+
const currentAppState = getAppState();
|
|
3644
|
+
const { serverName, enabled } = message.request;
|
|
3645
|
+
elicitationRegistered.delete(serverName);
|
|
3646
|
+
const config = getMcpConfigByName(serverName) ?? mcpClients.find((c) => c.name === serverName)?.config ?? sdkClients.find((c) => c.name === serverName)?.config ?? dynamicMcpState.clients.find((c) => c.name === serverName)?.config ?? currentAppState.mcp.clients.find((c) => c.name === serverName)?.config ?? null;
|
|
3647
|
+
if (!config) {
|
|
3648
|
+
sendControlResponseError(message, `Server not found: ${serverName}`);
|
|
3649
|
+
} else if (!enabled) {
|
|
3650
|
+
setMcpServerEnabled(serverName, false);
|
|
3651
|
+
const client = [
|
|
3652
|
+
...mcpClients,
|
|
3653
|
+
...sdkClients,
|
|
3654
|
+
...dynamicMcpState.clients,
|
|
3655
|
+
...currentAppState.mcp.clients
|
|
3656
|
+
].find((c) => c.name === serverName);
|
|
3657
|
+
if (client && client.type === "connected") {
|
|
3658
|
+
await clearServerCache(serverName, config);
|
|
3659
|
+
}
|
|
3660
|
+
const prefix = getMcpPrefix(serverName);
|
|
3661
|
+
setAppState((prev) => ({
|
|
3662
|
+
...prev,
|
|
3663
|
+
mcp: {
|
|
3664
|
+
...prev.mcp,
|
|
3665
|
+
clients: prev.mcp.clients.map((c) => c.name === serverName ? { name: serverName, type: "disabled", config } : c),
|
|
3666
|
+
tools: reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
|
|
3667
|
+
commands: reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
|
|
3668
|
+
resources: omit_default(prev.mcp.resources, serverName)
|
|
3669
|
+
}
|
|
3670
|
+
}));
|
|
3671
|
+
sendControlResponseSuccess(message);
|
|
3672
|
+
} else {
|
|
3673
|
+
setMcpServerEnabled(serverName, true);
|
|
3674
|
+
const result = await reconnectMcpServerImpl(serverName, config);
|
|
3675
|
+
const prefix = getMcpPrefix(serverName);
|
|
3676
|
+
setAppState((prev) => ({
|
|
3677
|
+
...prev,
|
|
3678
|
+
mcp: {
|
|
3679
|
+
...prev.mcp,
|
|
3680
|
+
clients: prev.mcp.clients.map((c) => c.name === serverName ? result.client : c),
|
|
3681
|
+
tools: [
|
|
3682
|
+
...reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
|
|
3683
|
+
...result.tools
|
|
3684
|
+
],
|
|
3685
|
+
commands: [
|
|
3686
|
+
...reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
|
|
3687
|
+
...result.commands
|
|
3688
|
+
],
|
|
3689
|
+
resources: result.resources && result.resources.length > 0 ? { ...prev.mcp.resources, [serverName]: result.resources } : omit_default(prev.mcp.resources, serverName)
|
|
3690
|
+
}
|
|
3691
|
+
}));
|
|
3692
|
+
if (result.client.type === "connected") {
|
|
3693
|
+
registerElicitationHandlers([result.client]);
|
|
3694
|
+
reregisterChannelHandlerAfterReconnect(result.client);
|
|
3695
|
+
sendControlResponseSuccess(message);
|
|
3696
|
+
} else {
|
|
3697
|
+
const errorMessage2 = result.client.type === "failed" ? result.client.error ?? "Connection failed" : `Server status: ${result.client.type}`;
|
|
3698
|
+
sendControlResponseError(message, errorMessage2);
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
} else if (message.request.subtype === "channel_enable") {
|
|
3702
|
+
const currentAppState = getAppState();
|
|
3703
|
+
handleChannelEnable(message.request_id, message.request.serverName, [
|
|
3704
|
+
...currentAppState.mcp.clients,
|
|
3705
|
+
...sdkClients,
|
|
3706
|
+
...dynamicMcpState.clients
|
|
3707
|
+
], output);
|
|
3708
|
+
} else if (message.request.subtype === "mcp_authenticate") {
|
|
3709
|
+
const { serverName } = message.request;
|
|
3710
|
+
const currentAppState = getAppState();
|
|
3711
|
+
const config = getMcpConfigByName(serverName) ?? mcpClients.find((c) => c.name === serverName)?.config ?? currentAppState.mcp.clients.find((c) => c.name === serverName)?.config ?? null;
|
|
3712
|
+
if (!config) {
|
|
3713
|
+
sendControlResponseError(message, `Server not found: ${serverName}`);
|
|
3714
|
+
} else if (config.type !== "sse" && config.type !== "http") {
|
|
3715
|
+
sendControlResponseError(message, `Server type "${config.type}" does not support OAuth authentication`);
|
|
3716
|
+
} else {
|
|
3717
|
+
try {
|
|
3718
|
+
activeOAuthFlows.get(serverName)?.abort();
|
|
3719
|
+
const controller = new AbortController;
|
|
3720
|
+
activeOAuthFlows.set(serverName, controller);
|
|
3721
|
+
let resolveAuthUrl;
|
|
3722
|
+
const authUrlPromise = new Promise((resolve) => {
|
|
3723
|
+
resolveAuthUrl = resolve;
|
|
3724
|
+
});
|
|
3725
|
+
const oauthPromise = performMCPOAuthFlow(serverName, config, (url) => resolveAuthUrl(url), controller.signal, {
|
|
3726
|
+
skipBrowserOpen: true,
|
|
3727
|
+
onWaitingForCallback: (submit) => {
|
|
3728
|
+
oauthCallbackSubmitters.set(serverName, submit);
|
|
3729
|
+
}
|
|
3730
|
+
});
|
|
3731
|
+
const authUrl = await Promise.race([
|
|
3732
|
+
authUrlPromise,
|
|
3733
|
+
oauthPromise.then(() => null)
|
|
3734
|
+
]);
|
|
3735
|
+
if (authUrl) {
|
|
3736
|
+
sendControlResponseSuccess(message, {
|
|
3737
|
+
authUrl,
|
|
3738
|
+
requiresUserAction: true
|
|
3739
|
+
});
|
|
3740
|
+
} else {
|
|
3741
|
+
sendControlResponseSuccess(message, {
|
|
3742
|
+
requiresUserAction: false
|
|
3743
|
+
});
|
|
3744
|
+
}
|
|
3745
|
+
oauthAuthPromises.set(serverName, oauthPromise);
|
|
3746
|
+
const fullFlowPromise = oauthPromise.then(async () => {
|
|
3747
|
+
if (isMcpServerDisabled(serverName)) {
|
|
3748
|
+
return;
|
|
3749
|
+
}
|
|
3750
|
+
if (oauthManualCallbackUsed.has(serverName)) {
|
|
3751
|
+
return;
|
|
3752
|
+
}
|
|
3753
|
+
const result = await reconnectMcpServerImpl(serverName, config);
|
|
3754
|
+
const prefix = getMcpPrefix(serverName);
|
|
3755
|
+
setAppState((prev) => ({
|
|
3756
|
+
...prev,
|
|
3757
|
+
mcp: {
|
|
3758
|
+
...prev.mcp,
|
|
3759
|
+
clients: prev.mcp.clients.map((c) => c.name === serverName ? result.client : c),
|
|
3760
|
+
tools: [
|
|
3761
|
+
...reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
|
|
3762
|
+
...result.tools
|
|
3763
|
+
],
|
|
3764
|
+
commands: [
|
|
3765
|
+
...reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
|
|
3766
|
+
...result.commands
|
|
3767
|
+
],
|
|
3768
|
+
resources: result.resources && result.resources.length > 0 ? {
|
|
3769
|
+
...prev.mcp.resources,
|
|
3770
|
+
[serverName]: result.resources
|
|
3771
|
+
} : omit_default(prev.mcp.resources, serverName)
|
|
3772
|
+
}
|
|
3773
|
+
}));
|
|
3774
|
+
dynamicMcpState = {
|
|
3775
|
+
...dynamicMcpState,
|
|
3776
|
+
clients: [
|
|
3777
|
+
...dynamicMcpState.clients.filter((c) => c.name !== serverName),
|
|
3778
|
+
result.client
|
|
3779
|
+
],
|
|
3780
|
+
tools: [
|
|
3781
|
+
...dynamicMcpState.tools.filter((t) => !t.name?.startsWith(prefix)),
|
|
3782
|
+
...result.tools
|
|
3783
|
+
]
|
|
3784
|
+
};
|
|
3785
|
+
}).catch((error) => {
|
|
3786
|
+
logForDebugging(`MCP OAuth failed for ${serverName}: ${error}`, { level: "error" });
|
|
3787
|
+
}).finally(() => {
|
|
3788
|
+
if (activeOAuthFlows.get(serverName) === controller) {
|
|
3789
|
+
activeOAuthFlows.delete(serverName);
|
|
3790
|
+
oauthCallbackSubmitters.delete(serverName);
|
|
3791
|
+
oauthManualCallbackUsed.delete(serverName);
|
|
3792
|
+
oauthAuthPromises.delete(serverName);
|
|
3793
|
+
}
|
|
3794
|
+
});
|
|
3795
|
+
} catch (error) {
|
|
3796
|
+
sendControlResponseError(message, errorMessage(error));
|
|
3797
|
+
}
|
|
3798
|
+
}
|
|
3799
|
+
} else if (message.request.subtype === "mcp_oauth_callback_url") {
|
|
3800
|
+
const { serverName, callbackUrl } = message.request;
|
|
3801
|
+
const submit = oauthCallbackSubmitters.get(serverName);
|
|
3802
|
+
if (submit) {
|
|
3803
|
+
let hasCodeOrError = false;
|
|
3804
|
+
try {
|
|
3805
|
+
const parsed = new URL(callbackUrl);
|
|
3806
|
+
hasCodeOrError = parsed.searchParams.has("code") || parsed.searchParams.has("error");
|
|
3807
|
+
} catch {}
|
|
3808
|
+
if (!hasCodeOrError) {
|
|
3809
|
+
sendControlResponseError(message, "Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.");
|
|
3810
|
+
} else {
|
|
3811
|
+
oauthManualCallbackUsed.add(serverName);
|
|
3812
|
+
submit(callbackUrl);
|
|
3813
|
+
const authPromise = oauthAuthPromises.get(serverName);
|
|
3814
|
+
if (authPromise) {
|
|
3815
|
+
try {
|
|
3816
|
+
await authPromise;
|
|
3817
|
+
sendControlResponseSuccess(message);
|
|
3818
|
+
} catch (error) {
|
|
3819
|
+
sendControlResponseError(message, error instanceof Error ? error.message : "OAuth authentication failed");
|
|
3820
|
+
}
|
|
3821
|
+
} else {
|
|
3822
|
+
sendControlResponseSuccess(message);
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3825
|
+
} else {
|
|
3826
|
+
sendControlResponseError(message, `No active OAuth flow for server: ${serverName}`);
|
|
3827
|
+
}
|
|
3828
|
+
} else if (message.request.subtype === "claude_authenticate") {
|
|
3829
|
+
const { loginWithClaudeAi } = message.request;
|
|
3830
|
+
claudeOAuth?.service.cleanup();
|
|
3831
|
+
logEvent("tengu_oauth_flow_start", {
|
|
3832
|
+
loginWithClaudeAi: loginWithClaudeAi ?? true
|
|
3833
|
+
});
|
|
3834
|
+
const service = new OAuthService;
|
|
3835
|
+
let urlResolver;
|
|
3836
|
+
const urlPromise = new Promise((resolve) => {
|
|
3837
|
+
urlResolver = resolve;
|
|
3838
|
+
});
|
|
3839
|
+
const flow = service.startOAuthFlow(async (manualUrl, automaticUrl) => {
|
|
3840
|
+
urlResolver({ manualUrl, automaticUrl });
|
|
3841
|
+
}, {
|
|
3842
|
+
loginWithClaudeAi: loginWithClaudeAi ?? true,
|
|
3843
|
+
skipBrowserOpen: true
|
|
3844
|
+
}).then(async (tokens) => {
|
|
3845
|
+
await installOAuthTokens(tokens);
|
|
3846
|
+
logEvent("tengu_oauth_success", {
|
|
3847
|
+
loginWithClaudeAi: loginWithClaudeAi ?? true
|
|
3848
|
+
});
|
|
3849
|
+
}).finally(() => {
|
|
3850
|
+
service.cleanup();
|
|
3851
|
+
if (claudeOAuth?.service === service) {
|
|
3852
|
+
claudeOAuth = null;
|
|
3853
|
+
}
|
|
3854
|
+
});
|
|
3855
|
+
claudeOAuth = { service, flow };
|
|
3856
|
+
flow.catch((err) => logForDebugging(`claude_authenticate flow ended: ${err}`, {
|
|
3857
|
+
level: "info"
|
|
3858
|
+
}));
|
|
3859
|
+
try {
|
|
3860
|
+
const { manualUrl, automaticUrl } = await Promise.race([
|
|
3861
|
+
urlPromise,
|
|
3862
|
+
flow.then(() => {
|
|
3863
|
+
throw new Error("OAuth flow completed without producing auth URLs");
|
|
3864
|
+
})
|
|
3865
|
+
]);
|
|
3866
|
+
sendControlResponseSuccess(message, {
|
|
3867
|
+
manualUrl,
|
|
3868
|
+
automaticUrl
|
|
3869
|
+
});
|
|
3870
|
+
} catch (error) {
|
|
3871
|
+
sendControlResponseError(message, errorMessage(error));
|
|
3872
|
+
}
|
|
3873
|
+
} else if (message.request.subtype === "claude_oauth_callback" || message.request.subtype === "claude_oauth_wait_for_completion") {
|
|
3874
|
+
if (!claudeOAuth) {
|
|
3875
|
+
sendControlResponseError(message, "No active claude_authenticate flow");
|
|
3876
|
+
} else {
|
|
3877
|
+
if (message.request.subtype === "claude_oauth_callback") {
|
|
3878
|
+
claudeOAuth.service.handleManualAuthCodeInput({
|
|
3879
|
+
authorizationCode: message.request.authorizationCode,
|
|
3880
|
+
state: message.request.state
|
|
3881
|
+
});
|
|
3882
|
+
}
|
|
3883
|
+
const { flow } = claudeOAuth;
|
|
3884
|
+
flow.then(() => {
|
|
3885
|
+
const accountInfo = getAccountInformation();
|
|
3886
|
+
sendControlResponseSuccess(message, {
|
|
3887
|
+
account: {
|
|
3888
|
+
email: accountInfo?.email,
|
|
3889
|
+
organization: accountInfo?.organization,
|
|
3890
|
+
subscriptionType: accountInfo?.subscription,
|
|
3891
|
+
tokenSource: accountInfo?.tokenSource,
|
|
3892
|
+
apiKeySource: accountInfo?.apiKeySource,
|
|
3893
|
+
apiProvider: getAPIProvider()
|
|
3894
|
+
}
|
|
3895
|
+
});
|
|
3896
|
+
}, (error) => sendControlResponseError(message, errorMessage(error)));
|
|
3897
|
+
}
|
|
3898
|
+
} else if (message.request.subtype === "mcp_clear_auth") {
|
|
3899
|
+
const { serverName } = message.request;
|
|
3900
|
+
const currentAppState = getAppState();
|
|
3901
|
+
const config = getMcpConfigByName(serverName) ?? mcpClients.find((c) => c.name === serverName)?.config ?? currentAppState.mcp.clients.find((c) => c.name === serverName)?.config ?? null;
|
|
3902
|
+
if (!config) {
|
|
3903
|
+
sendControlResponseError(message, `Server not found: ${serverName}`);
|
|
3904
|
+
} else if (config.type !== "sse" && config.type !== "http") {
|
|
3905
|
+
sendControlResponseError(message, `Cannot clear auth for server type "${config.type}"`);
|
|
3906
|
+
} else {
|
|
3907
|
+
await revokeServerTokens(serverName, config);
|
|
3908
|
+
const result = await reconnectMcpServerImpl(serverName, config);
|
|
3909
|
+
const prefix = getMcpPrefix(serverName);
|
|
3910
|
+
setAppState((prev) => ({
|
|
3911
|
+
...prev,
|
|
3912
|
+
mcp: {
|
|
3913
|
+
...prev.mcp,
|
|
3914
|
+
clients: prev.mcp.clients.map((c) => c.name === serverName ? result.client : c),
|
|
3915
|
+
tools: [
|
|
3916
|
+
...reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
|
|
3917
|
+
...result.tools
|
|
3918
|
+
],
|
|
3919
|
+
commands: [
|
|
3920
|
+
...reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
|
|
3921
|
+
...result.commands
|
|
3922
|
+
],
|
|
3923
|
+
resources: result.resources && result.resources.length > 0 ? {
|
|
3924
|
+
...prev.mcp.resources,
|
|
3925
|
+
[serverName]: result.resources
|
|
3926
|
+
} : omit_default(prev.mcp.resources, serverName)
|
|
3927
|
+
}
|
|
3928
|
+
}));
|
|
3929
|
+
sendControlResponseSuccess(message, {});
|
|
3930
|
+
}
|
|
3931
|
+
} else if (message.request.subtype === "apply_flag_settings") {
|
|
3932
|
+
const prevModel = getMainLoopModel();
|
|
3933
|
+
const existing = getFlagSettingsInline() ?? {};
|
|
3934
|
+
const incoming = message.request.settings;
|
|
3935
|
+
const merged = { ...existing, ...incoming };
|
|
3936
|
+
for (const key of Object.keys(merged)) {
|
|
3937
|
+
if (merged[key] === null) {
|
|
3938
|
+
delete merged[key];
|
|
3939
|
+
}
|
|
3940
|
+
}
|
|
3941
|
+
setFlagSettingsInline(merged);
|
|
3942
|
+
settingsChangeDetector.notifyChange("flagSettings");
|
|
3943
|
+
if ("model" in incoming) {
|
|
3944
|
+
if (incoming.model != null) {
|
|
3945
|
+
setMainLoopModelOverride(String(incoming.model));
|
|
3946
|
+
} else {
|
|
3947
|
+
setMainLoopModelOverride(undefined);
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3950
|
+
const newModel = getMainLoopModel();
|
|
3951
|
+
if (newModel !== prevModel) {
|
|
3952
|
+
activeUserSpecifiedModel = newModel;
|
|
3953
|
+
const modelArg = incoming.model ? String(incoming.model) : "default";
|
|
3954
|
+
notifySessionMetadataChanged({ model: newModel });
|
|
3955
|
+
injectModelSwitchBreadcrumbs(modelArg, newModel);
|
|
3956
|
+
}
|
|
3957
|
+
sendControlResponseSuccess(message);
|
|
3958
|
+
} else if (message.request.subtype === "get_settings") {
|
|
3959
|
+
const currentAppState = getAppState();
|
|
3960
|
+
const model = getMainLoopModel();
|
|
3961
|
+
const effort = modelSupportsEffort(model) ? resolveAppliedEffort(model, currentAppState.effortValue) : undefined;
|
|
3962
|
+
sendControlResponseSuccess(message, {
|
|
3963
|
+
...getSettingsWithSources(),
|
|
3964
|
+
applied: {
|
|
3965
|
+
model,
|
|
3966
|
+
effort: typeof effort === "string" ? effort : null
|
|
3967
|
+
}
|
|
3968
|
+
});
|
|
3969
|
+
} else if (message.request.subtype === "stop_task") {
|
|
3970
|
+
const { task_id: taskId } = message.request;
|
|
3971
|
+
try {
|
|
3972
|
+
await stopTask(taskId, {
|
|
3973
|
+
getAppState,
|
|
3974
|
+
setAppState
|
|
3975
|
+
});
|
|
3976
|
+
sendControlResponseSuccess(message, {});
|
|
3977
|
+
} catch (error) {
|
|
3978
|
+
sendControlResponseError(message, errorMessage(error));
|
|
3979
|
+
}
|
|
3980
|
+
} else if (message.request.subtype === "generate_session_title") {
|
|
3981
|
+
const { description, persist } = message.request;
|
|
3982
|
+
const titleSignal = (abortController && !abortController.signal.aborted ? abortController : createAbortController()).signal;
|
|
3983
|
+
(async () => {
|
|
3984
|
+
try {
|
|
3985
|
+
const title = await generateSessionTitle(description, titleSignal);
|
|
3986
|
+
if (title && persist) {
|
|
3987
|
+
try {
|
|
3988
|
+
saveAiGeneratedTitle(getSessionId(), title);
|
|
3989
|
+
} catch (e) {
|
|
3990
|
+
logError(e);
|
|
3991
|
+
}
|
|
3992
|
+
}
|
|
3993
|
+
sendControlResponseSuccess(message, { title });
|
|
3994
|
+
} catch (e) {
|
|
3995
|
+
sendControlResponseError(message, errorMessage(e));
|
|
3996
|
+
}
|
|
3997
|
+
})();
|
|
3998
|
+
} else if (message.request.subtype === "side_question") {
|
|
3999
|
+
const { question } = message.request;
|
|
4000
|
+
(async () => {
|
|
4001
|
+
try {
|
|
4002
|
+
const saved = getLastCacheSafeParams();
|
|
4003
|
+
const cacheSafeParams = saved ? {
|
|
4004
|
+
...saved,
|
|
4005
|
+
toolUseContext: {
|
|
4006
|
+
...saved.toolUseContext,
|
|
4007
|
+
abortController: createAbortController()
|
|
4008
|
+
}
|
|
4009
|
+
} : await buildSideQuestionFallbackParams({
|
|
4010
|
+
tools: buildAllTools(getAppState()),
|
|
4011
|
+
commands: currentCommands,
|
|
4012
|
+
mcpClients: [
|
|
4013
|
+
...getAppState().mcp.clients,
|
|
4014
|
+
...sdkClients,
|
|
4015
|
+
...dynamicMcpState.clients
|
|
4016
|
+
],
|
|
4017
|
+
messages: mutableMessages,
|
|
4018
|
+
readFileState,
|
|
4019
|
+
getAppState,
|
|
4020
|
+
setAppState,
|
|
4021
|
+
customSystemPrompt: options.systemPrompt,
|
|
4022
|
+
appendSystemPrompt: options.appendSystemPrompt,
|
|
4023
|
+
thinkingConfig: options.thinkingConfig,
|
|
4024
|
+
agents: currentAgents
|
|
4025
|
+
});
|
|
4026
|
+
const result = await runSideQuestion({
|
|
4027
|
+
question,
|
|
4028
|
+
cacheSafeParams
|
|
4029
|
+
});
|
|
4030
|
+
sendControlResponseSuccess(message, { response: result.response });
|
|
4031
|
+
} catch (e) {
|
|
4032
|
+
sendControlResponseError(message, errorMessage(e));
|
|
4033
|
+
}
|
|
4034
|
+
})();
|
|
4035
|
+
} else if (false) {} else if (message.request.subtype === "remote_control") {
|
|
4036
|
+
if (message.request.enabled) {
|
|
4037
|
+
if (bridgeHandle) {
|
|
4038
|
+
sendControlResponseSuccess(message, {
|
|
4039
|
+
session_url: getRemoteSessionUrl(bridgeHandle.bridgeSessionId, bridgeHandle.sessionIngressUrl),
|
|
4040
|
+
connect_url: buildBridgeConnectUrl(bridgeHandle.environmentId, bridgeHandle.sessionIngressUrl),
|
|
4041
|
+
environment_id: bridgeHandle.environmentId
|
|
4042
|
+
});
|
|
4043
|
+
} else {
|
|
4044
|
+
let bridgeFailureDetail;
|
|
4045
|
+
try {
|
|
4046
|
+
const { initReplBridge } = await import("./chunk-sq847dr5.js");
|
|
4047
|
+
const handle = await initReplBridge({
|
|
4048
|
+
onInboundMessage(msg) {
|
|
4049
|
+
const fields = extractInboundMessageFields(msg);
|
|
4050
|
+
if (!fields)
|
|
4051
|
+
return;
|
|
4052
|
+
const { content, uuid } = fields;
|
|
4053
|
+
enqueue({
|
|
4054
|
+
value: content,
|
|
4055
|
+
mode: "prompt",
|
|
4056
|
+
uuid,
|
|
4057
|
+
skipSlashCommands: true
|
|
4058
|
+
});
|
|
4059
|
+
run();
|
|
4060
|
+
},
|
|
4061
|
+
onPermissionResponse(response) {
|
|
4062
|
+
structuredIO.injectControlResponse(response);
|
|
4063
|
+
},
|
|
4064
|
+
onInterrupt() {
|
|
4065
|
+
abortController?.abort();
|
|
4066
|
+
},
|
|
4067
|
+
onSetModel(model) {
|
|
4068
|
+
const resolved = model === "default" ? getDefaultMainLoopModel() : model;
|
|
4069
|
+
activeUserSpecifiedModel = resolved;
|
|
4070
|
+
setMainLoopModelOverride(resolved);
|
|
4071
|
+
},
|
|
4072
|
+
onSetMaxThinkingTokens(maxTokens) {
|
|
4073
|
+
if (maxTokens === null) {
|
|
4074
|
+
options.thinkingConfig = undefined;
|
|
4075
|
+
} else if (maxTokens === 0) {
|
|
4076
|
+
options.thinkingConfig = { type: "disabled" };
|
|
4077
|
+
} else {
|
|
4078
|
+
options.thinkingConfig = {
|
|
4079
|
+
type: "enabled",
|
|
4080
|
+
budgetTokens: maxTokens
|
|
4081
|
+
};
|
|
4082
|
+
}
|
|
4083
|
+
},
|
|
4084
|
+
onStateChange(state, detail) {
|
|
4085
|
+
if (state === "failed") {
|
|
4086
|
+
bridgeFailureDetail = detail;
|
|
4087
|
+
}
|
|
4088
|
+
logForDebugging(`[bridge:sdk] State change: ${state}${detail ? ` \u2014 ${detail}` : ""}`);
|
|
4089
|
+
output.enqueue({
|
|
4090
|
+
type: "system",
|
|
4091
|
+
subtype: "bridge_state",
|
|
4092
|
+
state,
|
|
4093
|
+
detail,
|
|
4094
|
+
uuid: randomUUID4(),
|
|
4095
|
+
session_id: getSessionId()
|
|
4096
|
+
});
|
|
4097
|
+
},
|
|
4098
|
+
initialMessages: mutableMessages.length > 0 ? mutableMessages : undefined
|
|
4099
|
+
});
|
|
4100
|
+
if (!handle) {
|
|
4101
|
+
sendControlResponseError(message, bridgeFailureDetail ?? "Remote Control initialization failed");
|
|
4102
|
+
} else {
|
|
4103
|
+
bridgeHandle = handle;
|
|
4104
|
+
bridgeLastForwardedIndex = mutableMessages.length;
|
|
4105
|
+
structuredIO.setOnControlRequestSent((request) => {
|
|
4106
|
+
handle.sendControlRequest(request);
|
|
4107
|
+
});
|
|
4108
|
+
structuredIO.setOnControlRequestResolved((requestId) => {
|
|
4109
|
+
handle.sendControlCancelRequest(requestId);
|
|
4110
|
+
});
|
|
4111
|
+
sendControlResponseSuccess(message, {
|
|
4112
|
+
session_url: getRemoteSessionUrl(handle.bridgeSessionId, handle.sessionIngressUrl),
|
|
4113
|
+
connect_url: buildBridgeConnectUrl(handle.environmentId, handle.sessionIngressUrl),
|
|
4114
|
+
environment_id: handle.environmentId
|
|
4115
|
+
});
|
|
4116
|
+
}
|
|
4117
|
+
} catch (err) {
|
|
4118
|
+
sendControlResponseError(message, errorMessage(err));
|
|
4119
|
+
}
|
|
4120
|
+
}
|
|
4121
|
+
} else {
|
|
4122
|
+
if (bridgeHandle) {
|
|
4123
|
+
structuredIO.setOnControlRequestSent(undefined);
|
|
4124
|
+
structuredIO.setOnControlRequestResolved(undefined);
|
|
4125
|
+
await bridgeHandle.teardown();
|
|
4126
|
+
bridgeHandle = null;
|
|
4127
|
+
}
|
|
4128
|
+
sendControlResponseSuccess(message);
|
|
4129
|
+
}
|
|
4130
|
+
} else {
|
|
4131
|
+
sendControlResponseError(message, `Unsupported control request subtype: ${message.request.subtype}`);
|
|
4132
|
+
}
|
|
4133
|
+
continue;
|
|
4134
|
+
} else if (message.type === "control_response") {
|
|
4135
|
+
if (options.replayUserMessages) {
|
|
4136
|
+
output.enqueue(message);
|
|
4137
|
+
}
|
|
4138
|
+
continue;
|
|
4139
|
+
} else if (message.type === "keep_alive") {
|
|
4140
|
+
continue;
|
|
4141
|
+
} else if (message.type === "update_environment_variables") {
|
|
4142
|
+
continue;
|
|
4143
|
+
} else if (message.type === "assistant" || message.type === "system") {
|
|
4144
|
+
const internalMsgs = toInternalMessages([message]);
|
|
4145
|
+
mutableMessages.push(...internalMsgs);
|
|
4146
|
+
if (message.type === "assistant" && options.replayUserMessages) {
|
|
4147
|
+
output.enqueue(message);
|
|
4148
|
+
}
|
|
4149
|
+
continue;
|
|
4150
|
+
}
|
|
4151
|
+
if (message.type !== "user") {
|
|
4152
|
+
continue;
|
|
4153
|
+
}
|
|
4154
|
+
initialized = true;
|
|
4155
|
+
if (message.uuid) {
|
|
4156
|
+
const sessionId = getSessionId();
|
|
4157
|
+
const existsInSession = await doesMessageExistInSession(sessionId, message.uuid);
|
|
4158
|
+
if (existsInSession || receivedMessageUuids.has(message.uuid)) {
|
|
4159
|
+
logForDebugging(`Skipping duplicate user message: ${message.uuid}`);
|
|
4160
|
+
if (options.replayUserMessages) {
|
|
4161
|
+
logForDebugging(`Sending acknowledgment for duplicate user message: ${message.uuid}`);
|
|
4162
|
+
output.enqueue({
|
|
4163
|
+
type: "user",
|
|
4164
|
+
content: message.message?.content ?? "",
|
|
4165
|
+
message: message.message,
|
|
4166
|
+
session_id: sessionId,
|
|
4167
|
+
parent_tool_use_id: null,
|
|
4168
|
+
uuid: message.uuid,
|
|
4169
|
+
timestamp: message.timestamp,
|
|
4170
|
+
isReplay: true
|
|
4171
|
+
});
|
|
4172
|
+
}
|
|
4173
|
+
if (existsInSession) {
|
|
4174
|
+
notifyCommandLifecycle(message.uuid, "completed");
|
|
4175
|
+
}
|
|
4176
|
+
continue;
|
|
4177
|
+
}
|
|
4178
|
+
trackReceivedMessageUuid(message.uuid);
|
|
4179
|
+
}
|
|
4180
|
+
enqueue({
|
|
4181
|
+
mode: "prompt",
|
|
4182
|
+
value: await resolveAndPrepend(message, message.message.content),
|
|
4183
|
+
uuid: message.uuid,
|
|
4184
|
+
priority: message.priority
|
|
4185
|
+
});
|
|
4186
|
+
if (false) {}
|
|
4187
|
+
run();
|
|
4188
|
+
}
|
|
4189
|
+
inputClosed = true;
|
|
4190
|
+
cronScheduler?.stop();
|
|
4191
|
+
if (!running) {
|
|
4192
|
+
if (suggestionState.inflightPromise) {
|
|
4193
|
+
await Promise.race([suggestionState.inflightPromise, sleep(5000)]);
|
|
4194
|
+
}
|
|
4195
|
+
suggestionState.abortController?.abort();
|
|
4196
|
+
suggestionState.abortController = null;
|
|
4197
|
+
await finalizePendingAsyncHooks();
|
|
4198
|
+
unsubscribeSkillChanges();
|
|
4199
|
+
unsubscribeAuthStatus?.();
|
|
4200
|
+
statusListeners.delete(rateLimitListener);
|
|
4201
|
+
output.done();
|
|
4202
|
+
}
|
|
4203
|
+
})();
|
|
4204
|
+
return output;
|
|
4205
|
+
}
|
|
4206
|
+
function createCanUseToolWithPermissionPrompt(permissionPromptTool) {
|
|
4207
|
+
const canUseTool = async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => {
|
|
4208
|
+
const mainPermissionResult = forceDecision ?? await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseId);
|
|
4209
|
+
if (mainPermissionResult.behavior === "allow" || mainPermissionResult.behavior === "deny") {
|
|
4210
|
+
return mainPermissionResult;
|
|
4211
|
+
}
|
|
4212
|
+
const { signal: combinedSignal, cleanup: cleanupAbortListener } = createCombinedAbortSignal(toolUseContext.abortController.signal);
|
|
4213
|
+
if (combinedSignal.aborted) {
|
|
4214
|
+
cleanupAbortListener();
|
|
4215
|
+
return {
|
|
4216
|
+
behavior: "deny",
|
|
4217
|
+
message: "Permission prompt was aborted.",
|
|
4218
|
+
decisionReason: {
|
|
4219
|
+
type: "permissionPromptTool",
|
|
4220
|
+
permissionPromptToolName: tool.name,
|
|
4221
|
+
toolResult: undefined
|
|
4222
|
+
}
|
|
4223
|
+
};
|
|
4224
|
+
}
|
|
4225
|
+
const abortPromise = new Promise((resolve) => {
|
|
4226
|
+
combinedSignal.addEventListener("abort", () => resolve("aborted"), {
|
|
4227
|
+
once: true
|
|
4228
|
+
});
|
|
4229
|
+
});
|
|
4230
|
+
const toolCallPromise = permissionPromptTool.call({
|
|
4231
|
+
tool_name: tool.name,
|
|
4232
|
+
input,
|
|
4233
|
+
tool_use_id: toolUseId
|
|
4234
|
+
}, toolUseContext, canUseTool, assistantMessage);
|
|
4235
|
+
const raceResult = await Promise.race([toolCallPromise, abortPromise]);
|
|
4236
|
+
cleanupAbortListener();
|
|
4237
|
+
if (raceResult === "aborted" || combinedSignal.aborted) {
|
|
4238
|
+
return {
|
|
4239
|
+
behavior: "deny",
|
|
4240
|
+
message: "Permission prompt was aborted.",
|
|
4241
|
+
decisionReason: {
|
|
4242
|
+
type: "permissionPromptTool",
|
|
4243
|
+
permissionPromptToolName: tool.name,
|
|
4244
|
+
toolResult: undefined
|
|
4245
|
+
}
|
|
4246
|
+
};
|
|
4247
|
+
}
|
|
4248
|
+
const result = raceResult;
|
|
4249
|
+
const permissionToolResultBlockParam = permissionPromptTool.mapToolResultToToolResultBlockParam(result.data, "1");
|
|
4250
|
+
if (!permissionToolResultBlockParam.content || !Array.isArray(permissionToolResultBlockParam.content) || !permissionToolResultBlockParam.content[0] || permissionToolResultBlockParam.content[0].type !== "text" || typeof permissionToolResultBlockParam.content[0].text !== "string") {
|
|
4251
|
+
throw new Error('Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.');
|
|
4252
|
+
}
|
|
4253
|
+
return permissionPromptToolResultToPermissionDecision(outputSchema().parse(safeParseJSON(permissionToolResultBlockParam.content[0].text)), permissionPromptTool, input, toolUseContext);
|
|
4254
|
+
};
|
|
4255
|
+
return canUseTool;
|
|
4256
|
+
}
|
|
4257
|
+
function getCanUseToolFn(permissionPromptToolName, structuredIO, getMcpTools, onPermissionPrompt) {
|
|
4258
|
+
if (permissionPromptToolName === "stdio") {
|
|
4259
|
+
return structuredIO.createCanUseTool(onPermissionPrompt);
|
|
4260
|
+
}
|
|
4261
|
+
if (!permissionPromptToolName) {
|
|
4262
|
+
return async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => forceDecision ?? await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseId);
|
|
4263
|
+
}
|
|
4264
|
+
let resolved = null;
|
|
4265
|
+
return async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => {
|
|
4266
|
+
if (!resolved) {
|
|
4267
|
+
const mcpTools = getMcpTools();
|
|
4268
|
+
const permissionPromptTool = mcpTools.find((t) => toolMatchesName(t, permissionPromptToolName));
|
|
4269
|
+
if (!permissionPromptTool) {
|
|
4270
|
+
const error = `Error: MCP tool ${permissionPromptToolName} (passed via --permission-prompt-tool) not found. Available MCP tools: ${mcpTools.map((t) => t.name).join(", ") || "none"}`;
|
|
4271
|
+
process.stderr.write(`${error}
|
|
4272
|
+
`);
|
|
4273
|
+
gracefulShutdownSync(1);
|
|
4274
|
+
throw new Error(error);
|
|
4275
|
+
}
|
|
4276
|
+
if (!permissionPromptTool.inputJSONSchema) {
|
|
4277
|
+
const error = `Error: tool ${permissionPromptToolName} (passed via --permission-prompt-tool) must be an MCP tool`;
|
|
4278
|
+
process.stderr.write(`${error}
|
|
4279
|
+
`);
|
|
4280
|
+
gracefulShutdownSync(1);
|
|
4281
|
+
throw new Error(error);
|
|
4282
|
+
}
|
|
4283
|
+
resolved = createCanUseToolWithPermissionPrompt(permissionPromptTool);
|
|
4284
|
+
}
|
|
4285
|
+
return resolved(tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision);
|
|
4286
|
+
};
|
|
4287
|
+
}
|
|
4288
|
+
async function handleInitializeRequest(request, requestId, initialized, output, commands, modelInfos, structuredIO, enableAuthStatus, options, agents, getAppState) {
|
|
4289
|
+
if (initialized) {
|
|
4290
|
+
output.enqueue({
|
|
4291
|
+
type: "control_response",
|
|
4292
|
+
response: {
|
|
4293
|
+
subtype: "error",
|
|
4294
|
+
error: "Already initialized",
|
|
4295
|
+
request_id: requestId,
|
|
4296
|
+
pending_permission_requests: structuredIO.getPendingPermissionRequests()
|
|
4297
|
+
}
|
|
4298
|
+
});
|
|
4299
|
+
return;
|
|
4300
|
+
}
|
|
4301
|
+
if (request.systemPrompt !== undefined) {
|
|
4302
|
+
options.systemPrompt = request.systemPrompt;
|
|
4303
|
+
}
|
|
4304
|
+
if (request.appendSystemPrompt !== undefined) {
|
|
4305
|
+
options.appendSystemPrompt = request.appendSystemPrompt;
|
|
4306
|
+
}
|
|
4307
|
+
if (request.promptSuggestions !== undefined) {
|
|
4308
|
+
options.promptSuggestions = request.promptSuggestions;
|
|
4309
|
+
}
|
|
4310
|
+
if (request.agents) {
|
|
4311
|
+
const stdinAgents = parseAgentsFromJson(request.agents, "flagSettings");
|
|
4312
|
+
agents.push(...stdinAgents);
|
|
4313
|
+
}
|
|
4314
|
+
if (options.agent) {
|
|
4315
|
+
const alreadyResolved = getMainThreadAgentType() === options.agent;
|
|
4316
|
+
const mainThreadAgent = agents.find((a) => a.agentType === options.agent);
|
|
4317
|
+
if (mainThreadAgent && !alreadyResolved) {
|
|
4318
|
+
setMainThreadAgentType(mainThreadAgent.agentType);
|
|
4319
|
+
if (!options.systemPrompt && !isBuiltInAgent(mainThreadAgent)) {
|
|
4320
|
+
const agentSystemPrompt = mainThreadAgent.getSystemPrompt();
|
|
4321
|
+
if (agentSystemPrompt) {
|
|
4322
|
+
options.systemPrompt = agentSystemPrompt;
|
|
4323
|
+
}
|
|
4324
|
+
}
|
|
4325
|
+
if (!options.userSpecifiedModel && mainThreadAgent.model && mainThreadAgent.model !== "inherit") {
|
|
4326
|
+
const agentModel = parseUserSpecifiedModel(mainThreadAgent.model);
|
|
4327
|
+
setMainLoopModelOverride(agentModel);
|
|
4328
|
+
}
|
|
4329
|
+
if (mainThreadAgent.initialPrompt) {
|
|
4330
|
+
structuredIO.prependUserMessage(mainThreadAgent.initialPrompt);
|
|
4331
|
+
}
|
|
4332
|
+
} else if (mainThreadAgent?.initialPrompt) {
|
|
4333
|
+
structuredIO.prependUserMessage(mainThreadAgent.initialPrompt);
|
|
4334
|
+
}
|
|
4335
|
+
}
|
|
4336
|
+
const settings = getSettings_DEPRECATED();
|
|
4337
|
+
const outputStyle = settings?.outputStyle || DEFAULT_OUTPUT_STYLE_NAME;
|
|
4338
|
+
const availableOutputStyles = await getAllOutputStyles(getCwd());
|
|
4339
|
+
const accountInfo = getAccountInformation();
|
|
4340
|
+
if (request.hooks) {
|
|
4341
|
+
const hooks = {};
|
|
4342
|
+
for (const [event, matchers] of Object.entries(request.hooks)) {
|
|
4343
|
+
hooks[event] = matchers.map((matcher) => {
|
|
4344
|
+
const callbacks = matcher.hookCallbackIds.map((callbackId) => {
|
|
4345
|
+
return structuredIO.createHookCallback(callbackId, matcher.timeout);
|
|
4346
|
+
});
|
|
4347
|
+
return {
|
|
4348
|
+
matcher: matcher.matcher,
|
|
4349
|
+
hooks: callbacks
|
|
4350
|
+
};
|
|
4351
|
+
});
|
|
4352
|
+
}
|
|
4353
|
+
registerHookCallbacks(hooks);
|
|
4354
|
+
}
|
|
4355
|
+
if (request.jsonSchema) {
|
|
4356
|
+
setInitJsonSchema(request.jsonSchema);
|
|
4357
|
+
}
|
|
4358
|
+
const initResponse = {
|
|
4359
|
+
commands: commands.filter((cmd) => cmd.userInvocable !== false).map((cmd) => ({
|
|
4360
|
+
name: getCommandName(cmd),
|
|
4361
|
+
description: formatDescriptionWithSource(cmd),
|
|
4362
|
+
argumentHint: cmd.argumentHint || ""
|
|
4363
|
+
})),
|
|
4364
|
+
agents: agents.map((agent) => ({
|
|
4365
|
+
name: agent.agentType,
|
|
4366
|
+
description: agent.whenToUse,
|
|
4367
|
+
model: agent.model === "inherit" ? undefined : agent.model
|
|
4368
|
+
})),
|
|
4369
|
+
output_style: outputStyle,
|
|
4370
|
+
available_output_styles: Object.keys(availableOutputStyles),
|
|
4371
|
+
models: modelInfos,
|
|
4372
|
+
account: {
|
|
4373
|
+
email: accountInfo?.email,
|
|
4374
|
+
organization: accountInfo?.organization,
|
|
4375
|
+
subscriptionType: accountInfo?.subscription,
|
|
4376
|
+
tokenSource: accountInfo?.tokenSource,
|
|
4377
|
+
apiKeySource: accountInfo?.apiKeySource,
|
|
4378
|
+
apiProvider: getAPIProvider()
|
|
4379
|
+
},
|
|
4380
|
+
pid: process.pid
|
|
4381
|
+
};
|
|
4382
|
+
if (isFastModeEnabled() && isFastModeAvailable()) {
|
|
4383
|
+
const appState = getAppState();
|
|
4384
|
+
initResponse.fast_mode_state = getFastModeState(options.userSpecifiedModel ?? null, appState.fastMode);
|
|
4385
|
+
}
|
|
4386
|
+
output.enqueue({
|
|
4387
|
+
type: "control_response",
|
|
4388
|
+
response: {
|
|
4389
|
+
subtype: "success",
|
|
4390
|
+
request_id: requestId,
|
|
4391
|
+
response: initResponse
|
|
4392
|
+
}
|
|
4393
|
+
});
|
|
4394
|
+
if (enableAuthStatus) {
|
|
4395
|
+
const authStatusManager = AwsAuthStatusManager.getInstance();
|
|
4396
|
+
const status = authStatusManager.getStatus();
|
|
4397
|
+
if (status) {
|
|
4398
|
+
output.enqueue({
|
|
4399
|
+
type: "auth_status",
|
|
4400
|
+
isAuthenticating: status.isAuthenticating,
|
|
4401
|
+
output: status.output,
|
|
4402
|
+
error: status.error,
|
|
4403
|
+
uuid: randomUUID4(),
|
|
4404
|
+
session_id: getSessionId()
|
|
4405
|
+
});
|
|
4406
|
+
}
|
|
4407
|
+
}
|
|
4408
|
+
}
|
|
4409
|
+
async function handleRewindFiles(userMessageId, appState, setAppState, dryRun) {
|
|
4410
|
+
if (!fileHistoryEnabled()) {
|
|
4411
|
+
return { canRewind: false, error: "File rewinding is not enabled.", filesChanged: [] };
|
|
4412
|
+
}
|
|
4413
|
+
if (!fileHistoryCanRestore(appState.fileHistory, userMessageId)) {
|
|
4414
|
+
return {
|
|
4415
|
+
canRewind: false,
|
|
4416
|
+
error: "No file checkpoint found for this message.",
|
|
4417
|
+
filesChanged: []
|
|
4418
|
+
};
|
|
4419
|
+
}
|
|
4420
|
+
if (dryRun) {
|
|
4421
|
+
const diffStats = await fileHistoryGetDiffStats(appState.fileHistory, userMessageId);
|
|
4422
|
+
return {
|
|
4423
|
+
canRewind: true,
|
|
4424
|
+
filesChanged: diffStats?.filesChanged,
|
|
4425
|
+
insertions: diffStats?.insertions,
|
|
4426
|
+
deletions: diffStats?.deletions
|
|
4427
|
+
};
|
|
4428
|
+
}
|
|
4429
|
+
try {
|
|
4430
|
+
await fileHistoryRewind((updater) => setAppState((prev) => ({
|
|
4431
|
+
...prev,
|
|
4432
|
+
fileHistory: updater(prev.fileHistory)
|
|
4433
|
+
})), userMessageId);
|
|
4434
|
+
} catch (error) {
|
|
4435
|
+
return {
|
|
4436
|
+
canRewind: false,
|
|
4437
|
+
error: `Failed to rewind: ${errorMessage(error)}`,
|
|
4438
|
+
filesChanged: []
|
|
4439
|
+
};
|
|
4440
|
+
}
|
|
4441
|
+
return { canRewind: true, filesChanged: [] };
|
|
4442
|
+
}
|
|
4443
|
+
function handleSetPermissionMode(request, requestId, toolPermissionContext, output) {
|
|
4444
|
+
if (request.mode === "bypassPermissions") {
|
|
4445
|
+
if (isBypassPermissionsModeDisabled()) {
|
|
4446
|
+
output.enqueue({
|
|
4447
|
+
type: "control_response",
|
|
4448
|
+
response: {
|
|
4449
|
+
subtype: "error",
|
|
4450
|
+
request_id: requestId,
|
|
4451
|
+
error: "Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration"
|
|
4452
|
+
}
|
|
4453
|
+
});
|
|
4454
|
+
return toolPermissionContext;
|
|
4455
|
+
}
|
|
4456
|
+
if (!toolPermissionContext.isBypassPermissionsModeAvailable) {
|
|
4457
|
+
output.enqueue({
|
|
4458
|
+
type: "control_response",
|
|
4459
|
+
response: {
|
|
4460
|
+
subtype: "error",
|
|
4461
|
+
request_id: requestId,
|
|
4462
|
+
error: "Cannot set permission mode to bypassPermissions because the session was not launched with --dangerously-skip-permissions"
|
|
4463
|
+
}
|
|
4464
|
+
});
|
|
4465
|
+
return toolPermissionContext;
|
|
4466
|
+
}
|
|
4467
|
+
}
|
|
4468
|
+
if (false) {}
|
|
4469
|
+
output.enqueue({
|
|
4470
|
+
type: "control_response",
|
|
4471
|
+
response: {
|
|
4472
|
+
subtype: "success",
|
|
4473
|
+
request_id: requestId,
|
|
4474
|
+
response: {
|
|
4475
|
+
mode: request.mode
|
|
4476
|
+
}
|
|
4477
|
+
}
|
|
4478
|
+
});
|
|
4479
|
+
return {
|
|
4480
|
+
...transitionPermissionMode(toolPermissionContext.mode, request.mode, toolPermissionContext),
|
|
4481
|
+
mode: request.mode
|
|
4482
|
+
};
|
|
4483
|
+
}
|
|
4484
|
+
function handleChannelEnable(requestId, serverName, connectionPool, output) {
|
|
4485
|
+
const respondError = (error) => output.enqueue({
|
|
4486
|
+
type: "control_response",
|
|
4487
|
+
response: { subtype: "error", request_id: requestId, error }
|
|
4488
|
+
});
|
|
4489
|
+
if (true) {
|
|
4490
|
+
return respondError("channels feature not available in this build");
|
|
4491
|
+
}
|
|
4492
|
+
const connection = connectionPool.find((c) => c.name === serverName && c.type === "connected");
|
|
4493
|
+
if (!connection || connection.type !== "connected") {
|
|
4494
|
+
return respondError(`server ${serverName} is not connected`);
|
|
4495
|
+
}
|
|
4496
|
+
const pluginSource = connection.config.pluginSource;
|
|
4497
|
+
const parsed = pluginSource ? parsePluginIdentifier(pluginSource) : undefined;
|
|
4498
|
+
if (!parsed?.marketplace) {
|
|
4499
|
+
return respondError(`server ${serverName} is not plugin-sourced; channel_enable requires a marketplace plugin`);
|
|
4500
|
+
}
|
|
4501
|
+
const entry = {
|
|
4502
|
+
kind: "plugin",
|
|
4503
|
+
name: parsed.name,
|
|
4504
|
+
marketplace: parsed.marketplace
|
|
4505
|
+
};
|
|
4506
|
+
const prior = getAllowedChannels();
|
|
4507
|
+
const already = prior.some((e) => e.kind === "plugin" && e.name === entry.name && e.marketplace === entry.marketplace);
|
|
4508
|
+
if (!already)
|
|
4509
|
+
setAllowedChannels([...prior, entry]);
|
|
4510
|
+
const gate = gateChannelServer(serverName, connection.capabilities, pluginSource);
|
|
4511
|
+
if (gate.action === "skip") {
|
|
4512
|
+
if (!already)
|
|
4513
|
+
setAllowedChannels(prior);
|
|
4514
|
+
return respondError(gate.reason);
|
|
4515
|
+
}
|
|
4516
|
+
const pluginId = `${entry.name}@${entry.marketplace}`;
|
|
4517
|
+
logMCPDebug(serverName, "Channel notifications registered");
|
|
4518
|
+
logEvent("tengu_mcp_channel_enable", { plugin: pluginId });
|
|
4519
|
+
connection.client.setNotificationHandler(ChannelMessageNotificationSchema(), async (notification) => {
|
|
4520
|
+
const { content, meta } = notification.params;
|
|
4521
|
+
logMCPDebug(serverName, `notifications/claude/channel: ${content.slice(0, 80)}`);
|
|
4522
|
+
logEvent("tengu_mcp_channel_message", {
|
|
4523
|
+
content_length: content.length,
|
|
4524
|
+
meta_key_count: Object.keys(meta ?? {}).length,
|
|
4525
|
+
entry_kind: "plugin",
|
|
4526
|
+
is_dev: false,
|
|
4527
|
+
plugin: pluginId
|
|
4528
|
+
});
|
|
4529
|
+
enqueue({
|
|
4530
|
+
mode: "prompt",
|
|
4531
|
+
value: wrapChannelMessage(serverName, content, meta),
|
|
4532
|
+
priority: "next",
|
|
4533
|
+
isMeta: true,
|
|
4534
|
+
origin: { kind: "channel", server: serverName },
|
|
4535
|
+
skipSlashCommands: true
|
|
4536
|
+
});
|
|
4537
|
+
});
|
|
4538
|
+
output.enqueue({
|
|
4539
|
+
type: "control_response",
|
|
4540
|
+
response: {
|
|
4541
|
+
subtype: "success",
|
|
4542
|
+
request_id: requestId,
|
|
4543
|
+
response: undefined
|
|
4544
|
+
}
|
|
4545
|
+
});
|
|
4546
|
+
}
|
|
4547
|
+
function reregisterChannelHandlerAfterReconnect(connection) {
|
|
4548
|
+
if (true)
|
|
4549
|
+
return;
|
|
4550
|
+
if (connection.type !== "connected")
|
|
4551
|
+
return;
|
|
4552
|
+
const gate = gateChannelServer(connection.name, connection.capabilities, connection.config.pluginSource);
|
|
4553
|
+
if (gate.action !== "register")
|
|
4554
|
+
return;
|
|
4555
|
+
const entry = findChannelEntry(connection.name, getAllowedChannels());
|
|
4556
|
+
const pluginId = entry?.kind === "plugin" ? `${entry.name}@${entry.marketplace}` : undefined;
|
|
4557
|
+
logMCPDebug(connection.name, "Channel notifications re-registered after reconnect");
|
|
4558
|
+
connection.client.setNotificationHandler(ChannelMessageNotificationSchema(), async (notification) => {
|
|
4559
|
+
const { content, meta } = notification.params;
|
|
4560
|
+
logMCPDebug(connection.name, `notifications/claude/channel: ${content.slice(0, 80)}`);
|
|
4561
|
+
logEvent("tengu_mcp_channel_message", {
|
|
4562
|
+
content_length: content.length,
|
|
4563
|
+
meta_key_count: Object.keys(meta ?? {}).length,
|
|
4564
|
+
entry_kind: entry?.kind,
|
|
4565
|
+
is_dev: entry?.dev ?? false,
|
|
4566
|
+
plugin: pluginId
|
|
4567
|
+
});
|
|
4568
|
+
enqueue({
|
|
4569
|
+
mode: "prompt",
|
|
4570
|
+
value: wrapChannelMessage(connection.name, content, meta),
|
|
4571
|
+
priority: "next",
|
|
4572
|
+
isMeta: true,
|
|
4573
|
+
origin: { kind: "channel", server: connection.name },
|
|
4574
|
+
skipSlashCommands: true
|
|
4575
|
+
});
|
|
4576
|
+
});
|
|
4577
|
+
}
|
|
4578
|
+
function emitLoadError(message, outputFormat) {
|
|
4579
|
+
if (outputFormat === "stream-json") {
|
|
4580
|
+
const errorResult = {
|
|
4581
|
+
type: "result",
|
|
4582
|
+
subtype: "error_during_execution",
|
|
4583
|
+
duration_ms: 0,
|
|
4584
|
+
duration_api_ms: 0,
|
|
4585
|
+
is_error: true,
|
|
4586
|
+
num_turns: 0,
|
|
4587
|
+
stop_reason: null,
|
|
4588
|
+
session_id: getSessionId(),
|
|
4589
|
+
total_cost_usd: 0,
|
|
4590
|
+
usage: EMPTY_USAGE,
|
|
4591
|
+
modelUsage: {},
|
|
4592
|
+
permission_denials: [],
|
|
4593
|
+
uuid: randomUUID4(),
|
|
4594
|
+
errors: [message]
|
|
4595
|
+
};
|
|
4596
|
+
process.stdout.write(jsonStringify(errorResult) + `
|
|
4597
|
+
`);
|
|
4598
|
+
} else {
|
|
4599
|
+
process.stderr.write(message + `
|
|
4600
|
+
`);
|
|
4601
|
+
}
|
|
4602
|
+
}
|
|
4603
|
+
function removeInterruptedMessage(messages, interruptedUserMessage) {
|
|
4604
|
+
const idx = messages.findIndex((m) => m.uuid === interruptedUserMessage.uuid);
|
|
4605
|
+
if (idx !== -1) {
|
|
4606
|
+
messages.splice(idx, 2);
|
|
4607
|
+
}
|
|
4608
|
+
}
|
|
4609
|
+
async function loadInitialMessages(setAppState, options) {
|
|
4610
|
+
const persistSession = !isSessionPersistenceDisabled();
|
|
4611
|
+
if (options.continue) {
|
|
4612
|
+
try {
|
|
4613
|
+
logEvent("tengu_continue_print", {});
|
|
4614
|
+
const result = await loadConversationForResume(undefined, undefined);
|
|
4615
|
+
if (result) {
|
|
4616
|
+
if (false) {}
|
|
4617
|
+
if (!options.forkSession) {
|
|
4618
|
+
if (result.sessionId) {
|
|
4619
|
+
switchSession(asSessionId(result.sessionId), result.fullPath ? dirname(result.fullPath) : null);
|
|
4620
|
+
if (persistSession) {
|
|
4621
|
+
await resetSessionFilePointer();
|
|
4622
|
+
}
|
|
4623
|
+
}
|
|
4624
|
+
}
|
|
4625
|
+
restoreSessionStateFromLog(result, setAppState);
|
|
4626
|
+
restoreSessionMetadata(options.forkSession ? { ...result, worktreeSession: undefined } : result);
|
|
4627
|
+
if (false) {}
|
|
4628
|
+
return {
|
|
4629
|
+
messages: result.messages,
|
|
4630
|
+
turnInterruptionState: result.turnInterruptionState,
|
|
4631
|
+
agentSetting: result.agentSetting
|
|
4632
|
+
};
|
|
4633
|
+
}
|
|
4634
|
+
} catch (error) {
|
|
4635
|
+
logError(error);
|
|
4636
|
+
gracefulShutdownSync(1);
|
|
4637
|
+
return { messages: [] };
|
|
4638
|
+
}
|
|
4639
|
+
}
|
|
4640
|
+
if (options.teleport) {
|
|
4641
|
+
try {
|
|
4642
|
+
if (!isPolicyAllowed("allow_remote_sessions")) {
|
|
4643
|
+
throw new Error("Remote sessions are disabled by your organization's policy.");
|
|
4644
|
+
}
|
|
4645
|
+
logEvent("tengu_teleport_print", {});
|
|
4646
|
+
if (typeof options.teleport !== "string") {
|
|
4647
|
+
throw new Error("No session ID provided for teleport");
|
|
4648
|
+
}
|
|
4649
|
+
const {
|
|
4650
|
+
checkOutTeleportedSessionBranch,
|
|
4651
|
+
processMessagesForTeleportResume,
|
|
4652
|
+
teleportResumeCodeSession,
|
|
4653
|
+
validateGitState
|
|
4654
|
+
} = await import("./chunk-jkhvm8yk.js");
|
|
4655
|
+
await validateGitState();
|
|
4656
|
+
const teleportResult = await teleportResumeCodeSession(options.teleport);
|
|
4657
|
+
const { branchError } = await checkOutTeleportedSessionBranch(teleportResult.branch);
|
|
4658
|
+
return {
|
|
4659
|
+
messages: processMessagesForTeleportResume(teleportResult.log, branchError)
|
|
4660
|
+
};
|
|
4661
|
+
} catch (error) {
|
|
4662
|
+
logError(error);
|
|
4663
|
+
gracefulShutdownSync(1);
|
|
4664
|
+
return { messages: [] };
|
|
4665
|
+
}
|
|
4666
|
+
}
|
|
4667
|
+
if (options.resume) {
|
|
4668
|
+
try {
|
|
4669
|
+
logEvent("tengu_resume_print", {});
|
|
4670
|
+
const parsedSessionId = parseSessionIdentifier(typeof options.resume === "string" ? options.resume : "");
|
|
4671
|
+
if (!parsedSessionId) {
|
|
4672
|
+
let errorMessage2 = "Error: --resume requires a valid session ID when used with --print. Usage: claude -p --resume <session-id>";
|
|
4673
|
+
if (typeof options.resume === "string") {
|
|
4674
|
+
errorMessage2 += `. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${options.resume}" is not a valid UUID`;
|
|
4675
|
+
}
|
|
4676
|
+
emitLoadError(errorMessage2, options.outputFormat);
|
|
4677
|
+
gracefulShutdownSync(1);
|
|
4678
|
+
return { messages: [] };
|
|
4679
|
+
}
|
|
4680
|
+
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
|
|
4681
|
+
const [, metadata] = await Promise.all([
|
|
4682
|
+
hydrateFromCCRv2InternalEvents(parsedSessionId.sessionId),
|
|
4683
|
+
options.restoredWorkerState
|
|
4684
|
+
]);
|
|
4685
|
+
if (metadata) {
|
|
4686
|
+
setAppState(externalMetadataToAppState(metadata));
|
|
4687
|
+
if (typeof metadata.model === "string") {
|
|
4688
|
+
setMainLoopModelOverride(metadata.model);
|
|
4689
|
+
}
|
|
4690
|
+
}
|
|
4691
|
+
} else if (parsedSessionId.isUrl && parsedSessionId.ingressUrl && isEnvTruthy(process.env.ENABLE_SESSION_PERSISTENCE)) {
|
|
4692
|
+
await hydrateRemoteSession(parsedSessionId.sessionId, parsedSessionId.ingressUrl);
|
|
4693
|
+
}
|
|
4694
|
+
const result = await loadConversationForResume(parsedSessionId.sessionId, parsedSessionId.jsonlFile || undefined);
|
|
4695
|
+
if (!result || result.messages.length === 0) {
|
|
4696
|
+
if (parsedSessionId.isUrl || isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
|
|
4697
|
+
return {
|
|
4698
|
+
messages: await (options.sessionStartHooksPromise ?? processSessionStartHooks("startup"))
|
|
4699
|
+
};
|
|
4700
|
+
} else {
|
|
4701
|
+
emitLoadError(`No conversation found with session ID: ${parsedSessionId.sessionId}`, options.outputFormat);
|
|
4702
|
+
gracefulShutdownSync(1);
|
|
4703
|
+
return { messages: [] };
|
|
4704
|
+
}
|
|
4705
|
+
}
|
|
4706
|
+
if (options.resumeSessionAt) {
|
|
4707
|
+
const index = result.messages.findIndex((m) => m.uuid === options.resumeSessionAt);
|
|
4708
|
+
if (index < 0) {
|
|
4709
|
+
emitLoadError(`No message found with message.uuid of: ${options.resumeSessionAt}`, options.outputFormat);
|
|
4710
|
+
gracefulShutdownSync(1);
|
|
4711
|
+
return { messages: [] };
|
|
4712
|
+
}
|
|
4713
|
+
result.messages = index >= 0 ? result.messages.slice(0, index + 1) : [];
|
|
4714
|
+
}
|
|
4715
|
+
if (false) {}
|
|
4716
|
+
if (!options.forkSession && result.sessionId) {
|
|
4717
|
+
switchSession(asSessionId(result.sessionId), result.fullPath ? dirname(result.fullPath) : null);
|
|
4718
|
+
if (persistSession) {
|
|
4719
|
+
await resetSessionFilePointer();
|
|
4720
|
+
}
|
|
4721
|
+
}
|
|
4722
|
+
restoreSessionStateFromLog(result, setAppState);
|
|
4723
|
+
restoreSessionMetadata(options.forkSession ? { ...result, worktreeSession: undefined } : result);
|
|
4724
|
+
if (false) {}
|
|
4725
|
+
return {
|
|
4726
|
+
messages: result.messages,
|
|
4727
|
+
turnInterruptionState: result.turnInterruptionState,
|
|
4728
|
+
agentSetting: result.agentSetting
|
|
4729
|
+
};
|
|
4730
|
+
} catch (error) {
|
|
4731
|
+
logError(error);
|
|
4732
|
+
const errorMessage2 = error instanceof Error ? `Failed to resume session: ${error.message}` : "Failed to resume session with --print mode";
|
|
4733
|
+
emitLoadError(errorMessage2, options.outputFormat);
|
|
4734
|
+
gracefulShutdownSync(1);
|
|
4735
|
+
return { messages: [] };
|
|
4736
|
+
}
|
|
4737
|
+
}
|
|
4738
|
+
return {
|
|
4739
|
+
messages: await (options.sessionStartHooksPromise ?? processSessionStartHooks("startup"))
|
|
4740
|
+
};
|
|
4741
|
+
}
|
|
4742
|
+
function getStructuredIO(inputPrompt, options) {
|
|
4743
|
+
let inputStream;
|
|
4744
|
+
if (typeof inputPrompt === "string") {
|
|
4745
|
+
if (inputPrompt.trim() !== "") {
|
|
4746
|
+
inputStream = fromArray([
|
|
4747
|
+
jsonStringify({
|
|
4748
|
+
type: "user",
|
|
4749
|
+
content: inputPrompt,
|
|
4750
|
+
uuid: "",
|
|
4751
|
+
session_id: "",
|
|
4752
|
+
message: {
|
|
4753
|
+
role: "user",
|
|
4754
|
+
content: inputPrompt
|
|
4755
|
+
},
|
|
4756
|
+
parent_tool_use_id: null
|
|
4757
|
+
})
|
|
4758
|
+
]);
|
|
4759
|
+
} else {
|
|
4760
|
+
inputStream = fromArray([]);
|
|
4761
|
+
}
|
|
4762
|
+
} else {
|
|
4763
|
+
inputStream = inputPrompt;
|
|
4764
|
+
}
|
|
4765
|
+
return options.sdkUrl ? new RemoteIO(options.sdkUrl, inputStream, options.replayUserMessages) : new StructuredIO(inputStream, options.replayUserMessages);
|
|
4766
|
+
}
|
|
4767
|
+
async function handleOrphanedPermissionResponse({
|
|
4768
|
+
message,
|
|
4769
|
+
setAppState,
|
|
4770
|
+
onEnqueued,
|
|
4771
|
+
handledToolUseIds
|
|
4772
|
+
}) {
|
|
4773
|
+
const responseInner = message.response;
|
|
4774
|
+
if (responseInner?.subtype === "success" && responseInner.response?.toolUseID && typeof responseInner.response.toolUseID === "string") {
|
|
4775
|
+
const permissionResult = responseInner.response;
|
|
4776
|
+
const toolUseID = permissionResult.toolUseID;
|
|
4777
|
+
if (!toolUseID) {
|
|
4778
|
+
return false;
|
|
4779
|
+
}
|
|
4780
|
+
logForDebugging(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${toolUseID} request_id=${responseInner.request_id}`);
|
|
4781
|
+
if (handledToolUseIds.has(toolUseID)) {
|
|
4782
|
+
logForDebugging(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${toolUseID} (already handled)`);
|
|
4783
|
+
return false;
|
|
4784
|
+
}
|
|
4785
|
+
const assistantMessage = await findUnresolvedToolUse(toolUseID);
|
|
4786
|
+
if (!assistantMessage) {
|
|
4787
|
+
logForDebugging(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${toolUseID} (already resolved in transcript)`);
|
|
4788
|
+
return false;
|
|
4789
|
+
}
|
|
4790
|
+
handledToolUseIds.add(toolUseID);
|
|
4791
|
+
logForDebugging(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${toolUseID} messageID=${assistantMessage.message.id}`);
|
|
4792
|
+
enqueue({
|
|
4793
|
+
mode: "orphaned-permission",
|
|
4794
|
+
value: [],
|
|
4795
|
+
orphanedPermission: {
|
|
4796
|
+
permissionResult,
|
|
4797
|
+
assistantMessage
|
|
4798
|
+
}
|
|
4799
|
+
});
|
|
4800
|
+
onEnqueued?.();
|
|
4801
|
+
return true;
|
|
4802
|
+
}
|
|
4803
|
+
return false;
|
|
4804
|
+
}
|
|
4805
|
+
function toScopedConfig(config) {
|
|
4806
|
+
return { ...config, scope: "dynamic" };
|
|
4807
|
+
}
|
|
4808
|
+
async function handleMcpSetServers(servers, sdkState, dynamicState, setAppState) {
|
|
4809
|
+
const { allowed: allowedServers, blocked } = filterMcpServersByPolicy(servers);
|
|
4810
|
+
const policyErrors = {};
|
|
4811
|
+
for (const name of blocked) {
|
|
4812
|
+
policyErrors[name] = "Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)";
|
|
4813
|
+
}
|
|
4814
|
+
const sdkServers = {};
|
|
4815
|
+
const processServers = {};
|
|
4816
|
+
for (const [name, config] of Object.entries(allowedServers)) {
|
|
4817
|
+
if (config.type === "sdk") {
|
|
4818
|
+
sdkServers[name] = config;
|
|
4819
|
+
} else {
|
|
4820
|
+
processServers[name] = config;
|
|
4821
|
+
}
|
|
4822
|
+
}
|
|
4823
|
+
const currentSdkNames = new Set(Object.keys(sdkState.configs));
|
|
4824
|
+
const newSdkNames = new Set(Object.keys(sdkServers));
|
|
4825
|
+
const sdkAdded = [];
|
|
4826
|
+
const sdkRemoved = [];
|
|
4827
|
+
const newSdkConfigs = { ...sdkState.configs };
|
|
4828
|
+
let newSdkClients = [...sdkState.clients];
|
|
4829
|
+
let newSdkTools = [...sdkState.tools];
|
|
4830
|
+
for (const name of currentSdkNames) {
|
|
4831
|
+
if (!newSdkNames.has(name)) {
|
|
4832
|
+
const client = newSdkClients.find((c) => c.name === name);
|
|
4833
|
+
if (client && client.type === "connected") {
|
|
4834
|
+
await client.cleanup();
|
|
4835
|
+
}
|
|
4836
|
+
newSdkClients = newSdkClients.filter((c) => c.name !== name);
|
|
4837
|
+
const prefix = `mcp__${name}__`;
|
|
4838
|
+
newSdkTools = newSdkTools.filter((t) => !t.name.startsWith(prefix));
|
|
4839
|
+
delete newSdkConfigs[name];
|
|
4840
|
+
sdkRemoved.push(name);
|
|
4841
|
+
}
|
|
4842
|
+
}
|
|
4843
|
+
for (const [name, config] of Object.entries(sdkServers)) {
|
|
4844
|
+
if (!currentSdkNames.has(name)) {
|
|
4845
|
+
newSdkConfigs[name] = config;
|
|
4846
|
+
const pendingClient = {
|
|
4847
|
+
type: "pending",
|
|
4848
|
+
name,
|
|
4849
|
+
config: { ...config, scope: "dynamic" }
|
|
4850
|
+
};
|
|
4851
|
+
newSdkClients = [...newSdkClients, pendingClient];
|
|
4852
|
+
sdkAdded.push(name);
|
|
4853
|
+
}
|
|
4854
|
+
}
|
|
4855
|
+
const processResult = await reconcileMcpServers(processServers, dynamicState, setAppState);
|
|
4856
|
+
return {
|
|
4857
|
+
response: {
|
|
4858
|
+
added: [...sdkAdded, ...processResult.response.added],
|
|
4859
|
+
removed: [...sdkRemoved, ...processResult.response.removed],
|
|
4860
|
+
errors: { ...policyErrors, ...processResult.response.errors }
|
|
4861
|
+
},
|
|
4862
|
+
newSdkState: {
|
|
4863
|
+
configs: newSdkConfigs,
|
|
4864
|
+
clients: newSdkClients,
|
|
4865
|
+
tools: newSdkTools
|
|
4866
|
+
},
|
|
4867
|
+
newDynamicState: processResult.newState,
|
|
4868
|
+
sdkServersChanged: sdkAdded.length > 0 || sdkRemoved.length > 0
|
|
4869
|
+
};
|
|
4870
|
+
}
|
|
4871
|
+
async function reconcileMcpServers(desiredConfigs, currentState, setAppState) {
|
|
4872
|
+
const currentNames = new Set(Object.keys(currentState.configs));
|
|
4873
|
+
const desiredNames = new Set(Object.keys(desiredConfigs));
|
|
4874
|
+
const toRemove = [...currentNames].filter((n) => !desiredNames.has(n));
|
|
4875
|
+
const toAdd = [...desiredNames].filter((n) => !currentNames.has(n));
|
|
4876
|
+
const toCheck = [...currentNames].filter((n) => desiredNames.has(n));
|
|
4877
|
+
const toReplace = toCheck.filter((name) => {
|
|
4878
|
+
const currentConfig = currentState.configs[name];
|
|
4879
|
+
const desiredConfigRaw = desiredConfigs[name];
|
|
4880
|
+
if (!currentConfig || !desiredConfigRaw)
|
|
4881
|
+
return true;
|
|
4882
|
+
const desiredConfig = toScopedConfig(desiredConfigRaw);
|
|
4883
|
+
return !areMcpConfigsEqual(currentConfig, desiredConfig);
|
|
4884
|
+
});
|
|
4885
|
+
const removed = [];
|
|
4886
|
+
const added = [];
|
|
4887
|
+
const errors = {};
|
|
4888
|
+
let newClients = [...currentState.clients];
|
|
4889
|
+
let newTools = [...currentState.tools];
|
|
4890
|
+
for (const name of [...toRemove, ...toReplace]) {
|
|
4891
|
+
const client = newClients.find((c) => c.name === name);
|
|
4892
|
+
const config = currentState.configs[name];
|
|
4893
|
+
if (client && config) {
|
|
4894
|
+
if (client.type === "connected") {
|
|
4895
|
+
try {
|
|
4896
|
+
await client.cleanup();
|
|
4897
|
+
} catch (e) {
|
|
4898
|
+
logError(e);
|
|
4899
|
+
}
|
|
4900
|
+
}
|
|
4901
|
+
await clearServerCache(name, config);
|
|
4902
|
+
}
|
|
4903
|
+
const prefix = `mcp__${name}__`;
|
|
4904
|
+
newTools = newTools.filter((t) => !t.name.startsWith(prefix));
|
|
4905
|
+
newClients = newClients.filter((c) => c.name !== name);
|
|
4906
|
+
if (toRemove.includes(name)) {
|
|
4907
|
+
removed.push(name);
|
|
4908
|
+
}
|
|
4909
|
+
}
|
|
4910
|
+
for (const name of [...toAdd, ...toReplace]) {
|
|
4911
|
+
const config = desiredConfigs[name];
|
|
4912
|
+
if (!config)
|
|
4913
|
+
continue;
|
|
4914
|
+
const scopedConfig = toScopedConfig(config);
|
|
4915
|
+
if (config.type === "sdk") {
|
|
4916
|
+
added.push(name);
|
|
4917
|
+
continue;
|
|
4918
|
+
}
|
|
4919
|
+
try {
|
|
4920
|
+
const client = await connectToServer(name, scopedConfig);
|
|
4921
|
+
newClients.push(client);
|
|
4922
|
+
if (client.type === "connected") {
|
|
4923
|
+
const serverTools = await fetchToolsForClient(client);
|
|
4924
|
+
newTools.push(...serverTools);
|
|
4925
|
+
} else if (client.type === "failed") {
|
|
4926
|
+
errors[name] = client.error || "Connection failed";
|
|
4927
|
+
}
|
|
4928
|
+
added.push(name);
|
|
4929
|
+
} catch (e) {
|
|
4930
|
+
const err = toError(e);
|
|
4931
|
+
errors[name] = err.message;
|
|
4932
|
+
logError(err);
|
|
4933
|
+
}
|
|
4934
|
+
}
|
|
4935
|
+
const newConfigs = {};
|
|
4936
|
+
for (const name of desiredNames) {
|
|
4937
|
+
const config = desiredConfigs[name];
|
|
4938
|
+
if (config) {
|
|
4939
|
+
newConfigs[name] = toScopedConfig(config);
|
|
4940
|
+
}
|
|
4941
|
+
}
|
|
4942
|
+
const newState = {
|
|
4943
|
+
clients: newClients,
|
|
4944
|
+
tools: newTools,
|
|
4945
|
+
configs: newConfigs
|
|
4946
|
+
};
|
|
4947
|
+
setAppState((prev) => {
|
|
4948
|
+
const allDynamicServerNames = new Set([
|
|
4949
|
+
...Object.keys(currentState.configs),
|
|
4950
|
+
...Object.keys(newConfigs)
|
|
4951
|
+
]);
|
|
4952
|
+
const nonDynamicTools = prev.mcp.tools.filter((t) => {
|
|
4953
|
+
for (const serverName of allDynamicServerNames) {
|
|
4954
|
+
if (t.name.startsWith(`mcp__${serverName}__`)) {
|
|
4955
|
+
return false;
|
|
4956
|
+
}
|
|
4957
|
+
}
|
|
4958
|
+
return true;
|
|
4959
|
+
});
|
|
4960
|
+
const nonDynamicClients = prev.mcp.clients.filter((c) => {
|
|
4961
|
+
return !allDynamicServerNames.has(c.name);
|
|
4962
|
+
});
|
|
4963
|
+
return {
|
|
4964
|
+
...prev,
|
|
4965
|
+
mcp: {
|
|
4966
|
+
...prev.mcp,
|
|
4967
|
+
tools: [...nonDynamicTools, ...newTools],
|
|
4968
|
+
clients: [...nonDynamicClients, ...newClients]
|
|
4969
|
+
}
|
|
4970
|
+
};
|
|
4971
|
+
});
|
|
4972
|
+
return {
|
|
4973
|
+
response: { added, removed, errors },
|
|
4974
|
+
newState
|
|
4975
|
+
};
|
|
4976
|
+
}
|
|
4977
|
+
export {
|
|
4978
|
+
runHeadless,
|
|
4979
|
+
removeInterruptedMessage,
|
|
4980
|
+
reconcileMcpServers,
|
|
4981
|
+
joinPromptValues,
|
|
4982
|
+
handleOrphanedPermissionResponse,
|
|
4983
|
+
handleMcpSetServers,
|
|
4984
|
+
getCanUseToolFn,
|
|
4985
|
+
createCanUseToolWithPermissionPrompt,
|
|
4986
|
+
canBatchWith
|
|
4987
|
+
};
|