@qitqode/qitqode-android-arm64 0.1.26 → 0.1.28
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/bundle/{chunk-3bb7y9pq.js → chunk-04h4afhf.js} +2 -2
- package/bundle/{chunk-x3z8q0ep.js → chunk-04tw0r4s.js} +1 -1
- package/bundle/chunk-066eeq5q.js +2 -0
- package/bundle/chunk-07ws99b1.js +2 -0
- package/bundle/chunk-09c4ngag.js +2 -0
- package/bundle/{chunk-se195e52.js → chunk-09kba1hg.js} +2 -2
- package/bundle/{chunk-pfn1db1m.js → chunk-0a0vat1h.js} +2 -2
- package/bundle/chunk-0jgst767.js +2 -0
- package/bundle/chunk-0nj8axbw.js +7610 -0
- package/bundle/chunk-0psrr9vp.js +2 -0
- package/bundle/{chunk-z2q3mg73.js → chunk-12bssxd4.js} +2 -2
- package/bundle/{chunk-6vb26adv.js → chunk-13hz1kvh.js} +1 -1
- package/bundle/{chunk-hz1hd1bd.js → chunk-1bhvt33f.js} +1 -1
- package/bundle/{chunk-49tqzsy0.js → chunk-1dwcga8g.js} +2 -2
- package/bundle/chunk-1etdhr36.js +11 -0
- package/bundle/{chunk-9qtf8khv.js → chunk-1fbeendk.js} +1 -1
- package/bundle/chunk-1j73cnvz.js +2 -0
- package/bundle/{chunk-tyy4gx61.js → chunk-1m2e2w1q.js} +1 -1
- package/bundle/{chunk-eqaym8gm.js → chunk-1qshjfzm.js} +1 -1
- package/bundle/{chunk-d31yrcrn.js → chunk-1rp1cvmc.js} +2 -2
- package/bundle/{chunk-vx837ete.js → chunk-1sgby720.js} +1 -1
- package/bundle/{chunk-atbm0pnt.js → chunk-1t6bvbgy.js} +2 -2
- package/bundle/{chunk-wefjbwv6.js → chunk-1t9jne14.js} +1 -1
- package/bundle/chunk-1yddn03z.js +2 -0
- package/bundle/{chunk-n07rsssz.js → chunk-24xc0dvv.js} +1 -1
- package/bundle/{chunk-qngs31yf.js → chunk-26nfphsg.js} +1 -1
- package/bundle/{chunk-kkdgzeva.js → chunk-27yxgy03.js} +2 -2
- package/bundle/{chunk-f416n3mp.js → chunk-288hw03f.js} +2 -2
- package/bundle/{chunk-qan3kwbv.js → chunk-2abdrqrx.js} +1 -1
- package/bundle/{chunk-b79k456s.js → chunk-2ahqhh4z.js} +1 -1
- package/bundle/{chunk-fx7w497c.js → chunk-2bn4b42t.js} +1 -1
- package/bundle/{chunk-4k70wrhf.js → chunk-2dzk5txw.js} +1 -1
- package/bundle/{chunk-56qm8xpt.js → chunk-2jmxt3fb.js} +1 -1
- package/bundle/{chunk-r1yqmd4y.js → chunk-2km50rd3.js} +1 -1
- package/bundle/{chunk-j87bvp1b.js → chunk-2q96x1t5.js} +1 -1
- package/bundle/{chunk-77e1wh0j.js → chunk-2rs39vj2.js} +2 -2
- package/bundle/{chunk-qb5qemtp.js → chunk-2tnarng3.js} +1 -1
- package/bundle/{chunk-cr06m77n.js → chunk-2vepzgek.js} +2 -2
- package/bundle/{chunk-k7h6tfzj.js → chunk-371r2111.js} +1 -1
- package/bundle/{chunk-5jtd006j.js → chunk-37n34pzd.js} +2 -2
- package/bundle/chunk-37s5hwtc.js +2 -0
- package/bundle/chunk-38g8yzw0.js +2 -0
- package/bundle/chunk-3bkd0ar3.js +2 -0
- package/bundle/{chunk-6nkcfncg.js → chunk-3bmzjznz.js} +1 -1
- package/bundle/{chunk-2jn2hd12.js → chunk-3dvd1bb6.js} +2 -2
- package/bundle/chunk-3fx5jda0.js +2 -0
- package/bundle/{chunk-cn10hn58.js → chunk-3j9hedmx.js} +1 -1
- package/bundle/{chunk-7n2kpqh5.js → chunk-3nwve06r.js} +1 -1
- package/bundle/{chunk-ptf09vmp.js → chunk-3nyqh1d6.js} +1 -1
- package/bundle/chunk-457y2816.js +2 -0
- package/bundle/{chunk-6s2f5sv4.js → chunk-48fvrggx.js} +1 -1
- package/bundle/chunk-4amgp4yd.js +3 -0
- package/bundle/{chunk-f3c9667r.js → chunk-4qqkqrn9.js} +2 -2
- package/bundle/chunk-4sk0rmw3.js +28 -0
- package/bundle/chunk-4sz3jbc5.js +2 -0
- package/bundle/{chunk-1n4w8dya.js → chunk-4tbwha3m.js} +2 -2
- package/bundle/{chunk-hb4d06q0.js → chunk-4yawrap2.js} +2 -2
- package/bundle/{chunk-dv5zf5gz.js → chunk-5a5t01ka.js} +1 -1
- package/bundle/{chunk-880msfsd.js → chunk-5fgx6fa4.js} +1 -1
- package/bundle/{chunk-t1vtdgd6.js → chunk-5fz8tph5.js} +1 -1
- package/bundle/{chunk-ppvmy940.js → chunk-5g8108nf.js} +2 -2
- package/bundle/{chunk-e57d1he9.js → chunk-5qam3c8r.js} +1 -1
- package/bundle/{chunk-1qbm1k9y.js → chunk-5syxjhg3.js} +3 -3
- package/bundle/chunk-612f97vv.js +616 -0
- package/bundle/{chunk-fffj9447.js → chunk-61c62e5s.js} +2 -2
- package/bundle/{chunk-kp84yba1.js → chunk-61zpnwv6.js} +1 -1
- package/bundle/chunk-6d9wsjxm.js +2 -0
- package/bundle/{chunk-f6y7a5w3.js → chunk-6fp8a9ek.js} +2 -2
- package/bundle/{chunk-st74db4c.js → chunk-6hv59ere.js} +1 -1
- package/bundle/{chunk-56pwz1kk.js → chunk-6nbzdb0r.js} +1 -1
- package/bundle/{chunk-8ahpk8td.js → chunk-6p7yg5sr.js} +1 -1
- package/bundle/chunk-6q87abbr.js +2 -0
- package/bundle/{chunk-kfk1zqc1.js → chunk-6qy1ghrx.js} +1 -1
- package/bundle/chunk-730a2d1k.js +2 -0
- package/bundle/chunk-7bd0x9vf.js +2 -0
- package/bundle/chunk-7czkntef.js +2 -0
- package/bundle/chunk-7ex57nyh.js +2 -0
- package/bundle/chunk-7gpczxbh.js +2 -0
- package/bundle/chunk-7j0bgeh2.js +2 -0
- package/bundle/{chunk-w3pzv615.js → chunk-7jbz3dgt.js} +1 -1
- package/bundle/{chunk-0ndvy0nh.js → chunk-7ppd2phw.js} +2 -2
- package/bundle/chunk-7py443fe.js +2 -0
- package/bundle/{chunk-ykxde207.js → chunk-7yrhe3xq.js} +2 -2
- package/bundle/chunk-8815p61h.js +2 -0
- package/bundle/{chunk-3s0d17xe.js → chunk-89q1y7tc.js} +1 -1
- package/bundle/{chunk-9wm41z2f.js → chunk-89v6dgpp.js} +2 -2
- package/bundle/{chunk-njzpswgt.js → chunk-8tc8x27z.js} +7 -7
- package/bundle/chunk-90q5sae0.js +2 -0
- package/bundle/chunk-92d9469t.js +2 -0
- package/bundle/chunk-9grvepmd.js +2 -0
- package/bundle/chunk-9hrh15p2.js +2 -0
- package/bundle/{chunk-t7tstr83.js → chunk-9j1qqdr2.js} +1 -1
- package/bundle/{chunk-58gp7wbg.js → chunk-a1p2f16h.js} +2 -2
- package/bundle/{chunk-fk8cctjy.js → chunk-a1pw9r6f.js} +2 -2
- package/bundle/chunk-a2qz9m10.js +2 -0
- package/bundle/chunk-a7cxf56j.js +2 -0
- package/bundle/{chunk-0w5npkgr.js → chunk-ab6cabxh.js} +1 -1
- package/bundle/{chunk-sdsggxm4.js → chunk-anjg3mwn.js} +2 -2
- package/bundle/chunk-av6ezvxm.js +2 -0
- package/bundle/{chunk-s2za1y84.js → chunk-aztre27e.js} +1 -1
- package/bundle/{chunk-xdv9xt0y.js → chunk-b0syck9r.js} +2 -2
- package/bundle/{chunk-s1h0k1yj.js → chunk-b3dqcbsc.js} +1 -1
- package/bundle/{chunk-ewvgbg68.js → chunk-b8tw709r.js} +1 -1
- package/bundle/{chunk-7fmy4cvn.js → chunk-b9za12y1.js} +1 -1
- package/bundle/{chunk-hybq019j.js → chunk-be216spx.js} +2 -2
- package/bundle/chunk-beksar7w.js +2 -0
- package/bundle/chunk-bg66rqrx.js +2 -0
- package/bundle/chunk-bkbngcvc.js +2 -0
- package/bundle/{chunk-32zrch7h.js → chunk-bss414qz.js} +1 -1
- package/bundle/{chunk-vthm5q05.js → chunk-btneef3z.js} +1 -1
- package/bundle/{chunk-5mec6cde.js → chunk-btz9jvec.js} +1 -1
- package/bundle/{chunk-6nk3wx6f.js → chunk-bvkq0a5q.js} +1 -1
- package/bundle/{chunk-kn318ev4.js → chunk-c01z3cvg.js} +2 -2
- package/bundle/{chunk-z559gc3n.js → chunk-c5e6sk9c.js} +1 -1
- package/bundle/{chunk-453wpzg6.js → chunk-c8k32724.js} +1 -1
- package/bundle/{chunk-2q76qax6.js → chunk-cafzcmrg.js} +2 -2
- package/bundle/{chunk-g6dgc5af.js → chunk-cdhmc0t0.js} +1 -1
- package/bundle/{chunk-xc3fadkh.js → chunk-chmrvbbj.js} +1 -1
- package/bundle/{chunk-s86fj82v.js → chunk-cmbxrgyx.js} +2 -2
- package/bundle/{chunk-14ag9ea0.js → chunk-ct48575c.js} +1 -1
- package/bundle/{chunk-5ymj2q6j.js → chunk-cvdxgsq1.js} +2 -2
- package/bundle/{chunk-g8wvr7a1.js → chunk-cwqd48xt.js} +2 -2
- package/bundle/chunk-cy9s1ma5.js +2 -0
- package/bundle/chunk-cydewa1c.js +2 -0
- package/bundle/{chunk-fxb6vjcb.js → chunk-d5bxan80.js} +2 -2
- package/bundle/{chunk-p0k4sv89.js → chunk-d6r4xwtg.js} +4 -4
- package/bundle/chunk-d7qscj5p.js +2 -0
- package/bundle/{chunk-cyjzqa5p.js → chunk-dafbntks.js} +204 -202
- package/bundle/{chunk-dazye86e.js → chunk-df6a167w.js} +2 -2
- package/bundle/{chunk-rf625fxx.js → chunk-dfnv7vkn.js} +1 -1
- package/bundle/{chunk-06x1p3t4.js → chunk-dhjp0zx2.js} +1 -1
- package/bundle/chunk-dpkynwgm.js +3 -0
- package/bundle/{chunk-xak2r993.js → chunk-dq9kpj4a.js} +2 -2
- package/bundle/{chunk-7tbvr236.js → chunk-drs1gv2b.js} +1 -1
- package/bundle/{chunk-xqxpjbqk.js → chunk-ds69qc8b.js} +1 -1
- package/bundle/chunk-dvk2wwjj.js +2 -0
- package/bundle/{chunk-vpqd0t8a.js → chunk-e0152ayv.js} +2 -2
- package/bundle/chunk-e0jy9qxd.js +2 -0
- package/bundle/{chunk-t6xm49ea.js → chunk-eb9mytjq.js} +1 -1
- package/bundle/{chunk-fk3praj7.js → chunk-ebcv65e3.js} +1 -1
- package/bundle/{chunk-08y06vgt.js → chunk-ebrt1me3.js} +2 -2
- package/bundle/{chunk-hjratj6g.js → chunk-ecn8gbtz.js} +1 -1
- package/bundle/chunk-emtebxvs.js +3 -0
- package/bundle/chunk-erg0ske8.js +2 -0
- package/bundle/{chunk-txty44v2.js → chunk-f2tdfry8.js} +2 -2
- package/bundle/{chunk-afhg3w2j.js → chunk-f45tp3e3.js} +1 -1
- package/bundle/chunk-f72pppr7.js +2 -0
- package/bundle/{chunk-pnj8s20t.js → chunk-fff3151r.js} +1 -1
- package/bundle/{chunk-0mekr486.js → chunk-fkgv2hqd.js} +1 -1
- package/bundle/{chunk-zvsafnkp.js → chunk-fnbpap62.js} +2 -2
- package/bundle/{chunk-4nck07pc.js → chunk-fzna6jdj.js} +2 -2
- package/bundle/{chunk-wg5dv21f.js → chunk-g16zb3y1.js} +2 -2
- package/bundle/{chunk-5yaahmjb.js → chunk-g1dwbvkg.js} +1 -1
- package/bundle/{chunk-1xkwm21b.js → chunk-g3dhsmbt.js} +3 -3
- package/bundle/{chunk-c0k8j498.js → chunk-g7rjtehn.js} +1 -1
- package/bundle/{chunk-e58pdw5k.js → chunk-gf0pdgjs.js} +2 -2
- package/bundle/{chunk-0m2tj2h9.js → chunk-ggqst87g.js} +1 -1
- package/bundle/{chunk-9zrwbxx0.js → chunk-gj7y56y6.js} +2 -2
- package/bundle/chunk-gk34kh8p.js +2 -0
- package/bundle/{chunk-1yx4jesj.js → chunk-gm85xefs.js} +1 -1
- package/bundle/chunk-gn50xqbd.js +2 -0
- package/bundle/{chunk-wmrq9qqf.js → chunk-gsez13bg.js} +1 -1
- package/bundle/{chunk-s54c8fpf.js → chunk-h0rpmne5.js} +1 -1
- package/bundle/chunk-h602h2gx.js +2 -0
- package/bundle/chunk-h7s2w1e2.js +2 -0
- package/bundle/{chunk-91khd3fq.js → chunk-h9pvnp5c.js} +1 -1
- package/bundle/{chunk-07net7s8.js → chunk-hj5y7fvk.js} +1 -1
- package/bundle/{chunk-qmhcbdkg.js → chunk-hk698g9e.js} +2 -2
- package/bundle/chunk-hmv2cdnz.js +2 -0
- package/bundle/chunk-hnb8v476.js +2 -0
- package/bundle/chunk-ht81ensf.js +2 -0
- package/bundle/chunk-hxgs0d4t.js +2 -0
- package/bundle/chunk-j59ktwny.js +2 -0
- package/bundle/{chunk-3zn71txs.js → chunk-j5kb0y1m.js} +1 -1
- package/bundle/{chunk-qpv4438m.js → chunk-j6emx6jn.js} +2 -2
- package/bundle/{chunk-x36jhtex.js → chunk-j8efst22.js} +1 -1
- package/bundle/{chunk-z4ae6jmb.js → chunk-j9pcnkkq.js} +3 -3
- package/bundle/{chunk-y2ch07yv.js → chunk-jje0srjq.js} +2 -2
- package/bundle/{chunk-nxjbbq5h.js → chunk-jm1ptn8n.js} +1 -1
- package/bundle/chunk-jmz2mq3t.js +2 -0
- package/bundle/chunk-jr907144.js +2 -0
- package/bundle/{chunk-eq33vmze.js → chunk-jx27xrk1.js} +2 -2
- package/bundle/{chunk-m7txgh5w.js → chunk-k2tamnfv.js} +1 -1
- package/bundle/chunk-k309zez0.js +3 -0
- package/bundle/chunk-k3epfxmq.js +2 -0
- package/bundle/chunk-k3fn3yed.js +2 -0
- package/bundle/chunk-k5q52wdq.js +2 -0
- package/bundle/chunk-k7g3h9tn.js +3 -0
- package/bundle/{chunk-wg42cxrw.js → chunk-k7gq9bra.js} +1 -1
- package/bundle/{chunk-vyjsng14.js → chunk-kb6w3wbd.js} +1 -1
- package/bundle/{chunk-qm9ezq93.js → chunk-kdcnder5.js} +1 -1
- package/bundle/{chunk-28vnspd4.js → chunk-kfsb2stm.js} +1 -1
- package/bundle/chunk-kfsn9c7m.js +2 -0
- package/bundle/{chunk-kvz0vzsn.js → chunk-knpt9n8f.js} +1 -1
- package/bundle/chunk-kpw6nghv.js +2 -0
- package/bundle/{chunk-cbmw8fy2.js → chunk-kqn9h2gk.js} +1 -1
- package/bundle/chunk-krhkrca9.js +2 -0
- package/bundle/{chunk-kbyk7hyn.js → chunk-m02zt1a3.js} +2 -2
- package/bundle/{chunk-yqtfvgrp.js → chunk-m1h5a4vg.js} +1 -1
- package/bundle/chunk-m5ghbt5y.js +2 -0
- package/bundle/{chunk-7ryv0f5h.js → chunk-m612agnk.js} +1 -1
- package/bundle/{chunk-05amr7y9.js → chunk-m67tcnk4.js} +1 -1
- package/bundle/{chunk-2sy1wx99.js → chunk-m8yv4sd2.js} +1 -1
- package/bundle/{chunk-613kegcn.js → chunk-mgk9sh16.js} +1 -1
- package/bundle/{chunk-7e1aw8rw.js → chunk-mk6cddvd.js} +1 -1
- package/bundle/chunk-mn41f9qv.js +2 -0
- package/bundle/chunk-mqjf9sbm.js +2 -0
- package/bundle/{chunk-n10atvac.js → chunk-msegx0t7.js} +1 -1
- package/bundle/{chunk-8bzwgcjb.js → chunk-mskwkcgj.js} +1 -1
- package/bundle/chunk-my7mn79h.js +9 -0
- package/bundle/{chunk-7rxsj310.js → chunk-n0mygdfp.js} +2 -2
- package/bundle/chunk-n5gwrrbb.js +2 -0
- package/bundle/{chunk-1xpx1t40.js → chunk-n8h6x2en.js} +2 -2
- package/bundle/chunk-nfjhem1c.js +2 -0
- package/bundle/{chunk-j0ftbmex.js → chunk-ngchsw2g.js} +2 -2
- package/bundle/{chunk-3rgct4bd.js → chunk-nj4d554m.js} +1 -1
- package/bundle/{chunk-w4hbw37v.js → chunk-nt4e3em9.js} +1 -1
- package/bundle/chunk-nxyyn2ra.js +2 -0
- package/bundle/{chunk-md7vpe1e.js → chunk-nzehfpxp.js} +1 -1
- package/bundle/chunk-p5tceb4k.js +2 -0
- package/bundle/{chunk-3w64fpwn.js → chunk-p68rwmhc.js} +2 -2
- package/bundle/chunk-pdzpfkt0.js +3 -0
- package/bundle/{chunk-nszqy06d.js → chunk-pekm54ce.js} +1 -1
- package/bundle/{chunk-tedrfa7d.js → chunk-phxrg7aw.js} +2 -2
- package/bundle/{chunk-81engf0t.js → chunk-ppfjf7qx.js} +1 -1
- package/bundle/{chunk-41ftye7w.js → chunk-pxtqqmkc.js} +1 -1
- package/bundle/{chunk-s5krbdvd.js → chunk-q1v2pytx.js} +1 -1
- package/bundle/{chunk-w01gjnty.js → chunk-q6ztpfcs.js} +2 -2
- package/bundle/{chunk-z2m09m4w.js → chunk-qc1w4b12.js} +1 -1
- package/bundle/{chunk-yvj021eg.js → chunk-qhc90p4a.js} +2 -2
- package/bundle/chunk-qjgm3e2p.js +2 -0
- package/bundle/{chunk-qkwhgfjt.js → chunk-qjjch1zt.js} +2 -2
- package/bundle/{chunk-f3rrd2p6.js → chunk-qjn86fc0.js} +1 -1
- package/bundle/{chunk-qq71akpw.js → chunk-qrey2gwb.js} +2 -2
- package/bundle/{chunk-pjbbdm96.js → chunk-qv2s39dv.js} +2 -2
- package/bundle/{chunk-2yb59jwr.js → chunk-qvxvc2c2.js} +1 -1
- package/bundle/{chunk-ygwe0vf1.js → chunk-rmr38x2f.js} +2 -2
- package/bundle/chunk-s07j8hfy.js +2 -0
- package/bundle/chunk-s1cnzvb2.js +2 -0
- package/bundle/{chunk-01gwb793.js → chunk-s3yna2wm.js} +1 -1
- package/bundle/{chunk-0vqrakhw.js → chunk-s6bar2f9.js} +1 -1
- package/bundle/chunk-sbyey0qb.js +2 -0
- package/bundle/{chunk-ze00x1xb.js → chunk-scnz207s.js} +2 -2
- package/bundle/{chunk-xdwej3ae.js → chunk-scsf8r98.js} +1 -1
- package/bundle/{chunk-xcs2jbz9.js → chunk-sermjas1.js} +1 -1
- package/bundle/chunk-sj5v361q.js +2 -0
- package/bundle/{chunk-6wdwwpsc.js → chunk-smt14yjb.js} +2 -2
- package/bundle/{chunk-ynfbz3sz.js → chunk-snm5q21k.js} +2 -2
- package/bundle/{chunk-4920vf6a.js → chunk-srh4xvsj.js} +1 -1
- package/bundle/{chunk-g7vahvkz.js → chunk-szr0f7k2.js} +1 -1
- package/bundle/{chunk-vw673y0t.js → chunk-t12xrrfr.js} +2 -2
- package/bundle/{chunk-fvy5w4dh.js → chunk-t22jbw8x.js} +1 -1
- package/bundle/{chunk-hkmb3zer.js → chunk-t2tgz0rc.js} +2 -2
- package/bundle/{chunk-6fpfr8tk.js → chunk-tj78jsp9.js} +1 -1
- package/bundle/chunk-tpndnprb.js +2 -0
- package/bundle/{chunk-jdkxeqw5.js → chunk-tr8sf0dk.js} +1 -1
- package/bundle/{chunk-hyckncza.js → chunk-v2zp22r3.js} +2 -2
- package/bundle/{chunk-0cehm5fn.js → chunk-v4xcysh0.js} +1 -1
- package/bundle/{chunk-7qxn24qa.js → chunk-v965rsr8.js} +2 -2
- package/bundle/{chunk-0304b7xg.js → chunk-va316nee.js} +1 -1
- package/bundle/{chunk-6h2faxs9.js → chunk-vg2fmyje.js} +2 -2
- package/bundle/{chunk-yt1yk4j1.js → chunk-vj62pc0h.js} +1 -1
- package/bundle/{chunk-hk8j5ht8.js → chunk-vn7nkrqb.js} +2 -2
- package/bundle/chunk-vwxfgea7.js +2 -0
- package/bundle/chunk-w0kgcz1t.js +2 -0
- package/bundle/{chunk-zjvzc0my.js → chunk-w87a3mzm.js} +1 -1
- package/bundle/chunk-w9vh7rhg.js +2 -0
- package/bundle/{chunk-9p83me3p.js → chunk-whxjkz9a.js} +2 -2
- package/bundle/chunk-wksczmes.js +2 -0
- package/bundle/{chunk-2kdn66xt.js → chunk-wnqwb6fd.js} +1 -1
- package/bundle/chunk-wrfvqp2w.js +2 -0
- package/bundle/chunk-wsxta33r.js +2 -0
- package/bundle/{chunk-rvrjw0fy.js → chunk-wsy0m70r.js} +1 -1
- package/bundle/{chunk-w2gpgapp.js → chunk-wy46mbwt.js} +1 -1
- package/bundle/{chunk-cqhpbfcn.js → chunk-wz0zcddf.js} +3 -3
- package/bundle/{chunk-q2exgz82.js → chunk-x067eetw.js} +1 -1
- package/bundle/{chunk-d2n09yvh.js → chunk-x1rx6fm7.js} +2 -2
- package/bundle/{chunk-j7zs1yg2.js → chunk-x7ers083.js} +1 -1
- package/bundle/{chunk-admgf65a.js → chunk-x9s04nze.js} +1 -1
- package/bundle/{chunk-fkat2pw6.js → chunk-xc5044tm.js} +1 -1
- package/bundle/chunk-xck0sq3k.js +2 -0
- package/bundle/chunk-xjyhtm8r.js +2 -0
- package/bundle/{chunk-rs0nx844.js → chunk-xpc2zgj7.js} +2 -2
- package/bundle/{chunk-54pk7nna.js → chunk-xrxyrr00.js} +1 -1
- package/bundle/{chunk-zna6neq5.js → chunk-xs3xtz6x.js} +1 -1
- package/bundle/{chunk-kpnfndkg.js → chunk-xvfpzmrf.js} +1 -1
- package/bundle/{chunk-crap29f6.js → chunk-xxbqhg9n.js} +1 -1
- package/bundle/{chunk-gaxbbxk6.js → chunk-y062spw2.js} +1 -1
- package/bundle/{chunk-bse8p94q.js → chunk-y2v09y71.js} +1 -1
- package/bundle/{chunk-jzcz92pq.js → chunk-y88xh6w3.js} +2 -2
- package/bundle/{chunk-g4qwkcdv.js → chunk-yajd975f.js} +1 -1
- package/bundle/chunk-yc1jk3rm.js +2 -0
- package/bundle/{chunk-5dm3p5r6.js → chunk-ydp0q1hk.js} +1 -1
- package/bundle/{chunk-gxa2r4zc.js → chunk-yfkvjphe.js} +1 -1
- package/bundle/chunk-ygc5qegv.js +2 -0
- package/bundle/{chunk-kbg3k1az.js → chunk-yhk7d1j0.js} +1 -1
- package/bundle/chunk-yjqmzm51.js +2 -0
- package/bundle/{chunk-49ypxzfx.js → chunk-yjtdgcq5.js} +1 -1
- package/bundle/{chunk-mg239rc3.js → chunk-yp0a8q29.js} +3 -3
- package/bundle/{chunk-p31yg62z.js → chunk-yq3m8190.js} +2 -2
- package/bundle/{chunk-rze20q68.js → chunk-yt3f3j35.js} +1 -1
- package/bundle/{chunk-tfggzzqw.js → chunk-ywkvq7zb.js} +1 -1
- package/bundle/{chunk-z3hj5bfd.js → chunk-z37aqajx.js} +2 -2
- package/bundle/chunk-z4z8hk7e.js +2 -0
- package/bundle/{chunk-vy9xre57.js → chunk-z6dnv8g5.js} +1 -1
- package/bundle/chunk-z7y9pdj7.js +2 -0
- package/bundle/chunk-z8g819cz.js +2 -0
- package/bundle/{chunk-h56jxxvj.js → chunk-z8v2tsz2.js} +1 -1
- package/bundle/{chunk-vztxv9dj.js → chunk-zb0me4kk.js} +1 -1
- package/bundle/{chunk-7ez3ye6e.js → chunk-zcm2jdr5.js} +1 -1
- package/bundle/chunk-zqv7fx25.js +2 -0
- package/bundle/chunk-zt1nbwmm.js +2 -0
- package/bundle/{chunk-fd9zrmhr.js → chunk-ztc3gm8y.js} +2 -2
- package/bundle/chunk-zw0yh3dv.js +2 -0
- package/bundle/{chunk-x3931we7.js → chunk-zyhdxggp.js} +2 -2
- package/bundle/index.js +3 -3
- package/bundle/parser.worker.js +2 -2
- package/bundle/qffi.node +0 -0
- package/bundle/worker.js +1 -1
- package/package.json +1 -1
- package/bundle/chunk-09ecxdmd.js +0 -2
- package/bundle/chunk-0jaj2g7x.js +0 -2
- package/bundle/chunk-0nr2925m.js +0 -2
- package/bundle/chunk-0wbq1y92.js +0 -2
- package/bundle/chunk-12pxszgn.js +0 -2
- package/bundle/chunk-1337582e.js +0 -2
- package/bundle/chunk-182jf8fz.js +0 -2
- package/bundle/chunk-1ht3zcsh.js +0 -2
- package/bundle/chunk-25zkavr0.js +0 -2
- package/bundle/chunk-2cm91ktc.js +0 -3
- package/bundle/chunk-2jfd82jk.js +0 -2
- package/bundle/chunk-2k7bbzj2.js +0 -2
- package/bundle/chunk-30081kwd.js +0 -2
- package/bundle/chunk-3kdhvq0p.js +0 -3
- package/bundle/chunk-3vag59se.js +0 -2
- package/bundle/chunk-3x5v6sjw.js +0 -2
- package/bundle/chunk-43ep9d7a.js +0 -2
- package/bundle/chunk-48j09m6e.js +0 -3
- package/bundle/chunk-4qqja22v.js +0 -2
- package/bundle/chunk-5gazgxt5.js +0 -2
- package/bundle/chunk-63znhwx0.js +0 -2
- package/bundle/chunk-6hmyy7n6.js +0 -2
- package/bundle/chunk-7dyddrpk.js +0 -2
- package/bundle/chunk-7penjsgq.js +0 -2
- package/bundle/chunk-7t5gzkj6.js +0 -2
- package/bundle/chunk-89vgt8vq.js +0 -2
- package/bundle/chunk-8e8n82f9.js +0 -2
- package/bundle/chunk-97exhw9j.js +0 -2
- package/bundle/chunk-9cvkaht5.js +0 -2
- package/bundle/chunk-akdvstd9.js +0 -2
- package/bundle/chunk-ave2e4sa.js +0 -2
- package/bundle/chunk-axnwehc7.js +0 -2
- package/bundle/chunk-bmzyxspj.js +0 -2
- package/bundle/chunk-bvaqpfv8.js +0 -2
- package/bundle/chunk-cxb05cdg.js +0 -2
- package/bundle/chunk-cxe92z5c.js +0 -2
- package/bundle/chunk-d5wp85kw.js +0 -2
- package/bundle/chunk-dm5xnb4t.js +0 -2
- package/bundle/chunk-dpeqsvan.js +0 -2
- package/bundle/chunk-drxtmg5c.js +0 -2
- package/bundle/chunk-e9pfdjcy.js +0 -2
- package/bundle/chunk-ejn5hfzd.js +0 -2
- package/bundle/chunk-ek1fawsj.js +0 -3
- package/bundle/chunk-ernd18jb.js +0 -2
- package/bundle/chunk-ff9b4cg8.js +0 -2
- package/bundle/chunk-fpff6a4q.js +0 -2
- package/bundle/chunk-gq361kdt.js +0 -2
- package/bundle/chunk-hbagpppv.js +0 -2
- package/bundle/chunk-hf473xav.js +0 -2
- package/bundle/chunk-hr88054m.js +0 -2
- package/bundle/chunk-j3czd7v2.js +0 -28
- package/bundle/chunk-j9m2d6t5.js +0 -2
- package/bundle/chunk-jd9edy2s.js +0 -2
- package/bundle/chunk-jwtdbx31.js +0 -2
- package/bundle/chunk-kbjwdv1x.js +0 -8223
- package/bundle/chunk-krkxrej2.js +0 -2
- package/bundle/chunk-m26mcy8p.js +0 -2
- package/bundle/chunk-m62wgqp1.js +0 -2
- package/bundle/chunk-m84cn9c6.js +0 -2
- package/bundle/chunk-mvc7pvtq.js +0 -2
- package/bundle/chunk-nfp9xtca.js +0 -3
- package/bundle/chunk-ngz5xw45.js +0 -3
- package/bundle/chunk-p5t9mq8r.js +0 -2
- package/bundle/chunk-pfbykat1.js +0 -2
- package/bundle/chunk-qd0nvn4z.js +0 -2
- package/bundle/chunk-qh99kv2j.js +0 -2
- package/bundle/chunk-qyrafh4m.js +0 -2
- package/bundle/chunk-rc37cw86.js +0 -2
- package/bundle/chunk-rmpty636.js +0 -2
- package/bundle/chunk-rz54qjew.js +0 -2
- package/bundle/chunk-s3wjwxme.js +0 -2
- package/bundle/chunk-s4ncnbgd.js +0 -2
- package/bundle/chunk-snz3w30x.js +0 -2
- package/bundle/chunk-srw748gr.js +0 -2
- package/bundle/chunk-tn167yyz.js +0 -2
- package/bundle/chunk-v1xwe58d.js +0 -2
- package/bundle/chunk-vh05n2x3.js +0 -2
- package/bundle/chunk-vrfegg5f.js +0 -2
- package/bundle/chunk-w12tky28.js +0 -2
- package/bundle/chunk-w9ct698t.js +0 -2
- package/bundle/chunk-wms4skr9.js +0 -11
- package/bundle/chunk-wr5hdsst.js +0 -9
- package/bundle/chunk-wxnqgh8t.js +0 -2
- package/bundle/chunk-wzmte7sy.js +0 -3
- package/bundle/chunk-x0h1jdxt.js +0 -2
- package/bundle/chunk-x6hsmnhz.js +0 -2
- package/bundle/chunk-xg9e0enb.js +0 -2
- package/bundle/chunk-xtxxb25n.js +0 -2
- package/bundle/chunk-y3s7sh1e.js +0 -2
- package/bundle/chunk-ydvheqw9.js +0 -2
- package/bundle/chunk-yxnq0d7k.js +0 -2
- package/bundle/chunk-z2raegj9.js +0 -2
- package/bundle/chunk-z3pyhmg6.js +0 -2
- package/bundle/chunk-z7pg6sw1.js +0 -2
- package/bundle/chunk-z84376c6.js +0 -2
- package/bundle/chunk-zn8th65r.js +0 -2
- package/bundle/chunk-ztv1brgn.js +0 -2
- package/bundle/chunk-zyxvd9fj.js +0 -2
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{$h as L5,Bh as vV,Dh as G$,Fh as iJ,Gh as dV,Hh as Q$,Jh as _0,Kh as p4,Lh as q5,Mh as P$,Nh as G1,Oh as _4,Ph as v4,Qh as K7,Rh as mV,Sh as GJ,Th as r9,Uh as W0,Vh as h2,Wh as N5,Xh as x5,Yh as w5,Zh as b5,_h as P6,ai as m5,ih as J8,jh as fV,kh as V8,lh as c$,mh as EV,nh as zQ,oh as j$,ph as y$,qh as RJ,rh as CJ,sh as t4,th as YQ,uh as j1,wh as C5,yh as w6,zh as y1}from"./chunk-0nj8axbw.js";import{bi as GY}from"./chunk-p68rwmhc.js";import{Vi as U7}from"./chunk-a1pw9r6f.js";import{$j as d8,$k as i9,Ak as D5,Al as E2,Bk as uZ,Bl as v0,Ck as pZ,Cl as J2,Dk as y5,Dl as V2,Hk as S3,Ik as k3,Nk as O5,Wk as F5,Xj as u,Xk as O2,Zk as P5,_k as z5,bk as h9,ek as u4,fk as yZ,ik as B8,jk as A1,kk as F2,kl as hY,lk as x2,ll as A6,mk as Q2,ml as M2,nl as p8,ok as s6,ol as K2,pk as J$,pl as p2,rl as P2,sl as cV,tk as yJ,tl as p,uk as OJ,ul as xQ,wl as U2,xk as z0,xl as n9,yk as $1,yl as U6,zk as t0,zl as O7}from"./chunk-8tc8x27z.js";import{Fl as lV}from"./chunk-k7g3h9tn.js";import{Ql as e4,Tl as QV,Ul as DZ,Vl as k0,_l as z1,bm as a2,cm as l$,dm as D8,em as R$,fm as j5,im as IJ,jm as U$,lm as S2,mm as v,nm as FV,om as P0,pm as cZ}from"./chunk-rmr38x2f.js";import{rm as i1,sm as n1,tm as s1,wm as hJ,xm as D2}from"./chunk-5syxjhg3.js";import{An as K1,Bn as X0,Cn as t1,Dn as M4,Gn as G0,In as kY,On as TY,Pn as gY,Rn as vQ,co as dQ,do as E8}from"./chunk-nj4d554m.js";import{mp as hV}from"./chunk-cmbxrgyx.js";import{Gp as lJ}from"./chunk-nt4e3em9.js";import{Jp as I$,Yp as $0}from"./chunk-hk698g9e.js";import{Zp as cJ}from"./chunk-v965rsr8.js";import{Tq as W$,Uq as cY,dr as t$,er as RX}from"./chunk-yq3m8190.js";import{Gr as FY,Hr as JY}from"./chunk-btz9jvec.js";import{$r as B6}from"./chunk-m02zt1a3.js";import{ds as I0,is as gV,js as u5}from"./chunk-fzna6jdj.js";import{ls as E0,ms as a4,ps as r4}from"./chunk-x1rx6fm7.js";import{Bs as H$,Cs as NJ,Is as KZ,Js as xJ}from"./chunk-4qqkqrn9.js";import{qt as w2}from"./chunk-12bssxd4.js";import{st as M7}from"./chunk-24xc0dvv.js";import{Dt as O6,Ot as V5,bu as H6,gu as MV,ju as _6,ou as q$,pu as L0,tt as w1,xt as J5,yu as s}from"./chunk-ebrt1me3.js";import{Bu as O$,Du as q4,Hu as QJ,Ku as gJ,Nu as LV,Ou as n2,Su as V$,zu as k5}from"./chunk-whxjkz9a.js";import{Tu as P3}from"./chunk-89v6dgpp.js";import{Uu as q}from"./chunk-k309zez0.js";import{$u as R7,Vu as XX,Xu as x,Yu as lX,Zu as z2,_u as A2,av as cX,bv as m2,cv as c,dv as o,ev as i2,fv as _2,gv as C7,hv as S7,iv as T2,jv as R0,kv as i,lv as l2,mv as YX,nv as k7,ov as oX,pv as uX,qv as y2}from"./chunk-09kba1hg.js";import{Nv as G9,rv as mX}from"./chunk-t12xrrfr.js";import{HA as L7,wA as s4}from"./chunk-phxrg7aw.js";import{AP as TJ,BF as u2,HG as H8,IF as k2,NG as UJ,OO as K5,PI as Y,PO as G5,QO as H5,RC as B5,RO as m4,TO as E5,UC as Y0,UG as AJ,VO as l4,YF as d2,YO as v5,ZD as Z2,ZG as MJ,cK as i8,hP as c9,jE as F6,jP as d5,kI as HZ,kP as c4,mG as _,oH as _J,oI as jZ,oP as c2,pO as c0,tD as W5,uF as G2,yK as AX}from"./chunk-snm5q21k.js";import{$P as J9,bQ as L2,dQ as K$,eQ as mY,fQ as lY}from"./chunk-aztre27e.js";var y0={};L2(y0,{layer:()=>lZ,defaultLayer:()=>YB,SessionStatus:()=>y0,Service:()=>X6,Info:()=>mZ,Event:()=>y7});var mZ=q.union([q.object({type:q.literal("idle")}),q.object({type:q.literal("retry"),attempt:q.number(),message:q.string(),next:q.number()}),q.object({type:q.literal("busy"),message:q.string().optional()})]).meta({ref:"SessionStatus"}),y7={Status:D2.define("session.status",q.object({sessionID:F2.zod,status:mZ})),Idle:D2.define("session.idle",q.object({sessionID:F2.zod}))};class X6 extends Z2.Service()("@qitqode/SessionStatus"){}var lZ=_.effect(X6,Y.gen(function*(){let $=yield*u.Service,Z=yield*v.make(Y.fn("SessionStatus.state")(()=>Y.succeed(new Map))),X=Y.fn("SessionStatus.get")(function*(V){return(yield*v.get(Z)).get(V)??{type:"idle"}}),Q=Y.fn("SessionStatus.list")(function*(){return new Map(yield*v.get(Z))}),J=Y.fn("SessionStatus.set")(function*(V,B){let D=yield*v.get(Z);if(yield*$.publish(y7.Status,{sessionID:V,status:B}),B.type==="idle"){yield*$.publish(y7.Idle,{sessionID:V}),D.delete(V);return}D.set(V,B)});return X6.of({get:X,list:Q,set:J})})),YB=lZ.pipe(_.provide(u.layer));var O0={};L2(O0,{layer:()=>oZ,defaultLayer:()=>QB,SessionRunState:()=>O0,Service:()=>Q6});class Q6 extends Z2.Service()("@qitqode/SessionRunState"){}var Y6=($,Z)=>`${$}:${Z}`,oZ=_.effect(Q6,Y.gen(function*(){let $=yield*y0.Service,Z=E0.create({service:"SessionRunState"}),X=yield*v.make(Y.fn("SessionRunState.state")(function*(){let W=yield*d2.Scope,K=new Map;return yield*Y.addFinalizer(Y.fnUntraced(function*(){yield*Y.forEach(K.values(),(j)=>j.cancel,{concurrency:8,discard:!0}),K.clear()})),{runners:K,scope:W}})),Q=Y.fn("SessionRunState.runner")(function*(W,K,j){let G=Y6(W,K),z=yield*v.get(X),O=z.runners.get(G);if(O)return O;let P=K==="main",w=cZ.make(z.scope,{label:G,onReentryWarn:(L)=>Z.warn("runner-reentry",L),onIdle:P?Y.gen(function*(){z.runners.delete(G),yield*$.set(W,{type:"idle"})}):Y.sync(()=>{z.runners.delete(G)}),onBusy:P?$.set(W,{type:"busy"}):Y.void,onInterrupt:j,busy:()=>{throw new O7(W)}});return z.runners.set(G,w),w}),J=Y.fn("SessionRunState.assertNotBusy")(function*(W){if((yield*v.get(X)).runners.get(Y6(W,"main"))?.busy)throw new O7(W)}),V=Y.fn("SessionRunState.cancel")(function*(W){let K=Y6(W,"main"),G=(yield*v.get(X)).runners.get(K);if(!G||!G.busy){yield*$.set(W,{type:"idle"});return}yield*G.cancel}),B=Y.fn("SessionRunState.cancelActor")(function*(W,K){let j=Y6(W,K),z=(yield*v.get(X)).runners.get(j);if(!z||!z.busy)return;yield*z.cancel}),D=Y.fn("SessionRunState.ensureRunning")(function*(W,K,j,G){return yield*(yield*Q(W,K,j)).ensureRunning(G)}),H=Y.fn("SessionRunState.startShell")(function*(W,K,j){return yield*(yield*Q(W,"main",K)).startShell(j)});return Q6.of({assertNotBusy:J,cancel:V,cancelActor:B,ensureRunning:D,startShell:H})})),QB=oZ.pipe(_.provide(y0.defaultLayer));var F0={};L2(F0,{parseVerdictFromCompletion:()=>BB,layer:()=>iZ,defaultLayer:()=>VB,Verdict:()=>r$,Service:()=>V6,Goal:()=>F0,Event:()=>P7});var r$=q.object({ok:q.boolean(),impossible:q.boolean().optional(),reason:q.string()}),P7={Updated:D2.define("session.goal",q.object({sessionID:F2.zod,goal:q.object({condition:q.string()}).optional(),lastVerdict:r$.extend({attempt:q.number(),messageID:q.string().optional(),error:q.boolean().optional()}).optional()}))},J6=`You are evaluating a stop-condition hook in QitQode. Read the conversation transcript carefully, then judge whether the user-provided condition is satisfied.
|
|
3
|
+
|
|
4
|
+
Your response must be a JSON object with one of these shapes:
|
|
5
|
+
- {"ok": true, "reason": "<quote evidence from the transcript that satisfies the condition>"}
|
|
6
|
+
- {"ok": false, "reason": "<quote what is missing or what blocks the condition>"}
|
|
7
|
+
- {"ok": false, "impossible": true, "reason": "<explain why the condition can never be satisfied>"}
|
|
8
|
+
|
|
9
|
+
Always include a "reason" field, quoting specific text from the transcript whenever possible. If the transcript does not contain clear evidence that the condition is satisfied, return {"ok": false, "reason": "insufficient evidence in transcript"}.
|
|
10
|
+
|
|
11
|
+
Only use {"ok": false, "impossible": true} when the condition is genuinely unachievable in this session \u2014 for example: the condition is self-contradictory, it depends on a resource or capability that is unavailable, or the assistant has explicitly tried, exhausted reasonable approaches, and stated it cannot be done. Apply your own judgment when deciding this \u2014 the assistant claiming the goal is impossible is evidence, not proof; independently confirm the condition is genuinely unachievable rather than deferring to the assistant's self-assessment. Do not use it just because the goal has not been reached yet or because progress is slow. When in doubt, return {"ok": false} without "impossible".`,F7=($)=>`Based on the conversation transcript above, has the following stopping condition been satisfied? Answer based on transcript evidence only.
|
|
12
|
+
|
|
13
|
+
Condition: ${$}`;class V6 extends Z2.Service()("@qitqode/SessionGoal"){}var iZ=_.effect(V6,Y.gen(function*(){let $=yield*P2.Service,Z=yield*I$.Service,X=yield*V2.Service,Q=yield*u.Service,J=E0.create({service:"SessionGoal"}),V=yield*v.make(Y.fn("SessionGoal.state")(function*(){return{goals:new Map}})),B=Y.fn("SessionGoal.set")(function*(j,G){(yield*v.get(V)).goals.set(j,{condition:G,react:0}),yield*J.info("goal set",{sessionID:j,condition:G}),yield*Q.publish(P7.Updated,{sessionID:j,goal:{condition:G}})}),D=Y.fn("SessionGoal.get")(function*(j){return(yield*v.get(V)).goals.get(j)}),H=Y.fn("SessionGoal.clear")(function*(j){(yield*v.get(V)).goals.delete(j),yield*J.info("goal cleared",{sessionID:j}),yield*Q.publish(P7.Updated,{sessionID:j,goal:void 0})}),W=Y.fn("SessionGoal.bumpReact")(function*(j){let z=(yield*v.get(V)).goals.get(j);if(!z)return 0;return z.react+=1,z.react}),K=Y.fn("SessionGoal.evaluate")(function*(j){if(j.model.providerID==="qlex"){let I=j.msgs.slice(-20).map((M)=>{let f=M.parts.map((b)=>{let k=b;return k.type==="text"?String(k.text??""):""}).filter(Boolean).join(" ").slice(0,2000);return f?`${M.info.role}: ${f}`:null}).filter((M)=>M!==null).join(`
|
|
14
|
+
|
|
15
|
+
`);if(I){let M=`${J6}
|
|
16
|
+
|
|
17
|
+
${I}
|
|
18
|
+
|
|
19
|
+
${F7(j.condition)}`,f=yield*Y.promise(()=>$0.resolveChatCompletion(M,{temperature:0,timeoutMs:20000}).catch(()=>null));if(f?.content)try{let b=f.content.match(/\{[\s\S]*\}/);if(b){let k=r$.safeParse(JSON.parse(b[0]));if(k.success)return k.data}}catch{}}}let G=yield*X.get(),z=yield*$.getModel(j.model.providerID,j.model.modelID),O=yield*$.getLanguage(z),P=G.experimental?.openTelemetry?Y0.getOrUndefined(yield*Y.serviceOption(B6)):void 0,w=yield*Z.get(j.model.providerID).pipe(Y.orDie),L=j.model.providerID==="openai"&&w?.type==="oauth",F=yield*p.toModelMessagesEffect(j.msgs,z),U=(I,M)=>typeof M==="string"&&M.length>500?`\xAB${M.length} chars: ${M.slice(0,200)}\u2026\xBB`:M,y=[...L?[]:[{role:"system",content:J6}],...F,{role:"user",content:F7(j.condition)}];if(s.enabled("DEBUG"))yield*J.debug("goal judge transcript",{condition:j.condition,messageCount:y.length,messages:JSON.stringify(y,U)});let S={experimental_telemetry:{isEnabled:G.experimental?.openTelemetry,tracer:P,metadata:{userId:G.username??"unknown"}},temperature:0,messages:[...L?[]:[{role:"system",content:J6}],...F,{role:"user",content:F7(j.condition)}],model:O,schema:r$};if(L)return yield*Y.promise(async()=>{let I=pZ({...S,providerOptions:p2.providerOptions(z,{instructions:J6,store:!1}),onError:()=>{}});for await(let M of I.fullStream)if(M.type==="error")throw M.error;return r$.parse(await I.object)});return yield*Y.promise(()=>uZ(S).then((I)=>r$.parse(I.object)))});return V6.of({set:B,get:D,clear:H,bumpReact:W,evaluate:K})})),VB=iZ.pipe(_.provide(P2.defaultLayer),_.provide(I$.defaultLayer),_.provide(V2.defaultLayer),_.provide(u.layer));function BB($){try{let Z=$.match(/\{[\s\S]*\}/);if(!Z)return null;let X=r$.safeParse(JSON.parse(Z[0]));return X.success?X.data:null}catch{return null}}var d0={};L2(d0,{layer:()=>l5,defaultLayer:()=>AB,SessionProcessor:()=>d0,Service:()=>M6});var C2={};L2(C2,{subscribe:()=>aZ,jsonByteLength:()=>rZ,getInstallationID:()=>H6,ToolCall:()=>K6,ModelCall:()=>W6,Metrics:()=>C2,AgentRequest:()=>G6});var W6=D2.define("metrics.model_call",q.object({sessionID:q.string(),finish_reason:q.string(),ttft_ms:q.number().optional(),latency_ms:q.number(),cached_read_tokens:q.number(),model_id:q.string(),provider:q.string(),total_tokens_in:q.number(),total_tokens_out:q.number()})),K6=D2.define("metrics.tool_call",q.object({sessionID:q.string(),tool_name:q.string(),input_bytes:q.number(),output_bytes:q.number(),tool_call_id:q.string(),tool_call_status:q.enum(["success","error","cancelled"])})),G6=D2.define("metrics.agent_request",q.object({sessionID:q.string(),phase:q.string(),task_type:q.string(),surface:q.string(),total_tokens_in:q.number(),total_tokens_out:q.number(),files_changed:q.number(),validation_status:q.string()}));function nZ($,Z){let X={event:$,app_id:"qitqode-cli",instance_id:crypto.randomUUID(),instance_id_type:"uuid",e_ts:Date.now()};if(Z)X.uid=Z,X.uid_type="session_id";return X}async function sZ($){await fetch("https://telemetry.qitqode.com",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify($),signal:AbortSignal.timeout(60000)}).catch(()=>{})}var WB=!1;function z7($,Z,X){return sZ([{H:nZ($,Z),B:X}])}var aZ=Y.fn("Metrics.subscribe")(function*(){if(!WB)return;yield*Y.promise(()=>H6().catch(()=>"")),yield*u.Service.use(($)=>Y.all([$.subscribeCallback(W6,(Z)=>{let X=Z.properties;return z7("model_call",X.sessionID,{finish_reason:X.finish_reason,ttft_ms:X.ttft_ms,latency_ms:X.latency_ms,cached_read_tokens:X.cached_read_tokens,model_id:X.model_id,provider:X.provider,total_tokens_in:X.total_tokens_in,total_tokens_out:X.total_tokens_out})}),$.subscribeCallback(K6,(Z)=>{let X=Z.properties;return z7("tool_call",X.sessionID,{tool_name:X.tool_name,input_bytes:X.input_bytes,output_bytes:X.output_bytes,tool_call_id:X.tool_call_id,tool_call_status:X.tool_call_status})}),$.subscribeCallback(G6,(Z)=>{let X=Z.properties;return z7("agent_request",X.sessionID,{phase:X.phase,task_type:X.task_type,surface:X.surface,total_tokens_in:X.total_tokens_in,total_tokens_out:X.total_tokens_out,files_changed:X.files_changed,validation_status:X.validation_status})})]))});function rZ($){try{let Z=JSON.stringify($);if(typeof Z!=="string")return 0;return Buffer.byteLength(Z,"utf8")}catch{return 0}}var f2={};L2(f2,{persistentRetrySchedule:()=>U5,layer:()=>A5,isTransientCapacityError:()=>A7,hasToolCalls:()=>M5,defaultLayer:()=>PB,Service:()=>z6,OUTPUT_TOKEN_MAX:()=>yB,LLM:()=>f2});import x1 from"path";var D$={};L2(D$,{providerPromptName:()=>tZ,providerPrompt:()=>KB,layer:()=>eZ,defaultLayer:()=>GB,SystemPrompt:()=>D$,Service:()=>j6});function tZ($){if($.api.id.includes("gpt-4")||$.api.id.includes("o1")||$.api.id.includes("o3"))return"session/beast";if($.api.id.includes("gpt")){if($.api.id.includes("codex"))return"session/codex";return"session/gpt"}if($.api.id.includes("gemini-"))return"session/gemini";if($.api.id.includes("claude"))return"session/anthropic";if($.api.id.toLowerCase().includes("trinity"))return"session/trinity";if($.api.id.toLowerCase().includes("kimi"))return"session/kimi";return"session/default"}async function KB($){let Z=await $0.resolvePrompt(tZ($));return Z?[Z]:[]}class j6 extends Z2.Service()("@qitqode/SystemPrompt"){}var eZ=_.effect(j6,Y.gen(function*(){let $=yield*j$.Service;return j6.of({environment(Z,X){let Q=S2.project;return[["You are QitQode Agent, an interactive agent that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.",`You are powered by the model named ${Z.api.id}. The exact model ID is ${Z.providerID}/${Z.api.id}`,"Here is some useful information about the environment you are running in:","<env>",` Working directory: ${S2.directory}`,` Workspace root folder: ${S2.worktree}`,` Is directory a git repo: ${Q.vcs==="git"?"yes":"no"}`,` Platform: ${process.platform}`,` Today's date: ${new Date(X).toDateString()}`,"</env>"].join(`
|
|
20
|
+
`),"IMPORTANT: Your response must ALWAYS strictly follow the same major language as the user."]},skills:Y.fn("SystemPrompt.skills")(function*(Z){if(O2.disabled(["skill"],Z.permission).has("skill"))return;let X=yield*$.available(Z);return["Skills provide specialized instructions and workflows for specific tasks.","Use the skill tool to load a skill when a task matches its description.",j$.fmt(X,{verbose:!0})].join(`
|
|
21
|
+
`)})})})),GB=eZ.pipe(_.provide(j$.defaultLayer));var N7=2;function $5($){return $.toLowerCase().replace(/\s+/g," ").trim().split(" ").filter(Boolean)}function Z5($,Z,X){if($.length<Z||X<2)return!1;let Q=new Map;for(let J=0;J<=$.length-Z;J++){let V=$.slice(J,J+Z).join("\x00"),B=(Q.get(V)??0)+1;if(B>=X)return!0;Q.set(V,B)}return!1}var q7=["write","write_file","edit","edit_file","question","bash","read","read_file","glob","grep"],HB=["tool_call","tool_use","function_call","function_calls","invoke_name","invoke"],jB="<\\/?[a-z][\\w-]*__[\\w-]+\\b[^>]*>",DB=new RegExp(`(?:<\\/?(?:${q7.join("|")})\\b[^>]*>|\\b(?:${q7.join("|")})\\s*=\\s*"[^"]*"|\\/(?:${q7.join("|")})\\b|<\\/?(?:${HB.join("|")})\\b[^>]*>|${jB})`,"i");function D6($){return DB.test($)}var X5=`# Tool invocation rules
|
|
22
|
+
|
|
23
|
+
Tools are ONLY invoked through the structured tool-calling interface of this API. NEVER write tool calls as plain text in your response:
|
|
24
|
+
- NEVER emit XML-style tags like <tool_call>, <invoke>, <function_call>, <toolname>, or namespaced tags like <agent__toolname> in your text output
|
|
25
|
+
- NEVER write pseudo-syntax like toolname="..." or /toolname as text
|
|
26
|
+
- Text like that is NEVER executed \u2014 the user just sees garbled output and nothing happens
|
|
27
|
+
If you want to use a tool, issue a real structured tool call. If no tool fits, answer in plain prose.`;class x7{n;threshold;windowTokens;buffer="";tokens=[];fakeToolTag=!1;constructor($,Z,X){this.n=$;this.threshold=Z;this.windowTokens=X}append($){if(!$)return!1;this.buffer+=$;let Z=$5(this.buffer);if(this.tokens=Z.length>this.windowTokens?Z.slice(-this.windowTokens):Z,Z.length>this.windowTokens*2)this.buffer=this.tokens.join(" ");if(!this.fakeToolTag&&D6(this.buffer))this.fakeToolTag=!0;return Z5(this.tokens,this.n,this.threshold)||this.fakeToolTag}reset(){this.buffer="",this.tokens=[],this.fakeToolTag=!1}}function y6(){return{_tag:"TextNgramRepeat"}}function w7($){return typeof $==="object"&&$!==null&&"_tag"in $&&$._tag==="TextNgramRepeat"}function Y5($){return`<system-reminder>
|
|
28
|
+
MALFORMED OUTPUT DETECTED: Your recent output either repeats phrases (sliding n-gram match within your last ${$} tokens), or contains fake tool-call syntax written as plain text (e.g. \`write_file="..."\`, \`/write\`, \`<question>...\`, \`/question\`, \`<tool_call>\`, \`<invoke_name>...\`) instead of an actual tool call.
|
|
29
|
+
|
|
30
|
+
STOP and retry with a different approach:
|
|
31
|
+
- Vary your wording and reasoning \u2014 do not reuse the same phrases
|
|
32
|
+
- Tools are NEVER invoked by writing their name, tags, or \`key="value"\` attributes as plain text \u2014 that text is never executed and the user only sees garbled output. If you need to write a file, ask a question, run a command, etc., you MUST issue a real structured tool call.
|
|
33
|
+
- If you are blocked, explain what is blocking you instead of looping or faking a tool call
|
|
34
|
+
|
|
35
|
+
Do NOT output the same phrases again, and do NOT describe tool usage as inline text tags.
|
|
36
|
+
</system-reminder>`}var b7=`<system-reminder>
|
|
37
|
+
CRITICAL: You are STILL producing malformed output (repeated phrases or fake tool-call syntax written as plain text) after a recovery attempt.
|
|
38
|
+
|
|
39
|
+
You MUST completely replan before continuing:
|
|
40
|
+
1. Abandon your current approach entirely \u2014 it is stuck in repetition or fake tool-call text
|
|
41
|
+
2. Write out a NEW plan with different steps and a different strategy
|
|
42
|
+
3. State what you were trying to do, why it failed, and how your new plan differs
|
|
43
|
+
4. Any tool usage (write, edit, question, bash, read, etc.) MUST go through a real structured tool call \u2014 never write tool names, tags, or attributes as plain text
|
|
44
|
+
|
|
45
|
+
Do NOT continue the same line of reasoning, reuse the same wording, or fake a tool call as text.
|
|
46
|
+
</system-reminder>`;var Q5=s.create({service:"llm"}),yB=p2.OUTPUT_TOKEN_MAX;function A7($){return N5($)}var U5=H8.exponential(F6.millis(x5),w5).pipe(H8.modifyDelay(($,Z)=>{let X=F6.millis(b5);return Y.succeed(F6.isLessThanOrEqualTo(Z,X)?Z:X)}),H8.both(H8.recurs(P6)));function OB($,Z,X){let Q=x1.join(X,"projects",Z,"MEMORY.md"),J=x1.join(X,"sessions",$,"checkpoint.md"),V=x1.join(X,"sessions",$),B=x1.join(X,"global","MEMORY.md");return`# Memory system
|
|
47
|
+
|
|
48
|
+
You have a persistent file-based memory system. Four file types:
|
|
49
|
+
|
|
50
|
+
- Project memory at \`${Q}\` \u2014 persistent across all sessions in this project. Contains: project context, rules, architecture decisions, durable cross-task knowledge.
|
|
51
|
+
- Session checkpoint at \`${J}\` \u2014 current session's structured state, written ONLY by the checkpoint-writer subagent. 11 sections covering active intent, next action, directives, task tree, current work, files, learnings, errors, live resources, design decisions, and open notes. Task content lives inside \xA74 Task tree and \xA75 Current work.
|
|
52
|
+
- Per-task progress at \`${x1.join(V,"tasks","<id>","progress.md")}\` \u2014 writer-derived splitover from session-level progress.md (not LLM-written). When you spawn a subagent on a task, the subagent may be handed this path for reading; you do not maintain it.
|
|
53
|
+
- Global memory at \`${B}\` \u2014 user-level preferences and cross-project feedback that persist across all projects. Auto-injected into rebuild context under the "## Global memory" header when present.
|
|
54
|
+
|
|
55
|
+
The checkpoint writer is the sole curator of the structured files. You don't maintain them mid-task \u2014 the writer extracts everything from the conversation at checkpoint events.
|
|
56
|
+
|
|
57
|
+
## When to Edit MEMORY.md directly
|
|
58
|
+
|
|
59
|
+
You may Edit MEMORY.md when:
|
|
60
|
+
- User states a project-level rule that should hold across sessions \u2192 ## Rules
|
|
61
|
+
- User states a project-level architectural decision \u2192 ## Architecture decisions
|
|
62
|
+
- A clearly durable cross-session fact emerges that you want available immediately, before the next checkpoint \u2192 ## Discovered durable knowledge
|
|
63
|
+
|
|
64
|
+
These are exceptions, not the norm. The writer covers most extraction at checkpoint time.
|
|
65
|
+
|
|
66
|
+
## Notes scratchpad
|
|
67
|
+
|
|
68
|
+
You have a single legal scratchpad at \`${x1.join(V,"notes.md")}\`. Append entries to it when you want to record:
|
|
69
|
+
|
|
70
|
+
- A quote (from the user, an article, a known engineer) that has lasting value but isn't a task-specific decision
|
|
71
|
+
- An unresolved question \u2014 something you noticed but won't answer this turn
|
|
72
|
+
- A cross-project observation \u2014 "we did this in project X, similar pattern here"
|
|
73
|
+
- A note for future-self \u2014 context that would matter weeks later but doesn't fit any current task
|
|
74
|
+
|
|
75
|
+
Format each entry as:
|
|
76
|
+
## [turn N \xB7 YYYY-MM-DDTHH:MM:SSZ]
|
|
77
|
+
Free-form body. The writer reorganizes structured content at checkpoint time.
|
|
78
|
+
|
|
79
|
+
This is your ONLY legal scratchpad \u2014 don't create \`learning.md\`, \`scratch.md\`, or any other ad-hoc memory file.
|
|
80
|
+
|
|
81
|
+
## Subagent return format
|
|
82
|
+
|
|
83
|
+
When you (as a subagent) finish your task, your final assistant message will be delivered to the spawning agent. If the spawn machinery added a "Return format (required)" section to your prompt, follow it exactly:
|
|
84
|
+
|
|
85
|
+
**Status**: success | partial | failed | blocked
|
|
86
|
+
**Summary**: <one-line description>
|
|
87
|
+
|
|
88
|
+
<deliverable body>
|
|
89
|
+
|
|
90
|
+
**Files touched**: <comma-separated paths or "(none)">
|
|
91
|
+
**Findings worth promoting**: <bullet list, or "(none)">
|
|
92
|
+
|
|
93
|
+
If your spawn prompt didn't include this format (e.g., explore/title/summary agents have their own contracts), follow whatever your prompt specifies.
|
|
94
|
+
|
|
95
|
+
## What NOT to do
|
|
96
|
+
|
|
97
|
+
- Don't Edit checkpoint.md \u2014 that's the writer's domain.
|
|
98
|
+
- Don't create memory files other than notes.md (no learning.md, no scratch.md). Use notes.md for any free-form entry.
|
|
99
|
+
- Don't ask the user about something memory may already record \u2014 search first via Grep / Read.
|
|
100
|
+
|
|
101
|
+
## Active recall protocol
|
|
102
|
+
|
|
103
|
+
After a checkpoint rebuild, the following dumps may be already in your context (look for the "Summary of previous conversation from checkpoint files:" header followed by these dumps):
|
|
104
|
+
|
|
105
|
+
- checkpoint.md (full or budget-truncated)
|
|
106
|
+
- MEMORY.md (full or budget-truncated)
|
|
107
|
+
- notes.md (full or budget-truncated)
|
|
108
|
+
- global/MEMORY.md (full or budget-truncated)
|
|
109
|
+
|
|
110
|
+
If these dumps are visible in your context:
|
|
111
|
+
|
|
112
|
+
- Do NOT Read them again as whole files. The bytes are already in front of you.
|
|
113
|
+
- For specific past details (a particular turn's content, a specific tool output, an old command), use Grep with a keyword pattern to target the exact item \u2014 do not pull a whole file.
|
|
114
|
+
- For files NOT in the rebuild dump (per-task splitover progress.md files for tasks you don't actively need, spillover files, older session checkpoints in other sessions), Read on demand.
|
|
115
|
+
|
|
116
|
+
If a dump shows "\u26A0\uFE0F Truncated at ~N tokens. Read(<path>, offset=L) for the rest." \u2014 that file was budget-cut. Use Read with the offset only when you need the missing tail.
|
|
117
|
+
|
|
118
|
+
Memory entries name functions, files, flags, paths \u2014 those are CLAIMS about a point in time when they were written. Verify before acting on a specific name.
|
|
119
|
+
|
|
120
|
+
Don't ask the user about something memory may already record.
|
|
121
|
+
`}class z6 extends Z2.Service()("@qitqode/LLM"){}var FB=_.effect(z6,Y.gen(function*(){let $=yield*I$.Service,Z=yield*V2.Service,X=yield*P2.Service,Q=yield*K2.Service,J=yield*O2.Service,V=yield*M2.Service,B=yield*y$.Service,D=Y.fn("LLM.buildSystemArray")(function*(K){let j=[],G=K.agent.prompt?[K.agent.prompt]:yield*Y.promise(()=>D$.providerPrompt(K.model));if(j.push([...G,X5,...K.system,...K.user.system?[K.user.system]:[]].filter((P)=>P).join(`
|
|
122
|
+
`)),!(K.agentID?yield*V.isSystemSpawned(F2.make(K.sessionID),K.agentID):!1)){let P=q5()??j5.global;yield*Y.promise(()=>O5(P)).pipe(Y.ignore),j.push(OB(F2.make(K.sessionID),P,yield*B.root()))}let O=j[0];if(yield*Q.trigger("experimental.chat.system.transform",{sessionID:K.sessionID,model:K.model},{system:j}),j.length>2&&j[0]===O){let P=j.slice(1);j.length=0,j.push(O,P.join(`
|
|
123
|
+
`))}return j}),H=Y.fn("LLM.run")(function*(K){let j=Q5.clone().tag("providerID",K.model.providerID).tag("modelID",K.model.id).tag("session.id",K.sessionID).tag("small",(K.small??!1).toString()).tag("agent",K.agent.name).tag("mode",K.agent.mode).tag("posture",K.agent.posture??P5(K.agent));j.info("stream",{modelID:K.model.id,providerID:K.model.providerID});let[G,z,O,P]=yield*Y.all([X.getLanguage(K.model),Z.get(),X.getProvider(K.model.providerID),$.get(K.model.providerID)],{concurrency:"unbounded"}),w=O.id==="openai"&&P?.type==="oauth",L=K.prebuiltSystem??(yield*D({agent:K.agent,model:K.model,system:K.system,user:K.user,sessionID:K.sessionID,agentID:K.agentID})),F=!K.small&&K.model.variants&&K.user.model.variant?K.model.variants[K.user.model.variant]:{},U=K.small?p2.smallOptions(K.model):p2.options({model:K.model,sessionID:K.sessionID,providerOptions:O.options}),y=J5(U,O6(K.model.options),O6(K.agent.options),O6(F));if(w)y.instructions=L.join(`
|
|
124
|
+
`);let S=G instanceof U7,I=w?K.messages:S?K.messages:[...L.map((C)=>({role:"system",content:C})),...K.messages],M=yield*Q.trigger("chat.params",{sessionID:K.sessionID,agent:K.agent.name,model:K.model,provider:O,message:K.user},{temperature:K.model.capabilities.temperature?K.agent.temperature??p2.temperature(K.model):void 0,topP:K.agent.topP??p2.topP(K.model),topK:p2.topK(K.model),maxOutputTokens:p2.maxOutputTokens(K.model),options:y}),{headers:f}=yield*Q.trigger("chat.headers",{sessionID:K.sessionID,agent:K.agent.name,model:K.model,provider:O,message:K.user},{headers:{}}),b=zB(K);if((O.options?.litellmProxy===!0||K.model.providerID.toLowerCase().includes("litellm")||K.model.api.id.toLowerCase().includes("litellm")||K.model.providerID.includes("github-copilot"))&&Object.keys(b).length===0&&M5(K.messages))b._noop=t$({description:"Do not call this tool. It exists only for API compatibility and must never be invoked.",inputSchema:W$({type:"object",properties:{reason:{type:"string",description:"Unused"}}}),execute:async()=>({output:"",title:"",metadata:{}})});if(G instanceof U7){let C=G;C.sessionID=K.sessionID,C.systemPrompt=L.join(`
|
|
125
|
+
`),C.toolExecutor=async(g,E,m)=>{let e=b[g];if(!e||!e.execute)return{result:"",error:`Unknown tool: ${g}`};try{let n=await e.execute(JSON.parse(E),{toolCallId:m,messages:K.messages,abortSignal:K.abort});return{result:typeof n==="string"?n:n?.output??JSON.stringify(n),metadata:typeof n==="object"?n?.metadata:void 0,title:typeof n==="object"?n?.title:void 0}}catch(n){return{result:"",error:n.message??String(n)}}};let T=O2.merge(K.agent.permission??[],K.permission??[]);C.sessionPreapprovedTools=Object.keys(b).filter((g)=>{let E=T.findLast((m)=>V5.match(g,m.permission));return!E||E.action!=="ask"});let l=yield*P0.make(),d=new Set;C.approvalHandler=S2.bind(async(g)=>{let E=[...new Set(g.map((n)=>n.name))];if(E.every((n)=>d.has(n)))return{approved:!0};let m=F5.ascending(),e;try{e=u.subscribe(O2.Event.Replied,(H2)=>{if(H2.properties.requestID===m)H2.properties.reply});let n=g.map((H2)=>{try{let I2=JSON.parse(H2.args),t=I2?.title??I2?.name??"";return t?`${H2.name}: ${t}`:H2.name}catch{return H2.name}}),a=[...new Set(n)];await l.promise(J.ask({id:m,sessionID:F2.make(K.sessionID),permission:"workflow_tool_approval",patterns:a,metadata:{tools:g},always:a,ruleset:[]}));for(let H2 of E)d.add(H2);return C.sessionPreapprovedTools=[...C.sessionPreapprovedTools??[],...E],{approved:!0}}catch{return{approved:!1}}finally{e?.()}})}let h=z.experimental?.openTelemetry?B5(yield*Y.serviceOption(B6)):void 0,N=h?new Proxy(h,{get(C,T,l){if(T!=="startSpan")return Reflect.get(C,T,l);return(...d)=>{let g=C.startSpan(...d);return g.setAttribute("session.id",K.sessionID),g}}}):void 0,A=Date.now(),R=K.model.providerID==="qlex"?z5(K.agent,Object.keys(b)):void 0;return j.debug("streamText starting",{messageID:K.user.id,msgCount:I.length,toolCount:Object.keys(b).length,qortexPosture:R?.posture??null,qortexDirective:R?.directive??null}),D5({onError(C){j.debug("streamText error",{messageID:K.user.id,error:C instanceof Error?C.message:String(C),elapsedMs:Date.now()-A}),j.error("stream error",{error:C})},async experimental_repairToolCall(C){let T=C.toolCall.toolName.toLowerCase();if(T!==C.toolCall.toolName&&b[T])return j.info("repairing tool call",{tool:C.toolCall.toolName,repaired:T}),{...C.toolCall,toolName:T};return{...C.toolCall,input:JSON.stringify({tool:C.toolCall.toolName,error:C.error.message}),toolName:"invalid"}},temperature:M.temperature,topP:M.topP,topK:M.topK,providerOptions:p2.providerOptions(K.model,{...M.options,...R??{}}),activeTools:Object.keys(b).filter((C)=>C!=="invalid"),tools:b,toolChoice:K.toolChoice,maxOutputTokens:M.maxOutputTokens,abortSignal:K.abort,headers:{"x-session-affinity":K.sessionID,...K.parentSessionID?{"x-parent-session-id":K.parentSessionID}:{},...K.model.headers,...f,"User-Agent":`qitqode/${w1}`},maxRetries:K.retries??2,messages:I,model:y5({model:G,middleware:[{specificationVersion:"v3",async transformParams(C){if(C.type==="stream")C.params.prompt=p2.message(C.params.prompt,K.model,y);return C.params}}]}),experimental_telemetry:{isEnabled:z.experimental?.openTelemetry,functionId:"session.llm",tracer:N,metadata:{userId:z.username??"unknown",sessionId:K.sessionID}}})}),W=(K)=>H5(G5(Y.gen(function*(){let j=yield*Y.acquireRelease(Y.sync(()=>new AbortController),(w)=>Y.sync(()=>w.abort())),G=yield*L7.make(0),z=(w,L)=>Y.gen(function*(){if(Q5.debug("retry attempt",{sessionID:K.sessionID,messageID:K.user.id,attempt:L,reason:w instanceof Error?w.message:String(w)}),L>P6)return;let F=L5(L);yield*Y.promise(()=>u.publish(U2.RetryAttempt,{sessionID:F2.make(K.sessionID),messageID:K.user.id,attempt:L,maxAttempts:P6,reason:w instanceof Error?w.message:String(w),nextDelayMs:F}))}),P=yield*H({...K,abort:j.signal}).pipe(Y.tapError((w)=>{if(!A7(w))return Y.void;return L7.updateAndGet(G,(L)=>L+1).pipe(Y.flatMap((L)=>z(w,L)))})).pipe(Y.retry({while:A7,schedule:U5}));return K5(P.fullStream,(w)=>w instanceof Error?w:Error(String(w)))})));return z6.of({stream:W,buildSystemArray:D})})),A5=FB.pipe(_.provide(O2.defaultLayer)),PB=_.suspend(()=>A5.pipe(_.provide(I$.defaultLayer),_.provide(V2.defaultLayer),_.provide(P2.defaultLayer),_.provide(K2.defaultLayer),_.provide(M2.defaultLayer),_.provide(y$.defaultLayer)));function zB($){let Z=O2.disabled(Object.keys($.tools),O2.merge($.agent.permission,$.permission??[]));return W5.filter($.tools,(X,Q)=>$.user.tools?.[Q]!==!1&&!Z.has(Q))}function M5($){for(let Z of $){if(!Array.isArray(Z.content))continue;for(let X of Z.content)if(X.type==="tool-call"||X.type==="tool-result")return!0}return!1}var q0={};L2(q0,{layer:()=>_5,defaultLayer:()=>NB,SessionSummary:()=>q0,Service:()=>N6,DiffInput:()=>xB});function q6($){return{additions:$.reduce((Z,X)=>Z+X.additions,0),deletions:$.reduce((Z,X)=>Z+X.deletions,0),files:$.length}}function qB($){if(!$.startsWith('"'))return $;if(!$.endsWith('"'))return $;let Z=$.slice(1,-1),X=[];for(let Q=0;Q<Z.length;Q++){let J=Z[Q];if(J!=="\\"){X.push(J.charCodeAt(0));continue}let V=Z[Q+1];if(!V){X.push(92);continue}if(V>="0"&&V<="7"){let H=Z.slice(Q+1,Q+4).match(/^[0-7]{1,3}/);if(!H){X.push(V.charCodeAt(0)),Q++;continue}X.push(parseInt(H[0],8)),Q+=H[0].length;continue}let B=V==="n"?`
|
|
126
|
+
`:V==="r"?"\r":V==="t"?"\t":V==="b"?"\b":V==="f"?"\f":V==="v"?"\v":V==="\\"||V==='"'?V:void 0;X.push((B??V).charCodeAt(0)),Q++}return Buffer.from(X).toString()}class N6 extends Z2.Service()("@qitqode/SessionSummary"){}var _5=_.effect(N6,Y.gen(function*(){let $=yield*E2,Z=yield*z0.Service,X=yield*R$.Service,Q=yield*u.Service,J=Y.fn("SessionSummary.computeDiff")(function*(D){let H,W;for(let K of D.messages){if(!H){for(let j of K.parts)if(j.type==="step-start"&&j.snapshot){H=j.snapshot;break}}for(let j of K.parts)if(j.type==="step-finish"&&j.snapshot)W=j.snapshot}if(H&&W)return yield*Z.diffFull(H,W);return[]}),V=Y.fn("SessionSummary.summarize")(function*(D){let H=yield*$.messages({sessionID:D.sessionID,agentID:"main"});if(!H.length)return;let W=yield*J({messages:H});yield*$.setSummary({sessionID:D.sessionID,summary:q6(W)}),yield*X.write(["session_diff",D.sessionID],W).pipe(Y.ignore),yield*Q.publish(U2.Diff,{sessionID:D.sessionID,diff:W});let K=H.filter((z)=>z.info.id===D.messageID||z.info.role==="assistant"&&z.info.parentID===D.messageID),j=K.find((z)=>z.info.id===D.messageID);if(!j||j.info.role!=="user")return;let G=yield*J({messages:K});j.info.summary={...j.info.summary,diffs:G},yield*$.updateMessage(j.info)}),B=Y.fn("SessionSummary.diff")(function*(D){let H=yield*X.read(["session_diff",D.sessionID]).pipe(Y.catch(()=>Y.succeed([]))),W=H.map((j)=>{let G=qB(j.file);if(G===j.file)return j;return{...j,file:G}});if(W.some((j,G)=>j.file!==H[G]?.file))yield*X.write(["session_diff",D.sessionID],W).pipe(Y.ignore);return W});return N6.of({summarize:V,diff:B,computeDiff:J})})),NB=_.suspend(()=>_5.pipe(_.provide(v0),_.provide(z0.defaultLayer),_.provide(R$.defaultLayer),_.provide(u.layer))),xB=q.object({sessionID:F2.zod,messageID:x2.zod.optional()});function x6(){return new x7(L0.QITQODE_TEXT_NGRAM_N,L0.QITQODE_TEXT_REPEAT_THRESHOLD,L0.QITQODE_TEXT_WINDOW_TOKENS)}var I5=Y5(L0.QITQODE_TEXT_WINDOW_TOKENS);var U0=($)=>$;function R5($,Z){let{context:X,handleEvent:Q,cleanup:J,halt:V,setAborted:B,recordOverhead:D}=Z,H=new AbortController,W={inputTokens:0,outputTokens:0,totalTokens:0};return Y.gen(function*(){X.currentText=void 0,X.reasoningMap={},yield*Q(U0({type:"start"})),yield*Q(U0({type:"start-step",request:{},warnings:[]}));let j=[$.selection?`[max mode] selected candidate ${$.selection.winner+1} of ${$.selection.total}`:void 0,$.reasoning].filter(Boolean).join(`
|
|
127
|
+
|
|
128
|
+
`);if(j){let z=$.thinkingMs?Date.now()-$.thinkingMs:void 0;yield*Q(U0({type:"reasoning-start",id:"reasoning-replay",providerMetadata:$.reasoningMetadata,...z?{time:{start:z}}:{}})),yield*Q(U0({type:"reasoning-delta",id:"reasoning-replay",text:j,providerMetadata:$.reasoningMetadata})),yield*Q(U0({type:"reasoning-end",id:"reasoning-replay",providerMetadata:$.reasoningMetadata}))}if($.text)yield*Q(U0({type:"text-start",id:"text-replay",providerMetadata:$.textMetadata})),yield*Q(U0({type:"text-delta",id:"text-replay",text:$.text,providerMetadata:$.textMetadata})),yield*Q(U0({type:"text-end",id:"text-replay",providerMetadata:$.textMetadata}));for(let G of $.toolCalls){if(X.needsOverflowHandling)break;yield*Q(U0({type:"tool-input-start",id:G.toolCallId,toolName:G.toolName,providerMetadata:G.providerMetadata})),yield*Q(U0({type:"tool-call",toolCallId:G.toolCallId,toolName:G.toolName,input:G.input,providerMetadata:G.providerMetadata}));let z=$.tools[G.toolName];if(!z?.execute){yield*Q(U0({type:"tool-error",toolCallId:G.toolCallId,toolName:G.toolName,input:G.input,error:Error(`Tool "${G.toolName}" has no executor`)}));continue}let O=yield*Y.tryPromise({try:()=>z.execute(G.input,{toolCallId:G.toolCallId,messages:$.messages,abortSignal:H.signal}),catch:(P)=>P}).pipe(Y.map((P)=>({ok:!0,output:P})),Y.catch((P)=>Y.succeed({ok:!1,error:P})));if(!O.ok){yield*Q(U0({type:"tool-error",toolCallId:G.toolCallId,toolName:G.toolName,input:G.input,error:O.error}));continue}yield*Q(U0({type:"tool-result",toolCallId:G.toolCallId,toolName:G.toolName,input:G.input,output:O.output}))}if(yield*Q(U0({type:"finish-step",usage:$.usage??W,finishReason:$.finishReason,providerMetadata:$.providerMetadata})),$.overhead&&($.overhead.cost>0||$.overhead.tokensIn>0||$.overhead.tokensOut>0))yield*D($)}).pipe(Y.onInterrupt(()=>{if(B(),H.abort(),Z.context.assistantMessage.error)return Y.void;return V(new DOMException("Aborted","AbortError"))}),Y.catchCauseIf((K)=>!G2.hasInterruptsOnly(K),(K)=>Y.fail(G2.squash(K))),Y.catch(V),Y.ensuring(J()),Y.map(()=>{if(X.needsOverflowHandling)return"overflow";if(X.blocked||X.assistantMessage.error)return"stop";return"continue"}))}function S5($){let{ctx:Z,session:X}=$,Q=Y.fn("SessionProcessor.settleToolCall")(function*(K){let j=Z.toolcalls[K]?.done;if(delete Z.toolcalls[K],j)yield*k2.succeed(j,void 0).pipe(Y.ignore)}),J=Y.fn("SessionProcessor.readToolCall")(function*(K){let j=Z.toolcalls[K];if(!j)return;let G=yield*X.getPart({partID:j.partID,messageID:j.messageID,sessionID:j.sessionID});if(!G||G.type!=="tool"){delete Z.toolcalls[K];return}return{call:j,part:G}}),V=Y.fn("SessionProcessor.updateToolCall")(function*(K,j){let G=yield*J(K);if(!G)return;let z=yield*X.updatePart(j(G.part));return Z.toolcalls[K]={...G.call,partID:z.id,messageID:z.messageID,sessionID:z.sessionID},z}),B=Y.fn("SessionProcessor.completeToolCall")(function*(K,j){let G=yield*J(K);if(!G||G.part.state.status!=="running")return;if(yield*X.updatePart({...G.part,state:{status:"completed",input:G.part.state.input,output:j.output,metadata:j.metadata,title:j.title,time:{start:G.part.state.time.start,end:Date.now()},attachments:j.attachments}}),j.metadata?.declined===!0)Z.blocked=Z.shouldBreak;yield*Q(K)}),D=Y.fn("SessionProcessor.failToolCall")(function*(K,j){let G=yield*J(K);if(!G||G.part.state.status!=="running")return!1;let z=C5(j);if(yield*X.updatePart({...G.part,state:{status:"error",input:G.part.state.input,error:O$(j),...z?{metadata:{...G.part.state.metadata,recoverable:!0}}:{},time:{start:G.part.state.time.start,end:Date.now()}}}),j instanceof O2.RejectedError||j instanceof w6.RejectedError)Z.blocked=Z.shouldBreak;return yield*Q(K),!0});return{settleToolCall:Q,readToolCall:J,updateToolCall:V,completeToolCall:B,failToolCall:D,isBackendAuthRejection:(K)=>{let j=K;for(let G=0;G<5&&j!==void 0&&j!==null;G++){if(j instanceof $0.BackendAuthRejectedError)return!0;if(j instanceof Error&&j.name==="BackendAuthRejectedError")return!0;j=j instanceof Error?j.cause:void 0}return!1},backendBillingFailureMessage:(K)=>{let j=K;for(let G=0;G<5&&j!==void 0&&j!==null;G++){let z=j instanceof Error?j.name:void 0;if(j instanceof $0.BackendInsufficientBalanceError||z==="BackendInsufficientBalanceError")return M7.copy().insufficientBalance();if(j instanceof $0.BackendRateLimitError||z==="BackendRateLimitError")return M7.copy().rateLimit;j=j instanceof Error?j.cause:void 0}return}}}var b6=Y.fn("SessionProcessor.applySnapshotPatch")(function*($){if(!$.ctx.snapshot)return 0;let Z=yield*$.snapshot.patch($.ctx.snapshot);if(Z.files.length)yield*$.session.updatePart({id:Q2.ascending(),messageID:$.ctx.assistantMessage.id,sessionID:$.ctx.sessionID,type:"patch",hash:Z.hash,files:Z.files});return $.ctx.snapshot=void 0,Z.files.length});function T5($){let{ctx:Z,session:X,snapshot:Q,readToolCall:J}=$;return Y.fn("SessionProcessor.cleanup")(function*(){if(yield*b6({ctx:Z,session:X,snapshot:Q}),Z.currentText){let V=Date.now();Z.currentText.time={start:Z.currentText.time?.start??V,end:V},yield*X.updatePart(Z.currentText),Z.currentText=void 0}for(let V of Object.values(Z.reasoningMap)){let B=Date.now();yield*X.updatePart({...V,time:{start:V.time.start??B,end:B}})}Z.reasoningMap={},yield*Y.forEach(Object.values(Z.toolcalls),(V)=>k2.await(V.done).pipe(Y.timeout("250 millis"),Y.ignore),{concurrency:"unbounded"});for(let V of Object.keys(Z.toolcalls)){let B=yield*J(V);if(!B)continue;let D=B.part,H=Date.now(),W="metadata"in D.state&&k5(D.state.metadata)?D.state.metadata:{};yield*X.updatePart({...D,state:{...D.state,status:"error",error:"Tool execution aborted",metadata:{...W,interrupted:!0},time:{start:"time"in D.state?D.state.time.start:H,end:H}}})}Z.toolcalls={},Z.assistantMessage.time.completed=Date.now(),yield*X.updateMessage(Z.assistantMessage)})}var wB=20000,bB=20000;function b1($){let Z=$.model.limit.context;if(Z===0)return 0;let X=$.cfg.compaction?.reserved??Math.min(wB,p2.maxOutputTokens($.model)),Q=Math.min(p2.maxOutputTokens($.model),bB);return $.model.limit.input?Math.max(0,$.model.limit.input-X):Math.max(0,Z-Q-X)}function L1($){if($.cfg.compaction?.auto===!1)return!1;if($.model.limit.context===0)return!1;return($.tokens.total||$.tokens.input+$.tokens.output+$.tokens.cache.read+$.tokens.cache.write)>=b1($)}function L6($){if($.cfg.compaction?.auto===!1)return 0;if($.model.limit.context===0)return 0;let Z=$.tokens.total||$.tokens.input+$.tokens.output+$.tokens.cache.read+$.tokens.cache.write,X=b1($);if(X===0)return 0;let Q=Z/X;if(Q<0.5)return 0;if(Q<0.7)return 1;if(Q<0.85)return 2;return 3}function g5($){let{ctx:Z,session:X,snapshot:Q,bus:J,config:V,summary:B,scope:D}=$;return Y.fnUntraced(function*(H){let W=U6({model:Z.model,usage:H.usage,metadata:H.providerMetadata});if(Z.assistantMessage.finish=H.finishReason,Z.assistantMessage.cost+=W.cost,Z.assistantMessage.tokens=W.tokens,W.contextWindow!==void 0)Z.assistantMessage.contextWindow=W.contextWindow;yield*X.updatePart({id:Q2.ascending(),reason:H.finishReason,snapshot:yield*Q.track(),messageID:Z.assistantMessage.id,sessionID:Z.assistantMessage.sessionID,type:"step-finish",tokens:W.tokens,cost:W.cost,contextWindow:W.contextWindow}),yield*X.updateMessage(Z.assistantMessage);let K=yield*b6({ctx:Z,session:X,snapshot:Q}),j=W.tokens.input+W.tokens.cache.read+W.tokens.cache.write,G=W.tokens.output+W.tokens.reasoning;if(Z.agentMetrics)Z.agentMetrics.tokens_in+=j,Z.agentMetrics.tokens_out+=G,Z.agentMetrics.files_changed+=K;if(yield*J.publish(C2.ModelCall,{sessionID:Z.sessionID,finish_reason:H.finishReason,ttft_ms:Z.firstTokenAt&&Z.stepStartedAt?Z.firstTokenAt-Z.stepStartedAt:void 0,latency_ms:Z.stepStartedAt?Date.now()-Z.stepStartedAt:0,cached_read_tokens:W.tokens.cache.read,model_id:Z.model.id,provider:Z.model.providerID,total_tokens_in:j,total_tokens_out:G}).pipe(Y.ignore),yield*B.summarize({sessionID:Z.sessionID,messageID:Z.assistantMessage.parentID}).pipe(Y.ignore,Y.forkIn(D)),!Z.assistantMessage.summary&&L1({cfg:yield*V.get(),tokens:W.tokens,model:Z.model}))Z.needsOverflowHandling=!0})}var h5=3,LB=s.create({service:"session.processor.events"});function f5($){let{ctx:Z,session:X,snapshot:Q,agents:J,permission:V,plugin:B,bus:D,status:H,isMain:W,checkTextNgram:K,updateToolCall:j,completeToolCall:G,failToolCall:z,isBackendAuthRejection:O,backendBillingFailureMessage:P,finishStep:w}=$;return Y.fnUntraced(function*(F){switch(F.type){case"start":if(W)yield*H.set(Z.sessionID,{type:"busy"});return;case"reasoning-start":if(F.id in Z.reasoningMap)return;Z.reasoningMap[F.id]={id:Q2.ascending(),messageID:Z.assistantMessage.id,sessionID:Z.assistantMessage.sessionID,type:"reasoning",text:"",time:{start:F.time?.start??Date.now()},metadata:F.providerMetadata},yield*X.updatePart(Z.reasoningMap[F.id]),Z.stepPartIds.push(Z.reasoningMap[F.id].id);return;case"reasoning-delta":if(!Z.firstTokenAt)Z.firstTokenAt=Date.now();if(!(F.id in Z.reasoningMap))return;if(Z.reasoningMap[F.id].text+=F.text,K(F.text),F.providerMetadata)Z.reasoningMap[F.id].metadata=F.providerMetadata;yield*X.updatePartDelta({sessionID:Z.reasoningMap[F.id].sessionID,messageID:Z.reasoningMap[F.id].messageID,partID:Z.reasoningMap[F.id].id,field:"text",delta:F.text});return;case"reasoning-end":if(!(F.id in Z.reasoningMap))return;if(Z.reasoningMap[F.id].text=Z.reasoningMap[F.id].text,Z.reasoningMap[F.id].time={...Z.reasoningMap[F.id].time,end:Date.now()},F.providerMetadata)Z.reasoningMap[F.id].metadata=F.providerMetadata;yield*X.updatePart(Z.reasoningMap[F.id]),delete Z.reasoningMap[F.id];return;case"tool-input-start":if(Z.assistantMessage.summary)throw Error(`Tool call not allowed while generating summary: ${F.toolName}`);let U=yield*X.updatePart({id:Z.toolcalls[F.id]?.partID??Q2.ascending(),messageID:Z.assistantMessage.id,sessionID:Z.assistantMessage.sessionID,type:"tool",tool:F.toolName,callID:F.id,state:{status:"pending",input:{},raw:""},metadata:F.providerExecuted?{providerExecuted:!0}:void 0});Z.stepPartIds.push(U.id),Z.toolcalls[F.id]={done:yield*k2.make(),partID:U.id,messageID:U.messageID,sessionID:U.sessionID};return;case"tool-input-delta":return;case"tool-input-end":return;case"tool-call":{if(Z.assistantMessage.summary)throw Error(`Tool call not allowed while generating summary: ${F.toolName}`);yield*j(F.toolCallId,(b)=>({...b,tool:F.toolName,state:{...b.state,status:"running",input:F.input,time:{start:Date.now()}},metadata:b.metadata?.providerExecuted?{...F.providerMetadata,providerExecuted:!0}:F.providerMetadata}));let I=p.parts(Z.assistantMessage.id).slice(-h5),M=JSON.stringify(F.input);if(I.length!==h5||!I.every((b)=>b.type==="tool"&&b.tool===F.toolName&&b.state.status!=="pending"&&JSON.stringify(b.state.input)===M))return;let f=yield*J.get(Z.assistantMessage.agent);yield*V.ask({permission:"doom_loop",patterns:[F.toolName],sessionID:Z.assistantMessage.sessionID,metadata:{tool:F.toolName,input:F.input},always:[F.toolName],ruleset:f.permission,interactive:!A6.has(Z.assistantMessage.agent)});return}case"tool-result":{yield*G(F.toolCallId,F.output);return}case"tool-error":{yield*z(F.toolCallId,F.error);let S=O(F.error)?O$(F.error):P(F.error);if(S)yield*D.publish(U2.Error,{sessionID:Z.sessionID,error:new w2.Unknown({message:S}).toObject()});yield*D.publish(C2.ToolCall,{sessionID:Z.sessionID,tool_name:F.toolName,input_bytes:C2.jsonByteLength(F.input),output_bytes:0,tool_call_id:F.toolCallId,tool_call_status:"error"}).pipe(Y.ignore);return}case"error":throw F.error;case"start-step":if(Z.stepStartedAt=Date.now(),Z.firstTokenAt=void 0,!Z.snapshot)Z.snapshot=yield*Q.track();let y=Q2.ascending();yield*X.updatePart({id:y,messageID:Z.assistantMessage.id,sessionID:Z.sessionID,snapshot:Z.snapshot,type:"step-start"}),Z.stepPartIds.push(y);return;case"finish-step":yield*w(F);return;case"text-start":Z.currentText={id:Q2.ascending(),messageID:Z.assistantMessage.id,sessionID:Z.assistantMessage.sessionID,type:"text",text:"",time:{start:Date.now()},metadata:F.providerMetadata},yield*X.updatePart(Z.currentText),Z.stepPartIds.push(Z.currentText.id);return;case"text-delta":if(!Z.firstTokenAt)Z.firstTokenAt=Date.now();if(!Z.currentText)return;if(Z.currentText.text+=F.text,K(F.text),F.providerMetadata)Z.currentText.metadata=F.providerMetadata;yield*X.updatePartDelta({sessionID:Z.currentText.sessionID,messageID:Z.currentText.messageID,partID:Z.currentText.id,field:"text",delta:F.text});return;case"text-end":if(!Z.currentText)return;Z.currentText.text=Z.currentText.text,Z.currentText.text=(yield*B.trigger("experimental.text.complete",{sessionID:Z.sessionID,messageID:Z.assistantMessage.id,partID:Z.currentText.id},{text:Z.currentText.text})).text;{let S=Date.now();Z.currentText.time={start:Z.currentText.time?.start??S,end:S}}if(F.providerMetadata)Z.currentText.metadata=F.providerMetadata;yield*X.updatePart(Z.currentText),Z.currentText=void 0;return;case"finish":return;default:LB.info("unhandled",{event:F.type,value:F});return}})}var UB=s.create({service:"session.processor"});class M6 extends Z2.Service()("@qitqode/SessionProcessor"){}var l5=_.effect(M6,Y.gen(function*(){let $=yield*E2,Z=yield*V2.Service,X=yield*u.Service,Q=yield*z0.Service,J=yield*h2.Service,V=yield*f2.Service,B=yield*O2.Service,D=yield*K2.Service,H=yield*q0.Service,W=yield*d2.Scope,K=yield*y0.Service,j=Y.fn("SessionProcessor.create")(function*(G){let z=yield*Q.track(),O={assistantMessage:G.assistantMessage,sessionID:G.sessionID,model:G.model,agentMetrics:G.agentMetrics,toolcalls:{},shouldBreak:!1,snapshot:z,blocked:!1,needsOverflowHandling:!1,currentText:void 0,reasoningMap:{},stepStartedAt:void 0,firstTokenAt:void 0,stepPartIds:[],textNgramMonitor:void 0,textNgramRepeat:!1},P=!1,w=!O.assistantMessage.agentID||O.assistantMessage.agentID==="main",L=UB.clone().tag("session.id",G.sessionID).tag("messageID",G.assistantMessage.id),F=(d)=>p.fromError(d,{providerID:G.model.providerID,aborted:P}),U=S5({ctx:O,session:$}),{settleToolCall:y,readToolCall:S,updateToolCall:I,completeToolCall:M,failToolCall:f,isBackendAuthRejection:b,backendBillingFailureMessage:k}=U,h=(d)=>{if(O.textNgramRepeat||!O.textNgramMonitor)return;if(O.textNgramMonitor.append(d))O.textNgramRepeat=!0},N=g5({ctx:O,session:$,snapshot:Q,bus:X,config:Z,summary:H,scope:W}),A=f5({ctx:O,session:$,snapshot:Q,agents:J,permission:B,plugin:D,bus:X,status:K,isMain:w,checkTextNgram:h,updateToolCall:I,completeToolCall:M,failToolCall:f,isBackendAuthRejection:b,backendBillingFailureMessage:k,finishStep:N}),R=T5({ctx:O,session:$,snapshot:Q,readToolCall:S}),C=Y.fn("SessionProcessor.halt")(function*(d){L.error("process",{error:O$(d),stack:d instanceof Error?d.stack:void 0});let g=F(d);if(p.ContextOverflowError.isInstance(g)){O.needsOverflowHandling=!0,yield*X.publish(U2.Error,{sessionID:O.sessionID,error:g});return}if(O.assistantMessage.error=g,yield*X.publish(U2.Error,{sessionID:O.assistantMessage.sessionID,error:O.assistantMessage.error}),w)yield*K.set(O.sessionID,{type:"idle"})}),T=Y.fn("SessionProcessor.process")(function*(d){return L.info("process"),O.needsOverflowHandling=!1,O.shouldBreak=(yield*Z.get()).experimental?.continue_loop_on_deny!==!0,yield*Y.gen(function*(){if(yield*Y.gen(function*(){O.currentText=void 0,O.reasoningMap={},O.stepPartIds=[],O.toolcalls={},O.textNgramRepeat=!1,O.textNgramMonitor=x6(),yield*V.stream(d).pipe(E5((E)=>A(E)),v5(()=>O.needsOverflowHandling||O.textNgramRepeat),d5)}).pipe(Y.onInterrupt(()=>Y.gen(function*(){if(P=!0,!O.assistantMessage.error)yield*C(new DOMException("Aborted","AbortError"))})),Y.catchCauseIf((g)=>!G2.hasInterruptsOnly(g),(g)=>Y.fail(G2.squash(g))),Y.tapError(()=>Y.gen(function*(){for(let g of O.stepPartIds)yield*$.removePart({sessionID:O.sessionID,messageID:O.assistantMessage.id,partID:g});O.stepPartIds=[]})),Y.retry(m5.policy({parse:F,set:(g)=>w?K.set(O.sessionID,{type:"retry",attempt:g.attempt,message:g.message,next:g.next}):Y.void})),Y.catch(C),Y.ensuring(R())),O.needsOverflowHandling)return"overflow";if(!O.textNgramRepeat&&!O.assistantMessage.error){let g=new Set(O.stepPartIds);for(let E of p.parts(O.assistantMessage.id)){if(!g.has(E.id))continue;if(E.type!=="text"&&E.type!=="reasoning")continue;if(D6(E.text)){L.info("fake tool tag detected in end-of-turn sweep",{partID:E.id}),O.textNgramRepeat=!0;break}}}if(O.textNgramRepeat){let g=new Set(O.stepPartIds),E=new Set;for(let m of p.parts(O.assistantMessage.id)){if(!g.has(m.id))continue;if(m.type!=="text"&&m.type!=="reasoning")continue;yield*$.removePart({sessionID:O.sessionID,messageID:O.assistantMessage.id,partID:m.id}),E.add(m.id)}return O.stepPartIds=O.stepPartIds.filter((m)=>!E.has(m)),"text-repeat"}if(O.blocked||O.assistantMessage.error)return"stop";return"continue"})}),l=Y.fn("SessionProcessor.replay")(function*(d){return L.info("replay",{toolCalls:d.toolCalls.length,finish:d.finishReason}),O.needsOverflowHandling=!1,O.shouldBreak=(yield*Z.get()).experimental?.continue_loop_on_deny!==!0,yield*R5(d,{context:O,handleEvent:A,cleanup:R,halt:C,setAborted:()=>{P=!0},recordOverhead:(g)=>{let E=g.overhead;if(!E)return Y.void;return O.assistantMessage.cost+=E.cost,Y.gen(function*(){if(yield*$.updateMessage(O.assistantMessage),O.agentMetrics)O.agentMetrics.tokens_in+=E.tokensIn,O.agentMetrics.tokens_out+=E.tokensOut;yield*X.publish(C2.ModelCall,{sessionID:O.sessionID,finish_reason:"max-mode-overhead",latency_ms:0,cached_read_tokens:0,model_id:O.model.id,provider:O.model.providerID,total_tokens_in:E.tokensIn,total_tokens_out:E.tokensOut}).pipe(Y.ignore)})}})});return{get message(){return O.assistantMessage},updateToolCall:I,completeToolCall:M,process:T,replay:l}});return M6.of({create:j})})),AB=_.suspend(()=>l5.pipe(_.provide(v0),_.provide(z0.defaultLayer),_.provide(h2.defaultLayer),_.provide(f2.defaultLayer),_.provide(O2.defaultLayer),_.provide(K2.defaultLayer),_.provide(q0.defaultLayer),_.provide(y0.defaultLayer),_.provide(u.layer),_.provide(V2.defaultLayer)));var F$={};L2(F$,{prune:()=>kB,layer:()=>n5,isOverflow:()=>SB,extractQortexSummary:()=>p5,defaultLayer:()=>s5,create:()=>TB,SessionCompaction:()=>F$,Service:()=>j8,PRUNE_PROTECT:()=>_7,PRUNE_MINIMUM:()=>U1,Event:()=>i5});var U1=20000,_7=40000,MB=["skill"];function I6($){let Z=0,X=0,Q=[],J=0;$:for(let V=$.length-1;V>=0;V--){let B=$[V];if(B.info.role==="user")J++;if(J<2)continue;if(B.info.role==="assistant"&&B.info.summary)break $;for(let D=B.parts.length-1;D>=0;D--){let H=B.parts[D];if(H.type==="tool"){if(H.state.status==="completed"){if(MB.includes(H.tool))continue;if(H.state.time.compacted)break $;let W=_6.estimate(H.state.output);if(Z+=W,Z>_7)X+=W,Q.push(H)}}}}return{total:Z,pruned:X,toPrune:Q}}function R6($,Z){return Y.gen(function*(){for(let X of $){if(X.state.status!=="completed")continue;X.state.time.compacted=Date.now(),yield*Z(X)}})}function c5($,Z){let X=(Q)=>{let J;try{J=$.parse(Q)}catch(V){if(V instanceof y2.ZodError){let B=JSON.stringify(V.issues,null,2);throw Error(`Schema validation failed:
|
|
129
|
+
${B}`,{cause:V})}throw V}return Z(J)};return X.force=(Q)=>Z(Q),X.schema=$,X}var e$=s.create({service:"session.compaction"});function p5($){if($.summary)return $.summary;if(!Array.isArray($.messages)||$.messages.length===0)return null;let Z=$.startIndex??0;for(let X=Z;X<$.messages.length;X++){let Q=$.messages[X];if(Q?.role!=="assistant")continue;let J=Q.content;if(typeof J==="string"&&J.trim())return J.trim();if(Array.isArray(J)){let V=J.filter((B)=>B?.type==="text"&&typeof B?.text==="string").map((B)=>B.text).join(`
|
|
130
|
+
`).trim();if(V)return V}}return null}var i5={Compacted:D2.define("session.compacted",q.object({sessionID:F2.zod}))},o5=2,_B=2000,IB=8000;function RB($){return $.cfg.compaction?.preserve_recent_tokens??Math.min(IB,Math.max(_B,Math.floor(b1($)*0.25)))}function CB($){let Z=[];for(let X=0;X<$.length;X++){let Q=$[X];if(Q.info.role!=="user")continue;if(Q.parts.some((J)=>J.type==="compaction"))continue;Z.push({start:X,end:$.length,id:Q.info.id})}for(let X=0;X<Z.length-1;X++)Z[X].end=Z[X+1].start;return Z}class j8 extends Z2.Service()("@qitqode/SessionCompaction"){}var n5=_.effect(j8,Y.gen(function*(){let $=yield*u.Service,Z=yield*V2.Service,X=yield*E2,Q=yield*h2.Service,J=yield*K2.Service,V=yield*d0.Service,B=yield*P2.Service,D=Y.fn("SessionCompaction.isOverflow")(function*(P){return L1({cfg:yield*Z.get(),tokens:P.tokens,model:P.model})}),H=5000,W=new Map,K=Y.fn("SessionCompaction.estimate")(function*(P){let w=`${P.model.providerID}\x00${P.model.id}\x00${P.model.api.npm}\x00${P.model.api.id}`,L=0;for(let F of P.messages){let U=`${w}\x00${p.fingerprint(F)}`,y=W.get(U);if(y===void 0){let S=yield*p.toModelMessagesEffect([F],P.model);y=0;for(let I of S)y+=_6.estimate(JSON.stringify(I));if(W.size>=5000)W.delete(W.keys().next().value);W.set(U,y)}else W.delete(U),W.set(U,y);L+=y}return L}),j=Y.fn("SessionCompaction.select")(function*(P){let w=P.cfg.compaction?.tail_turns??o5;if(w<=0)return{head:P.messages,tail_start_id:void 0};let L=RB({cfg:P.cfg,model:P.model}),F=CB(P.messages);if(!F.length)return{head:P.messages,tail_start_id:void 0};let U=F.slice(-w),y=yield*Y.forEach(U,(M)=>K({messages:P.messages.slice(M.start,M.end),model:P.model}),{concurrency:1});if(y.at(-1)>L)return e$.info("tail fallback",{tokenBudget:L,size:y.at(-1)}),{head:P.messages,tail_start_id:void 0};let S=0,I;for(let M=U.length-1;M>=0;M--){let f=y[M];if(S+f>L)break;S+=f,I=U[M]}if(!I||I.start===0)return{head:P.messages,tail_start_id:void 0};return{head:P.messages.slice(0,I.start),tail_start_id:I.id}}),G=Y.fn("SessionCompaction.prune")(function*(P){if(!(yield*Z.get()).compaction?.prune)return;e$.info("pruning",{agentID:P.agentID??"main"});let L=yield*p.filterCompactedEffect(P.sessionID,{agentID:P.agentID}).pipe(Y.catchIf(D8.isInstance,()=>Y.succeed(void 0)));if(!L)return;let{total:F,pruned:U,toPrune:y}=I6(L);if(e$.info("found",{pruned:U,total:F}),U>U1)yield*R6(y,(S)=>X.updatePart(S)),e$.info("pruned",{count:y.length})}),z=Y.fn("SessionCompaction.process")(function*(P){let w=P.messages.findLast((g)=>g.info.id===P.parentID);if(!w||w.info.role!=="user")throw Error(`Compaction parent must be a user message: ${P.parentID}`);let L=w.info,F=w.parts.find((g)=>g.type==="compaction"),U=P.messages,y;if(P.overflow){let g=P.messages.findIndex((m)=>m.info.id===P.parentID);for(let m=g-1;m>=0;m--){let e=P.messages[m];if(e.info.role==="user"&&!e.parts.some((n)=>n.type==="compaction")){y={info:e.info,parts:e.parts},U=P.messages.slice(0,m);break}}if(!(y&&U.some((m)=>m.info.role==="user"&&!m.parts.some((e)=>e.type==="compaction"))))y=void 0,U=P.messages}let S=yield*Q.get("compaction"),I=S.model?yield*B.getModel(S.model.providerID,S.model.modelID):yield*B.getModel(L.model.providerID,L.model.modelID),M=yield*Z.get(),f=F&&U.at(-1)?.info.id===P.parentID?U.slice(0,-1):U,b=yield*j({messages:f,cfg:M,model:I}),k=yield*J.trigger("experimental.session.compacting",{sessionID:P.sessionID},{context:[],prompt:void 0}),h=`When constructing the summary, try to stick to this template:
|
|
131
|
+
---
|
|
132
|
+
## Goal
|
|
133
|
+
|
|
134
|
+
[What goal(s) is the user trying to accomplish?]
|
|
135
|
+
|
|
136
|
+
## Instructions
|
|
137
|
+
|
|
138
|
+
- [What important instructions did the user give you that are relevant]
|
|
139
|
+
- [If there is a plan or spec, include information about it so next agent can continue using it]
|
|
140
|
+
|
|
141
|
+
## Discoveries
|
|
142
|
+
|
|
143
|
+
[What notable things were learned during this conversation that would be useful for the next agent to know when continuing the work]
|
|
144
|
+
|
|
145
|
+
## Accomplished
|
|
146
|
+
|
|
147
|
+
[What work has been completed, what work is still in progress, and what work is left?]
|
|
148
|
+
|
|
149
|
+
## Relevant files / directories
|
|
150
|
+
|
|
151
|
+
[Construct a structured list of relevant files that have been read, edited, or created that pertain to the task at hand. If all the files in a directory are relevant, include the path to the directory.]
|
|
152
|
+
---`,N=k.prompt??[h,...k.context].join(`
|
|
153
|
+
|
|
154
|
+
`),A=structuredClone(b.head);yield*J.trigger("experimental.chat.messages.transform",{},{messages:A});let R=yield*p.toModelMessagesEffect(A,I,{stripMedia:!0}),C=yield*v.context,T={id:x2.ascending(),role:"assistant",parentID:P.parentID,sessionID:P.sessionID,agentID:P.agentID??void 0,mode:"compaction",agent:"compaction",variant:L.model.variant,summary:!0,path:{cwd:C.directory,root:C.worktree},cost:0,tokens:{output:0,input:0,reasoning:0,cache:{read:0,write:0}},modelID:I.id,providerID:I.providerID,time:{created:Date.now()}},l=null,d=yield*Y.promise(()=>$0.resolveCompressTrajectorySafe({messages:R,tier:"economical",protectFirstSystem:!0,protectFirstUser:!0,protectLastTurns:M.compaction?.tail_turns??o5}).catch((g)=>{let E=$0.isBackendBillingError(g);return e$.warn(E?"compressTrajectorySafe rejected (qredits/rate limit); using local compaction fallback":"compressTrajectorySafe unavailable; using local compaction fallback",{error:g instanceof Error?g.message:String(g),...E?{billing:!0}:{},sessionID:P.sessionID}),null}));if(d!==null){if(!d.safe)e$.info("compressTrajectorySafe: no safe middle span; falling back to local compaction",{sessionID:P.sessionID,reason:d.reason});else if(l=p5(d),l===null)e$.warn("compressTrajectorySafe: could not extract summary text; using local compaction fallback",{sessionID:P.sessionID})}if(l!==null){let g=Date.now();yield*X.updateMessage(T),yield*X.updatePart({id:Q2.ascending(),messageID:T.id,sessionID:P.sessionID,type:"text",text:l,time:{start:g,end:g}}),yield*X.updateMessage({...T,finish:"done"})}else{yield*X.updateMessage(T);let g=yield*V.create({assistantMessage:T,sessionID:P.sessionID,model:I}),E=yield*g.process({user:L,agent:S,sessionID:P.sessionID,tools:{},system:[],messages:[...R,{role:"user",content:[{type:"text",text:N}]}],model:I});if(E==="overflow")return g.message.error=new p.ContextOverflowError({message:y?"Conversation history too large to compact - exceeds model context limit":"Session too large to compact - context exceeds model limit even after stripping media"}).toObject(),g.message.finish="error",yield*X.updateMessage(g.message),"stop";if(E==="text-repeat")return"stop";if(g.message.error)return"stop"}if(F&&b.tail_start_id&&F.tail_start_id!==b.tail_start_id)yield*X.updatePart({...F,tail_start_id:b.tail_start_id});if(P.auto){if(y){let g=y.info,E=yield*X.updateMessage({id:x2.ascending(),role:"user",sessionID:P.sessionID,agentID:P.agentID??void 0,time:{created:Date.now()},agent:g.agent,model:g.model,format:g.format,tools:g.tools,system:g.system});for(let m of y.parts){if(m.type==="compaction")continue;let e=m.type==="file"&&p.isMedia(m.mime)?{type:"text",text:`[Attached ${m.mime}: ${m.filename??"file"}]`}:m;yield*X.updatePart({...e,id:Q2.ascending(),messageID:E.id,sessionID:P.sessionID})}}if(!y){let g=yield*B.getProvider(L.model.providerID);if((yield*J.trigger("experimental.compaction.autocontinue",{sessionID:P.sessionID,agent:L.agent,model:yield*B.getModel(L.model.providerID,L.model.modelID),provider:{source:g.source,info:g,options:g.options},message:L,overflow:P.overflow===!0},{enabled:!0})).enabled){let E=yield*X.updateMessage({id:x2.ascending(),role:"user",sessionID:P.sessionID,agentID:P.agentID??void 0,time:{created:Date.now()},agent:L.agent,model:L.model}),m=(P.overflow?`The previous request exceeded the provider's size limit due to large media attachments. The conversation was compacted and media files were removed from context. If the user was asking about attached images or files, explain that the attachments were too large to process and suggest they try again with smaller or fewer files.
|
|
155
|
+
|
|
156
|
+
`:"")+"Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.";yield*X.updatePart({id:Q2.ascending(),messageID:E.id,sessionID:P.sessionID,type:"text",metadata:{compaction_continue:!0},synthetic:!0,text:m,time:{start:Date.now(),end:Date.now()}})}}}return yield*$.publish(i5.Compacted,{sessionID:P.sessionID}),"continue"}),O=Y.fn("SessionCompaction.create")(function*(P){let w=yield*X.updateMessage({id:x2.ascending(),role:"user",model:P.model,sessionID:P.sessionID,agentID:P.agentID??void 0,agent:P.agent,time:{created:Date.now()}});yield*X.updatePart({id:Q2.ascending(),messageID:w.id,sessionID:w.sessionID,type:"compaction",auto:P.auto,overflow:P.overflow})});return j8.of({isOverflow:D,prune:G,process:z,create:O})})),s5=_.suspend(()=>n5.pipe(_.provide(P2.defaultLayer),_.provide(v0),_.provide(d0.defaultLayer),_.provide(h2.defaultLayer),_.provide(K2.defaultLayer),_.provide(u.layer),_.provide(V2.defaultLayer))),{runPromise:I7}=u5(j8,s5);function SB($){return I7((Z)=>Z.isOverflow($))}function kB($){return I7((Z)=>Z.prune($))}var TB=c5(q.object({sessionID:F2.zod,agent:q.string(),model:q.object({providerID:$1.zod,modelID:t0.zod}),auto:q.boolean(),overflow:q.boolean().optional(),agentID:q.string().optional()}),($)=>I7((Z)=>Z.create($)));var z$={};L2(z$,{resolveThresholds:()=>e5,parseThreshold:()=>t5,layer:()=>$X,defaultThresholdsFor:()=>r5,defaultLayer:()=>mB,SessionPrune:()=>z$,Service:()=>C6});var e0=s.create({service:"session.prune"}),gB=4096,hB=1536,fB=1536,EB=300000,vB=13000,dB=3;function r5($){if($<25000)return[];if($<=200000)return["20%","40%","60%","80%"];if($<=500000)return["10%","20%","30%","40%","50%","60%","70%","80%","90%"];return Array.from({length:18},(Z,X)=>`${(X+1)*5}%`)}function a5($,Z){if(!$)return!0;let X=$.cacheTTL??EB;if(!Z)return!0;return Date.now()-Z>X}function t5($,Z){let X=$.trim();if(X.endsWith("%")){let B=parseFloat(X.slice(0,-1));if(!Number.isFinite(B)||B<=0||B>100)throw Error(`Invalid checkpoint threshold percentage: "${$}" (must be 0 < n <= 100)`);let D=Math.floor(Z*B/100);if(D<=0)throw Error(`Invalid checkpoint threshold percentage: "${$}" (resolves to zero tokens)`);return D}let Q=X.match(/^(\d+(?:\.\d+)?)([KkMm]?)$/);if(!Q)throw Error(`Invalid checkpoint threshold format: "${$}"`);let J=parseFloat(Q[1]);if(Q[2]==="K"||Q[2]==="k")J*=1000;else if(Q[2]==="M"||Q[2]==="m")J*=1e6;let V=Math.floor(J);if(V<=0)throw Error(`Invalid checkpoint threshold: "${$}" (must be greater than 0)`);return V}function e5($,Z,X){let Q=X??vB,J=Z-Q;if(J<=0)throw Error(`Model window size (${Z}) is too small for checkpoints (need > ${Q} reserved tokens)`);let V=$.map((K)=>({raw:K,value:t5(K,Z)})),B=[],D=!1;for(let K of V){if(K.value<=J){B.push(K.value);continue}if(!D){e0.info(`checkpoint threshold "${K.raw}" (${K.value}) exceeds maxAllowed (${J}) \u2014 clamped to maxAllowed`),B.push(J),D=!0;continue}e0.info(`checkpoint threshold "${K.raw}" (${K.value}) exceeds maxAllowed (${J}) \u2014 dropped (already clamped earlier)`)}let H=B.sort((K,j)=>K-j),W=[];for(let K of H)if(W.length===0||W[W.length-1]!==K)W.push(K);return W}class C6 extends Z2.Service()("@qitqode/SessionPrune"){}var $X=_.effect(C6,Y.gen(function*(){let $=yield*V2.Service,Z=yield*E2,X=yield*P$.Service,Q=yield*M2.Service,J=new Map,V=new Set,B=new Map,D=Y.fn("SessionPrune.stripNonEssential")(function*(G){if(!a5(G.model,G.lastAssistantTime))return;let z=yield*Z.messages({sessionID:G.sessionID,agentID:"main"}).pipe(Y.catchIf(D8.isInstance,()=>Y.succeed(void 0)));if(!z)return;let O=0,P=z.length;for(let L=z.length-1;L>=0;L--){if(z[L].info.role==="user")O++;if(O>3){P=L;break}}let w=0;for(let L=0;L<P;L++){let F=z[L];for(let U of F.parts){if(U.type==="file"&&p.isMedia(U.mime))yield*Z.updatePart({...U,url:"",filename:`[stripped: ${U.filename??U.mime}]`}),w++;if(U.type==="reasoning"&&F.info.role==="assistant")yield*Z.updatePart({...U,text:""}),w++}}if(w>0)e0.info("stripped non-essential content",{count:w})}),H=Y.fn("SessionPrune.fireCheckpoints")(function*(G){if(G.agentID&&(yield*Q.isSystemSpawned(G.sessionID,G.agentID)))return;if((G.agentID?yield*Q.get(G.sessionID,G.agentID):void 0)?.mode==="subagent")return;if(yield*X.isWriterRunning(G.sessionID)){e0.info("checkpoint writer running, skipping new threshold trigger",{sessionID:G.sessionID});return}let O=yield*$.get(),P=b1({cfg:O,model:G.model});if(P===0)return;let w=O.checkpoint?.thresholds??r5(P),L=e5(w,P,O.checkpoint?.reserved);if(L.length===0)return;let F=O.checkpoint?.max_writer_failures??dB,U=G.tokens.total||G.tokens.input+G.tokens.output+G.tokens.cache.read+G.tokens.cache.write,y=J.get(G.sessionID)??new Set,S=L[L.length-1];for(let I of L){if(U<I)break;if(y.has(I))continue;let M;if((yield*X.tryStartCheckpointWriter({sessionID:G.sessionID,model:{providerID:G.model.providerID,modelID:G.model.id},promptOps:G.promptOps,onStarted:(b)=>{M=b}}).pipe(Y.catch(()=>Y.succeed("skipped"))))==="started")yield*Y.gen(function*(){let b=M?yield*k2.await(M):yield*X.waitForWriter(G.sessionID).pipe(Y.map((h)=>h==="success"?{status:"success"}:h==="failure"?{status:"failure",error:"writer failed"}:{status:"cancelled"}));if(b.status==="success"){B.delete(G.sessionID);return}if(b.status!=="failure")return;let k=(B.get(G.sessionID)??0)+1;if(B.set(G.sessionID,k),k<F)J.delete(G.sessionID),V.delete(G.sessionID),e0.info("checkpoint writer failed \u2014 cleared thresholds for retry",{sessionID:G.sessionID,attempt:k,maxAttempts:F});else e0.warn("checkpoint writer gave up after max consecutive failures",{sessionID:G.sessionID,maxAttempts:F})}).pipe(Y.forkDetach);if(y.add(I),e0.info("checkpoint triggered",{threshold:I,currentTokens:U}),I===S)V.add(G.sessionID)}J.set(G.sessionID,y)}),W=Y.fn("SessionPrune.prune")(function*(G){let z=yield*$.get();if(!z.compaction?.prune)return;if(!a5(G.model,G.lastAssistantTime))return;let O=L6({cfg:z,tokens:G.tokens,model:G.model});if(O===0)return;let P=O>=2?2:1;e0.info("pruning",{level:P});let w=yield*Z.messages({sessionID:G.sessionID,agentID:"main"}).pipe(Y.catchIf(D8.isInstance,()=>Y.succeed(void 0)));if(!w)return;let{total:L,pruned:F,toPrune:U}=I6(w);if(e0.info("found",{pruned:F,total:L,level:P}),P===1){for(let y of U)if(y.state.status==="completed"){let S=y.state.output;if(S.length>gB)y.state.output=S.slice(0,hB)+`
|
|
157
|
+
|
|
158
|
+
[... trimmed \u2014 kept first and last 1.5K of `+S.length+` chars ...]
|
|
159
|
+
|
|
160
|
+
`+S.slice(-fB),yield*Z.updatePart(y)}e0.info("soft-trimmed",{count:U.length})}else if(F>U1)yield*R6(U,(y)=>Z.updatePart(y)),e0.info("pruned",{count:U.length});if(P>=2)yield*D({sessionID:G.sessionID,model:G.model,lastAssistantTime:G.lastAssistantTime})}),K=Y.fn("SessionPrune.maxThresholdCrossed")(function*(G){return V.has(G)}),j=Y.fn("SessionPrune.resetThresholds")(function*(G){J.delete(G),V.delete(G)});return C6.of({prune:W,fireCheckpoints:H,maxThresholdCrossed:K,resetThresholds:j})})),mB=_.suspend(()=>$X.pipe(_.provide(v0),_.provide(V2.defaultLayer),_.provide(P$.defaultLayer),_.provide(M2.defaultLayer)));var $$={};L2($$,{layer:()=>ZX,defaultLayer:()=>oB,SessionRevert:()=>$$,Service:()=>S6,RevertInput:()=>cB});var lB=s.create({service:"session.revert"}),cB=q.object({sessionID:F2.zod,messageID:x2.zod,partID:Q2.zod.optional()});class S6 extends Z2.Service()("@qitqode/SessionRevert"){}var ZX=_.effect(S6,Y.gen(function*(){let $=yield*E2,Z=yield*z0.Service,X=yield*R$.Service,Q=yield*u.Service,J=yield*q0.Service,V=yield*O0.Service,B=Y.fn("SessionRevert.revert")(function*(W){yield*V.assertNotBusy(W.sessionID);let K=yield*$.messages({sessionID:W.sessionID,agentID:"*"}),j,G=yield*$.get(W.sessionID),z,O=[];for(let F of K){if(F.info.role==="user")j=F.info;let U=[];for(let y of F.parts){if(z){if(y.type==="patch")O.push(y);continue}if(!z){if(F.info.id===W.messageID&&!W.partID||y.id===W.partID){let S=U.some((I)=>["text","tool"].includes(I.type))?W.partID:void 0;z={messageID:!S&&j?j.id:F.info.id,partID:S}}U.push(y)}}}if(!z)return G;let P=z.messageID;if(z.snapshot=G.revert?.snapshot??(yield*Z.track()),G.revert?.snapshot)yield*Z.restore(G.revert.snapshot);if(yield*Z.revert(O),z.snapshot)z.diff=yield*Z.diff(z.snapshot);let w=K.filter((F)=>F.info.id>=P),L=yield*J.computeDiff({messages:w});return yield*X.write(["session_diff",W.sessionID],L).pipe(Y.ignore),yield*Q.publish(U2.Diff,{sessionID:W.sessionID,diff:L}),yield*$.setRevert({sessionID:W.sessionID,revert:z,summary:q6(L)}),yield*$.get(W.sessionID)}),D=Y.fn("SessionRevert.unrevert")(function*(W){lB.info("unreverting",W),yield*V.assertNotBusy(W.sessionID);let K=yield*$.get(W.sessionID);if(!K.revert)return K;if(K.revert.snapshot)yield*Z.restore(K.revert.snapshot);return yield*$.clearRevert(W.sessionID),yield*$.get(W.sessionID)}),H=Y.fn("SessionRevert.cleanup")(function*(W){if(!W.revert)return;let K=W.id,j=yield*$.messages({sessionID:K,agentID:"*"}),G=W.revert.messageID,z=[],O;for(let P of j){if(P.info.id<G)continue;if(P.info.id>G){z.push(P);continue}if(W.revert.partID){O=P;continue}z.push(P)}for(let P of z)A1.run(p.Event.Removed,{sessionID:K,messageID:P.info.id});if(W.revert.partID&&O){let P=W.revert.partID,w=O.parts.findIndex((L)=>L.id===P);if(w>=0){let L=O.parts.slice(w);O.parts=O.parts.slice(0,w);for(let F of L)A1.run(p.Event.PartRemoved,{sessionID:K,messageID:O.info.id,partID:F.id})}}yield*$.clearRevert(K)});return S6.of({revert:B,unrevert:D,cleanup:H})})),oB=_.suspend(()=>ZX.pipe(_.provide(O0.defaultLayer),_.provide(v0),_.provide(z0.defaultLayer),_.provide(R$.defaultLayer),_.provide(u.layer),_.provide(q0.defaultLayer)));var m$={};L2(m$,{stepSignature:()=>f8,stableStringify:()=>Z8,recallHintLines:()=>h8,layer:()=>HJ,defaultLayer:()=>zG,createStructuredOutputTool:()=>C4,ShellInput:()=>WJ,SessionPrompt:()=>m$,Service:()=>v8,PromptInput:()=>VJ,LoopInput:()=>BJ,CommandInput:()=>KJ});var N0={};L2(N0,{layer:()=>xY,defaultLayer:()=>qK,ToolsChanged:()=>V9,Status:()=>M3,Service:()=>N4,Resource:()=>U3,MCP:()=>N0,Failed:()=>A3,BrowserOpenFailed:()=>B9,AuthRequired:()=>i6});var UX=J9(P3(),1);import u6 from"process";import{PassThrough as z3}from"stream";var _1="2025-11-25";var QX=[_1,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],C$="io.modelcontextprotocol/related-task",T6="2.0",Q0=YX(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),JX=_2([x(),z2().int()]),VX=x(),FO=i2({ttl:_2([z2(),R7()]).optional(),pollInterval:z2().optional()}),pB=o({ttl:z2().optional()}),iB=o({taskId:x()}),T7=i2({progressToken:JX.optional(),[C$]:iB.optional()}),C0=o({_meta:T7.optional()}),y8=C0.extend({task:pB.optional()}),BX=($)=>y8.safeParse($).success,J0=o({method:x(),params:C0.loose().optional()}),m0=o({_meta:T7.optional()}),l0=o({method:x(),params:m0.loose().optional()}),V0=i2({_meta:T7.optional()}),g6=_2([x(),z2().int()]),WX=o({jsonrpc:i(T6),id:g6,...J0.shape}).strict(),O8=($)=>WX.safeParse($).success,KX=o({jsonrpc:i(T6),...l0.shape}).strict(),GX=($)=>KX.safeParse($).success,g7=o({jsonrpc:i(T6),id:g6,result:V0}).strict(),Z1=($)=>g7.safeParse($).success;var $2;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})($2||($2={}));var h7=o({jsonrpc:i(T6),id:g6.optional(),error:o({code:z2().int(),message:x(),data:m2().optional()})}).strict();var HX=($)=>h7.safeParse($).success;var S$=_2([WX,KX,g7,h7]),PO=_2([g7,h7]),X1=V0.strict(),nB=m0.extend({requestId:g6.optional(),reason:x().optional()}),h6=l0.extend({method:i("notifications/cancelled"),params:nB}),sB=o({src:x(),mimeType:x().optional(),sizes:c(x()).optional(),theme:R0(["light","dark"]).optional()}),F8=o({icons:c(sB).optional()}),M1=o({name:x(),title:x().optional()}),jX=M1.extend({...M1.shape,...F8.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),aB=S7(o({applyDefaults:A2().optional()}),T2(x(),m2())),rB=k7(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},S7(o({form:aB.optional(),url:Q0.optional()}),T2(x(),m2()).optional())),tB=i2({list:Q0.optional(),cancel:Q0.optional(),requests:i2({sampling:i2({createMessage:Q0.optional()}).optional(),elicitation:i2({create:Q0.optional()}).optional()}).optional()}),eB=i2({list:Q0.optional(),cancel:Q0.optional(),requests:i2({tools:i2({call:Q0.optional()}).optional()}).optional()}),$W=o({experimental:T2(x(),Q0).optional(),sampling:o({context:Q0.optional(),tools:Q0.optional()}).optional(),elicitation:rB.optional(),roots:o({listChanged:A2().optional()}).optional(),tasks:tB.optional()}),ZW=C0.extend({protocolVersion:x(),capabilities:$W,clientInfo:jX}),XW=J0.extend({method:i("initialize"),params:ZW});var YW=o({experimental:T2(x(),Q0).optional(),logging:Q0.optional(),completions:Q0.optional(),prompts:o({listChanged:A2().optional()}).optional(),resources:o({subscribe:A2().optional(),listChanged:A2().optional()}).optional(),tools:o({listChanged:A2().optional()}).optional(),tasks:eB.optional()}),f7=V0.extend({protocolVersion:x(),capabilities:YW,serverInfo:jX,instructions:x().optional()}),DX=l0.extend({method:i("notifications/initialized"),params:m0.optional()}),yX=($)=>DX.safeParse($).success,f6=J0.extend({method:i("ping"),params:C0.optional()}),QW=o({progress:z2(),total:l2(z2()),message:l2(x())}),JW=o({...m0.shape,...QW.shape,progressToken:JX}),E6=l0.extend({method:i("notifications/progress"),params:JW}),VW=C0.extend({cursor:VX.optional()}),P8=J0.extend({params:VW.optional()}),z8=V0.extend({nextCursor:VX.optional()}),BW=R0(["working","input_required","completed","failed","cancelled"]),q8=o({taskId:x(),status:BW,ttl:_2([z2(),R7()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:l2(z2()),statusMessage:l2(x())}),Y1=V0.extend({task:q8}),WW=m0.merge(q8),N8=l0.extend({method:i("notifications/tasks/status"),params:WW}),v6=J0.extend({method:i("tasks/get"),params:C0.extend({taskId:x()})}),d6=V0.merge(q8),m6=J0.extend({method:i("tasks/result"),params:C0.extend({taskId:x()})}),zO=V0.loose(),l6=P8.extend({method:i("tasks/list")}),c6=z8.extend({tasks:c(q8)}),o6=J0.extend({method:i("tasks/cancel"),params:C0.extend({taskId:x()})}),OX=V0.merge(q8),FX=o({uri:x(),mimeType:l2(x()),_meta:T2(x(),m2()).optional()}),PX=FX.extend({text:x()}),E7=x().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),zX=FX.extend({blob:E7}),x8=R0(["user","assistant"]),I1=o({audience:c(x8).optional(),priority:z2().min(0).max(1).optional(),lastModified:XX.datetime({offset:!0}).optional()}),qX=o({...M1.shape,...F8.shape,uri:x(),description:l2(x()),mimeType:l2(x()),annotations:I1.optional(),_meta:l2(i2({}))}),KW=o({...M1.shape,...F8.shape,uriTemplate:x(),description:l2(x()),mimeType:l2(x()),annotations:I1.optional(),_meta:l2(i2({}))}),GW=P8.extend({method:i("resources/list")}),v7=z8.extend({resources:c(qX)}),HW=P8.extend({method:i("resources/templates/list")}),d7=z8.extend({resourceTemplates:c(KW)}),m7=C0.extend({uri:x()}),jW=m7,DW=J0.extend({method:i("resources/read"),params:jW}),l7=V0.extend({contents:c(_2([PX,zX]))}),c7=l0.extend({method:i("notifications/resources/list_changed"),params:m0.optional()}),yW=m7,OW=J0.extend({method:i("resources/subscribe"),params:yW}),FW=m7,PW=J0.extend({method:i("resources/unsubscribe"),params:FW}),zW=m0.extend({uri:x()}),qW=l0.extend({method:i("notifications/resources/updated"),params:zW}),NW=o({name:x(),description:l2(x()),required:l2(A2())}),xW=o({...M1.shape,...F8.shape,description:l2(x()),arguments:l2(c(NW)),_meta:l2(i2({}))}),wW=P8.extend({method:i("prompts/list")}),o7=z8.extend({prompts:c(xW)}),bW=C0.extend({name:x(),arguments:T2(x(),x()).optional()}),LW=J0.extend({method:i("prompts/get"),params:bW}),u7=o({type:i("text"),text:x(),annotations:I1.optional(),_meta:T2(x(),m2()).optional()}),p7=o({type:i("image"),data:E7,mimeType:x(),annotations:I1.optional(),_meta:T2(x(),m2()).optional()}),i7=o({type:i("audio"),data:E7,mimeType:x(),annotations:I1.optional(),_meta:T2(x(),m2()).optional()}),UW=o({type:i("tool_use"),name:x(),id:x(),input:T2(x(),m2()),_meta:T2(x(),m2()).optional()}),AW=o({type:i("resource"),resource:_2([PX,zX]),annotations:I1.optional(),_meta:T2(x(),m2()).optional()}),MW=qX.extend({type:i("resource_link")}),n7=_2([u7,p7,i7,MW,AW]),_W=o({role:x8,content:n7}),s7=V0.extend({description:x().optional(),messages:c(_W)}),a7=l0.extend({method:i("notifications/prompts/list_changed"),params:m0.optional()}),IW=o({title:x().optional(),readOnlyHint:A2().optional(),destructiveHint:A2().optional(),idempotentHint:A2().optional(),openWorldHint:A2().optional()}),RW=o({taskSupport:R0(["required","optional","forbidden"]).optional()}),NX=o({...M1.shape,...F8.shape,description:x().optional(),inputSchema:o({type:i("object"),properties:T2(x(),Q0).optional(),required:c(x()).optional()}).catchall(m2()),outputSchema:o({type:i("object"),properties:T2(x(),Q0).optional(),required:c(x()).optional()}).catchall(m2()).optional(),annotations:IW.optional(),execution:RW.optional(),_meta:T2(x(),m2()).optional()}),CW=P8.extend({method:i("tools/list")}),r7=z8.extend({tools:c(NX)}),k$=V0.extend({content:c(n7).default([]),structuredContent:T2(x(),m2()).optional(),isError:A2().optional()}),qO=k$.or(V0.extend({toolResult:m2()})),SW=y8.extend({name:x(),arguments:T2(x(),m2()).optional()}),kW=J0.extend({method:i("tools/call"),params:SW}),w8=l0.extend({method:i("notifications/tools/list_changed"),params:m0.optional()}),xX=o({autoRefresh:A2().default(!0),debounceMs:z2().int().nonnegative().default(300)}),wX=R0(["debug","info","notice","warning","error","critical","alert","emergency"]),TW=C0.extend({level:wX}),gW=J0.extend({method:i("logging/setLevel"),params:TW}),hW=m0.extend({level:wX,logger:x().optional(),data:m2()}),fW=l0.extend({method:i("notifications/message"),params:hW}),EW=o({name:x().optional()}),vW=o({hints:c(EW).optional(),costPriority:z2().min(0).max(1).optional(),speedPriority:z2().min(0).max(1).optional(),intelligencePriority:z2().min(0).max(1).optional()}),dW=o({mode:R0(["auto","required","none"]).optional()}),mW=o({type:i("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:c(n7).default([]),structuredContent:o({}).loose().optional(),isError:A2().optional(),_meta:T2(x(),m2()).optional()}),lW=C7("type",[u7,p7,i7]),k6=C7("type",[u7,p7,i7,UW,mW]),cW=o({role:x8,content:_2([k6,c(k6)]),_meta:T2(x(),m2()).optional()}),oW=y8.extend({messages:c(cW),modelPreferences:vW.optional(),systemPrompt:x().optional(),includeContext:R0(["none","thisServer","allServers"]).optional(),temperature:z2().optional(),maxTokens:z2().int(),stopSequences:c(x()).optional(),metadata:Q0.optional(),tools:c(NX).optional(),toolChoice:dW.optional()}),t7=J0.extend({method:i("sampling/createMessage"),params:oW}),e7=V0.extend({model:x(),stopReason:l2(R0(["endTurn","stopSequence","maxTokens"]).or(x())),role:x8,content:lW}),$9=V0.extend({model:x(),stopReason:l2(R0(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:x8,content:_2([k6,c(k6)])}),uW=o({type:i("boolean"),title:x().optional(),description:x().optional(),default:A2().optional()}),pW=o({type:i("string"),title:x().optional(),description:x().optional(),minLength:z2().optional(),maxLength:z2().optional(),format:R0(["email","uri","date","date-time"]).optional(),default:x().optional()}),iW=o({type:R0(["number","integer"]),title:x().optional(),description:x().optional(),minimum:z2().optional(),maximum:z2().optional(),default:z2().optional()}),nW=o({type:i("string"),title:x().optional(),description:x().optional(),enum:c(x()),default:x().optional()}),sW=o({type:i("string"),title:x().optional(),description:x().optional(),oneOf:c(o({const:x(),title:x()})),default:x().optional()}),aW=o({type:i("string"),title:x().optional(),description:x().optional(),enum:c(x()),enumNames:c(x()).optional(),default:x().optional()}),rW=_2([nW,sW]),tW=o({type:i("array"),title:x().optional(),description:x().optional(),minItems:z2().optional(),maxItems:z2().optional(),items:o({type:i("string"),enum:c(x())}),default:c(x()).optional()}),eW=o({type:i("array"),title:x().optional(),description:x().optional(),minItems:z2().optional(),maxItems:z2().optional(),items:o({anyOf:c(o({const:x(),title:x()}))}),default:c(x()).optional()}),$3=_2([tW,eW]),Z3=_2([aW,rW,$3]),X3=_2([Z3,uW,pW,iW]),Y3=y8.extend({mode:i("form").optional(),message:x(),requestedSchema:o({type:i("object"),properties:T2(x(),X3),required:c(x()).optional()})}),Q3=y8.extend({mode:i("url"),message:x(),elicitationId:x(),url:x().url()}),J3=_2([Y3,Q3]),Z9=J0.extend({method:i("elicitation/create"),params:J3}),V3=m0.extend({elicitationId:x()}),B3=l0.extend({method:i("notifications/elicitation/complete"),params:V3}),X9=V0.extend({action:R0(["accept","decline","cancel"]),content:k7(($)=>$===null?void 0:$,T2(x(),_2([x(),z2(),A2(),c(x())])).optional())}),W3=o({type:i("ref/resource"),uri:x()});var K3=o({type:i("ref/prompt"),name:x()}),G3=C0.extend({ref:_2([K3,W3]),argument:o({name:x(),value:x()}),context:o({arguments:T2(x(),x()).optional()}).optional()}),H3=J0.extend({method:i("completion/complete"),params:G3});var Y9=V0.extend({completion:i2({values:c(x()).max(100),total:l2(z2().int()),hasMore:l2(A2())})}),j3=o({uri:x().startsWith("file://"),name:x().optional(),_meta:T2(x(),m2()).optional()}),D3=J0.extend({method:i("roots/list"),params:C0.optional()}),y3=V0.extend({roots:c(j3)}),O3=l0.extend({method:i("notifications/roots/list_changed"),params:m0.optional()}),NO=_2([f6,XW,H3,gW,LW,wW,GW,HW,DW,OW,PW,kW,CW,v6,m6,l6,o6]),xO=_2([h6,E6,DX,O3,N8]),wO=_2([X1,e7,$9,X9,y3,d6,c6,Y1]),bO=_2([f6,t7,Z9,D3,v6,m6,l6,o6]),LO=_2([h6,E6,fW,qW,c7,w8,a7,N8,B3]),UO=_2([X1,f7,Y9,s7,o7,v7,d7,l7,k$,r7,d6,c6,Y1]);class r extends Error{constructor($,Z,X){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=X,this.name="McpError"}static fromError($,Z,X){if($===$2.UrlElicitationRequired&&X){let Q=X;if(Q.elicitations)return new bX(Q.elicitations,Z)}return new r($,Z,X)}}class bX extends r{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super($2.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}class Q9{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
|
|
161
|
+
`);if($===-1)return null;let Z=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),F3(Z)}clear(){this._buffer=void 0}}function F3($){return S$.parse(JSON.parse($))}function LX($){return JSON.stringify($)+`
|
|
162
|
+
`}var q3=u6.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function N3(){let $={};for(let Z of q3){let X=u6.env[Z];if(X===void 0)continue;if(X.startsWith("()"))continue;$[Z]=X}return $}class b8{constructor($){if(this._readBuffer=new Q9,this._stderrStream=null,this._serverParams=$,$.stderr==="pipe"||$.stderr==="overlapped")this._stderrStream=new z3}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise(($,Z)=>{if(this._process=UX.default(this._serverParams.command,this._serverParams.args??[],{env:{...N3(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:u6.platform==="win32"&&x3(),cwd:this._serverParams.cwd}),this._process.on("error",(X)=>{Z(X),this.onerror?.(X)}),this._process.on("spawn",()=>{$()}),this._process.on("close",(X)=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",(X)=>{this.onerror?.(X)}),this._process.stdout?.on("data",(X)=>{this._readBuffer.append(X),this.processReadBuffer()}),this._process.stdout?.on("error",(X)=>{this.onerror?.(X)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){if(this._stderrStream)return this._stderrStream;return this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._process){let $=this._process;this._process=void 0;let Z=new Promise((X)=>{$.once("close",()=>{X()})});try{$.stdin?.end()}catch{}if(await Promise.race([Z,new Promise((X)=>setTimeout(X,2000).unref())]),$.exitCode===null){try{$.kill("SIGTERM")}catch{}await Promise.race([Z,new Promise((X)=>setTimeout(X,2000).unref())])}if($.exitCode===null)try{$.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send($){return new Promise((Z)=>{if(!this._process?.stdin)throw Error("Not connected");let X=LX($);if(this._process.stdin.write(X))Z();else this._process.stdin.once("drain",Z)})}}function x3(){return"type"in u6}var T$={};L2(T$,{layer:()=>IX,defaultLayer:()=>L3,Tokens:()=>MX,Service:()=>p6,McpAuth:()=>T$,Entry:()=>b3,ClientInfo:()=>_X});import w3 from"path";var MX=q.object({accessToken:q.string(),refreshToken:q.string().optional(),expiresAt:q.number().optional(),scope:q.string().optional()}),_X=q.object({clientId:q.string(),clientSecret:q.string().optional(),clientIdIssuedAt:q.number().optional(),clientSecretExpiresAt:q.number().optional()}),b3=q.object({tokens:MX.optional(),clientInfo:_X.optional(),codeVerifier:q.string().optional(),oauthState:q.string().optional(),serverUrl:q.string().optional()}),L8=w3.join(q$.Path.data,"mcp-auth.json");class p6 extends Z2.Service()("@qitqode/McpAuth"){}var IX=_.effect(p6,Y.gen(function*(){let $=yield*n2.Service,Z=AX.makeUnsafe(1),X=Y.fn("McpAuth.read")(function*(){return yield*$.readJson(L8).pipe(Y.map((F)=>F),Y.catch(()=>Y.succeed({})))}),Q=Y.fn("McpAuth.all")(function*(){let F=yield*X();return Object.fromEntries(Object.entries(F).filter(([U])=>!U.includes("\x00")))}),J=Y.fn("McpAuth.get")(function*(F){return(yield*X())[F]}),V=Y.fn("McpAuth.getForUrl")(function*(F,U){let y=yield*J(F);if(!y)return;if(!y.serverUrl)return;if(y.serverUrl!==U)return;return y}),B=Y.fn("McpAuth.set")(function*(F,U,y){yield*Z.withPermits(1)(Y.gen(function*(){let S=yield*X();if(y)U.serverUrl=y;yield*$.writeJson(L8,{...S,[F]:U},384).pipe(Y.orDie)}))}),D=Y.fn("McpAuth.remove")(function*(F){yield*Z.withPermits(1)(Y.gen(function*(){let U=yield*X();delete U[F],yield*$.writeJson(L8,U,384).pipe(Y.orDie)}))}),H=(F,U)=>Y.fn(`McpAuth.${U}`)(function*(y,S,I){yield*Z.withPermits(1)(Y.gen(function*(){let M=yield*X(),f=M[y]??{};if(f[F]=S,I)f.serverUrl=I;yield*$.writeJson(L8,{...M,[y]:f},384).pipe(Y.orDie)}))}),W=(F,U)=>Y.fn(`McpAuth.${U}`)(function*(y){yield*Z.withPermits(1)(Y.gen(function*(){let S=yield*X(),I=S[y];if(!I)return;delete I[F],yield*$.writeJson(L8,S,384).pipe(Y.orDie)}))}),K=H("tokens","updateTokens"),j=H("clientInfo","updateClientInfo"),G=H("codeVerifier","updateCodeVerifier"),z=H("oauthState","updateOAuthState"),O=W("codeVerifier","clearCodeVerifier"),P=W("oauthState","clearOAuthState"),w=Y.fn("McpAuth.getOAuthState")(function*(F){return(yield*J(F))?.oauthState}),L=Y.fn("McpAuth.isTokenExpired")(function*(F){let U=yield*J(F);if(!U?.tokens)return null;if(!U.tokens.expiresAt)return!1;return U.tokens.expiresAt<Date.now()/1000});return p6.of({all:Q,get:J,getForUrl:V,set:B,remove:D,updateTokens:K,updateClientInfo:j,updateCodeVerifier:G,clearCodeVerifier:O,updateOAuthState:z,getOAuthState:w,clearOAuthState:P,isTokenExpired:L})})),L3=IX.pipe(_.provide(n2.defaultLayer));var U3=y2.object({name:y2.string(),uri:y2.string(),description:y2.string().optional(),mimeType:y2.string().optional(),client:y2.string()}).meta({ref:"McpResource"}),V9=D2.define("mcp.tools.changed",y2.object({server:y2.string()})),B9=D2.define("mcp.browser.open.failed",y2.object({mcpName:y2.string(),url:y2.string()})),i6=D2.define("mcp.auth.required",y2.object({server:y2.string(),reason:y2.enum(["client_registration","login"])})),A3=w2.create("MCPFailed",y2.object({name:y2.string()})),M3=y2.discriminatedUnion("status",[y2.object({status:y2.literal("connected")}).meta({ref:"MCPStatusConnected"}),y2.object({status:y2.literal("disabled")}).meta({ref:"MCPStatusDisabled"}),y2.object({status:y2.literal("pending")}).meta({ref:"MCPStatusPending"}),y2.object({status:y2.literal("failed"),error:y2.string()}).meta({ref:"MCPStatusFailed"}),y2.object({status:y2.literal("needs_auth")}).meta({ref:"MCPStatusNeedsAuth"}),y2.object({status:y2.literal("needs_client_registration"),error:y2.string()}).meta({ref:"MCPStatusNeedsClientRegistration"})]).meta({ref:"MCPStatus"});var a6=30000,W9=s.create({service:"mcp.catalog"}),n6=($)=>$.replace(/[^a-zA-Z0-9_-]/g,"_");function U8($){return typeof $==="object"&&$!==null&&"type"in $}function _3($,Z,X){let Q=$.inputSchema,J={...Q,type:"object",properties:Q.properties??{},additionalProperties:!1};return RX({description:$.description??"",inputSchema:W$(J),execute:async(V)=>Z.callTool({name:$.name,arguments:V||{}},k$,{resetTimeoutOnProgress:!0,timeout:X})})}function R1($,Z,X){return Y.tryPromise({try:()=>s6(Z.listTools(),X??a6),catch:(Q)=>Q instanceof Error?Q:Error(String(Q))}).pipe(Y.map((Q)=>Q.tools),Y.catch((Q)=>{return W9.error("failed to get tools from client",{key:$,error:Q}),Y.succeed(void 0)}))}function I3($,Z,X,Q){return Y.tryPromise({try:()=>X(Z),catch:(J)=>{return W9.error(`failed to get ${Q}`,{clientName:$,error:J instanceof Error?J.message:String(J)}),J}}).pipe(Y.map((J)=>{let V={},B=n6($);for(let D of J)V[B+":"+n6(D.name)]={...D,client:$};return V}),Y.orElseSucceed(()=>{return}))}function CX($,Z,X){let Q={};for(let[J,V]of Object.entries($.clients)){if($.status[J]?.status!=="connected")continue;let B=$.defs[J];if(!B){W9.warn("missing cached tools for connected server",{clientName:J});continue}let H=(U8(Z[J])?Z[J]:void 0)?.timeout??X;for(let W of B)Q[n6(J)+"_"+n6(W.name)]=_3(W,V,H)}return Q}function K9($,Z,X){return Y.forEach(Object.entries($.clients).filter(([Q])=>$.status[Q]?.status==="connected"),([Q,J])=>I3(Q,J,Z,X).pipe(Y.map((V)=>Object.entries(V??{}))),{concurrency:8}).pipe(Y.map((Q)=>Object.fromEntries(Q.flat())))}function SX($,Z){return $.type==="local"&&Z?.type==="claude"}function C1($){return!!$._zod}function Z$($,Z){if(C1($))return G9($,Z);return $.safeParse(Z)}function r6($){if(!$)return;let Z;if(C1($))Z=$._zod?.def?.shape;else Z=$.shape;if(!Z)return;if(typeof Z==="function")try{return Z()}catch{return}return Z}function kX($){if(C1($)){let V=$._zod?.def;if(V){if(V.value!==void 0)return V.value;if(Array.isArray(V.values)&&V.values.length>0)return V.values[0]}}let X=$._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let Q=$.value;if(Q!==void 0)return Q;return}function g$($){return $==="completed"||$==="failed"||$==="cancelled"}function H9($){let X=r6($)?.method;if(!X)throw Error("Schema is missing a method literal");let Q=kX(X);if(typeof Q!=="string")throw Error("Schema method literal must be a string");return Q}function j9($,Z){let X=Z$($,Z);if(!X.success)throw X.error;return X.data}var C3=60000;class D9{constructor($){if(this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(h6,(Z)=>{this._oncancel(Z)}),this.setNotificationHandler(E6,(Z)=>{this._onprogress(Z)}),this.setRequestHandler(f6,(Z)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(v6,async(Z,X)=>{let Q=await this._taskStore.getTask(Z.params.taskId,X.sessionId);if(!Q)throw new r($2.InvalidParams,"Failed to retrieve task: Task not found");return{...Q}}),this.setRequestHandler(m6,async(Z,X)=>{let Q=async()=>{let J=Z.params.taskId;if(this._taskMessageQueue){let B;while(B=await this._taskMessageQueue.dequeue(J,X.sessionId)){if(B.type==="response"||B.type==="error"){let D=B.message,H=D.id,W=this._requestResolvers.get(H);if(W)if(this._requestResolvers.delete(H),B.type==="response")W(D);else{let K=D,j=new r(K.error.code,K.error.message,K.error.data);W(j)}else{let K=B.type==="response"?"Response":"Error";this._onerror(Error(`${K} handler missing for request ${H}`))}continue}await this._transport?.send(B.message,{relatedRequestId:X.requestId})}}let V=await this._taskStore.getTask(J,X.sessionId);if(!V)throw new r($2.InvalidParams,`Task not found: ${J}`);if(!g$(V.status))return await this._waitForTaskUpdate(J,X.signal),await Q();if(g$(V.status)){let B=await this._taskStore.getTaskResult(J,X.sessionId);return this._clearTaskQueue(J),{...B,_meta:{...B._meta,[C$]:{taskId:J}}}}return await Q()};return await Q()}),this.setRequestHandler(l6,async(Z,X)=>{try{let{tasks:Q,nextCursor:J}=await this._taskStore.listTasks(Z.params?.cursor,X.sessionId);return{tasks:Q,nextCursor:J,_meta:{}}}catch(Q){throw new r($2.InvalidParams,`Failed to list tasks: ${Q instanceof Error?Q.message:String(Q)}`)}}),this.setRequestHandler(o6,async(Z,X)=>{try{let Q=await this._taskStore.getTask(Z.params.taskId,X.sessionId);if(!Q)throw new r($2.InvalidParams,`Task not found: ${Z.params.taskId}`);if(g$(Q.status))throw new r($2.InvalidParams,`Cannot cancel task in terminal status: ${Q.status}`);await this._taskStore.updateTaskStatus(Z.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Z.params.taskId);let J=await this._taskStore.getTask(Z.params.taskId,X.sessionId);if(!J)throw new r($2.InvalidParams,`Task not found after cancellation: ${Z.params.taskId}`);return{_meta:{},...J}}catch(Q){if(Q instanceof r)throw Q;throw new r($2.InvalidRequest,`Failed to cancel task: ${Q instanceof Error?Q.message:String(Q)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,Z,X,Q,J=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(Q,Z),startTime:Date.now(),timeout:Z,maxTotalTimeout:X,resetTimeoutOnProgress:J,onTimeout:Q})}_resetTimeout($){let Z=this._timeoutInfo.get($);if(!Z)return!1;let X=Date.now()-Z.startTime;if(Z.maxTotalTimeout&&X>=Z.maxTotalTimeout)throw this._timeoutInfo.delete($),r.fromError($2.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Z.maxTotalTimeout,totalElapsed:X});return clearTimeout(Z.timeoutId),Z.timeoutId=setTimeout(Z.onTimeout,Z.timeout),!0}_cleanupTimeout($){let Z=this._timeoutInfo.get($);if(Z)clearTimeout(Z.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let Z=this.transport?.onclose;this._transport.onclose=()=>{Z?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(J)=>{X?.(J),this._onerror(J)};let Q=this._transport?.onmessage;this._transport.onmessage=(J,V)=>{if(Q?.(J,V),Z1(J)||HX(J))this._onresponse(J);else if(O8(J))this._onrequest(J,V);else if(GX(J))this._onnotification(J);else this._onerror(Error(`Unknown message type: ${JSON.stringify(J)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let X of this._requestHandlerAbortControllers.values())X.abort();this._requestHandlerAbortControllers.clear();let Z=r.fromError($2.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of $.values())X(Z)}_onerror($){this.onerror?.($)}_onnotification($){let Z=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(Z===void 0)return;Promise.resolve().then(()=>Z($)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest($,Z){let X=this._requestHandlers.get($.method)??this.fallbackRequestHandler,Q=this._transport,J=$.params?._meta?.[C$]?.taskId;if(X===void 0){let W={jsonrpc:"2.0",id:$.id,error:{code:$2.MethodNotFound,message:"Method not found"}};if(J&&this._taskMessageQueue)this._enqueueTaskMessage(J,{type:"error",message:W,timestamp:Date.now()},Q?.sessionId).catch((K)=>this._onerror(Error(`Failed to enqueue error response: ${K}`)));else Q?.send(W).catch((K)=>this._onerror(Error(`Failed to send an error response: ${K}`)));return}let V=new AbortController;this._requestHandlerAbortControllers.set($.id,V);let B=BX($.params)?$.params.task:void 0,D=this._taskStore?this.requestTaskStore($,Q?.sessionId):void 0,H={signal:V.signal,sessionId:Q?.sessionId,_meta:$.params?._meta,sendNotification:async(W)=>{if(V.signal.aborted)return;let K={relatedRequestId:$.id};if(J)K.relatedTask={taskId:J};await this.notification(W,K)},sendRequest:async(W,K,j)=>{if(V.signal.aborted)throw new r($2.ConnectionClosed,"Request was cancelled");let G={...j,relatedRequestId:$.id};if(J&&!G.relatedTask)G.relatedTask={taskId:J};let z=G.relatedTask?.taskId??J;if(z&&D)await D.updateTaskStatus(z,"input_required");return await this.request(W,K,G)},authInfo:Z?.authInfo,requestId:$.id,requestInfo:Z?.requestInfo,taskId:J,taskStore:D,taskRequestedTtl:B?.ttl,closeSSEStream:Z?.closeSSEStream,closeStandaloneSSEStream:Z?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(B)this.assertTaskHandlerCapability($.method)}).then(()=>X($,H)).then(async(W)=>{if(V.signal.aborted)return;let K={result:W,jsonrpc:"2.0",id:$.id};if(J&&this._taskMessageQueue)await this._enqueueTaskMessage(J,{type:"response",message:K,timestamp:Date.now()},Q?.sessionId);else await Q?.send(K)},async(W)=>{if(V.signal.aborted)return;let K={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(W.code)?W.code:$2.InternalError,message:W.message??"Internal error",...W.data!==void 0&&{data:W.data}}};if(J&&this._taskMessageQueue)await this._enqueueTaskMessage(J,{type:"error",message:K,timestamp:Date.now()},Q?.sessionId);else await Q?.send(K)}).catch((W)=>this._onerror(Error(`Failed to send response: ${W}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:Z,...X}=$.params,Q=Number(Z),J=this._progressHandlers.get(Q);if(!J){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let V=this._responseHandlers.get(Q),B=this._timeoutInfo.get(Q);if(B&&V&&B.resetTimeoutOnProgress)try{this._resetTimeout(Q)}catch(D){this._responseHandlers.delete(Q),this._progressHandlers.delete(Q),this._cleanupTimeout(Q),V(D);return}J(X)}_onresponse($){let Z=Number($.id),X=this._requestResolvers.get(Z);if(X){if(this._requestResolvers.delete(Z),Z1($))X($);else{let V=new r($.error.code,$.error.message,$.error.data);X(V)}return}let Q=this._responseHandlers.get(Z);if(Q===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(Z),this._cleanupTimeout(Z);let J=!1;if(Z1($)&&$.result&&typeof $.result==="object"){let V=$.result;if(V.task&&typeof V.task==="object"){let B=V.task;if(typeof B.taskId==="string")J=!0,this._taskProgressTokens.set(B.taskId,Z)}}if(!J)this._progressHandlers.delete(Z);if(Z1($))Q($);else{let V=r.fromError($.error.code,$.error.message,$.error.data);Q(V)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,Z,X){let{task:Q}=X??{};if(!Q){try{yield{type:"result",result:await this.request($,Z,X)}}catch(V){yield{type:"error",error:V instanceof r?V:new r($2.InternalError,String(V))}}return}let J;try{let V=await this.request($,Y1,X);if(V.task)J=V.task.taskId,yield{type:"taskCreated",task:V.task};else throw new r($2.InternalError,"Task creation did not return a task");while(!0){let B=await this.getTask({taskId:J},X);if(yield{type:"taskStatus",task:B},g$(B.status)){if(B.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:J},Z,X)};else if(B.status==="failed")yield{type:"error",error:new r($2.InternalError,`Task ${J} failed`)};else if(B.status==="cancelled")yield{type:"error",error:new r($2.InternalError,`Task ${J} was cancelled`)};return}if(B.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:J},Z,X)};return}let D=B.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,D)),X?.signal?.throwIfAborted()}}catch(V){yield{type:"error",error:V instanceof r?V:new r($2.InternalError,String(V))}}}request($,Z,X){let{relatedRequestId:Q,resumptionToken:J,onresumptiontoken:V,task:B,relatedTask:D}=X??{};return new Promise((H,W)=>{let K=(L)=>{W(L)};if(!this._transport){K(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),B)this.assertTaskCapability($.method)}catch(L){K(L);return}X?.signal?.throwIfAborted();let j=this._requestMessageId++,G={...$,jsonrpc:"2.0",id:j};if(X?.onprogress)this._progressHandlers.set(j,X.onprogress),G.params={...$.params,_meta:{...$.params?._meta||{},progressToken:j}};if(B)G.params={...G.params,task:B};if(D)G.params={...G.params,_meta:{...G.params?._meta||{},[C$]:D}};let z=(L)=>{this._responseHandlers.delete(j),this._progressHandlers.delete(j),this._cleanupTimeout(j),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:j,reason:String(L)}},{relatedRequestId:Q,resumptionToken:J,onresumptiontoken:V}).catch((U)=>this._onerror(Error(`Failed to send cancellation: ${U}`)));let F=L instanceof r?L:new r($2.RequestTimeout,String(L));W(F)};this._responseHandlers.set(j,(L)=>{if(X?.signal?.aborted)return;if(L instanceof Error)return W(L);try{let F=Z$(Z,L.result);if(!F.success)W(F.error);else H(F.data)}catch(F){W(F)}}),X?.signal?.addEventListener("abort",()=>{z(X?.signal?.reason)});let O=X?.timeout??C3,P=()=>z(r.fromError($2.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(j,O,X?.maxTotalTimeout,P,X?.resetTimeoutOnProgress??!1);let w=D?.taskId;if(w){let L=(F)=>{let U=this._responseHandlers.get(j);if(U)U(F);else this._onerror(Error(`Response handler missing for side-channeled request ${j}`))};this._requestResolvers.set(j,L),this._enqueueTaskMessage(w,{type:"request",message:G,timestamp:Date.now()}).catch((F)=>{this._cleanupTimeout(j),W(F)})}else this._transport.send(G,{relatedRequestId:Q,resumptionToken:J,onresumptiontoken:V}).catch((L)=>{this._cleanupTimeout(j),W(L)})})}async getTask($,Z){return this.request({method:"tasks/get",params:$},d6,Z)}async getTaskResult($,Z,X){return this.request({method:"tasks/result",params:$},Z,X)}async listTasks($,Z){return this.request({method:"tasks/list",params:$},c6,Z)}async cancelTask($,Z){return this.request({method:"tasks/cancel",params:$},OX,Z)}async notification($,Z){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let X=Z?.relatedTask?.taskId;if(X){let B={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[C$]:Z.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:B,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!Z?.relatedRequestId&&!Z?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let B={...$,jsonrpc:"2.0"};if(Z?.relatedTask)B={...B,params:{...B.params,_meta:{...B.params?._meta||{},[C$]:Z.relatedTask}}};this._transport?.send(B,Z).catch((D)=>this._onerror(D))});return}let V={...$,jsonrpc:"2.0"};if(Z?.relatedTask)V={...V,params:{...V.params,_meta:{...V.params?._meta||{},[C$]:Z.relatedTask}}};await this._transport.send(V,Z)}setRequestHandler($,Z){let X=H9($);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(Q,J)=>{let V=j9($,Q);return Promise.resolve(Z(V,J))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,Z){let X=H9($);this._notificationHandlers.set(X,(Q)=>{let J=j9($,Q);return Promise.resolve(Z(J))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let Z=this._taskProgressTokens.get($);if(Z!==void 0)this._progressHandlers.delete(Z),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,Z,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let Q=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,Z,X,Q)}async _clearTaskQueue($,Z){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll($,Z);for(let Q of X)if(Q.type==="request"&&O8(Q.message)){let J=Q.message.id,V=this._requestResolvers.get(J);if(V)V(new r($2.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(J);else this._onerror(Error(`Resolver missing for request ${J} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,Z){let X=this._options?.defaultTaskPollInterval??1000;try{let Q=await this._taskStore?.getTask($);if(Q?.pollInterval)X=Q.pollInterval}catch{}return new Promise((Q,J)=>{if(Z.aborted){J(new r($2.InvalidRequest,"Request cancelled"));return}let V=setTimeout(Q,X);Z.addEventListener("abort",()=>{clearTimeout(V),J(new r($2.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,Z){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(Q)=>{if(!$)throw Error("No request provided");return await X.createTask(Q,$.id,{method:$.method,params:$.params},Z)},getTask:async(Q)=>{let J=await X.getTask(Q,Z);if(!J)throw new r($2.InvalidParams,"Failed to retrieve task: Task not found");return J},storeTaskResult:async(Q,J,V)=>{await X.storeTaskResult(Q,J,V,Z);let B=await X.getTask(Q,Z);if(B){let D=N8.parse({method:"notifications/tasks/status",params:B});if(await this.notification(D),g$(B.status))this._cleanupTaskProgressHandler(Q)}},getTaskResult:(Q)=>{return X.getTaskResult(Q,Z)},updateTaskStatus:async(Q,J,V)=>{let B=await X.getTask(Q,Z);if(!B)throw new r($2.InvalidParams,`Task "${Q}" not found - it may have been cleaned up`);if(g$(B.status))throw new r($2.InvalidParams,`Cannot update task "${Q}" from terminal status "${B.status}" to "${J}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(Q,J,V,Z);let D=await X.getTask(Q,Z);if(D){let H=N8.parse({method:"notifications/tasks/status",params:D});if(await this.notification(H),g$(D.status))this._cleanupTaskProgressHandler(Q)}},listTasks:(Q)=>{return X.listTasks(Q,Z)}}}}function TX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function gX($,Z){let X={...$};for(let Q in Z){let J=Q,V=Z[J];if(V===void 0)continue;let B=X[J];if(TX(B)&&TX(V))X[J]={...B,...V};else X[J]=V}return X}var hX=J9(S3(),1),fX=J9(k3(),1);function T3(){let $=new hX.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return fX.default($),$}class y9{constructor($){this._ajv=$??T3()}getValidator($){let Z="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(X)=>{if(Z(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Z.errors)}}}}class O9{constructor($){this._client=$}async*callToolStream($,Z=k$,X){let Q=this._client,J={...X,task:X?.task??(Q.isToolTask($.name)?{}:void 0)},V=Q.requestStream({method:"tools/call",params:$},Z,J),B=Q.getToolOutputValidator($.name);for await(let D of V){if(D.type==="result"&&B){let H=D.result;if(!H.structuredContent&&!H.isError){yield{type:"error",error:new r($2.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`)};return}if(H.structuredContent)try{let W=B(H.structuredContent);if(!W.valid){yield{type:"error",error:new r($2.InvalidParams,`Structured content does not match the tool's output schema: ${W.errorMessage}`)};return}}catch(W){if(W instanceof r){yield{type:"error",error:W};return}yield{type:"error",error:new r($2.InvalidParams,`Failed to validate structured content: ${W instanceof Error?W.message:String(W)}`)};return}}yield D}}async getTask($,Z){return this._client.getTask({taskId:$},Z)}async getTaskResult($,Z,X){return this._client.getTaskResult({taskId:$},Z,X)}async listTasks($,Z){return this._client.listTasks($?{cursor:$}:void 0,Z)}async cancelTask($,Z){return this._client.cancelTask({taskId:$},Z)}requestStream($,Z,X){return this._client.requestStream($,Z,X)}}function EX($,Z,X){if(!$)throw Error(`${X} does not support task creation (required for ${Z})`);switch(Z){case"tools/call":if(!$.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Z})`);break;default:break}}function vX($,Z,X){if(!$)throw Error(`${X} does not support task creation (required for ${Z})`);switch(Z){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Z})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Z})`);break;default:break}}function t6($,Z){if(!$||Z===null||typeof Z!=="object")return;if($.type==="object"&&$.properties&&typeof $.properties==="object"){let X=Z,Q=$.properties;for(let J of Object.keys(Q)){let V=Q[J];if(X[J]===void 0&&Object.prototype.hasOwnProperty.call(V,"default"))X[J]=V.default;if(X[J]!==void 0)t6(V,X[J])}}if(Array.isArray($.anyOf)){for(let X of $.anyOf)if(typeof X!=="boolean")t6(X,Z)}if(Array.isArray($.oneOf)){for(let X of $.oneOf)if(typeof X!=="boolean")t6(X,Z)}}function g3($){if(!$)return{supportsFormMode:!1,supportsUrlMode:!1};let Z=$.form!==void 0,X=$.url!==void 0;return{supportsFormMode:Z||!Z&&!X,supportsUrlMode:X}}class A8 extends D9{constructor($,Z){super(Z);if(this._clientInfo=$,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=Z?.capabilities??{},this._jsonSchemaValidator=Z?.jsonSchemaValidator??new y9,Z?.listChanged)this._pendingListChangedConfig=Z.listChanged}_setupListChangedHandlers($){if($.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",w8,$.tools,async()=>{return(await this.listTools()).tools});if($.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",a7,$.prompts,async()=>{return(await this.listPrompts()).prompts});if($.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",c7,$.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new O9(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=gX(this._capabilities,$)}setRequestHandler($,Z){let Q=r6($)?.method;if(!Q)throw Error("Schema is missing a method literal");let J;if(C1(Q)){let B=Q;J=B._zod?.def?.value??B.value}else{let B=Q;J=B._def?.value??B.value}if(typeof J!=="string")throw Error("Schema method literal must be a string");let V=J;if(V==="elicitation/create"){let B=async(D,H)=>{let W=Z$(Z9,D);if(!W.success){let L=W.error instanceof Error?W.error.message:String(W.error);throw new r($2.InvalidParams,`Invalid elicitation request: ${L}`)}let{params:K}=W.data;K.mode=K.mode??"form";let{supportsFormMode:j,supportsUrlMode:G}=g3(this._capabilities.elicitation);if(K.mode==="form"&&!j)throw new r($2.InvalidParams,"Client does not support form-mode elicitation requests");if(K.mode==="url"&&!G)throw new r($2.InvalidParams,"Client does not support URL-mode elicitation requests");let z=await Promise.resolve(Z(D,H));if(K.task){let L=Z$(Y1,z);if(!L.success){let F=L.error instanceof Error?L.error.message:String(L.error);throw new r($2.InvalidParams,`Invalid task creation result: ${F}`)}return L.data}let O=Z$(X9,z);if(!O.success){let L=O.error instanceof Error?O.error.message:String(O.error);throw new r($2.InvalidParams,`Invalid elicitation result: ${L}`)}let P=O.data,w=K.mode==="form"?K.requestedSchema:void 0;if(K.mode==="form"&&P.action==="accept"&&P.content&&w){if(this._capabilities.elicitation?.form?.applyDefaults)try{t6(w,P.content)}catch{}}return P};return super.setRequestHandler($,B)}if(V==="sampling/createMessage"){let B=async(D,H)=>{let W=Z$(t7,D);if(!W.success){let P=W.error instanceof Error?W.error.message:String(W.error);throw new r($2.InvalidParams,`Invalid sampling request: ${P}`)}let{params:K}=W.data,j=await Promise.resolve(Z(D,H));if(K.task){let P=Z$(Y1,j);if(!P.success){let w=P.error instanceof Error?P.error.message:String(P.error);throw new r($2.InvalidParams,`Invalid task creation result: ${w}`)}return P.data}let z=K.tools||K.toolChoice?$9:e7,O=Z$(z,j);if(!O.success){let P=O.error instanceof Error?O.error.message:String(O.error);throw new r($2.InvalidParams,`Invalid sampling result: ${P}`)}return O.data};return super.setRequestHandler($,B)}return super.setRequestHandler($,Z)}assertCapability($,Z){if(!this._serverCapabilities?.[$])throw Error(`Server does not support ${$} (required for ${Z})`)}async connect($,Z){if(await super.connect($),$.sessionId!==void 0)return;try{let X=await this.request({method:"initialize",params:{protocolVersion:_1,capabilities:this._capabilities,clientInfo:this._clientInfo}},f7,Z);if(X===void 0)throw Error(`Server sent invalid initialize result: ${X}`);if(!QX.includes(X.protocolVersion))throw Error(`Server's protocol version is not supported: ${X.protocolVersion}`);if(this._serverCapabilities=X.capabilities,this._serverVersion=X.serverInfo,$.setProtocolVersion)$.setProtocolVersion(X.protocolVersion);if(this._instructions=X.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(X){throw this.close(),X}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod($){switch($){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${$})`);if($==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${$})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${$})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${$})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${$})`);break;case"ping":break}}assertTaskCapability($){EX(this._serverCapabilities?.tasks?.requests,$,"Server")}assertTaskHandlerCapability($){if(!this._capabilities)return;vX(this._capabilities.tasks?.requests,$,"Client")}async ping($){return this.request({method:"ping"},X1,$)}async complete($,Z){return this.request({method:"completion/complete",params:$},Y9,Z)}async setLoggingLevel($,Z){return this.request({method:"logging/setLevel",params:{level:$}},X1,Z)}async getPrompt($,Z){return this.request({method:"prompts/get",params:$},s7,Z)}async listPrompts($,Z){return this.request({method:"prompts/list",params:$},o7,Z)}async listResources($,Z){return this.request({method:"resources/list",params:$},v7,Z)}async listResourceTemplates($,Z){return this.request({method:"resources/templates/list",params:$},d7,Z)}async readResource($,Z){return this.request({method:"resources/read",params:$},l7,Z)}async subscribeResource($,Z){return this.request({method:"resources/subscribe",params:$},X1,Z)}async unsubscribeResource($,Z){return this.request({method:"resources/unsubscribe",params:$},X1,Z)}async callTool($,Z=k$,X){if(this.isToolTaskRequired($.name))throw new r($2.InvalidRequest,`Tool "${$.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let Q=await this.request({method:"tools/call",params:$},Z,X),J=this.getToolOutputValidator($.name);if(J){if(!Q.structuredContent&&!Q.isError)throw new r($2.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`);if(Q.structuredContent)try{let V=J(Q.structuredContent);if(!V.valid)throw new r($2.InvalidParams,`Structured content does not match the tool's output schema: ${V.errorMessage}`)}catch(V){if(V instanceof r)throw V;throw new r($2.InvalidParams,`Failed to validate structured content: ${V instanceof Error?V.message:String(V)}`)}}return Q}isToolTask($){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has($)}isToolTaskRequired($){return this._cachedRequiredTaskTools.has($)}cacheToolMetadata($){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let Z of $){if(Z.outputSchema){let Q=this._jsonSchemaValidator.getValidator(Z.outputSchema);this._cachedToolOutputValidators.set(Z.name,Q)}let X=Z.execution?.taskSupport;if(X==="required"||X==="optional")this._cachedKnownTaskTools.add(Z.name);if(X==="required")this._cachedRequiredTaskTools.add(Z.name)}}getToolOutputValidator($){return this._cachedToolOutputValidators.get($)}async listTools($,Z){let X=await this.request({method:"tools/list",params:$},r7,Z);return this.cacheToolMetadata(X.tools),X}_setupListChangedHandler($,Z,X,Q){let J=xX.safeParse(X);if(!J.success)throw Error(`Invalid ${$} listChanged options: ${J.error.message}`);if(typeof X.onChanged!=="function")throw Error(`Invalid ${$} listChanged options: onChanged must be a function`);let{autoRefresh:V,debounceMs:B}=J.data,{onChanged:D}=X,H=async()=>{if(!V){D(null,null);return}try{let K=await Q();D(null,K)}catch(K){let j=K instanceof Error?K:Error(String(K));D(j,null)}},W=()=>{if(B){let K=this._listChangedDebounceTimers.get($);if(K)clearTimeout(K);let j=setTimeout(H,B);this._listChangedDebounceTimers.set($,j)}else H()};this.setNotificationHandler(Z,W)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function S1($){if(!$)return{};if($ instanceof Headers)return Object.fromEntries($.entries());if(Array.isArray($))return Object.fromEntries($);return{...$}}function e6($=fetch,Z){if(!Z)return $;return async(X,Q)=>{let J={...Z,...Q,headers:Q?.headers?{...S1(Z.headers),...S1(Q.headers)}:Z.headers};return $(X,J)}}var F9;F9=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(($)=>$.webcrypto);async function h3($){return(await F9).getRandomValues(new Uint8Array($))}async function f3($){let X=Math.pow(2,8)-Math.pow(2,8)%66,Q="";while(Q.length<$){let J=await h3($-Q.length);for(let V of J)if(V<X)Q+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[V%66]}return Q}async function E3($){return await f3($)}async function v3($){let Z=await(await F9).subtle.digest("SHA-256",new TextEncoder().encode($));return btoa(String.fromCharCode(...new Uint8Array(Z))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function P9($){if(!$)$=43;if($<43||$>128)throw`Expected a length between 43 and 128. Received ${$}.`;let Z=await E3($),X=await v3(Z);return{code_verifier:Z,code_challenge:X}}var B0=lX().superRefine(($,Z)=>{if(!URL.canParse($))return Z.addIssue({code:oX.custom,message:"URL must be parseable",fatal:!0}),mX}).refine(($)=>{let Z=new URL($);return Z.protocol!=="javascript:"&&Z.protocol!=="data:"&&Z.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),pX=i2({resource:x().url(),authorization_servers:c(B0).optional(),jwks_uri:x().url().optional(),scopes_supported:c(x()).optional(),bearer_methods_supported:c(x()).optional(),resource_signing_alg_values_supported:c(x()).optional(),resource_name:x().optional(),resource_documentation:x().optional(),resource_policy_uri:x().url().optional(),resource_tos_uri:x().url().optional(),tls_client_certificate_bound_access_tokens:A2().optional(),authorization_details_types_supported:c(x()).optional(),dpop_signing_alg_values_supported:c(x()).optional(),dpop_bound_access_tokens_required:A2().optional()}),z9=i2({issuer:x(),authorization_endpoint:B0,token_endpoint:B0,registration_endpoint:B0.optional(),scopes_supported:c(x()).optional(),response_types_supported:c(x()),response_modes_supported:c(x()).optional(),grant_types_supported:c(x()).optional(),token_endpoint_auth_methods_supported:c(x()).optional(),token_endpoint_auth_signing_alg_values_supported:c(x()).optional(),service_documentation:B0.optional(),revocation_endpoint:B0.optional(),revocation_endpoint_auth_methods_supported:c(x()).optional(),revocation_endpoint_auth_signing_alg_values_supported:c(x()).optional(),introspection_endpoint:x().optional(),introspection_endpoint_auth_methods_supported:c(x()).optional(),introspection_endpoint_auth_signing_alg_values_supported:c(x()).optional(),code_challenge_methods_supported:c(x()).optional(),client_id_metadata_document_supported:A2().optional()}),d3=i2({issuer:x(),authorization_endpoint:B0,token_endpoint:B0,userinfo_endpoint:B0.optional(),jwks_uri:B0,registration_endpoint:B0.optional(),scopes_supported:c(x()).optional(),response_types_supported:c(x()),response_modes_supported:c(x()).optional(),grant_types_supported:c(x()).optional(),acr_values_supported:c(x()).optional(),subject_types_supported:c(x()),id_token_signing_alg_values_supported:c(x()),id_token_encryption_alg_values_supported:c(x()).optional(),id_token_encryption_enc_values_supported:c(x()).optional(),userinfo_signing_alg_values_supported:c(x()).optional(),userinfo_encryption_alg_values_supported:c(x()).optional(),userinfo_encryption_enc_values_supported:c(x()).optional(),request_object_signing_alg_values_supported:c(x()).optional(),request_object_encryption_alg_values_supported:c(x()).optional(),request_object_encryption_enc_values_supported:c(x()).optional(),token_endpoint_auth_methods_supported:c(x()).optional(),token_endpoint_auth_signing_alg_values_supported:c(x()).optional(),display_values_supported:c(x()).optional(),claim_types_supported:c(x()).optional(),claims_supported:c(x()).optional(),service_documentation:x().optional(),claims_locales_supported:c(x()).optional(),ui_locales_supported:c(x()).optional(),claims_parameter_supported:A2().optional(),request_parameter_supported:A2().optional(),request_uri_parameter_supported:A2().optional(),require_request_uri_registration:A2().optional(),op_policy_uri:B0.optional(),op_tos_uri:B0.optional(),client_id_metadata_document_supported:A2().optional()}),iX=o({...d3.shape,...z9.pick({code_challenge_methods_supported:!0}).shape}),nX=o({access_token:x(),id_token:x().optional(),token_type:x(),expires_in:uX.number().optional(),scope:x().optional(),refresh_token:x().optional()}).strip(),sX=o({error:x(),error_description:x().optional(),error_uri:x().optional()}),dX=B0.optional().or(i("").transform(()=>{return})),m3=o({redirect_uris:c(B0),token_endpoint_auth_method:x().optional(),grant_types:c(x()).optional(),response_types:c(x()).optional(),client_name:x().optional(),client_uri:B0.optional(),logo_uri:dX,scope:x().optional(),contacts:c(x()).optional(),tos_uri:dX,policy_uri:x().optional(),jwks_uri:B0.optional(),jwks:cX().optional(),software_id:x().optional(),software_version:x().optional(),software_statement:x().optional()}).strip(),l3=o({client_id:x(),client_secret:x().optional(),client_id_issued_at:z2().optional(),client_secret_expires_at:z2().optional()}).strip(),aX=m3.merge(l3),kF=o({error:x(),error_description:x().optional()}).strip(),TF=o({token:x(),token_type_hint:x().optional()}).strip();function rX($){let Z=typeof $==="string"?new URL($):new URL($.href);return Z.hash="",Z}function tX({requestedResource:$,configuredResource:Z}){let X=typeof $==="string"?new URL($):new URL($.href),Q=typeof Z==="string"?new URL(Z):new URL(Z.href);if(X.origin!==Q.origin)return!1;if(X.pathname.length<Q.pathname.length)return!1;let J=X.pathname.endsWith("/")?X.pathname:X.pathname+"/",V=Q.pathname.endsWith("/")?Q.pathname:Q.pathname+"/";return J.startsWith(V)}class o2 extends Error{constructor($,Z){super($);this.errorUri=Z,this.name=this.constructor.name}toResponseObject(){let $={error:this.errorCode,error_description:this.message};if(this.errorUri)$.error_uri=this.errorUri;return $}get errorCode(){return this.constructor.errorCode}}class $4 extends o2{}$4.errorCode="invalid_request";class k1 extends o2{}k1.errorCode="invalid_client";class T1 extends o2{}T1.errorCode="invalid_grant";class g1 extends o2{}g1.errorCode="unauthorized_client";class Z4 extends o2{}Z4.errorCode="unsupported_grant_type";class X4 extends o2{}X4.errorCode="invalid_scope";class Y4 extends o2{}Y4.errorCode="access_denied";class h$ extends o2{}h$.errorCode="server_error";class Q4 extends o2{}Q4.errorCode="temporarily_unavailable";class J4 extends o2{}J4.errorCode="unsupported_response_type";class V4 extends o2{}V4.errorCode="unsupported_token_type";class B4 extends o2{}B4.errorCode="invalid_token";class W4 extends o2{}W4.errorCode="method_not_allowed";class K4 extends o2{}K4.errorCode="too_many_requests";class h1 extends o2{}h1.errorCode="invalid_client_metadata";class G4 extends o2{}G4.errorCode="insufficient_scope";class H4 extends o2{}H4.errorCode="invalid_target";var eX={[$4.errorCode]:$4,[k1.errorCode]:k1,[T1.errorCode]:T1,[g1.errorCode]:g1,[Z4.errorCode]:Z4,[X4.errorCode]:X4,[Y4.errorCode]:Y4,[h$.errorCode]:h$,[Q4.errorCode]:Q4,[J4.errorCode]:J4,[V4.errorCode]:V4,[B4.errorCode]:B4,[W4.errorCode]:W4,[K4.errorCode]:K4,[h1.errorCode]:h1,[G4.errorCode]:G4,[H4.errorCode]:H4};class Z0 extends Error{constructor($){super($??"Unauthorized")}}function c3($){return["client_secret_basic","client_secret_post","none"].includes($)}var q9="code",N9="S256";function o3($,Z){let X=$.client_secret!==void 0;if(Z.length===0)return X?"client_secret_post":"none";if("token_endpoint_auth_method"in $&&$.token_endpoint_auth_method&&c3($.token_endpoint_auth_method)&&Z.includes($.token_endpoint_auth_method))return $.token_endpoint_auth_method;if(X&&Z.includes("client_secret_basic"))return"client_secret_basic";if(X&&Z.includes("client_secret_post"))return"client_secret_post";if(Z.includes("none"))return"none";return X?"client_secret_post":"none"}function u3($,Z,X,Q){let{client_id:J,client_secret:V}=Z;switch($){case"client_secret_basic":p3(J,V,X);return;case"client_secret_post":i3(J,V,Q);return;case"none":n3(J,Q);return;default:throw Error(`Unsupported client authentication method: ${$}`)}}function p3($,Z,X){if(!Z)throw Error("client_secret_basic authentication requires a client_secret");let Q=btoa(`${$}:${Z}`);X.set("Authorization",`Basic ${Q}`)}function i3($,Z,X){if(X.set("client_id",$),Z)X.set("client_secret",Z)}function n3($,Z){Z.set("client_id",$)}async function ZY($){let Z=$ instanceof Response?$.status:void 0,X=$ instanceof Response?await $.text():$;try{let Q=sX.parse(JSON.parse(X)),{error:J,error_description:V,error_uri:B}=Q;return new(eX[J]||h$)(V||"",B)}catch(Q){let J=`${Z?`HTTP ${Z}: `:""}Invalid OAuth error response: ${Q}. Raw body: ${X}`;return new h$(J)}}async function N$($,Z){try{return await x9($,Z)}catch(X){if(X instanceof k1||X instanceof g1)return await $.invalidateCredentials?.("all"),await x9($,Z);else if(X instanceof T1)return await $.invalidateCredentials?.("tokens"),await x9($,Z);throw X}}async function x9($,{serverUrl:Z,authorizationCode:X,scope:Q,resourceMetadataUrl:J,fetchFn:V}){let B=await $.discoveryState?.(),D,H,W,K=J;if(!K&&B?.resourceMetadataUrl)K=new URL(B.resourceMetadataUrl);if(B?.authorizationServerUrl){if(H=B.authorizationServerUrl,D=B.resourceMetadata,W=B.authorizationServerMetadata??await YY(H,{fetchFn:V}),!D)try{D=await XY(Z,{resourceMetadataUrl:K},V)}catch{}if(W!==B.authorizationServerMetadata||D!==B.resourceMetadata)await $.saveDiscoveryState?.({authorizationServerUrl:String(H),resourceMetadataUrl:K?.toString(),resourceMetadata:D,authorizationServerMetadata:W})}else{let F=await ZK(Z,{resourceMetadataUrl:K,fetchFn:V});H=F.authorizationServerUrl,W=F.authorizationServerMetadata,D=F.resourceMetadata,await $.saveDiscoveryState?.({authorizationServerUrl:String(H),resourceMetadataUrl:K?.toString(),resourceMetadata:D,authorizationServerMetadata:W})}let j=await a3(Z,$,D),G=await Promise.resolve($.clientInformation());if(!G){if(X!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let F=W?.client_id_metadata_document_supported===!0,U=$.clientMetadataUrl;if(U&&!s3(U))throw new h1(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${U}`);if(F&&U)G={client_id:U},await $.saveClientInformation?.(G);else{if(!$.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let S=await VK(H,{metadata:W,clientMetadata:$.clientMetadata,fetchFn:V});await $.saveClientInformation(S),G=S}}let z=!$.redirectUrl;if(X!==void 0||z){let F=await JK($,H,{metadata:W,resource:j,authorizationCode:X,fetchFn:V});return await $.saveTokens(F),"AUTHORIZED"}let O=await $.tokens();if(O?.refresh_token)try{let F=await QK(H,{metadata:W,clientInformation:G,refreshToken:O.refresh_token,resource:j,addClientAuthentication:$.addClientAuthentication,fetchFn:V});return await $.saveTokens(F),"AUTHORIZED"}catch(F){if(!(F instanceof o2)||F instanceof h$);else throw F}let P=$.state?await $.state():void 0,{authorizationUrl:w,codeVerifier:L}=await XK(H,{metadata:W,clientInformation:G,state:P,redirectUrl:$.redirectUrl,scope:Q||D?.scopes_supported?.join(" ")||$.clientMetadata.scope,resource:j});return await $.saveCodeVerifier(L),await $.redirectToAuthorization(w),"REDIRECT"}function s3($){if(!$)return!1;try{let Z=new URL($);return Z.protocol==="https:"&&Z.pathname!=="/"}catch{return!1}}async function a3($,Z,X){let Q=rX($);if(Z.validateResourceURL)return await Z.validateResourceURL(Q,X?.resource);if(!X)return;if(!tX({requestedResource:Q,configuredResource:X.resource}))throw Error(`Protected resource ${X.resource} does not match expected ${Q} (or origin)`);return new URL(X.resource)}function f1($){let Z=$.headers.get("WWW-Authenticate");if(!Z)return{};let[X,Q]=Z.split(" ");if(X.toLowerCase()!=="bearer"||!Q)return{};let J=w9($,"resource_metadata")||void 0,V;if(J)try{V=new URL(J)}catch{}let B=w9($,"scope")||void 0,D=w9($,"error")||void 0;return{resourceMetadataUrl:V,scope:B,error:D}}function w9($,Z){let X=$.headers.get("WWW-Authenticate");if(!X)return null;let Q=new RegExp(`${Z}=(?:"([^"]+)"|([^\\s,]+))`),J=X.match(Q);if(J)return J[1]||J[2];return null}async function XY($,Z,X=fetch){let Q=await e3($,"oauth-protected-resource",X,{protocolVersion:Z?.protocolVersion,metadataUrl:Z?.resourceMetadataUrl});if(!Q||Q.status===404)throw await Q?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!Q.ok)throw await Q.body?.cancel(),Error(`HTTP ${Q.status} trying to load well-known OAuth protected resource metadata.`);return pX.parse(await Q.json())}async function b9($,Z,X=fetch){try{return await X($,{headers:Z})}catch(Q){if(Q instanceof TypeError)if(Z)return b9($,void 0,X);else return;throw Q}}function r3($,Z="",X={}){if(Z.endsWith("/"))Z=Z.slice(0,-1);return X.prependPathname?`${Z}/.well-known/${$}`:`/.well-known/${$}${Z}`}async function $Y($,Z,X=fetch){return await b9($,{"MCP-Protocol-Version":Z},X)}function t3($,Z){return!$||$.status>=400&&$.status<500&&Z!=="/"}async function e3($,Z,X,Q){let J=new URL($),V=Q?.protocolVersion??_1,B;if(Q?.metadataUrl)B=new URL(Q.metadataUrl);else{let H=r3(Z,J.pathname);B=new URL(H,Q?.metadataServerUrl??J),B.search=J.search}let D=await $Y(B,V,X);if(!Q?.metadataUrl&&t3(D,J.pathname)){let H=new URL(`/.well-known/${Z}`,J);D=await $Y(H,V,X)}return D}function $K($){let Z=typeof $==="string"?new URL($):$,X=Z.pathname!=="/",Q=[];if(!X)return Q.push({url:new URL("/.well-known/oauth-authorization-server",Z.origin),type:"oauth"}),Q.push({url:new URL("/.well-known/openid-configuration",Z.origin),type:"oidc"}),Q;let J=Z.pathname;if(J.endsWith("/"))J=J.slice(0,-1);return Q.push({url:new URL(`/.well-known/oauth-authorization-server${J}`,Z.origin),type:"oauth"}),Q.push({url:new URL(`/.well-known/openid-configuration${J}`,Z.origin),type:"oidc"}),Q.push({url:new URL(`${J}/.well-known/openid-configuration`,Z.origin),type:"oidc"}),Q}async function YY($,{fetchFn:Z=fetch,protocolVersion:X=_1}={}){let Q={"MCP-Protocol-Version":X,Accept:"application/json"},J=$K($);for(let{url:V,type:B}of J){let D=await b9(V,Q,Z);if(!D)continue;if(!D.ok){if(await D.body?.cancel(),D.status>=400&&D.status<500)continue;throw Error(`HTTP ${D.status} trying to load ${B==="oauth"?"OAuth":"OpenID provider"} metadata from ${V}`)}if(B==="oauth")return z9.parse(await D.json());else return iX.parse(await D.json())}return}async function ZK($,Z){let X,Q;try{if(X=await XY($,{resourceMetadataUrl:Z?.resourceMetadataUrl},Z?.fetchFn),X.authorization_servers&&X.authorization_servers.length>0)Q=X.authorization_servers[0]}catch{}if(!Q)Q=String(new URL("/",$));let J=await YY(Q,{fetchFn:Z?.fetchFn});return{authorizationServerUrl:Q,authorizationServerMetadata:J,resourceMetadata:X}}async function XK($,{metadata:Z,clientInformation:X,redirectUrl:Q,scope:J,state:V,resource:B}){let D;if(Z){if(D=new URL(Z.authorization_endpoint),!Z.response_types_supported.includes(q9))throw Error(`Incompatible auth server: does not support response type ${q9}`);if(Z.code_challenge_methods_supported&&!Z.code_challenge_methods_supported.includes(N9))throw Error(`Incompatible auth server: does not support code challenge method ${N9}`)}else D=new URL("/authorize",$);let H=await P9(),W=H.code_verifier,K=H.code_challenge;if(D.searchParams.set("response_type",q9),D.searchParams.set("client_id",X.client_id),D.searchParams.set("code_challenge",K),D.searchParams.set("code_challenge_method",N9),D.searchParams.set("redirect_uri",String(Q)),V)D.searchParams.set("state",V);if(J)D.searchParams.set("scope",J);if(J?.includes("offline_access"))D.searchParams.append("prompt","consent");if(B)D.searchParams.set("resource",B.href);return{authorizationUrl:D,codeVerifier:W}}function YK($,Z,X){return new URLSearchParams({grant_type:"authorization_code",code:$,code_verifier:Z,redirect_uri:String(X)})}async function QY($,{metadata:Z,tokenRequestParams:X,clientInformation:Q,addClientAuthentication:J,resource:V,fetchFn:B}){let D=Z?.token_endpoint?new URL(Z.token_endpoint):new URL("/token",$),H=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(V)X.set("resource",V.href);if(J)await J(H,X,D,Z);else if(Q){let K=Z?.token_endpoint_auth_methods_supported??[],j=o3(Q,K);u3(j,Q,H,X)}let W=await(B??fetch)(D,{method:"POST",headers:H,body:X});if(!W.ok)throw await ZY(W);return nX.parse(await W.json())}async function QK($,{metadata:Z,clientInformation:X,refreshToken:Q,resource:J,addClientAuthentication:V,fetchFn:B}){let D=new URLSearchParams({grant_type:"refresh_token",refresh_token:Q}),H=await QY($,{metadata:Z,tokenRequestParams:D,clientInformation:X,addClientAuthentication:V,resource:J,fetchFn:B});return{refresh_token:Q,...H}}async function JK($,Z,{metadata:X,resource:Q,authorizationCode:J,fetchFn:V}={}){let B=$.clientMetadata.scope,D;if($.prepareTokenRequest)D=await $.prepareTokenRequest(B);if(!D){if(!J)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!$.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");let W=await $.codeVerifier();D=YK(J,W,$.redirectUrl)}let H=await $.clientInformation();return QY(Z,{metadata:X,tokenRequestParams:D,clientInformation:H??void 0,addClientAuthentication:$.addClientAuthentication,resource:Q,fetchFn:V})}async function VK($,{metadata:Z,clientMetadata:X,fetchFn:Q}){let J;if(Z){if(!Z.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");J=new URL(Z.registration_endpoint)}else J=new URL("/register",$);let V=await(Q??fetch)(J,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)});if(!V.ok)throw await ZY(V);return aX.parse(await V.json())}var BK={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Q1 extends Error{constructor($,Z){super(`Streamable HTTP error: ${Z}`);this.code=$}}class M8{constructor($,Z){this._hasCompletedAuthFlow=!1,this._url=$,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=Z?.requestInit,this._authProvider=Z?.authProvider,this._fetch=Z?.fetch,this._fetchWithInit=e6(Z?.fetch,Z?.requestInit),this._sessionId=Z?.sessionId,this._reconnectionOptions=Z?.reconnectionOptions??BK}async _authThenStart(){if(!this._authProvider)throw new Z0("No auth provider");let $;try{$=await N$(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(Z){throw this.onerror?.(Z),Z}if($!=="AUTHORIZED")throw new Z0;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let $={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)$.Authorization=`Bearer ${X.access_token}`}if(this._sessionId)$["mcp-session-id"]=this._sessionId;if(this._protocolVersion)$["mcp-protocol-version"]=this._protocolVersion;let Z=S1(this._requestInit?.headers);return new Headers({...$,...Z})}async _startOrAuthSse($){let{resumptionToken:Z}=$;try{let X=await this._commonHeaders();if(X.set("Accept","text/event-stream"),Z)X.set("last-event-id",Z);let Q=await(this._fetch??fetch)(this._url,{method:"GET",headers:X,signal:this._abortController?.signal});if(!Q.ok){if(await Q.body?.cancel(),Q.status===401&&this._authProvider)return await this._authThenStart();if(Q.status===405)return;throw new Q1(Q.status,`Failed to open SSE stream: ${Q.statusText}`)}this._handleSseStream(Q.body,$,!0)}catch(X){throw this.onerror?.(X),X}}_getNextReconnectionDelay($){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let Z=this._reconnectionOptions.initialReconnectionDelay,X=this._reconnectionOptions.reconnectionDelayGrowFactor,Q=this._reconnectionOptions.maxReconnectionDelay;return Math.min(Z*Math.pow(X,$),Q)}_scheduleReconnection($,Z=0){let X=this._reconnectionOptions.maxRetries;if(Z>=X){this.onerror?.(Error(`Maximum reconnection attempts (${X}) exceeded.`));return}let Q=this._getNextReconnectionDelay(Z);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse($).catch((J)=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${J instanceof Error?J.message:String(J)}`)),this._scheduleReconnection($,Z+1)})},Q)}_handleSseStream($,Z,X){if(!$)return;let{onresumptiontoken:Q,replayMessageId:J}=Z,V,B=!1,D=!1;(async()=>{try{let W=$.pipeThrough(new TextDecoderStream).pipeThrough(new JY({onRetry:(G)=>{this._serverRetryMs=G}})).getReader();while(!0){let{value:G,done:z}=await W.read();if(z)break;if(G.id)V=G.id,B=!0,Q?.(G.id);if(!G.data)continue;if(!G.event||G.event==="message")try{let O=S$.parse(JSON.parse(G.data));if(Z1(O)){if(D=!0,J!==void 0)O.id=J}this.onmessage?.(O)}catch(O){this.onerror?.(O)}}if((X||B)&&!D&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:V,onresumptiontoken:Q,replayMessageId:J},0)}catch(W){if(this.onerror?.(Error(`SSE stream disconnected: ${W}`)),(X||B)&&!D&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:V,onresumptiontoken:Q,replayMessageId:J},0)}catch(G){this.onerror?.(Error(`Failed to reconnect: ${G instanceof Error?G.message:String(G)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth($){if(!this._authProvider)throw new Z0("No auth provider");if(await N$(this._authProvider,{serverUrl:this._url,authorizationCode:$,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Z0("Failed to authorize")}async close(){if(this._reconnectionTimeout)clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0;this._abortController?.abort(),this.onclose?.()}async send($,Z){try{let{resumptionToken:X,onresumptiontoken:Q}=Z||{};if(X){this._startOrAuthSse({resumptionToken:X,replayMessageId:O8($)?$.id:void 0}).catch((j)=>this.onerror?.(j));return}let J=await this._commonHeaders();J.set("content-type","application/json"),J.set("accept","application/json, text/event-stream");let V={...this._requestInit,method:"POST",headers:J,body:JSON.stringify($),signal:this._abortController?.signal},B=await(this._fetch??fetch)(this._url,V),D=B.headers.get("mcp-session-id");if(D)this._sessionId=D;if(!B.ok){let j=await B.text().catch(()=>null);if(B.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Q1(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:G,scope:z}=f1(B);if(this._resourceMetadataUrl=G,this._scope=z,await N$(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Z0;return this._hasCompletedAuthFlow=!0,this.send($)}if(B.status===403&&this._authProvider){let{resourceMetadataUrl:G,scope:z,error:O}=f1(B);if(O==="insufficient_scope"){let P=B.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===P)throw new Q1(403,"Server returned 403 after trying upscoping");if(z)this._scope=z;if(G)this._resourceMetadataUrl=G;if(this._lastUpscopingHeader=P??void 0,await N$(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Z0;return this.send($)}}throw new Q1(B.status,`Error POSTing to endpoint: ${j}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,B.status===202){if(await B.body?.cancel(),yX($))this._startOrAuthSse({resumptionToken:void 0}).catch((j)=>this.onerror?.(j));return}let W=(Array.isArray($)?$:[$]).filter((j)=>("method"in j)&&("id"in j)&&j.id!==void 0).length>0,K=B.headers.get("content-type");if(W)if(K?.includes("text/event-stream"))this._handleSseStream(B.body,{onresumptiontoken:Q},!1);else if(K?.includes("application/json")){let j=await B.json(),G=Array.isArray(j)?j.map((z)=>S$.parse(z)):[S$.parse(j)];for(let z of G)this.onmessage?.(z)}else throw await B.body?.cancel(),new Q1(-1,`Unexpected content type: ${K}`);else await B.body?.cancel()}catch(X){throw this.onerror?.(X),X}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let $=await this._commonHeaders(),Z={...this._requestInit,method:"DELETE",headers:$,signal:this._abortController?.signal},X=await(this._fetch??fetch)(this._url,Z);if(await X.body?.cancel(),!X.ok&&X.status!==405)throw new Q1(X.status,`Failed to terminate session: ${X.statusText}`);this._sessionId=void 0}catch($){throw this.onerror?.($),$}}setProtocolVersion($){this._protocolVersion=$}get protocolVersion(){return this._protocolVersion}async resumeStream($,Z){await this._startOrAuthSse({resumptionToken:$,onresumptiontoken:Z?.onresumptiontoken})}}var _8=s.create({service:"mcp.oauth"}),v1=19876,E1="/mcp/oauth/callback";class I8{mcpName;serverUrl;config;callbacks;auth;authKey;constructor($,Z,X,Q,J,V){this.mcpName=$;this.serverUrl=Z;this.config=X;this.callbacks=Q;this.auth=J;this.authKey=V??$}get redirectUrl(){if(this.config.redirectUri)return this.config.redirectUri;return`http://127.0.0.1:${v1}${E1}`}get clientMetadata(){return{redirect_uris:[this.redirectUrl],client_name:"QitQode",client_uri:"https://qitqode.com",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:this.config.clientSecret?"client_secret_post":"none"}}async clientInformation(){if(this.config.clientId)return{client_id:this.config.clientId,client_secret:this.config.clientSecret};let $=await Y.runPromise(this.auth.getForUrl(this.mcpName,this.serverUrl));if($?.clientInfo){if($.clientInfo.clientSecretExpiresAt&&$.clientInfo.clientSecretExpiresAt<Date.now()/1000){_8.info("client secret expired, need to re-register",{mcpName:this.mcpName});return}return{client_id:$.clientInfo.clientId,client_secret:$.clientInfo.clientSecret}}return}async saveClientInformation($){await Y.runPromise(this.auth.updateClientInfo(this.mcpName,{clientId:$.client_id,clientSecret:$.client_secret,clientIdIssuedAt:$.client_id_issued_at,clientSecretExpiresAt:$.client_secret_expires_at},this.serverUrl)),_8.info("saved dynamically registered client",{mcpName:this.mcpName,clientId:$.client_id})}async tokens(){let $=await Y.runPromise(this.auth.getForUrl(this.mcpName,this.serverUrl));if(!$?.tokens)return;return{access_token:$.tokens.accessToken,token_type:"Bearer",refresh_token:$.tokens.refreshToken,expires_in:$.tokens.expiresAt?Math.max(0,Math.floor($.tokens.expiresAt-Date.now()/1000)):void 0,scope:$.tokens.scope}}async saveTokens($){await Y.runPromise(this.auth.updateTokens(this.mcpName,{accessToken:$.access_token,refreshToken:$.refresh_token,expiresAt:$.expires_in?Date.now()/1000+$.expires_in:void 0,scope:$.scope},this.serverUrl)),_8.info("saved oauth tokens",{mcpName:this.mcpName})}async redirectToAuthorization($){_8.info("redirecting to authorization",{mcpName:this.mcpName,url:$.toString()}),await this.callbacks.onRedirect($)}async saveCodeVerifier($){await Y.runPromise(this.auth.updateCodeVerifier(this.authKey,$))}async codeVerifier(){let $=await Y.runPromise(this.auth.get(this.authKey));if(!$?.codeVerifier)throw Error(`No code verifier saved for MCP server: ${this.mcpName}`);return $.codeVerifier}async saveState($){await Y.runPromise(this.auth.updateOAuthState(this.authKey,$))}async state(){let $=await Y.runPromise(this.auth.get(this.authKey));if($?.oauthState)return $.oauthState;let Z=Array.from(crypto.getRandomValues(new Uint8Array(32))).map((X)=>X.toString(16).padStart(2,"0")).join("");return await Y.runPromise(this.auth.updateOAuthState(this.authKey,Z)),Z}async invalidateCredentials($){_8.info("invalidating credentials",{mcpName:this.mcpName,type:$});let Z=await Y.runPromise(this.auth.get(this.mcpName));if(!Z)return;switch($){case"all":await Y.runPromise(this.auth.remove(this.mcpName));break;case"client":delete Z.clientInfo,await Y.runPromise(this.auth.set(this.mcpName,Z));break;case"tokens":delete Z.tokens,await Y.runPromise(this.auth.set(this.mcpName,Z));break}}}function VY($){if(!$)return{port:v1,path:E1};try{let Z=new URL($),X=Z.port?parseInt(Z.port,10):Z.protocol==="https:"?443:80,Q=Z.pathname||E1;return{port:X,path:Q}}catch{return{port:v1,path:E1}}}var w$={};L2(w$,{waitForCallback:()=>yK,stop:()=>KY,isRunning:()=>FK,isPortInUse:()=>WY,ensureRunning:()=>DK,cancelPending:()=>OK,McpOAuthCallback:()=>w$});import{createConnection as WK}from"net";import{createServer as KK}from"http";var J1=s.create({service:"mcp.oauth-callback"}),d1=v1,D4=E1,GK=`<!DOCTYPE html>
|
|
163
|
+
<html>
|
|
164
|
+
<head>
|
|
165
|
+
<title>QitQode - Authorization Successful</title>
|
|
166
|
+
<style>
|
|
167
|
+
body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
|
|
168
|
+
.container { text-align: center; padding: 2rem; }
|
|
169
|
+
h1 { color: #4ade80; margin-bottom: 1rem; }
|
|
170
|
+
p { color: #aaa; }
|
|
171
|
+
</style>
|
|
172
|
+
</head>
|
|
173
|
+
<body>
|
|
174
|
+
<div class="container">
|
|
175
|
+
<h1>Authorization Successful</h1>
|
|
176
|
+
<p>You can close this window and return to QitQode.</p>
|
|
177
|
+
</div>
|
|
178
|
+
<script>setTimeout(() => window.close(), 2000);</script>
|
|
179
|
+
</body>
|
|
180
|
+
</html>`,j4=($)=>`<!DOCTYPE html>
|
|
181
|
+
<html>
|
|
182
|
+
<head>
|
|
183
|
+
<title>QitQode - Authorization Failed</title>
|
|
184
|
+
<style>
|
|
185
|
+
body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
|
|
186
|
+
.container { text-align: center; padding: 2rem; }
|
|
187
|
+
h1 { color: #f87171; margin-bottom: 1rem; }
|
|
188
|
+
p { color: #aaa; }
|
|
189
|
+
.error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
|
|
190
|
+
</style>
|
|
191
|
+
</head>
|
|
192
|
+
<body>
|
|
193
|
+
<div class="container">
|
|
194
|
+
<h1>Authorization Failed</h1>
|
|
195
|
+
<p>An error occurred during authorization.</p>
|
|
196
|
+
<div class="error">${$}</div>
|
|
197
|
+
</div>
|
|
198
|
+
</body>
|
|
199
|
+
</html>`,x$,A0=new Map,V1=new Map,HK=300000;function BY($){for(let[Z,X]of V1)if(X===$){V1.delete(Z);break}}function jK($,Z){let X=new URL($.url||"/",`http://localhost:${d1}`);if(X.pathname!==D4){Z.writeHead(404),Z.end("Not found");return}let Q=X.searchParams.get("code"),J=X.searchParams.get("state"),V=X.searchParams.get("error"),B=X.searchParams.get("error_description");if(J1.info("received oauth callback",{hasCode:!!Q,state:J,error:V}),!J){J1.error("oauth callback missing state parameter",{url:X.toString()}),Z.writeHead(400,{"Content-Type":"text/html"}),Z.end(j4("Missing required state parameter - potential CSRF attack"));return}if(V){let H=B||V;if(A0.has(J)){let W=A0.get(J);clearTimeout(W.timeout),A0.delete(J),BY(J),W.reject(Error(H))}Z.writeHead(200,{"Content-Type":"text/html"}),Z.end(j4(H));return}if(!Q){Z.writeHead(400,{"Content-Type":"text/html"}),Z.end(j4("No authorization code provided"));return}if(!A0.has(J)){J1.error("oauth callback with invalid state",{state:J,pendingStates:Array.from(A0.keys())}),Z.writeHead(400,{"Content-Type":"text/html"}),Z.end(j4("Invalid or expired state parameter - potential CSRF attack"));return}let D=A0.get(J);clearTimeout(D.timeout),A0.delete(J),BY(J),D.resolve(Q),Z.writeHead(200,{"Content-Type":"text/html"}),Z.end(GK)}async function DK($){let{port:Z,path:X}=VY($);if(x$&&(d1!==Z||D4!==X))J1.info("stopping oauth callback server to reconfigure",{oldPort:d1,newPort:Z}),await KY();if(x$)return;if(await WY(Z)){J1.info("oauth callback server already running on another instance",{port:Z});return}d1=Z,D4=X,x$=KK(jK),await new Promise((J,V)=>{x$.listen(d1,()=>{J1.info("oauth callback server started",{port:d1,path:D4}),J()}),x$.on("error",V)})}function yK($,Z){if(Z)V1.set(Z,$);return new Promise((X,Q)=>{let J=setTimeout(()=>{if(A0.has($)){if(A0.delete($),Z)V1.delete(Z);Q(Error("OAuth callback timeout - authorization took too long"))}},HK);A0.set($,{resolve:X,reject:Q,timeout:J})})}function OK($){let X=V1.get($)??$,Q=A0.get(X);if(Q)clearTimeout(Q.timeout),A0.delete(X),V1.delete($),Q.reject(Error("Authorization cancelled"))}async function WY($=v1){return new Promise((Z)=>{let X=WK($,"127.0.0.1");X.on("connect",()=>{X.destroy(),Z(!0)}),X.on("error",()=>{Z(!1)})})}async function KY(){if(x$)await new Promise(($)=>x$.close(()=>$())),x$=void 0,J1.info("oauth callback server stopped");for(let[$,Z]of A0)clearTimeout(Z.timeout),Z.reject(Error("OAuth callback server stopped"));A0.clear(),V1.clear()}function FK(){return x$!==void 0}var f$=new Map,HY="\x00",F4=($,Z)=>$+HY+Z,O4=($)=>Y.tryPromise(()=>$.close()).pipe(Y.ignore),L9=($,Z)=>{let X=f$.get($);if(f$.set($,Z),!X||X===Z)return Y.void;return O4(X)},y4=($,Z)=>Y.gen(function*(){let X=f$.get($);if(!X||Z&&X!==Z)return;f$.delete($),yield*O4(X)}),jY=($)=>{let Z=$+HY;return Y.forEach(Array.from(f$.entries()).filter(([X])=>X.startsWith(Z)),([X,Q])=>y4(X,Q),{concurrency:"unbounded",discard:!0})};function DY($){let Z=Y.fn("MCP.startAuth")(function*(H){let W=yield*$.getConfig(H);if(!W)throw Error(`MCP server ${H} not found or disabled`);if(W.type!=="remote")throw Error(`MCP server ${H} is not a remote server`);if(W.oauth===!1)throw Error(`MCP server ${H} has OAuth explicitly disabled`);let K=yield*$.pendingKey(H);w$.cancelPending(K);let j=typeof W.oauth==="object"?W.oauth:void 0;yield*Y.promise(()=>w$.ensureRunning(j?.redirectUri));let G=Array.from(crypto.getRandomValues(new Uint8Array(32))).map((w)=>w.toString(16).padStart(2,"0")).join("");yield*$.auth.updateOAuthState(K,G);let z,O=new I8(H,W.url,{clientId:j?.clientId,clientSecret:j?.clientSecret,scope:j?.scope,redirectUri:j?.redirectUri},{onRedirect:async(w)=>{z=w}},$.auth,K),P=new M8(new URL(W.url),{authProvider:O});return yield*Y.tryPromise({try:()=>{let w=new A8({name:"qitqode",version:w1});return w.connect(P).then(()=>({authorizationUrl:"",oauthState:G,pendingKey:K,transport:void 0,client:w}))},catch:(w)=>w}).pipe(Y.catch((w)=>{if(w instanceof Z0&&z)return L9(K,P).pipe(Y.as({authorizationUrl:z.toString(),oauthState:G,pendingKey:K,transport:P}));return O4(P).pipe(Y.andThen(Y.die(w)))}))}),X=Y.fn("MCP.finishAuth")(function*(H,W){let K=yield*$.pendingKey(H),j=f$.get(K);if(!j)throw Error(`No pending OAuth flow for MCP server: ${H}`);let G=yield*Y.tryPromise({try:()=>j.finishAuth(W).then(()=>!0),catch:(z)=>z}).pipe(Y.option);if(Y0.isNone(G))return yield*y4(K,j),{status:"failed",error:"OAuth completion failed"};if(f$.get(K)===j)f$.delete(K);return yield*Y.gen(function*(){yield*$.auth.clearCodeVerifier(K);let z=yield*$.getConfig(H);if(!z)return{status:"failed",error:"MCP config not found after auth"};return yield*$.createAndStore(H,z)}).pipe(Y.ensuring(O4(j)))}),Q=Y.fn("MCP.authenticate")(function*(H){let W=yield*Z(H);if(!W.authorizationUrl){let j="client"in W?W.client:void 0,G=yield*$.getConfig(H);if(!G)return yield*Y.tryPromise(()=>j?.close()??Promise.resolve()).pipe(Y.ignore),{status:"failed",error:"MCP config not found after auth"};let z=j?yield*R1(H,j,G.timeout):void 0;if(!j||!z)return yield*Y.tryPromise(()=>j?.close()??Promise.resolve()).pipe(Y.ignore),{status:"failed",error:"Failed to get tools"};return yield*$.auth.clearOAuthState(W.pendingKey),yield*$.storeClient(H,j,z,G.timeout)}let K=w$.waitForCallback(W.oauthState,W.pendingKey);return yield*Y.gen(function*(){if(!(yield*Y.promise(()=>GY(W.authorizationUrl))))yield*$.bus.publish(B9,{mcpName:H,url:W.authorizationUrl}).pipe(Y.ignore);let G=yield*Y.promise(()=>K);if((yield*$.auth.getOAuthState(W.pendingKey))!==W.oauthState)throw yield*$.auth.clearOAuthState(W.pendingKey),Error("OAuth state mismatch - potential CSRF attack");return yield*$.auth.clearOAuthState(W.pendingKey),yield*X(H,G)}).pipe(Y.ensuring(Y.sync(()=>w$.cancelPending(W.pendingKey)).pipe(Y.andThen(y4(W.pendingKey,W.transport)))))}),J=Y.fn("MCP.removeAuth")(function*(H){yield*$.auth.remove(H);let W=yield*$.pendingKey(H);yield*$.auth.clearCodeVerifier(W),yield*$.auth.clearOAuthState(W),w$.cancelPending(W),yield*y4(W)}),V=Y.fn("MCP.supportsOAuth")(function*(H){let W=yield*$.getConfig(H);return!!W&&W.type==="remote"&&W.oauth!==!1}),B=Y.fn("MCP.hasStoredTokens")(function*(H){return!!(yield*$.auth.get(H))?.tokens}),D=Y.fn("MCP.getAuthStatus")(function*(H){if(!(yield*$.auth.get(H))?.tokens)return"not_authenticated";return(yield*$.auth.isTokenExpired(H))?"expired":"authenticated"});return{startAuth:Z,authenticate:Q,finishAuth:X,removeAuth:J,supportsOAuth:V,hasStoredTokens:B,getAuthStatus:D}}class U9 extends Event{constructor($,Z){var X,Q;super($),this.code=(X=Z==null?void 0:Z.code)!=null?X:void 0,this.message=(Q=Z==null?void 0:Z.message)!=null?Q:void 0}[Symbol.for("nodejs.util.inspect.custom")]($,Z,X){return X(yY(this),Z)}[Symbol.for("Deno.customInspect")]($,Z){return $(yY(this),Z)}}function PK($){let Z=globalThis.DOMException;return typeof Z=="function"?new Z($,"SyntaxError"):SyntaxError($)}function A9($){return $ instanceof Error?"errors"in $&&Array.isArray($.errors)?$.errors.map(A9).join(", "):("cause"in $)&&$.cause instanceof Error?`${$}: ${A9($.cause)}`:$.message:`${$}`}function yY($){return{type:$.type,message:$.message,code:$.code,defaultPrevented:$.defaultPrevented,cancelable:$.cancelable,timeStamp:$.timeStamp}}var PY=($)=>{throw TypeError($)},T9=($,Z,X)=>Z.has($)||PY("Cannot "+X),B2=($,Z,X)=>(T9($,Z,"read from private field"),X?X.call($):Z.get($)),s2=($,Z,X)=>Z.has($)?PY("Cannot add the same private member more than once"):Z instanceof WeakSet?Z.add($):Z.set($,X),g2=($,Z,X,Q)=>(T9($,Z,"write to private field"),Z.set($,X),X),b$=($,Z,X)=>(T9($,Z,"access private method"),X),M0,B1,m1,P4,z4,S8,o1,k8,E$,l1,u1,c1,R8,X$,M9,_9,I9,OY,R9,C9,C8,S9,k9;class p1 extends EventTarget{constructor($,Z){var X,Q;super(),s2(this,X$),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,s2(this,M0),s2(this,B1),s2(this,m1),s2(this,P4),s2(this,z4),s2(this,S8),s2(this,o1),s2(this,k8,null),s2(this,E$),s2(this,l1),s2(this,u1,null),s2(this,c1,null),s2(this,R8,null),s2(this,_9,async(J)=>{var V;B2(this,l1).reset();let{body:B,redirected:D,status:H,headers:W}=J;if(H===204){b$(this,X$,C8).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(D?g2(this,m1,new URL(J.url)):g2(this,m1,void 0),H!==200){b$(this,X$,C8).call(this,`Non-200 status code (${H})`,H);return}if(!(W.get("content-type")||"").startsWith("text/event-stream")){b$(this,X$,C8).call(this,'Invalid content type, expected "text/event-stream"',H);return}if(B2(this,M0)===this.CLOSED)return;g2(this,M0,this.OPEN);let K=new Event("open");if((V=B2(this,R8))==null||V.call(this,K),this.dispatchEvent(K),typeof B!="object"||!B||!("getReader"in B)){b$(this,X$,C8).call(this,"Invalid response body, expected a web ReadableStream",H),this.close();return}let j=new TextDecoder,G=B.getReader(),z=!0;do{let{done:O,value:P}=await G.read();P&&B2(this,l1).feed(j.decode(P,{stream:!O})),O&&(z=!1,B2(this,l1).reset(),b$(this,X$,S9).call(this))}while(z)}),s2(this,I9,(J)=>{g2(this,E$,void 0),!(J.name==="AbortError"||J.type==="aborted")&&b$(this,X$,S9).call(this,A9(J))}),s2(this,R9,(J)=>{typeof J.id=="string"&&g2(this,k8,J.id);let V=new MessageEvent(J.event||"message",{data:J.data,origin:B2(this,m1)?B2(this,m1).origin:B2(this,B1).origin,lastEventId:J.id||""});B2(this,c1)&&(!J.event||J.event==="message")&&B2(this,c1).call(this,V),this.dispatchEvent(V)}),s2(this,C9,(J)=>{g2(this,S8,J)}),s2(this,k9,()=>{g2(this,o1,void 0),B2(this,M0)===this.CONNECTING&&b$(this,X$,M9).call(this)});try{if($ instanceof URL)g2(this,B1,$);else if(typeof $=="string")g2(this,B1,new URL($,zK()));else throw Error("Invalid URL")}catch{throw PK("An invalid or illegal string was specified")}g2(this,l1,FY({onEvent:B2(this,R9),onRetry:B2(this,C9)})),g2(this,M0,this.CONNECTING),g2(this,S8,3000),g2(this,z4,(X=Z==null?void 0:Z.fetch)!=null?X:globalThis.fetch),g2(this,P4,(Q=Z==null?void 0:Z.withCredentials)!=null?Q:!1),b$(this,X$,M9).call(this)}get readyState(){return B2(this,M0)}get url(){return B2(this,B1).href}get withCredentials(){return B2(this,P4)}get onerror(){return B2(this,u1)}set onerror($){g2(this,u1,$)}get onmessage(){return B2(this,c1)}set onmessage($){g2(this,c1,$)}get onopen(){return B2(this,R8)}set onopen($){g2(this,R8,$)}addEventListener($,Z,X){let Q=Z;super.addEventListener($,Q,X)}removeEventListener($,Z,X){let Q=Z;super.removeEventListener($,Q,X)}close(){B2(this,o1)&&clearTimeout(B2(this,o1)),B2(this,M0)!==this.CLOSED&&(B2(this,E$)&&B2(this,E$).abort(),g2(this,M0,this.CLOSED),g2(this,E$,void 0))}}M0=new WeakMap,B1=new WeakMap,m1=new WeakMap,P4=new WeakMap,z4=new WeakMap,S8=new WeakMap,o1=new WeakMap,k8=new WeakMap,E$=new WeakMap,l1=new WeakMap,u1=new WeakMap,c1=new WeakMap,R8=new WeakMap,X$=new WeakSet,M9=function(){g2(this,M0,this.CONNECTING),g2(this,E$,new AbortController),B2(this,z4)(B2(this,B1),b$(this,X$,OY).call(this)).then(B2(this,_9)).catch(B2(this,I9))},_9=new WeakMap,I9=new WeakMap,OY=function(){var $;let Z={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...B2(this,k8)?{"Last-Event-ID":B2(this,k8)}:void 0},cache:"no-store",signal:($=B2(this,E$))==null?void 0:$.signal};return"window"in globalThis&&(Z.credentials=this.withCredentials?"include":"same-origin"),Z},R9=new WeakMap,C9=new WeakMap,C8=function($,Z){var X;B2(this,M0)!==this.CLOSED&&g2(this,M0,this.CLOSED);let Q=new U9("error",{code:Z,message:$});(X=B2(this,u1))==null||X.call(this,Q),this.dispatchEvent(Q)},S9=function($,Z){var X;if(B2(this,M0)===this.CLOSED)return;g2(this,M0,this.CONNECTING);let Q=new U9("error",{code:Z,message:$});(X=B2(this,u1))==null||X.call(this,Q),this.dispatchEvent(Q),g2(this,o1,setTimeout(B2(this,k9),B2(this,S8)))},k9=new WeakMap,p1.CONNECTING=0,p1.OPEN=1,p1.CLOSED=2;function zK(){let $="document"in globalThis?globalThis.document:void 0;return $&&typeof $=="object"&&"baseURI"in $&&typeof $.baseURI=="string"?$.baseURI:void 0}class zY extends Error{constructor($,Z,X){super(`SSE error: ${Z}`);this.code=$,this.event=X}}class g9{constructor($,Z){this._url=$,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=Z?.eventSourceInit,this._requestInit=Z?.requestInit,this._authProvider=Z?.authProvider,this._fetch=Z?.fetch,this._fetchWithInit=e6(Z?.fetch,Z?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Z0("No auth provider");let $;try{$=await N$(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(Z){throw this.onerror?.(Z),Z}if($!=="AUTHORIZED")throw new Z0;return await this._startOrAuth()}async _commonHeaders(){let $={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)$.Authorization=`Bearer ${X.access_token}`}if(this._protocolVersion)$["mcp-protocol-version"]=this._protocolVersion;let Z=S1(this._requestInit?.headers);return new Headers({...$,...Z})}_startOrAuth(){let $=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((Z,X)=>{this._eventSource=new p1(this._url.href,{...this._eventSourceInit,fetch:async(Q,J)=>{let V=await this._commonHeaders();V.set("Accept","text/event-stream");let B=await $(Q,{...J,headers:V});if(B.status===401&&B.headers.has("www-authenticate")){let{resourceMetadataUrl:D,scope:H}=f1(B);this._resourceMetadataUrl=D,this._scope=H}return B}}),this._abortController=new AbortController,this._eventSource.onerror=(Q)=>{if(Q.code===401&&this._authProvider){this._authThenStart().then(Z,X);return}let J=new zY(Q.code,Q.message,Q);X(J),this.onerror?.(J)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(Q)=>{let J=Q;try{if(this._endpoint=new URL(J.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(V){X(V),this.onerror?.(V),this.close();return}Z()}),this._eventSource.onmessage=(Q)=>{let J=Q,V;try{V=S$.parse(JSON.parse(J.data))}catch(B){this.onerror?.(B);return}this.onmessage?.(V)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth($){if(!this._authProvider)throw new Z0("No auth provider");if(await N$(this._authProvider,{serverUrl:this._url,authorizationCode:$,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Z0("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send($){if(!this._endpoint)throw Error("Not connected");try{let Z=await this._commonHeaders();Z.set("content-type","application/json");let X={...this._requestInit,method:"POST",headers:Z,body:JSON.stringify($),signal:this._abortController?.signal},Q=await(this._fetch??fetch)(this._endpoint,X);if(!Q.ok){let J=await Q.text().catch(()=>null);if(Q.status===401&&this._authProvider){let{resourceMetadataUrl:V,scope:B}=f1(Q);if(this._resourceMetadataUrl=V,this._scope=B,await N$(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Z0;return this.send($)}throw Error(`Error POSTing to endpoint (HTTP ${Q.status}): ${J}`)}await Q.body?.cancel()}catch(Z){throw this.onerror?.(Z),Z}}setProtocolVersion($){this._protocolVersion=$}}var L$=s.create({service:"mcp.connection"});function qY($){let Z=(J,V,B)=>Y.acquireUseRelease(Y.succeed(J),(D)=>Y.tryPromise({try:()=>{let H=new A8({name:"qitqode",version:w1});return s6(H.connect(D),V).then(()=>H)},catch:(H)=>H instanceof Error?H:Error(String(H))}),(D,H)=>{if(!u2.isFailure(H))return Y.void;if(B?.(G2.squash(H.cause)))return Y.void;return Y.tryPromise(()=>D.close()).pipe(Y.ignore)}),X=Y.fn("MCP.connectRemote")(function*(J,V){let B=yield*$.directory(),D=F4(B,J),H=V.oauth===!1,W=typeof V.oauth==="object"?V.oauth:void 0,K;if(!H)K=new I8(J,V.url,{clientId:W?.clientId,clientSecret:W?.clientSecret,scope:W?.scope,redirectUri:W?.redirectUri},{onRedirect:async(L)=>{L$.info("oauth redirect requested",{key:J,url:L.toString()})}},$.auth,D);let j=[{name:"StreamableHTTP",transport:new M8(new URL(V.url),{authProvider:K,requestInit:V.headers?{headers:V.headers}:void 0})},{name:"SSE",transport:new g9(new URL(V.url),{authProvider:K,requestInit:V.headers?{headers:V.headers}:void 0})}],G=V.timeout??a6,z,O=(L)=>{let F=L instanceof Error?L.message:String(L);return L instanceof Z0||!!K&&F.includes("OAuth")},P=(L)=>{let F=L instanceof Error?L.message:String(L);return F.includes("registration")||F.includes("client_id")},w=(L)=>!!K&&O(L)&&!P(L);for(let{name:L,transport:F}of j){let U=yield*Z(F,G,w).pipe(Y.map((y)=>({client:y,transportName:L})),Y.catch((y)=>{let S=y instanceof Error?y:Error(String(y));if(O(y)){if(L$.info("mcp server requires authentication",{key:J,transport:L}),P(y))return z={status:"needs_client_registration",error:"Server does not support dynamic client registration. Please provide clientId in config."},$.publish(i6,{server:J,reason:"client_registration"}).pipe(Y.ignore,Y.as(void 0));if(!K)return z={status:"failed",error:`MCP server requires authentication, but OAuth is disabled: ${S.message}`},Y.succeed(void 0);return z={status:"needs_auth"},L9(D,F).pipe(Y.andThen($.publish(i6,{server:J,reason:"login"})),Y.ignore,Y.as(void 0))}return L$.debug("transport connection failed",{key:J,transport:L,url:h9.redactString(V.url),error:S.message}),z={status:"failed",error:S.message},Y.succeed(void 0)}));if(U)return L$.info("connected",{key:J,transport:U.transportName}),{client:U.client,status:{status:"connected"}};if(z?.status==="needs_auth"||z?.status==="needs_client_registration")break}return{client:void 0,status:z??{status:"failed",error:"Unknown error"}}}),Q=Y.fn("MCP.connectLocal")(function*(J,V){let[B,...D]=V.command,H=yield*$.directory(),W=new b8({stderr:"pipe",command:B,args:D,cwd:H,env:{...q4(),...B==="qitqode"||B==="opencode"?{BUN_BE_BUN:"1"}:{},...V.environment}});W.stderr?.on("data",(j)=>{L$.info(`mcp stderr: ${j.toString()}`,{key:J})});let K=V.timeout??a6;return yield*Z(W,K).pipe(Y.map((j)=>({client:j,status:{status:"connected"}})),Y.catch((j)=>{let G=j instanceof Error?j.message:String(j);return L$.error("local mcp startup failed",{key:J,command:h9.redactCommand(V.command),cwd:H,error:G}),Y.succeed({client:void 0,status:{status:"failed",error:G}})}))});return Y.fn("MCP.create")(function*(J,V){if(V.enabled===!1)return L$.info("mcp server disabled",{key:J}),{status:{status:"disabled"}};L$.info("found",{key:J,type:V.type});let B=V.type==="remote"?yield*X(J,V):yield*Q(J,V);if(!B.client)return{status:B.status};let D=yield*R1(J,B.client,V.timeout);if(!D)return yield*Y.tryPromise(()=>B.client.close()).pipe(Y.ignore),{status:{status:"failed",error:"Failed to get tools"}};return L$.info("create() successfully created client",{key:J,toolCount:D.length}),{client:B.client,status:B.status,defs:D}})}var T8=s.create({service:"mcp"});class N4 extends Z2.Service()("@qitqode/MCP"){}var xY=_.effect(N4,Y.gen(function*(){let $=yield*i1.ChildProcessSpawner,Z=yield*T$.Service,X=yield*u.Service,Q=qY({auth:Z,directory:()=>v.directory,publish:(b,k)=>X.publish(b,k)}),J=(b,k)=>Q(b,k).pipe(Y.map((h)=>({mcpClient:h.client,status:h.status,defs:h.defs}))),V=yield*V2.Service,B=Y.fnUntraced(function*(b){if(process.platform==="win32")return[];let k=[],h=[b];while(h.length>0){let N=h.shift(),A=yield*$.spawn(n1.make("pgrep",["-P",String(N)],{stdin:"ignore"})),R=yield*c2.mkString(c2.decodeText(A.stdout));yield*A.exitCode;for(let C of R.split(`
|
|
200
|
+
`)){let T=parseInt(C,10);if(!isNaN(T)&&!k.includes(T))k.push(T),h.push(T)}}return k},Y.scoped,Y.catch(()=>Y.succeed([])));function D(b,k,h,N,A){h.setNotificationHandler(w8,async()=>{if(T8.info("tools list changed notification received",{server:k}),b.clients[k]!==h||b.status[k]?.status!=="connected")return;let R=await N.promise(R1(k,h,A));if(!R)return;if(b.clients[k]!==h||b.status[k]?.status!=="connected")return;b.defs[k]=R,await N.promise(X.publish(V9,{server:k}).pipe(Y.ignore))})}let H=yield*v.make(Y.fn("MCP.state")(function*(){let b=yield*V.get(),k=yield*P0.make(),h=yield*v.directory,N=b.mcp??{},A={status:{},clients:{},defs:{}};return yield*Y.forEach(Object.entries(N),([R,C])=>Y.gen(function*(){if(!U8(C)){T8.error("Ignoring MCP config entry without type",{key:R});return}if(C.enabled===!1){A.status[R]={status:"disabled"};return}if(SX(C,b.mcp_origins?.[R])){A.status[R]={status:"pending"};return}let T=yield*J(R,C).pipe(Y.catch(()=>Y.void));if(!T)return;if(A.status[R]=T.status,T.mcpClient)A.clients[R]=T.mcpClient,A.defs[R]=T.defs,D(A,R,T.mcpClient,k,C.timeout)}),{concurrency:8}),yield*Y.addFinalizer(()=>Y.gen(function*(){yield*Y.forEach(Object.values(A.clients),(R)=>Y.gen(function*(){let C=R.transport instanceof b8?R.transport.pid:null;if(typeof C==="number"){let T=yield*B(C);for(let l of T)try{process.kill(l,"SIGTERM")}catch{}}yield*Y.tryPromise(()=>R.close()).pipe(Y.ignore)}),{concurrency:8}),yield*jY(h)})),A}));function W(b,k){let h=b.clients[k];if(delete b.defs[k],!h)return Y.void;return Y.tryPromise(()=>h.close()).pipe(Y.ignore)}let K=Y.fnUntraced(function*(b,k,h,N,A){let R=yield*P0.make();return yield*W(b,k),b.status[k]={status:"connected"},b.clients[k]=h,b.defs[k]=N,D(b,k,h,R,A),b.status[k]}),j=Y.fn("MCP.status")(function*(){let b=yield*v.get(H),h=(yield*V.get()).mcp??{},N={};for(let[A,R]of Object.entries(h)){if(!U8(R))continue;N[A]=b.status[A]??{status:"disabled"}}return N}),G=Y.fn("MCP.clients")(function*(){return(yield*v.get(H)).clients}),z=Y.fn("MCP.createAndStore")(function*(b,k){let h=yield*v.get(H),N=yield*J(b,k);if(h.status[b]=N.status,!N.mcpClient)return yield*W(h,b),delete h.clients[b],N.status;return yield*K(h,b,N.mcpClient,N.defs,k.timeout)}),O=Y.fn("MCP.add")(function*(b,k){return yield*z(b,k),{status:(yield*v.get(H)).status}}),P=Y.fn("MCP.connect")(function*(b){let k=yield*M(b);if(!k){T8.error("MCP config not found or invalid",{name:b});return}yield*z(b,{...k,enabled:!0})}),w=Y.fn("MCP.disconnect")(function*(b){let k=yield*v.get(H);yield*W(k,b),delete k.clients[b],k.status[b]={status:"disabled"}}),L=Y.fn("MCP.tools")(function*(){let b=yield*v.get(H),k=yield*V.get();return CX(b,k.mcp??{},k.experimental?.mcp_timeout)}),F=Y.fn("MCP.prompts")(function*(){let b=yield*v.get(H);return yield*K9(b,(k)=>k.listPrompts().then((h)=>h.prompts),"prompts")}),U=Y.fn("MCP.resources")(function*(){let b=yield*v.get(H);return yield*K9(b,(k)=>k.listResources().then((h)=>h.resources),"resources")}),y=Y.fnUntraced(function*(b,k,h,N){let R=(yield*v.get(H)).clients[b];if(!R){T8.warn(`client not found for ${h}`,{clientName:b});return}return yield*Y.tryPromise({try:()=>k(R),catch:(C)=>{return T8.error(`failed to ${h}`,{clientName:b,...N,error:C?.message}),C}}).pipe(Y.orElseSucceed(()=>{return}))}),S=Y.fn("MCP.getPrompt")(function*(b,k,h){return yield*y(b,(N)=>N.getPrompt({name:k,arguments:h}),"getPrompt",{promptName:k})}),I=Y.fn("MCP.readResource")(function*(b,k){return yield*y(b,(h)=>h.readResource({uri:k}),"readResource",{resourceUri:k})}),M=Y.fnUntraced(function*(b){let h=(yield*V.get()).mcp?.[b];if(!h||!U8(h))return;return h}),f=DY({auth:Z,bus:X,pendingKey:(b)=>Y.map(v.directory,(k)=>F4(k,b)),getConfig:M,storeClient:(b,k,h,N)=>Y.gen(function*(){let A=yield*v.get(H);return yield*K(A,b,k,h,N)}),createAndStore:z});return N4.of({status:j,clients:G,tools:L,prompts:F,resources:U,add:O,connect:P,disconnect:w,getPrompt:S,readResource:I,startAuth:f.startAuth,authenticate:f.authenticate,finishAuth:f.finishAuth,removeAuth:f.removeAuth,supportsOAuth:f.supportsOAuth,hasStoredTokens:f.hasStoredTokens,getAuthStatus:f.getAuthStatus})})),qK=xY.pipe(_.provide(T$.layer),_.provide(u.layer),_.provide(V2.defaultLayer),_.provide(s1),_.provide(n2.defaultLayer));var x0={};L2(x0,{layer:()=>UY,hints:()=>x4,defaultLayer:()=>LK,deepResearchTemplate:()=>LY,Service:()=>w4,Info:()=>bK,Event:()=>wK,Default:()=>S0,Command:()=>x0});var wY=`Create or update \`AGENTS.md\` for this repository.
|
|
201
|
+
|
|
202
|
+
The goal is a compact instruction file that helps future QitQode sessions avoid mistakes and ramp up quickly. Every line should answer: "Would an agent likely miss this without help?" If not, leave it out.
|
|
203
|
+
|
|
204
|
+
User-provided focus or constraints (honor these):
|
|
205
|
+
$ARGUMENTS
|
|
206
|
+
|
|
207
|
+
## How to investigate
|
|
208
|
+
|
|
209
|
+
Read the highest-value sources first:
|
|
210
|
+
- \`README*\`, root manifests, workspace config, lockfiles
|
|
211
|
+
- build, test, lint, formatter, typecheck, and codegen config
|
|
212
|
+
- CI workflows and pre-commit / task runner config
|
|
213
|
+
- existing instruction files (\`AGENTS.md\`, \`CLAUDE.md\`, \`.cursor/rules/\`, \`.cursorrules\`, \`.github/copilot-instructions.md\`)
|
|
214
|
+
- repo-local QitQode config such as \`qitqode.json\`
|
|
215
|
+
|
|
216
|
+
If architecture is still unclear after reading config and docs, inspect a small number of representative code files to find the real entrypoints, package boundaries, and execution flow. Prefer reading the files that explain how the system is wired together over random leaf files.
|
|
217
|
+
|
|
218
|
+
Prefer executable sources of truth over prose. If docs conflict with config or scripts, trust the executable source and only keep what you can verify.
|
|
219
|
+
|
|
220
|
+
## What to extract
|
|
221
|
+
|
|
222
|
+
Look for the highest-signal facts for an agent working in this repo:
|
|
223
|
+
- exact developer commands, especially non-obvious ones
|
|
224
|
+
- how to run a single test, a single package, or a focused verification step
|
|
225
|
+
- required command order when it matters, such as \`lint -> typecheck -> test\`
|
|
226
|
+
- monorepo or multi-package boundaries, ownership of major directories, and the real app/library entrypoints
|
|
227
|
+
- framework or toolchain quirks: generated code, migrations, codegen, build artifacts, special env loading, dev servers, infra deploy flow
|
|
228
|
+
- repo-specific style or workflow conventions that differ from defaults
|
|
229
|
+
- testing quirks: fixtures, integration test prerequisites, snapshot workflows, required services, flaky or expensive suites
|
|
230
|
+
- important constraints from existing instruction files worth preserving
|
|
231
|
+
|
|
232
|
+
Good \`AGENTS.md\` content is usually hard-earned context that took reading multiple files to infer.
|
|
233
|
+
|
|
234
|
+
## Questions
|
|
235
|
+
|
|
236
|
+
Only ask the user questions if the repo cannot answer something important. Use the \`question\` tool for one short batch at most.
|
|
237
|
+
|
|
238
|
+
Good questions:
|
|
239
|
+
- undocumented team conventions
|
|
240
|
+
- branch / PR / release expectations
|
|
241
|
+
- missing setup or test prerequisites that are known but not written down
|
|
242
|
+
|
|
243
|
+
Do not ask about anything the repo already makes clear.
|
|
244
|
+
|
|
245
|
+
## Writing rules
|
|
246
|
+
|
|
247
|
+
Include only high-signal, repo-specific guidance such as:
|
|
248
|
+
- exact commands and shortcuts the agent would otherwise guess wrong
|
|
249
|
+
- architecture notes that are not obvious from filenames
|
|
250
|
+
- conventions that differ from language or framework defaults
|
|
251
|
+
- setup requirements, environment quirks, and operational gotchas
|
|
252
|
+
- references to existing instruction sources that matter
|
|
253
|
+
|
|
254
|
+
Exclude:
|
|
255
|
+
- generic software advice
|
|
256
|
+
- long tutorials or exhaustive file trees
|
|
257
|
+
- obvious language conventions
|
|
258
|
+
- speculative claims or anything you could not verify
|
|
259
|
+
- content better stored in another file referenced via \`qitqode.json\` \`instructions\`
|
|
260
|
+
|
|
261
|
+
When in doubt, omit.
|
|
262
|
+
|
|
263
|
+
Prefer short sections and bullets. If the repo is simple, keep the file simple. If the repo is large, summarize the few structural facts that actually change how an agent should work.
|
|
264
|
+
|
|
265
|
+
If \`AGENTS.md\` already exists at \`\${path}\`, improve it in place rather than rewriting blindly. Preserve verified useful guidance, delete fluff or stale claims, and reconcile it with the current codebase.
|
|
266
|
+
`;var bY=`You are a code reviewer. Your job is to review code changes and provide actionable feedback.
|
|
267
|
+
|
|
268
|
+
---
|
|
269
|
+
|
|
270
|
+
Input: $ARGUMENTS
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## Determining What to Review
|
|
275
|
+
|
|
276
|
+
Based on the input provided, determine which type of review to perform:
|
|
277
|
+
|
|
278
|
+
1. **No arguments (default)**: Review all uncommitted changes
|
|
279
|
+
- Run: \`git diff\` for unstaged changes
|
|
280
|
+
- Run: \`git diff --cached\` for staged changes
|
|
281
|
+
- Run: \`git status --short\` to identify untracked (net new) files
|
|
282
|
+
|
|
283
|
+
2. **Commit hash** (40-char SHA or short hash): Review that specific commit
|
|
284
|
+
- Run: \`git show $ARGUMENTS\`
|
|
285
|
+
|
|
286
|
+
3. **Branch name**: Compare current branch to the specified branch
|
|
287
|
+
- Run: \`git diff $ARGUMENTS...HEAD\`
|
|
288
|
+
|
|
289
|
+
4. **PR URL or number** (contains "github.com" or "pull" or looks like a PR number): Review the pull request
|
|
290
|
+
- Run: \`gh pr view $ARGUMENTS\` to get PR context
|
|
291
|
+
- Run: \`gh pr diff $ARGUMENTS\` to get the diff
|
|
292
|
+
|
|
293
|
+
Use best judgement when processing input.
|
|
294
|
+
|
|
295
|
+
---
|
|
296
|
+
|
|
297
|
+
## Gathering Context
|
|
298
|
+
|
|
299
|
+
**Diffs alone are not enough.** After getting the diff, read the entire file(s) being modified to understand the full context. Code that looks wrong in isolation may be correct given surrounding logic\u2014and vice versa.
|
|
300
|
+
|
|
301
|
+
- Use the diff to identify which files changed
|
|
302
|
+
- Use \`git status --short\` to identify untracked files, then read their full contents
|
|
303
|
+
- Read the full file to understand existing patterns, control flow, and error handling
|
|
304
|
+
- Check for existing style guide or conventions files (CONVENTIONS.md, AGENTS.md, .editorconfig, etc.)
|
|
305
|
+
|
|
306
|
+
---
|
|
307
|
+
|
|
308
|
+
## What to Look For
|
|
309
|
+
|
|
310
|
+
**Bugs** - Your primary focus.
|
|
311
|
+
- Logic errors, off-by-one mistakes, incorrect conditionals
|
|
312
|
+
- If-else guards: missing guards, incorrect branching, unreachable code paths
|
|
313
|
+
- Edge cases: null/empty/undefined inputs, error conditions, race conditions
|
|
314
|
+
- Security issues: injection, auth bypass, data exposure
|
|
315
|
+
- Broken error handling that swallows failures, throws unexpectedly or returns error types that are not caught.
|
|
316
|
+
|
|
317
|
+
**Structure** - Does the code fit the codebase?
|
|
318
|
+
- Does it follow existing patterns and conventions?
|
|
319
|
+
- Are there established abstractions it should use but doesn't?
|
|
320
|
+
- Excessive nesting that could be flattened with early returns or extraction
|
|
321
|
+
|
|
322
|
+
**Performance** - Only flag if obviously problematic.
|
|
323
|
+
- O(n\xB2) on unbounded data, N+1 queries, blocking I/O on hot paths
|
|
324
|
+
|
|
325
|
+
**Behavior Changes** - If a behavioral change is introduced, raise it (especially if it's possibly unintentional).
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
## Before You Flag Something
|
|
330
|
+
|
|
331
|
+
**Be certain.** If you're going to call something a bug, you need to be confident it actually is one.
|
|
332
|
+
|
|
333
|
+
- Only review the changes - do not review pre-existing code that wasn't modified
|
|
334
|
+
- Don't flag something as a bug if you're unsure - investigate first
|
|
335
|
+
- Don't invent hypothetical problems - if an edge case matters, explain the realistic scenario where it breaks
|
|
336
|
+
- If you need more context to be sure, use the tools below to get it
|
|
337
|
+
|
|
338
|
+
**Don't be a zealot about style.** When checking code against conventions:
|
|
339
|
+
|
|
340
|
+
- Verify the code is *actually* in violation. Don't complain about else statements if early returns are already being used correctly.
|
|
341
|
+
- Some "violations" are acceptable when they're the simplest option. A \`let\` statement is fine if the alternative is convoluted.
|
|
342
|
+
- Excessive nesting is a legitimate concern regardless of other style choices.
|
|
343
|
+
- Don't flag style preferences as issues unless they clearly violate established project conventions.
|
|
344
|
+
|
|
345
|
+
---
|
|
346
|
+
|
|
347
|
+
## Tools
|
|
348
|
+
|
|
349
|
+
Use these to inform your review:
|
|
350
|
+
|
|
351
|
+
- **Explore agent** - Find how existing code handles similar problems. Check patterns, conventions, and prior art before claiming something doesn't fit.
|
|
352
|
+
- **Exa Code Context** - Verify correct usage of libraries/APIs before flagging something as wrong.
|
|
353
|
+
- **Exa Web Search** - Research best practices if you're unsure about a pattern.
|
|
354
|
+
|
|
355
|
+
If you're uncertain about something and can't verify it with these tools, say "I'm not sure about X" rather than flagging it as a definite issue.
|
|
356
|
+
|
|
357
|
+
---
|
|
358
|
+
|
|
359
|
+
## Output
|
|
360
|
+
|
|
361
|
+
1. If there is a bug, be direct and clear about why it is a bug.
|
|
362
|
+
2. Clearly communicate severity of issues. Do not overstate severity.
|
|
363
|
+
3. Critiques should clearly and explicitly communicate the scenarios, environments, or inputs that are necessary for the bug to arise. The comment should immediately indicate that the issue's severity depends on these factors.
|
|
364
|
+
4. Your tone should be matter-of-fact and not accusatory or overly positive. It should read as a helpful AI assistant suggestion without sounding too much like a human reviewer.
|
|
365
|
+
5. Write so the reader can quickly understand the issue without reading too closely.
|
|
366
|
+
6. AVOID flattery, do not give any comments that are not helpful to the reader. Avoid phrasing like "Great job ...", "Thanks for ...".
|
|
367
|
+
`;var f9=wY,E9=bY;var wK={Executed:D2.define("command.executed",q.object({name:q.string(),sessionID:F2.zod,arguments:q.string(),messageID:x2.zod}))},bK=q.object({name:q.string(),description:q.string().optional(),agent:q.string().optional(),model:q.string().optional(),source:q.enum(["command","mcp","skill"]).optional(),template:q.promise(q.string()).or(q.string()),subtask:q.boolean().optional(),hints:q.array(q.string())}).meta({ref:"Command"});function x4($){let Z=[],X=$.match(/\$\d+/g);if(X)for(let Q of[...new Set(X)].sort())Z.push(Q);if($.includes("$ARGUMENTS"))Z.push("$ARGUMENTS");return Z}var S0={INIT:"init",REVIEW:"review",DREAM:"dream",DISTILL:"distill",GOAL:"goal",DEEP_RESEARCH:"deep-research"};function LY(){return["The user wants a deep, multi-source, fact-checked research report.","","Research request:","$ARGUMENTS","","If the request is underspecified (missing scope, constraints, region, time range, etc.),","ask 2-3 brief clarifying questions FIRST, then weave the answers into a refined question.","","When the request is specific enough, run the built-in deep-research workflow:",' workflow({ operation: "run", name: "deep-research", args: "<the refined research question>" })',"","Pass the full refined question as `args`. The workflow fans out web searches, fetches sources,","adversarially verifies claims, and returns a cited report; relay its result to the user."].join(`
|
|
368
|
+
`)}class w4 extends Z2.Service()("@qitqode/Command"){}var UY=_.effect(w4,Y.gen(function*(){let $=yield*V2.Service,Z=yield*N0.Service,X=yield*j$.Service,Q=Y.fn("Command.state")(function*(D){let H=yield*$.get(),W=yield*P0.make(),K={};if(K[S0.INIT]={name:S0.INIT,description:"guided AGENTS.md setup",source:"command",get template(){return f9.replace("${path}",D.worktree)},hints:x4(f9)},K[S0.REVIEW]={name:S0.REVIEW,description:"review changes [commit|branch|pr], defaults to uncommitted",source:"command",get template(){return E9.replace("${path}",D.worktree)},subtask:!0,hints:x4(E9)},K[S0.DREAM]={name:S0.DREAM,description:"manually consolidate project memory from memory files and raw trajectory",agent:"dream",source:"command",subtask:!1,get template(){return["Run one manual dream memory consolidation pass for the current project.","","User focus or constraints:","$ARGUMENTS","","Use the memory files as the working index and the raw qitqode trajectory database as the source of truth.","Use bash for read-only SQLite and filesystem inspection. Do not modify the database.","Consolidate only durable, verified information into project memory."].join(`
|
|
369
|
+
`)},hints:["$ARGUMENTS"]},K[S0.DISTILL]={name:S0.DISTILL,description:"find repeated workflows in recent work and package them into skills, subagents, or commands",agent:"distill",source:"command",subtask:!1,get template(){return["Run one manual distill pass for the current project.","","User focus or constraints:","$ARGUMENTS","","Look back over recent work and identify repeated manual workflows worth packaging.","Use the raw qitqode trajectory database as the source of truth and memory files to spot cross-session patterns.","Inventory existing skills, agents, and commands first so you reuse or extend instead of duplicating.","Use bash for read-only SQLite and filesystem inspection. Do not modify the database.","Produce a compact shortlist, then create only the high-confidence missing assets."].join(`
|
|
370
|
+
`)},hints:["$ARGUMENTS"]},K[S0.GOAL]={name:S0.GOAL,description:"set a stop-condition goal; runs until a judge says it's met. /goal clear to abort",source:"command",subtask:!1,get template(){return"$ARGUMENTS"},hints:["$ARGUMENTS"]},L0.QITQODE_EXPERIMENTAL_WORKFLOW_TOOL)K[S0.DEEP_RESEARCH]={name:S0.DEEP_RESEARCH,description:"deep multi-source, fact-checked research report (runs the deep-research workflow)",source:"command",subtask:!1,get template(){return LY()},hints:["$ARGUMENTS"]};for(let[j,G]of Object.entries(H.command??{}))K[j]={name:j,agent:G.agent,model:G.model,description:G.description,source:"command",get template(){return G.template},subtask:G.subtask,hints:x4(G.template)};for(let[j,G]of Object.entries(yield*Z.prompts()))K[j]={name:j,source:"mcp",description:G.description,get template(){return W.promise(Z.getPrompt(G.client,G.name,G.arguments?Object.fromEntries(G.arguments.map((z,O)=>[z.name,`$${O+1}`])):{}).pipe(Y.map((z)=>z?.messages.map((O)=>O.content.type==="text"?O.content.text:"").join(`
|
|
371
|
+
`)||"")))},hints:G.arguments?.map((z,O)=>`$${O+1}`)??[]};for(let j of yield*X.all()){if(K[j.name])continue;K[j.name]={name:j.name,description:j.description,source:"skill",get template(){return j.content},hints:[]}}return{commands:K}}),J=yield*v.make((D)=>Q(D)),V=Y.fn("Command.get")(function*(D){return(yield*v.get(J)).commands[D]}),B=Y.fn("Command.list")(function*(){let D=yield*v.get(J);return Object.values(D.commands)});return w4.of({get:V,list:B})})),LK=UY.pipe(_.provide(V2.defaultLayer),_.provide(N0.defaultLayer),_.provide(j$.defaultLayer));var AY=new WeakMap;function b4($,Z){let X=AY.get(Z);if(!X)X=new Map,AY.set(Z,X);let Q=`${$.providerID}\x00${$.api.id}`,J=X.get(Q);if(J)return J;let V=p2.schema($,q.toJSONSchema(Z));return X.set(Q,V),V}var L4=Y.fn("Session.buildLLMRequestPrefix")(function*($){let Z=yield*f2.Service,X=yield*W0.Service,Q=yield*p.toModelMessagesEffect($.msgs,$.model),J=$.msgs.findLast((W)=>W.info.role==="user");if(!J)return yield*Y.die(Error("buildLLMRequestPrefix: no user message in msgs"));let V=J.info,B=yield*Z.buildSystemArray({agent:$.agent,model:$.model,system:$.additions,user:V,sessionID:$.sessionID,agentID:V.agentID}),D=yield*X.tools({modelID:t0.make($.model.api.id),providerID:$.model.providerID,agent:$.agent}),H={};for(let W of D){let K=b4($.model,W.parameters);H[W.id]=t$({description:W.description,inputSchema:W$(K)})}return{system:B,tools:H,inheritedMessages:Q}});var o0={};L2(o0,{layer:()=>vY,gcInboxRows:()=>EY,defaultLayer:()=>kK,Service:()=>I4,MAX_DRAIN_PER_TURN:()=>fY,InboxReceiverNotFound:()=>v9});import U4 from"crypto";var _Y="0123456789ABCDEFGHJKMNPQRSTVWXYZ",A4=32;var UK=16,IY=10,MY=281474976710655;var W1;(function($){$.Base32IncorrectEncoding="B32_ENC_INVALID",$.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",$.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",$.EncodeTimeNegative="ENC_TIME_NEG",$.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",$.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",$.PRNGDetectFailure="PRNG_DETECT",$.ULIDInvalid="ULID_INVALID",$.Unexpected="UNEXPECTED",$.UUIDInvalid="UUID_INVALID"})(W1||(W1={}));class a1 extends Error{constructor($,Z){super(`${Z} (${$})`);this.name="ULIDError",this.code=$}}function AK($){let Z=Math.floor($()*A4)%A4;return _Y.charAt(Z)}function MK($){let Z=_K(),X=Z&&(Z.crypto||Z.msCrypto)||(typeof U4<"u"?U4:null);if(typeof X?.getRandomValues==="function")return()=>{let Q=new Uint8Array(1);return X.getRandomValues(Q),Q[0]/255};else if(typeof X?.randomBytes==="function")return()=>X.randomBytes(1).readUInt8()/255;else if(U4?.randomBytes)return()=>U4.randomBytes(1).readUInt8()/255;throw new a1(W1.PRNGDetectFailure,"Failed to find a reliable PRNG")}function _K(){if(CK())return self;if(typeof window<"u")return window;if(typeof global<"u")return global;if(typeof globalThis<"u")return globalThis;return null}function IK($,Z){let X="";for(;$>0;$--)X=AK(Z)+X;return X}function RK($,Z=IY){if(isNaN($))throw new a1(W1.EncodeTimeValueMalformed,`Time must be a number: ${$}`);else if($>MY)throw new a1(W1.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${MY}: ${$}`);else if($<0)throw new a1(W1.EncodeTimeNegative,`Time must be positive: ${$}`);else if(Number.isInteger($)===!1)throw new a1(W1.EncodeTimeValueMalformed,`Time must be an integer: ${$}`);let X,Q="";for(let J=Z;J>0;J--)X=$%A4,Q=_Y.charAt(X)+Q,$=($-X)/A4;return Q}function CK(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function r1($,Z){let X=Z||MK(),Q=!$||isNaN($)?Date.now():$;return RK(Q,IY)+IK(UK,X)}var Y$=M4("inbox",{id:X0().primaryKey(),receiver_session_id:X0().$type().notNull().references(()=>k0.id,{onDelete:"cascade"}),receiver_actor_id:X0().notNull(),sender_session_id:X0().$type(),sender_actor_id:X0(),type:X0().notNull().default("text"),content:X0({mode:"json"}).$type().notNull(),created_at:K1().notNull()},($)=>[t1("inbox_receiver_idx").on($.receiver_session_id,$.receiver_actor_id,$.id),t1("inbox_created_idx").on($.created_at)]);function RY($){if($.type==="actor_notification")return $.content.text??"(no notification body)";let Z=$.content,X=$.sender_session_id?`${$.sender_session_id}:${$.sender_actor_id??"?"}`:"system",Q=new Date($.created_at).toISOString();return`<inbox from="${X}" sent_at="${Q}">
|
|
372
|
+
${Z.text??"(empty)"}
|
|
373
|
+
</inbox>`}function CY($){let Z=`Background actor "${$.description}" (actor_id: ${$.actorID})`;if($.status==="completed"){let X=`Status: ${$.reportedStatus??"unknown"}`,Q=$.reportedSummary?`
|
|
374
|
+
Summary: ${$.reportedSummary}`:"";return`<actor-notification>
|
|
375
|
+
${Z} completed.
|
|
376
|
+
${X}${Q}
|
|
377
|
+
Result: ${$.result??"(no output)"}
|
|
378
|
+
</actor-notification>`}if($.status==="failed")return`<actor-notification>
|
|
379
|
+
${Z} failed.
|
|
380
|
+
Error: ${$.error??"unknown"}
|
|
381
|
+
</actor-notification>`;return`<actor-notification>
|
|
382
|
+
${Z} was cancelled.
|
|
383
|
+
</actor-notification>`}var SY=s.create({service:"inbox"}),SK=604800000,fY=100;function EY($){return Y.sync(()=>a2.use((Z)=>Z.delete(Y$).where(TY(Y$.created_at,$)).run()))}class v9 extends c0.TaggedErrorClass()("InboxReceiverNotFound",{receiverSessionID:c0.String,receiverActorID:c0.String}){}class I4 extends Z2.Service()("@qitqode/Inbox"){}var vY=_.effect(I4,Y.gen(function*(){let $=yield*u.Service,Z=yield*M2.Service,X=yield*J2.Service,Q=yield*d2.Scope;yield*EY(Date.now()-SK),SY.info("inbox gc-on-init complete");let J=Y.fn("Inbox.send")(function*(D){if(!(yield*Z.get(D.receiverSessionID,D.receiverActorID)))return yield*Y.fail(new v9({receiverSessionID:D.receiverSessionID,receiverActorID:D.receiverActorID}));let W={id:r1(),receiver_session_id:D.receiverSessionID,receiver_actor_id:D.receiverActorID,sender_session_id:D.senderSessionID??null,sender_actor_id:D.senderActorID??null,type:D.type??"text",content:{text:D.content},created_at:Date.now()};yield*Y.sync(()=>a2.use((j)=>j.insert(Y$).values(W).run())),yield*$.publish(hY,{receiverSessionID:D.receiverSessionID,receiverActorID:D.receiverActorID,...D.senderSessionID!==void 0?{senderSessionID:D.senderSessionID}:{},...D.senderActorID!==void 0?{senderActorID:D.senderActorID}:{},inboxID:W.id,type:W.type});let K=G1.current;if(K)yield*K.loop({sessionID:D.receiverSessionID,agentID:D.receiverActorID}).pipe(Y.ignore,Y.forkIn(Q));else SY.warn("inbox.send: sessionPromptRef.current undefined \u2014 wake skipped",{receiverActorID:D.receiverActorID});return{inboxID:W.id}}),V=Y.fn("Inbox.drain")(function*(D,H){let W=yield*Y.sync(()=>a2.use((O)=>O.select().from(Y$).where(kY(G0(Y$.receiver_session_id,D),G0(Y$.receiver_actor_id,H))).orderBy(Y$.id).limit(fY).all()));if(W.length===0)return 0;let j=(yield*X.messages({sessionID:D,agentID:H})).findLast((O)=>(O.info.role==="user"||O.info.role==="assistant")&&("model"in O.info)&&O.info.model!==void 0&&O.info.model.providerID!=="system"&&O.info.agent!=="system");if(!j||!("model"in j.info)||!j.info.model||!("agent"in j.info))return 0;let G=x2.ascending(),z=Date.now();yield*X.updateMessage({id:G,role:"user",sessionID:D,agentID:H,time:{created:z},agent:j.info.agent,model:j.info.model});for(let O of W)yield*X.updatePart({id:Q2.ascending(),messageID:G,sessionID:D,type:"text",synthetic:!0,text:RY(O)});return yield*Y.sync(()=>a2.use((O)=>O.delete(Y$).where(gY(Y$.id,W.map((P)=>P.id))).run())),W.length}),B=I4.of({send:J,drain:V});return _4.current=B,yield*Y.addFinalizer(()=>Y.sync(()=>{if(_4.current===B)_4.current=void 0})),B})),kK=vY.pipe(_.provide(u.defaultLayer),_.provide(M2.defaultLayer),_.provide(J2.defaultLayer));function g8($){return $.replace(/<think>[\s\S]*?<\/think>\s*/g,"").split(`
|
|
384
|
+
`).map((Z)=>Z.trim()).find((Z)=>Z.length>0)}var H1={};L2(H1,{layer:()=>dY,defaultLayer:()=>TK,TaskGateState:()=>H1,Service:()=>R4});class R4 extends Z2.Service()("@qitqode/TaskGateState"){}var dY=_.effect(R4,Y.gen(function*(){let $=yield*v.make(Y.fn("TaskGateState.state")(function*(){return{counts:new Map}})),Z=Y.fn("TaskGateState.get")(function*(J){return(yield*v.get($)).counts.get(J)??0}),X=Y.fn("TaskGateState.bump")(function*(J){let V=yield*v.get($),B=(V.counts.get(J)??0)+1;return V.counts.set(J,B),B}),Q=Y.fn("TaskGateState.clear")(function*(J){(yield*v.get($)).counts.delete(J)});return R4.of({get:Z,bump:X,clear:Q})})),TK=dY;var v$=s.create({service:"session.prompt"}),gK=`Use this tool to return your final response in the requested structured format.
|
|
385
|
+
|
|
386
|
+
IMPORTANT:
|
|
387
|
+
- You MUST call this tool exactly once at the end of your response
|
|
388
|
+
- The input must be valid JSON matching the required schema
|
|
389
|
+
- Complete all necessary research and tool calls BEFORE calling this tool
|
|
390
|
+
- This tool provides your final answer - no further actions are taken after calling it`,oY="IMPORTANT: The user has requested structured output. You MUST use the StructuredOutput tool to provide your final response. Do NOT respond with plain text - you MUST call the StructuredOutput tool with your answer formatted according to the schema.";function hK($){return/\/\.qitqode\/(tools?|skills?|hooks?)\//.test($)}function C4($){let{$schema:Z,...X}=$.schema;return t$({description:gK,inputSchema:W$(X),async execute(Q){return $.onSuccess(Q),{output:"Structured output captured successfully.",title:"Structured Output",metadata:{valid:!0}}},toModelOutput({output:Q}){return{type:"text",value:Q.output}}})}function uY($){return Y.gen(function*(){let Z=yield*W0.Service,X=yield*N0.Service,Q=yield*j1.Service,J=yield*u.Service,V=yield*O2.Service,B=yield*K2.Service,D=yield*M2.Service;return Y.fn("SessionPrompt.resolveTools")(function*(W){let F=[];try{const K=mY(F,v$.time("resolveTools"),0);let j={};let G=yield*P0.make();let z=yield*$();let O=Y.fn("SessionPrompt.whitelistFor")(function*(){if(!W.agentID)return;let I=yield*D.get(W.session.id,W.agentID);if(!I||!Array.isArray(I.tools))return;return new Set(I.tools)});let P=yield*O();let w=(I)=>({title:"Tool not permitted",output:`The "${I}" tool is not in this actor's whitelist. Allowed tools: ${P?[...P].join(", "):"(none)"}.`,metadata:{rejected:!0,reason:"tool-whitelist"}});let L=(I,M)=>({sessionID:W.session.id,abort:M.abortSignal,messageID:W.processor.message.id,callID:M.toolCallId,extra:{model:W.model,bypassAgentCheck:W.bypassAgentCheck,promptOps:z},agent:W.agent.name,actorID:W.agentID,taskId:W.task_id,messages:W.messages,metadata:(f)=>W.processor.updateToolCall(M.toolCallId,(b)=>{if(!["running","pending"].includes(b.state.status))return b;return{...b,state:{title:f.title,metadata:f.metadata,status:"running",input:I,time:{start:Date.now()}}}}),ask:(f)=>V.ask({...f,sessionID:W.session.id,tool:{messageID:W.processor.message.id,callID:M.toolCallId},ruleset:O2.merge(W.agent.permission,W.session.permission??[]),interactive:!A6.has(W.agent.name)},M.abortSignal).pipe(Y.orDie)});for(let I of yield*Z.tools({modelID:t0.make(W.model.api.id),providerID:W.model.providerID,agent:W.agent})){let M=b4(W.model,I.parameters);j[I.id]=t$({description:I.description,inputSchema:W$(M),execute(f,b){return G.promise(Y.gen(function*(){let k=Date.now(),h=b?.toolCallId??"?";v$.debug("tool execute start",{tool:I.id,callID:h,sessionID:W.session.id});let N=L(f,b);if(P&&!P.has(I.id)){let T=w(I.id);return v$.debug("tool execute rejected",{tool:I.id,callID:h,durationMs:Date.now()-k}),yield*W.processor.completeToolCall(b.toolCallId,T),T}let A={args:f};if(yield*B.trigger("tool.execute.before",{tool:I.id,sessionID:N.sessionID,callID:N.callID},A),A.cancel){let T={title:"Cancelled",output:A.cancelReason||"Tool call cancelled by hook",metadata:{cancelled:!0}};return yield*J.publish(C2.ToolCall,{sessionID:N.sessionID,tool_name:I.id,input_bytes:C2.jsonByteLength(A.args),output_bytes:0,tool_call_id:b.toolCallId,tool_call_status:"cancelled"}).pipe(Y.ignore),yield*W.processor.completeToolCall(b.toolCallId,T),T}let R=yield*I.execute(A.args,N);v$.debug("tool execute done",{tool:I.id,callID:h,durationMs:Date.now()-k,ok:!0});let C={...R,attachments:R.attachments?.map((T)=>({...T,id:Q2.ascending(),sessionID:N.sessionID,messageID:W.processor.message.id}))};if(yield*B.trigger("tool.execute.after",{tool:I.id,sessionID:N.sessionID,callID:N.callID,args:A.args},C),(I.id==="write"||I.id==="edit")&&A.args?.filePath&&hK(A.args.filePath))yield*Z.reload().pipe(Y.tapError((T)=>Y.sync(()=>v$.warn("extension reload failed",{error:T}))),Y.ignore);if(yield*J.publish(C2.ToolCall,{sessionID:N.sessionID,tool_name:I.id,input_bytes:C2.jsonByteLength(A.args),output_bytes:Buffer.byteLength(C.output??"","utf8"),tool_call_id:b.toolCallId,tool_call_status:"success"}).pipe(Y.ignore),b.abortSignal?.aborted)yield*W.processor.completeToolCall(b.toolCallId,C);return C}))}})}for(let[I,M]of Object.entries(yield*X.tools())){let f=M.execute;if(!f)continue;let b=yield*Y.promise(()=>Promise.resolve(cY(M.inputSchema).jsonSchema)),k=p2.schema(W.model,b);M.inputSchema=W$(k),M.execute=(h,N)=>G.promise(Y.gen(function*(){let A=Date.now(),R=N?.toolCallId??"?";v$.debug("tool execute start (mcp)",{tool:I,callID:R,sessionID:W.session.id});let C=L(h,N);if(P&&!P.has(I)){let n=w(I),a={title:n.title,metadata:n.metadata,output:n.output,attachments:[],content:[{type:"text",text:n.output}]};return v$.debug("tool execute rejected (mcp)",{tool:I,callID:R,durationMs:Date.now()-A}),yield*W.processor.completeToolCall(N.toolCallId,a),a}let T={args:h};if(yield*B.trigger("tool.execute.before",{tool:I,sessionID:C.sessionID,callID:N.toolCallId},T),T.cancel){let n={content:[{type:"text",text:T.cancelReason||"Tool call cancelled by hook"}]};return yield*J.publish(C2.ToolCall,{sessionID:C.sessionID,tool_name:I,input_bytes:C2.jsonByteLength(T.args),output_bytes:0,tool_call_id:N.toolCallId,tool_call_status:"cancelled"}).pipe(Y.ignore),n}yield*C.ask({permission:I,metadata:{},patterns:["*"],always:["*"]});let l=yield*Y.promise(()=>f(T.args,N));v$.debug("tool execute done (mcp)",{tool:I,callID:R,durationMs:Date.now()-A,ok:!0}),yield*B.trigger("tool.execute.after",{tool:I,sessionID:C.sessionID,callID:N.toolCallId,args:h},l);let d=[];yield*J.publish(C2.ToolCall,{sessionID:C.sessionID,tool_name:I,input_bytes:C2.jsonByteLength(h),output_bytes:C2.jsonByteLength(l.content??""),tool_call_id:N.toolCallId,tool_call_status:"success"}).pipe(Y.ignore);let g=[];for(let n of l.content)if(n.type==="text")d.push(n.text);else if(n.type==="image")g.push({type:"file",mime:n.mimeType,url:`data:${n.mimeType};base64,${n.data}`});else if(n.type==="resource"){let{resource:a}=n;if(a.text)d.push(a.text);if(a.blob)g.push({type:"file",mime:a.mimeType??"application/octet-stream",url:`data:${a.mimeType??"application/octet-stream"};base64,${a.blob}`,filename:a.uri})}let E=yield*Q.output(d.join(`
|
|
391
|
+
|
|
392
|
+
`),{},W.agent),e={title:"",metadata:{...l.metadata,truncated:E.truncated,...E.truncated&&{outputPath:E.outputPath}},output:E.content,attachments:g.map((n)=>({...n,id:Q2.ascending(),sessionID:C.sessionID,messageID:W.processor.message.id})),content:l.content};if(N.abortSignal?.aborted)yield*W.processor.completeToolCall(N.toolCallId,e);return e})),j[I]=M}return j}catch(U){var y=U,S=1}finally{lY(F,y,S)}})})}function pY($){let Z=$.assistant;if($.parts.some((X)=>X.type==="tool"&&!X.metadata?.providerExecuted&&X.state.status!=="error"))return{type:"continue"};if(!Z.finish)return{type:"continue"};if(Z.finish==="tool-calls")return{type:"continue"};if($.phase==="existing-assistant"&&!($.lastUser.id<Z.id))return{type:"continue"};if(Z.error)return{type:"failed",reason:Z.error.name};if(Z.structured!==void 0)return{type:"final"};if(Z.summary)return{type:"final"};if(Z.finish==="content-filter")return{type:"filtered"};if(Z.finish==="error")return{type:"failed",reason:"model error finish"};if($.parts.some((X)=>X.type==="text"&&!X.synthetic&&!X.ignored&&X.text.trim().length>0))return Z.finish==="other"?{type:"final",degraded:!0}:{type:"final"};if($.parts.some((X)=>X.type==="reasoning"&&X.text.trim().length>0))return{type:"think-only"};return{type:"invalid",reason:"empty output"}}function d9($){return pY($)}var S4=Y.gen(function*(){return{bus:yield*u.Service,status:yield*y0.Service,sessions:yield*E2,agents:yield*h2.Service,provider:yield*P2.Service,processor:yield*d0.Service,prune:yield*z$.Service,checkpoint:yield*P$.Service,compaction:yield*F$.Service,config:yield*V2.Service,plugin:yield*K2.Service,permission:yield*O2.Service,fsys:yield*n2.Service,registry:yield*W0.Service,scope:yield*d2.Scope,instruction:yield*G$.Service,state:yield*O0.Service,goal:yield*F0.Service,taskGateState:yield*H1.Service,taskRegistry:yield*_0.Service,revert:yield*$$.Service,summary:yield*q0.Service,sys:yield*D$.Service,llm:yield*f2.Service,actorRegistry:yield*M2.Service,inbox:yield*o0.Service}}),m9=Y.fnUntraced(function*($,Z,X,Q){let J=(yield*$.list()).filter((D)=>!D.hidden).map((D)=>D.name),V=J.length?` Available agents: ${J.join(", ")}`:"",B=new w2.Unknown({message:`Agent not found: "${X}".${V}`});return yield*Z.publish(U2.Error,{sessionID:Q,error:B.toObject()}),B}),d$=Y.fnUntraced(function*($,Z,X,Q){let J=yield*$.get(X);if(!J)throw yield*m9($,Z,X,Q);return J}),e1=Y.fnUntraced(function*($,Z,X){if(!Z)return X;let Q=yield*$.resolveModelRef(Z);return{providerID:Q.providerID,modelID:Q.id}});function fK($,Z,X){if(!$.startsWith("data:"))return $;return`[data-url:${Z}${X?`:${X}`:""}]`}function iY($){return{...$,url:fK($.url,$.mime,$.filename)}}function EK($){if($.status==="completed"&&$.attachments&&$.attachments.length>0)return{...$,attachments:$.attachments.map(iY)};return $}function vK($){if($.type==="file")return iY($);if($.type==="tool")return{...$,state:EK($.state)};return $}function k4($){if(!$)return;if(typeof $==="object"&&$!==null&&"message"in $&&typeof $.message==="string")return $.message;return JSON.stringify($)}function nY($){return $.filter((Z)=>Z.type==="text"&&!Z.synthetic&&!Z.ignored).map((Z)=>Z.text).join(`
|
|
393
|
+
`)}function T4($,Z){if($.structured!==void 0)return JSON.stringify($.structured);return Z.findLast((X)=>X.type==="text"&&!X.synthetic)?.text}function g4($){return $.map((Z)=>({...Z.info,created:Z.info.time.created,parts:Z.parts.map(vK)}))}function sY($,Z,X){let Q=$.findIndex((J)=>J.info.id===Z.id);if(Q===-1)return[...$,{info:Z,parts:X}];return $.map((J,V)=>V===Q?{info:Z,parts:X}:J)}function l9($,Z,X){return X.pipe(Y.catchDefect((Q)=>{if(!(Q instanceof $0.BackendAuthRejectedError))return Y.die(Q);return Z.publish(U2.Error,{sessionID:$,error:new w2.Unknown({message:Q.message}).toObject()}).pipe(Y.andThen(Y.die(Q)))}))}var aY=Y.fn("SessionPrompt.prepareStep")(function*($){let X=$.msgs.findLast((V)=>V.info.role==="user")?.parts.some((V)=>V.type==="agent")??!1,Q=yield*$.resolveTools({agent:$.agent,session:$.session,model:$.model,tools:$.lastUser.tools,processor:$.handle,bypassAgentCheck:X,messages:$.msgs,agentID:$.lastUser.agentID,task_id:$.task_id});if($.lastUser.format?.type==="json_schema")Q.StructuredOutput=$.createStructuredOutputTool({schema:$.lastUser.format.schema,onSuccess(V){$.structured.value=V}});if($.step===1)yield*$.summary.summarize({sessionID:$.sessionID,messageID:$.lastUser.id}).pipe(Y.ignore,Y.forkIn($.scope));if($.step>1&&$.lastFinished)for(let V of $.msgs){if(V.info.role!=="user"||V.info.id<=$.lastFinished.id)continue;for(let B of V.parts){if(B.type!=="text"||B.ignored||B.synthetic)continue;if(!B.text.trim())continue;B.text=["<system-reminder>","The user sent the following message:",B.text,"","Please address this message and continue with your tasks.","</system-reminder>"].join(`
|
|
394
|
+
`)}}yield*$.plugin.trigger("experimental.chat.messages.transform",{},{messages:$.msgs});let J=$.msgs.findLast((V)=>V.info.role==="user"&&V.info.id===$.lastUser.id)?.parts??[];return{tools:Q,format:$.lastUser.format??{type:"text"},query:nY(J)}});function rY($){return{cancelledByPlugin:Y.gen(function*(){let Q={cancel:void 0,cancelReason:void 0};if(yield*$.plugin.trigger("session.userQuery.pre",{sessionID:$.sessionID,agentID:$.agentID,step:$.step,messageID:$.lastUser.id,query:$.query},Q),!Q.cancel)return!1;return $.cancellation.cancelled=!0,$.cancellation.reason=Q.cancelReason,$.handle.message.error=new p.AbortedError({message:Q.cancelReason??"Step cancelled by plugin"}).toObject(),$.handle.message.finish="cancelled",yield*$.sessions.updateMessage($.handle.message),yield*$.plugin.trigger("session.userQuery.post",{sessionID:$.sessionID,agentID:$.agentID,step:$.step,messageID:$.lastUser.id,query:$.query,assistantMessageID:$.handle.message.id,finish:$.handle.message.finish,error:Q.cancelReason,trajectory:$.trajectoryForStep($.msgs,$.handle.message)},{}),!0}),withUserQueryPost:(Q)=>Q.pipe(Y.onExit((J)=>$.plugin.trigger("session.userQuery.post",{sessionID:$.sessionID,agentID:$.agentID,step:$.step,messageID:$.lastUser.id,query:$.query,assistantMessageID:$.handle.message.id,finish:$.handle.message.finish,error:u2.isFailure(J)?G2.pretty(J.cause):k4($.handle.message.error),finalText:T4($.handle.message,p.parts($.handle.message.id)),trajectory:$.trajectoryForStep($.msgs,$.handle.message)},{}).pipe(Y.ignore)))}}var $8={};L2($8,{toSchemaOnlyTools:()=>eY,runMaxStep:()=>cK,runCandidate:()=>$Q,parseJudgeIndex:()=>ZQ,judge:()=>XQ,MaxMode:()=>$8,MAX_MODE_AGENT:()=>dK,DEFAULT_CANDIDATES:()=>tY});var h4=s.create({service:"session.max-mode"}),tY=5,dK="max";function eY($){let Z={};for(let[X,Q]of Object.entries($)){let{execute:J,...V}=Q;Z[X]=V}return Z}var $Q=($,Z)=>Y.gen(function*(){let X=x6(),Q={index:Z,reasoning:"",text:"",toolCalls:[],finishReason:"stop"},J=eY($.tools),V=$.llm.stream({user:$.user,sessionID:$.sessionID,parentSessionID:$.parentSessionID,model:$.model,agent:$.agent,permission:$.permission,system:$.system,prebuiltSystem:$.prebuiltSystem,messages:$.messages,tools:J,agentID:$.agentID});return yield*c9(V,(B)=>{switch(B.type){case"reasoning-delta":if(Q.reasoning+=B.text,X.append(B.text))return Y.fail(y6());if(B.providerMetadata)Q.reasoningMetadata=B.providerMetadata;break;case"text-delta":if(Q.text+=B.text,X.append(B.text))return Y.fail(y6());if(B.providerMetadata)Q.textMetadata=B.providerMetadata;break;case"tool-call":Q.toolCalls.push({toolCallId:B.toolCallId,toolName:B.toolName,input:B.input??{},providerMetadata:B.providerMetadata});break;case"finish-step":Q.finishReason=B.finishReason??Q.finishReason,Q.usage=B.usage,Q.providerMetadata=B.providerMetadata;break;case"error":return Y.fail(B.error);default:break}return Y.void}),Q}).pipe(Y.catchCauseIf((X)=>!G2.hasInterruptsOnly(X),(X)=>Y.fail(G2.squash(X))),Y.retry({while:f2.isTransientCapacityError,schedule:f2.persistentRetrySchedule}),Y.catchIf(w7,()=>Y.succeed("text-repeat")),Y.catch((X)=>Y.sync(()=>{return h4.warn("candidate failed",{index:Z,error:X instanceof Error?X.message:String(X)}),null})));function mK($,Z){let X=$.toolCalls.length===0?"(no tool calls \u2014 final answer / text only)":$.toolCalls.map((V)=>` - ${V.toolName}(${JSON.stringify(V.input)})`).join(`
|
|
395
|
+
`),Q=$.reasoning.trim()?$.reasoning.trim():"(no reasoning emitted)",J=$.text.trim()?$.text.trim():"(no text emitted)";return[`### Candidate ${Z}`,`Reasoning:
|
|
396
|
+
${Q}`,`Message:
|
|
397
|
+
${J}`,`Proposed tool calls:
|
|
398
|
+
${X}`].join(`
|
|
399
|
+
`)}var lK=["You are a judge selecting the single best next step for a coding agent.","You will see several independent candidate drafts for the SAME step. Each candidate contains its reasoning, its message text, and the tool calls it proposes to make next.","Pick the ONE candidate that has the most correct, grounded, and useful next step. Prefer candidates whose reasoning is sound and whose proposed tool calls are appropriate and safe.","Respond with ONLY the integer index of the winning candidate (e.g. `2`). No other text."].join(`
|
|
400
|
+
`);function ZQ($,Z){let X=$.match(/\d+/);if(!X)return 0;let Q=parseInt(X[0],10);if(Number.isNaN(Q)||Q<0||Q>=Z)return 0;return Q}var XQ=($,Z)=>Y.gen(function*(){if(Z.length===1)return{pick:0,usage:void 0};let X=Z.map((H,W)=>mK(H,W)).join(`
|
|
401
|
+
|
|
402
|
+
`),J=[{role:"user",content:[`There are ${Z.length} candidates, indexed 0..${Z.length-1}.`,"",X,"",`Reply with ONLY the integer index (0..${Z.length-1}) of the best candidate.`].join(`
|
|
403
|
+
`)}],V="",B,D=$.llm.stream({user:$.user,sessionID:$.sessionID,parentSessionID:$.parentSessionID,model:$.model,agent:$.agent,permission:$.permission,system:[lK],messages:J,tools:{},toolChoice:"none",agentID:$.agentID});return yield*c9(D,(H)=>{if(H.type==="text-delta")V+=H.text;else if(H.type==="finish-step")B=H.usage;else if(H.type==="error")return Y.fail(H.error);return Y.void}),{pick:ZQ(V,Z.length),usage:B}}).pipe(Y.catchCauseIf((X)=>!G2.hasInterruptsOnly(X),(X)=>Y.fail(G2.squash(X))),Y.retry({while:f2.isTransientCapacityError,schedule:f2.persistentRetrySchedule}),Y.catch((X)=>{return h4.warn("judge failed, defaulting to candidate 0",{error:X instanceof Error?X.message:String(X)}),Y.succeed({pick:0,usage:void 0})})),cK=($)=>Y.gen(function*(){let Z=Math.max(1,$.candidates??tY),X=(j)=>$.setStatus?$.setStatus(j):Y.void,Q=Date.now();yield*X(`thinking \u2014 ${Z} candidates`);let J=yield*Y.all(Array.from({length:Z},(j,G)=>$Q($,G)),{concurrency:Z});if(J.some((j)=>j==="text-repeat"))return"text-repeat";let V=J.filter((j)=>j!==null&&j!=="text-repeat");if(V.length===0)return h4.warn("all candidates failed, falling back to single process"),yield*X(void 0),yield*$.handle.process({user:$.user,agent:$.agent,permission:$.permission,sessionID:$.sessionID,parentSessionID:$.parentSessionID,system:$.system,prebuiltSystem:$.prebuiltSystem,messages:$.messages,tools:$.tools,model:$.model,agentID:$.agentID});yield*X(`judging ${V.length} candidates`);let{pick:B,usage:D}=yield*XQ($,V),H=V[B];h4.info("max step",{candidates:Z,survivors:V.length,winner:B,toolCalls:H.toolCalls.length});let K=[...V.filter((j,G)=>G!==B).map((j)=>j.usage),D].reduce((j,G)=>{if(!G)return j;let z=U6({model:$.model,usage:G});return j.cost+=z.cost,j.tokensIn+=z.tokens.input+z.tokens.cache.read+z.tokens.cache.write,j.tokensOut+=z.tokens.output+z.tokens.reasoning,j},{cost:0,tokensIn:0,tokensOut:0});return yield*X(void 0),yield*$.handle.replay({reasoning:H.reasoning,reasoningMetadata:H.reasoningMetadata,text:H.text,textMetadata:H.textMetadata,toolCalls:H.toolCalls,finishReason:H.finishReason,usage:H.usage,providerMetadata:H.providerMetadata,tools:$.tools,messages:$.messages,selection:{winner:B,total:V.length},thinkingMs:Date.now()-Q,overhead:K})});var QQ=Y.fn("SessionPrompt.executeLlmStep")(function*($){let Z=$.lastUser.agentID?yield*$.actorRegistry.get($.sessionID,$.lastUser.agentID).pipe(Y.orElseSucceed(()=>{return})):void 0;if(Z?.contextMode==="full"&&(Z.mode==="subagent"||Z.mode==="peer")){let O=Q$.current?.getForkContext($.lastUser.agentID),P=O?yield*O:void 0;if(!P)return yield*$.slog.warn("fork agent runLoop: missing forkContext, failing actor",{sessionID:$.sessionID,agentID:$.lastUser.agentID}),yield*$.actorRegistry.updateStatus($.sessionID,$.lastUser.agentID,{status:"idle",lastOutcome:"failure",lastError:"missing fork context"}).pipe(Y.ignore),{kind:"break",reason:"missing-fork-context"};let w=$.msgs.filter((y)=>y.info.id>P.watermarkMsgID&&y.info.agentID===$.lastUser.agentID),L=yield*p.toModelMessagesEffect(w,$.model),F=[...P.inheritedMessages,...L];if(yield*$.cancelledByPlugin)return{kind:"processed",result:"stop",fork:!0};return{kind:"processed",result:yield*$.withUserQueryPost($.handle.process({user:$.lastUser,agent:$.agent,permission:P.parentPermission??$.session.permission,sessionID:$.sessionID,parentSessionID:$.session.parentID,system:[],prebuiltSystem:P.system,messages:[...F,...$.isLastStep?[{role:"assistant",content:$.maxStepsText}]:[]],tools:$.tools,model:$.model,toolChoice:$.format.type==="json_schema"?"required":void 0,agentID:$.lastUser.agentID})),fork:!0}}let[Q,J,V]=yield*Y.all([$.sys.skills($.agent),Y.sync(()=>$.sys.environment($.model,$.session.time.created)),$.instruction.system().pipe(Y.orDie)]);if(!$.session.parentID&&!$.instructionsNotified.has($.sessionID)){$.instructionsNotified.add($.sessionID);let O=(yield*v.context).worktree,P=Array.from(V.paths,(w)=>G$.display(w,O));if(P.length>0)yield*$.bus.publish(YQ,{files:P}).pipe(Y.ignore)}let B=[...J,...Q?[Q]:[],...V.content,...$.format.type==="json_schema"?[oY]:[]],{system:D,inheritedMessages:H}=yield*L4({sessionID:$.sessionID,agent:$.agent,model:$.model,msgs:$.msgs,additions:B}).pipe(Y.provideService(f2.Service,$.llm),Y.provideService(W0.Service,$.registry)),W=(yield*$.config.get()).experimental?.maxMode,K=$.agent.name===$8.MAX_MODE_AGENT&&W!==void 0&&$.format.type!=="json_schema",j={user:$.lastUser,agent:$.agent,permission:$.session.permission,sessionID:$.sessionID,parentSessionID:$.session.parentID,system:B,prebuiltSystem:D,messages:[...H,...$.isLastStep?[{role:"assistant",content:$.maxStepsText}]:[]],tools:$.tools,model:$.model,toolChoice:$.format.type==="json_schema"?"required":void 0,agentID:$.lastUser.agentID};if(yield*$.cancelledByPlugin)return{kind:"processed",result:"stop",fork:!1};let G=K?$8.runMaxStep({...j,handle:$.handle,llm:$.llm,candidates:W?.candidates,setStatus:(O)=>$.status.set($.sessionID,O?{type:"busy",message:O}:{type:"busy"})}):$.handle.process(j);return{kind:"processed",result:yield*$.withUserQueryPost(G),fork:!1}});function JQ($){if($.length===0)return;let Z=$[$.length-1];if(Z.role==="assistant")return{role:"assistant",finish:Z.finish==="tool-calls"?"tool-calls":"stop"};if(Z.role==="tool")return{role:"tool"};return{role:"user"}}function f4($,Z,X){return $.compaction.create({sessionID:Z.sessionID,agent:Z.lastUser.agent,model:{providerID:Z.model.providerID,modelID:Z.model.id},auto:!0,...X?{overflow:!0}:{},agentID:Z.lastUser.agentID}).pipe(Y.ignore)}function VQ($,Z){return Y.gen(function*(){yield*$.checkpoint.waitForWriter(Z.sessionID).pipe(Y.ignore);let X=yield*$.checkpoint.lastBoundary(Z.sessionID).pipe(Y.catch(()=>Y.succeed(void 0))),Q=X?Z.msgs.find((J)=>J.info.id===X):void 0;return X?yield*$.checkpoint.insertRebuildBoundary({sessionID:Z.sessionID,boundary:X,lastMessageInfo:JQ(Z.msgs.map((J)=>J.info)),agentID:Z.lastUser.agentID,agent:Z.lastUser.agent,model:{providerID:Z.model.providerID,modelID:Z.model.id},boundaryCreatedAt:Q?.info.time.created}).pipe(Y.catch(()=>Y.succeed(!1))):!1})}var BQ=Y.fn("SessionPrompt.handlePreStepOverflow")(function*($,Z){if(Z.isBoundedComputation||Z.lastFinished.summary===!0)return!1;let X=yield*$.config.get();if(!(L1({cfg:X,tokens:Z.lastFinished.tokens,model:Z.model})||(yield*$.prune.maxThresholdCrossed(Z.sessionID))))return!1;if(Z.lastUser.agentID&&Z.lastUser.agentID!=="main")return yield*f4($,Z,!1),!0;if(yield*$.checkpoint.hasCheckpoint(Z.sessionID).pipe(Y.catch(()=>Y.succeed(!1)))){if(yield*VQ($,Z))return yield*$.prune.resetThresholds(Z.sessionID),!0}return yield*f4($,Z,!1),!0}),WQ=Y.fn("SessionPrompt.handleProviderOverflow")(function*($,Z){if(!Z.isBoundedComputation&&Z.lastUser.agentID&&Z.lastUser.agentID!=="main")return yield*f4($,Z,!0),!0;if(!Z.isBoundedComputation){let X=yield*$.checkpoint.isWriterRunning(Z.sessionID).pipe(Y.catch(()=>Y.succeed(!1))),Q=yield*$.checkpoint.hasCheckpoint(Z.sessionID).pipe(Y.catch(()=>Y.succeed(!1)));if(X||Q){if(yield*VQ($,Z))return yield*$.prune.resetThresholds(Z.sessionID),!0}yield*f4($,Z,!0)}return!0});function KQ($){return(Z)=>Y.gen(function*(){let X=yield*p.filterCompactedEffect($.sessionID,{contextFrom:$.session.contextFrom,contextWatermark:$.session.contextWatermark,agentID:$.agentID}).pipe(Y.catch(()=>Y.succeed([]))),Q=X.findLast((K)=>K.info.role==="assistant"),J=Q&&Q.info.role==="assistant"?Q.info:void 0,V=Q?.parts??[],B=u2.isFailure(Z),D=!!J?.error,H=$.cancellation.cancelled?"cancelled":B||D?"error":"completed",W=$.cancellation.cancelled?$.cancellation.reason:B?G2.pretty(Z.cause):J?k4(J.error):void 0;yield*$.plugin.trigger("session.post",{sessionID:$.sessionID,agentID:$.agentID,task_id:$.task_id,outcome:H,error:W,finalText:J?T4(J,V):void 0,assistantMessageID:J?.id,trajectory:g4(X)},{})}).pipe(Y.ignore)}function GQ($){let Z={cancelled:!1,reason:void 0},X={tokens_in:0,tokens_out:0,files_changed:0},Q=Y.gen(function*(){let B={cancel:void 0,cancelReason:void 0};if(yield*$.plugin.trigger("session.pre",{sessionID:$.sessionID,agentID:$.agentID,task_id:$.task_id},B),!B.cancel)return;return Z.cancelled=!0,Z.reason=B.cancelReason,yield*Y.fail(new w2.Unknown({message:B.cancelReason??"Session cancelled by plugin"}))});return{cancellation:Z,agentMetrics:X,before:Q,publishAgentRequest:(B,D)=>$.bus.publish(C2.AgentRequest,{sessionID:$.sessionID,phase:B,task_type:D,surface:L0.QITQODE_CLIENT,total_tokens_in:X.tokens_in,total_tokens_out:X.tokens_out,files_changed:X.files_changed,validation_status:"skipped"}).pipe(Y.ignore),schedulePrune:(B)=>$.prune.prune({sessionID:$.sessionID,model:B.model,tokens:B.lastFinished.tokens,lastAssistantTime:B.lastFinished.time.completed,promptOps:B.promptOps}).pipe(Y.ignore,Y.forkIn($.scope),Y.asVoid)}}var HQ={input:0,output:0,reasoning:0,cache:{read:0,write:0}};function E4($){return{id:x2.ascending(),sessionID:$.sessionID,role:"assistant",parentID:$.parentID,agentID:$.agentID,mode:$.agent,agent:$.agent,variant:$.variant,path:{cwd:$.cwd,root:$.root},cost:0,tokens:{...HQ,cache:{...HQ.cache}},modelID:$.modelID,providerID:$.providerID,time:{created:$.created??Date.now()}}}var oK=s.create({service:"session.prompt"}),jQ=Y.fn("SessionPrompt.getModel")(function*($,Z,X,Q,J){let V=yield*$.getModel(X,Q).pipe(Y.exit);if(u2.isSuccess(V))return V.value;let B=G2.squash(V.cause);if(P2.ModelNotFoundError.isInstance(B)){let D=B.data.suggestions?.length?` Did you mean: ${B.data.suggestions.join(", ")}?`:"";yield*Z.publish(U2.Error,{sessionID:J,error:new w2.Unknown({message:`Model not found: ${B.data.providerID}/${B.data.modelID}.${D}`}).toObject()})}return yield*Y.failCause(V.cause)}),DQ=jQ,d4=Y.fn("SessionPrompt.getModel")(function*($,Z,X){let Q=yield*P2.Service,J=yield*u.Service;return yield*jQ(Q,J,$,Z,X)}),yQ=Y.fnUntraced(function*($,Z,X){if(X!==void 0){let V=yield*$.messages({sessionID:Z,agentID:X}),B=V.findLast((D)=>D.info.role==="assistant");if(B)return B;if(V.length>0)return V[V.length-1]}let Q=yield*$.findMessage(Z,(V)=>V.info.role!=="user",{agentID:"*"});if(Y0.isSome(Q))return Q.value;let J=yield*$.messages({sessionID:Z,limit:1,agentID:"*"});if(J.length>0)return J[0];throw Error("Impossible")}),OQ=yQ,uK=Y.fnUntraced(function*($,Z){let X=yield*E2;return yield*yQ(X,$,Z)}),o9=Y.fn("SessionPrompt.handleSubtask")(function*($){let{task:Z,model:X,lastUser:Q,sessionID:J,session:V,msgs:B,getOps:D}=$,H=yield*v.context,W=yield*u.Service,K=yield*W0.Service,j=yield*E2,G=yield*h2.Service,z=yield*K2.Service,O=yield*O2.Service,P=yield*D(),{actor:w}=yield*K.named(),L=Z.model?yield*d4(Z.model.providerID,Z.model.modelID,J):X,F=yield*j.updateMessage(E4({sessionID:J,parentID:Q.id,agentID:Q.agentID,agent:Z.agent,variant:Q.model.variant,cwd:H.directory,root:H.worktree,modelID:L.id,providerID:L.providerID})),U={operation:{action:"run",prompt:Z.prompt,description:Z.description,subagent_type:Z.agent,command:Z.command}},y=yield*j.updatePart({id:Q2.ascending(),messageID:F.id,sessionID:F.sessionID,type:"tool",callID:r1(),tool:v4.id,state:{status:"running",input:U,time:{start:Date.now()}}});yield*z.trigger("tool.execute.before",{tool:v4.id,sessionID:J,callID:y.id},{args:U});let S=yield*d$(G,W,Z.agent,J),I,M=new AbortController,f=yield*w.execute(U,{agent:Z.agent,messageID:F.id,sessionID:J,abort:M.signal,callID:y.callID,extra:{bypassAgentCheck:!0,promptOps:P},messages:B,metadata:(h)=>Y.gen(function*(){y=yield*j.updatePart({...y,type:"tool",state:{...y.state,...h}})}),ask:(h)=>O.ask({...h,sessionID:J,ruleset:O2.merge(S.permission,V.permission??[])}).pipe(Y.orDie)}).pipe(Y.catchCause((h)=>{let N=G2.squash(h);return I=N instanceof Error?N:Error(String(N)),oK.error("subtask execution failed",{error:I,agent:Z.agent,description:Z.description}),Y.void}),Y.onInterrupt(()=>Y.gen(function*(){if(M.abort(),F.finish="tool-calls",F.time.completed=Date.now(),yield*j.updateMessage(F),y.state.status==="running")yield*j.updatePart({...y,state:{status:"error",error:"Cancelled",time:{start:y.state.time.start,end:Date.now()},metadata:y.state.metadata,input:y.state.input}})}))),b=f?.attachments?.map((h)=>({...h,id:Q2.ascending(),sessionID:J,messageID:F.id}));if(yield*z.trigger("tool.execute.after",{tool:v4.id,sessionID:J,callID:y.id,args:U},f),F.finish="tool-calls",F.time.completed=Date.now(),yield*j.updateMessage(F),f&&y.state.status==="running")yield*j.updatePart({...y,state:{status:"completed",input:y.state.input,title:f.title,metadata:f.metadata,output:f.output,attachments:b,time:{...y.state.time,end:Date.now()}}});if(!f)yield*j.updatePart({...y,state:{status:"error",error:I?`Tool execution failed: ${I.message}`:"Tool execution failed",time:{start:y.state.status==="running"?y.state.time.start:Date.now(),end:Date.now()},metadata:y.state.status==="pending"?void 0:y.state.metadata,input:y.state.input}});if(!Z.command)return;let k={id:x2.ascending(),sessionID:J,role:"user",agentID:Q.agentID,time:{created:Date.now()},agent:Q.agent,model:Q.model};yield*j.updateMessage(k),yield*j.updatePart({id:Q2.ascending(),messageID:k.id,sessionID:J,type:"text",text:"Summarize the actor tool output above and continue with your task.",synthetic:!0})});var D1={};L2(D1,{decide:()=>iK,TaskGate:()=>D1,MAX_TASK_GATE_SUBAGENT_REACT:()=>u9,MAX_TASK_GATE_MAIN_REACT:()=>p9});var u9=2,p9=3,pK=($,Z)=>{let X=Z==="subagent"?"You are about to finish, but these tasks you own are still unfinished:":"You are about to finish, but these tasks in this session are still unfinished:",Q=Z==="subagent"?"Then re-emit your final message starting with the **Status**/**Summary** header.":"Then continue or respond.";return["<system-reminder>",X,...$.map((J)=>`- ${J.id} (${J.status}): ${J.summary}`),"For EACH: complete the work then `task done <id> <summary>`, or `task abandon <id> <reason>` if it is genuinely not needed.",Q,"</system-reminder>"].join(`
|
|
404
|
+
`)},iK=Y.fn("TaskGate.decide")(function*($){let Q=(yield*(yield*_0.Service).list({session_id:$.session_id,owner:$.owner,include_terminal:!1}).pipe(Y.orElseSucceed(()=>[]))).filter((J)=>J.status==="open"||J.status==="in_progress");if(Q.length===0)return{needReentry:!1,capExceeded:!1,incompleteTasks:[]};if($.reactCount>=$.maxReact)return{needReentry:!1,capExceeded:!0,incompleteTasks:Q.map((J)=>J.id)};return{needReentry:!0,capExceeded:!1,reentryText:pK(Q,$.mode),incompleteTasks:Q.map((J)=>J.id)}});function FQ($){return Y.fn("SessionPrompt.taskGate")(function*(Z){if(($.agentID??"main")!=="main")return!1;let X=yield*$.agents.get("main").pipe(Y.orElseSucceed(()=>{return}));if(X&&O2.disabled(["task"],X.permission).has("task"))return!1;if(Z.tools?.task===!1)return!1;let Q=yield*$.taskGateState.get($.sessionID),J=yield*D1.decide({session_id:$.sessionID,owner:void 0,reactCount:Q,maxReact:p9,mode:"main"}).pipe(Y.provideService(_0.Service,$.taskRegistry));if(!J.needReentry){if(J.capExceeded)yield*$.slog.warn("task gate hit cap; allowing stop",{sessionID:$.sessionID,incompleteTasks:J.incompleteTasks});return yield*$.taskGateState.clear($.sessionID),!1}return yield*$.taskGateState.bump($.sessionID),yield*$.appendSyntheticUserTurn({lastUser:Z,sessionID:$.sessionID,text:J.reentryText}),!0})}var nK=12;function PQ($){return Y.fn("SessionPrompt.goalGate")(function*(Z){if(($.agentID??"main")!=="main")return!1;let X=yield*$.goal.get($.sessionID);if(!X)return!1;let Q=yield*p.filterCompactedEffect($.sessionID,{contextFrom:$.session.contextFrom,contextWatermark:$.session.contextWatermark,agentID:"main"}),J=Q.findLast((D)=>D.info.role==="assistant")?.info.id,V=yield*$.goal.evaluate({condition:X.condition,msgs:Q,model:Z.model}).pipe(Y.catch((D)=>Y.gen(function*(){return yield*$.slog.warn("goal judge failed; allowing stop",{error:String(D)}),{ok:!0,reason:"judge error",judgeFailed:!0}})));if(V.ok||V.impossible)return yield*$.slog.info("goal satisfied; allowing stop",{sessionID:$.sessionID,impossible:V.impossible===!0}),yield*$.bus.publish(F0.Event.Updated,{sessionID:$.sessionID,goal:void 0,lastVerdict:{...V,attempt:X.react,messageID:J,error:"judgeFailed"in V?!0:void 0}}),yield*$.goal.clear($.sessionID),!1;let B=yield*$.goal.bumpReact($.sessionID);if(B>nK)return yield*$.slog.warn("goal hit MAX_GOAL_REACT cap; allowing stop",{sessionID:$.sessionID,condition:X.condition,count:B}),yield*$.bus.publish(F0.Event.Updated,{sessionID:$.sessionID,goal:void 0,lastVerdict:{...V,attempt:B,messageID:J}}),yield*$.goal.clear($.sessionID),!1;return yield*$.slog.info("goal not satisfied; re-entering",{sessionID:$.sessionID,attempt:B}),yield*$.bus.publish(F0.Event.Updated,{sessionID:$.sessionID,goal:{condition:X.condition},lastVerdict:{...V,attempt:B,messageID:J}}),yield*$.appendSyntheticUserTurn({lastUser:Z,sessionID:$.sessionID,text:["<system-reminder>",`Your goal is not yet satisfied: "${X.condition}".`,"A judge reviewed the transcript and reported what is still missing:",V.reason,"Keep working toward the goal. Do not stop until it is genuinely met or impossible.","</system-reminder>"].join(`
|
|
405
|
+
`)}),!0})}import sK from"path";function qQ($){return Y.fn("SessionPrompt.ensureTitle")(function*(Z){if(Z.session.parentID)return;if(!xQ(Z.session.title))return;let X=(P)=>P.info.role==="user"&&!P.parts.every((w)=>("synthetic"in w)&&w.synthetic),Q=Z.history.findIndex(X);if(Q===-1||Z.history.filter(X).length!==1)return;let J=Z.history.slice(0,Q+1),V=J[Q];if(!V||V.info.role!=="user")return;let B=V.info,D=V.parts.filter((P)=>P.type==="subtask"),H=D.length>0&&V.parts.every((P)=>P.type==="subtask");if(Z.providerID==="qlex"){let P=H?D.map((w)=>w.prompt).join(`
|
|
406
|
+
`):V.parts.map((w)=>{let L=w;return L.type==="text"&&!L.synthetic?String(L.text??""):""}).filter(Boolean).join(`
|
|
407
|
+
`).slice(0,4000);if(P){let w=yield*Y.promise(()=>$0.resolveChatCompletion(`Generate a very short title (5 words or fewer) for this conversation. Reply with ONLY the title, no quotes or punctuation:
|
|
408
|
+
|
|
409
|
+
${P}`,{temperature:0.5,timeoutMs:1e4}).catch(()=>null));if(w?.content){let L=g8(w.content);if(L){let F=L.length>100?L.substring(0,97)+"...":L;yield*$.sessions.setTitle({sessionID:Z.session.id,title:F}).pipe(Y.catchCause((U)=>$.elog.error("failed to generate title",{error:G2.squash(U)})));return}}}}let W=yield*$.agents.get("title");if(!W)return;let K=W.modelRef?yield*$.provider.resolveModelRef(W.modelRef,Z.providerID):W.model?yield*$.provider.getModel(W.model.providerID,W.model.modelID):(yield*$.provider.getSmallModel(Z.providerID))??(yield*$.provider.getModel(Z.providerID,Z.modelID)),j=H?[{role:"user",content:D.map((P)=>P.prompt).join(`
|
|
410
|
+
`)}]:yield*p.toModelMessagesEffect(J,K),G=yield*$.llm.stream({agent:W,user:B,system:[],small:!0,tools:{},model:K,sessionID:Z.session.id,retries:2,messages:[{role:"user",content:`Generate a title for this conversation:
|
|
411
|
+
`},...j]}).pipe(l4((P)=>P.type==="text-delta"),m4((P)=>P.text),c4,Y.orDie),z=g8(G);if(!z)return;let O=z.length>100?z.substring(0,97)+"...":z;yield*$.sessions.setTitle({sessionID:Z.session.id,title:O}).pipe(Y.catchCause((P)=>$.elog.error("failed to generate title",{error:G2.squash(P)})))})}function NQ($){return Y.fn("SessionPrompt.insertReminders")(function*(Z){let X=Z.messages.findLast((H)=>H.info.role==="user");if(!X)return Z.messages;let Q=Z.messages.find((H)=>H.info.role==="user"&&H.info.agent==="compose");if(Q){let H=zQ();Q.parts.unshift({id:Q2.ascending(),messageID:Q.info.id,sessionID:Q.info.sessionID,type:"text",text:i9({source:"mode",trust:"local-policy",posture:"workflow-compose",body:$.promptCompose+(H?`
|
|
412
|
+
|
|
413
|
+
`+H:"")}),synthetic:!0})}let J=Z.messages.findLast((H)=>H.info.role==="assistant");if(Z.agent.name!=="plan"&&J?.info.agent==="plan"){let H=n9(Z.session);if(!(yield*$.fsys.existsSafe(H)))return Z.messages;let W=yield*$.sessions.updatePart({id:Q2.ascending(),messageID:X.info.id,sessionID:X.info.sessionID,type:"text",text:`${$.buildSwitch}
|
|
414
|
+
|
|
415
|
+
A plan file exists at ${H}. You should execute on the plan defined within it`,synthetic:!0});return X.parts.push(W),Z.messages}if(Z.agent.name!=="plan"||J?.info.agent==="plan")return Z.messages;let V=n9(Z.session),B=yield*$.fsys.existsSafe(V);if(!B)yield*$.fsys.ensureDir(sK.dirname(V)).pipe(Y.catch(Y.die));let D=yield*$.sessions.updatePart({id:Q2.ascending(),messageID:X.info.id,sessionID:X.info.sessionID,type:"text",text:i9({source:"mode",trust:"local-policy",posture:"read-only-plan",envelope:"system-reminder",body:`
|
|
416
|
+
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
|
|
417
|
+
|
|
418
|
+
## Plan File Info:
|
|
419
|
+
${B?`A plan file already exists at ${V}. You can read it and make incremental edits using the edit tool.`:`No plan file exists yet. You should create your plan at ${V} using the write tool.`}
|
|
420
|
+
You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
|
|
421
|
+
|
|
422
|
+
## Plan Workflow
|
|
423
|
+
|
|
424
|
+
### Phase 1: Initial Understanding
|
|
425
|
+
Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should only use the explore subagent type.
|
|
426
|
+
|
|
427
|
+
1. Focus on understanding the user's request and the code associated with their request
|
|
428
|
+
|
|
429
|
+
2. **Launch up to 3 explore agents IN PARALLEL** (single message, multiple tool calls) to efficiently explore the codebase.
|
|
430
|
+
- Use 1 agent when the task is isolated to known files, the user provided specific file paths, or you're making a small targeted change.
|
|
431
|
+
- Use multiple agents when: the scope is uncertain, multiple areas of the codebase are involved, or you need to understand existing patterns before planning.
|
|
432
|
+
- Quality over quantity - 3 agents maximum, but you should try to use the minimum number of agents necessary (usually just 1)
|
|
433
|
+
- If using multiple agents: Provide each agent with a specific search focus or area to explore. Example: One agent searches for existing implementations, another explores related components, a third investigates testing patterns
|
|
434
|
+
|
|
435
|
+
3. After exploring the code, use the question tool to clarify ambiguities in the user request up front.
|
|
436
|
+
|
|
437
|
+
### Phase 2: Design
|
|
438
|
+
Goal: Design an implementation approach.
|
|
439
|
+
|
|
440
|
+
Launch general agent(s) to design the implementation based on the user's intent and your exploration results from Phase 1.
|
|
441
|
+
|
|
442
|
+
You can launch up to 1 agent(s) in parallel.
|
|
443
|
+
|
|
444
|
+
**Guidelines:**
|
|
445
|
+
- **Default**: Launch at least 1 Plan agent for most tasks - it helps validate your understanding and consider alternatives
|
|
446
|
+
- **Skip agents**: Only for truly trivial tasks (typo fixes, single-line changes, simple renames)
|
|
447
|
+
|
|
448
|
+
Examples of when to use multiple agents:
|
|
449
|
+
- The task touches multiple parts of the codebase
|
|
450
|
+
- It's a large refactor or architectural change
|
|
451
|
+
- There are many edge cases to consider
|
|
452
|
+
- You'd benefit from exploring different approaches
|
|
453
|
+
|
|
454
|
+
Example perspectives by task type:
|
|
455
|
+
- New feature: simplicity vs performance vs maintainability
|
|
456
|
+
- Bug fix: root cause vs workaround vs prevention
|
|
457
|
+
- Refactoring: minimal change vs clean architecture
|
|
458
|
+
|
|
459
|
+
In the agent prompt:
|
|
460
|
+
- Provide comprehensive background context from Phase 1 exploration including filenames and code path traces
|
|
461
|
+
- Describe requirements and constraints
|
|
462
|
+
- Request a detailed implementation plan
|
|
463
|
+
|
|
464
|
+
### Phase 3: Review
|
|
465
|
+
Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
|
|
466
|
+
1. Read the critical files identified by agents to deepen your understanding
|
|
467
|
+
2. Ensure that the plans align with the user's original request
|
|
468
|
+
3. Use question tool to clarify any remaining questions with the user
|
|
469
|
+
|
|
470
|
+
### Phase 4: Final Plan
|
|
471
|
+
Goal: Write your final plan to the plan file (the only file you can edit).
|
|
472
|
+
- Include only your recommended approach, not all alternatives
|
|
473
|
+
- Ensure that the plan file is concise enough to scan quickly, but detailed enough to execute effectively
|
|
474
|
+
- Include the paths of critical files to be modified
|
|
475
|
+
- Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
|
|
476
|
+
|
|
477
|
+
### Phase 5: Call plan_exit tool
|
|
478
|
+
At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call plan_exit to indicate to the user that you are done planning.
|
|
479
|
+
This is critical - your turn should only end with either asking the user a question or calling plan_exit. Do not stop unless it's for these 2 reasons.
|
|
480
|
+
|
|
481
|
+
**Important:** Use question tool to clarify requirements/approach, use plan_exit to request plan approval. Do NOT use question tool to ask "Is this plan okay?" - that's what plan_exit does.
|
|
482
|
+
|
|
483
|
+
NOTE: At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
|
|
484
|
+
`.trim()}),synthetic:!0});return X.parts.push(D),Z.messages})}var wQ=5,o4=3,s9=2;function bQ($){return $.trim().toLowerCase().replace(/\s+/g," ").replace(/^(let me |i'll |i will |let's )/i,"").slice(0,200)}function LQ($,Z){if(Z<=0||$.length<Z)return!1;let X=$.slice(-Z);return X.every((Q)=>Q===X[0])}var UQ=`<system-reminder>
|
|
485
|
+
LOOP DETECTED: Your last several outputs were identical. You are stuck in a repetitive pattern.
|
|
486
|
+
|
|
487
|
+
STOP what you are doing and take a DIFFERENT approach:
|
|
488
|
+
- If you were about to call a tool, try a different tool or different arguments
|
|
489
|
+
- If you were planning an action, reconsider and pick an alternative strategy
|
|
490
|
+
- If you are blocked, explain what's blocking you and ask the user for help
|
|
491
|
+
|
|
492
|
+
Do NOT repeat the same text or action again.
|
|
493
|
+
</system-reminder>`,AQ=`<system-reminder>
|
|
494
|
+
CRITICAL: You are STILL stuck in a loop after a previous recovery attempt.
|
|
495
|
+
|
|
496
|
+
Your previous approach has failed repeatedly. You MUST:
|
|
497
|
+
1. Abandon your current plan entirely
|
|
498
|
+
2. State what you were trying to do and why it failed
|
|
499
|
+
3. Ask the user for guidance on how to proceed
|
|
500
|
+
|
|
501
|
+
If you repeat the same output again, the session will be terminated.
|
|
502
|
+
</system-reminder>`;var a9=($)=>Y.fnUntraced(function*(Z){let X=yield*$.updateMessage({id:x2.ascending(),role:"user",sessionID:Z.sessionID,agentID:Z.lastUser.agentID,agent:Z.lastUser.agent,model:Z.lastUser.model,tools:Z.lastUser.tools,format:Z.lastUser.format,time:{created:Date.now()}});return yield*$.updatePart({id:Q2.ascending(),messageID:X.id,sessionID:X.sessionID,type:"text",synthetic:!0,text:Z.text}),X});function MQ(){return["<system-reminder>","The previous assistant response hit the model output token limit before completing.","Continue the same task from the exact point where it stopped.","Do not restart, recap, or repeat prior reasoning. Keep reasoning concise, prefer concrete tool calls or final output, and only stop when the user's task is complete or genuinely blocked.","</system-reminder>"].join(`
|
|
503
|
+
`)}function _Q(){return["<system-reminder>","Your previous response contained no usable answer (it had only reasoning, or was empty).","Provide a final answer to the user now, or call a valid tool to make progress on the task.","Do not respond with only reasoning/thinking.","</system-reminder>"].join(`
|
|
504
|
+
`)}function IQ(){return["<system-reminder>","Your previous response did not produce valid structured output via the StructuredOutput tool","(it was plain text, empty, or only reasoning).","You MUST call the StructuredOutput tool now, passing JSON that matches the requested schema.","Do not reply with plain text and do not respond with only reasoning/thinking.","</system-reminder>"].join(`
|
|
505
|
+
`)}function RQ($){return $===0?I5:b7}function CQ($){return $===0?UQ:AQ}var aK=L0.QITQODE_OUTPUT_LENGTH_CONTINUATION_LIMIT,rK=L0.QITQODE_INVALID_OUTPUT_CONTINUATION_LIMIT;function SQ($){let Z=0,X=0,Q=0,J=0,V=Y.fnUntraced(function*(G){yield*$.sessions.updateMessage(G),yield*$.bus.publish(U2.Error,{sessionID:G.sessionID,error:G.error})}),B=Y.fn("SessionPrompt.autoContinueOutputLength")(function*(G){if(G.assistant.finish!=="length"||G.assistant.error||G.assistant.summary)return!1;if(p.parts(G.assistant.id).some((z)=>z.type==="tool"&&!z.metadata?.providerExecuted))return!1;if(Z>=aK)return G.assistant.error=new p.OutputLengthError({}).toObject(),yield*V(G.assistant),!1;return Z++,yield*$.slog.info("auto-continuing output length",{attempt:Z}),yield*$.appendSyntheticUserTurn({lastUser:G.lastUser,sessionID:G.lastUser.sessionID,text:MQ()}),!0}),D=Y.fn("SessionPrompt.autoContinueInvalidOutput")(function*(G){if(G.assistant.error||G.assistant.summary||G.assistant.structured!==void 0)return!1;if(X>=rK)return G.assistant.error=new p.InvalidOutputError({message:G.reason}).toObject(),yield*V(G.assistant),!1;return X++,yield*$.slog.info("auto-continuing invalid output",{attempt:X,reason:G.reason}),yield*$.appendSyntheticUserTurn({lastUser:G.lastUser,sessionID:G.lastUser.sessionID,text:_Q()}),!0}),H=Y.fn("SessionPrompt.autoRetryStructuredOutput")(function*(G){if(G.assistant.error||G.assistant.summary||G.assistant.structured!==void 0)return!1;let z=G.lastUser.format?.type==="json_schema"?G.lastUser.format.retryCount:0;if(Q>=z)return G.assistant.error=new p.StructuredOutputError({message:"Model did not produce structured output",retries:Q}).toObject(),yield*V(G.assistant),!1;return Q++,yield*$.slog.info("retrying structured output",{attempt:Q}),yield*$.appendSyntheticUserTurn({lastUser:G.lastUser,sessionID:G.lastUser.sessionID,text:IQ()}),!0}),W=Y.fn("SessionPrompt.handleTextRepeat")(function*(G){if(J>=N7)return yield*$.slog.info("text n-gram: max recovery exceeded, terminating"),yield*$.bus.publish(U2.Error,{sessionID:$.sessionID,error:new w2.Unknown({message:"The model produced malformed output and couldn't recover. Please try again or switch to a stronger tier."}).toObject()}),!1;return yield*$.appendSyntheticUserTurn({lastUser:G.lastUser,sessionID:$.sessionID,text:RQ(J)}),J++,yield*$.slog.info("text n-gram: recovery injected",{attempt:J}),!0}),K=Y.fn("SessionPrompt.writeContentFilterError")(function*(G){if(G.assistant.error)return;G.assistant.error=new p.ContentFilterError({message:"The response was withheld by the model provider's content safety filter."}).toObject(),yield*V(G.assistant)}),j=Y.fn("SessionPrompt.writeModelError")(function*(G){if(G.assistant.error)return;G.assistant.error=new p.ModelError({message:G.reason}).toObject(),yield*V(G.assistant)});return{autoContinueOutputLength:B,autoContinueInvalidOutput:D,autoRetryStructuredOutput:H,handleTextRepeat:W,writeContentFilterError:K,writeModelError:j}}function kQ($){let Z=[],X=0;return{check:Y.fnUntraced(function*(J){let V=J.completedParts.filter((K)=>K.type==="text"&&!K.synthetic).map((K)=>K.text).join(" ");if(!V.trim())return"none";let B=J.completedParts.filter((K)=>K.type==="tool").map((K)=>`${K.tool}:${JSON.stringify(K.state&&"input"in K.state?K.state.input:"")}`).join("|"),D=bQ(V)+(B?`\x00${B}`:"");if(Z.push(D),Z.length>wQ)Z.shift();if(Z.length<o4)return"none";if(!LQ(Z,o4))return"none";if(X>=s9)return yield*$.slog.info("text loop: max recovery exceeded, terminating"),yield*$.bus.publish(U2.Error,{sessionID:$.sessionID,error:new w2.Unknown({message:`Text loop detected: model repeated the same output ${o4} times after ${s9} recovery attempts. Session terminated.`}).toObject()}),"terminate";let W=CQ(X);return yield*$.appendSyntheticUserTurn({lastUser:J.lastUser,sessionID:$.sessionID,text:W}),X++,Z.length=0,yield*$.slog.info("text loop: recovery injected",{attempt:X}),"recovered"})}}import tK from"path";function h8($){let Z=r9($,"task")==="shell"?"- task list":'- task({ operation: "list" })',X=r9($,"actor")==="shell"?"- actor status <actor_id>":'- actor({ operation: "status", actor_id: "<id>" })';return['- memory({ operation: "search", query: "<keyword>" })',Z,X]}function Z8($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return"["+$.map(Z8).join(",")+"]";return"{"+Object.keys($).sort().map((X)=>JSON.stringify(X)+":"+Z8($[X])).join(",")+"}"}function f8($){let Z=[];for(let X of $)if(X.type==="tool")Z.push("tool:"+X.tool+":"+Z8(X.state.input??{}));if(Z.length===0)return;return Z.join(`
|
|
506
|
+
`)}var t9=3,TQ=Y.fnUntraced(function*($){let Z=$.msgs.findLast((V)=>V.info.role==="user");if(!Z)return;if(!(yield*$.checkpoint.hasMemoryOrTasks($.sessionID).pipe(Y.catch(()=>Y.succeed(!1)))))return;let Q=tK.join(q$.Path.data,"memory","sessions",$.sessionID),J=h8((yield*$.config.get()).tool);Z.parts.push({id:Q2.ascending(),messageID:Z.info.id,sessionID:$.sessionID,type:"text",synthetic:!0,text:["<system-reminder>",`This session has memory at ${Q}/. Recall content`,"not in your context with:",J[0],`- Read(file_path="${Q}/...")`,J[1],J[2],"","Don't ask the user about something memory may already record.","</system-reminder>"].join(`
|
|
507
|
+
`)})}),gQ=Y.fnUntraced(function*($){let{lastFinished:Z,model:X}=$;if(!Z||Z.summary===!0||!X)return;let Q=yield*$.config.get(),J=L6({cfg:Q,tokens:Z.tokens,model:X});if(J<2)return;let V=$.msgs.findLast((B)=>B.info.role==="user");if(!V||V.parts.some((B)=>B.type==="text"&&B.text?.includes("Context is filling up")))return;V.parts.push({id:Q2.ascending(),messageID:V.info.id,sessionID:$.sessionID,type:"text",synthetic:!0,text:["<system-reminder>",`Context is filling up (${J>=3?">85%":">70%"}).`,"If you have important learnings or decisions from this session,","consider writing them to memory now before context may be reset.","</system-reminder>"].join(`
|
|
508
|
+
`)})});function hQ($){if(!$.lastFinished)return;let Z=[];for(let J=$.msgs.length-1;J>=0&&Z.length<t9;J--){let V=$.msgs[J];if(V.info.role!=="assistant"||!V.info.finish)continue;let B=f8(V.parts);if(B===void 0)break;Z.push(B)}if(!(Z.length===t9&&Z.every((J)=>J===Z[0])))return;let Q=$.msgs.findLast((J)=>J.info.role==="user");if(!Q||Q.parts.some((J)=>J.type==="text"&&J.text?.includes("repeating the same action")))return;Q.parts.push({id:Q2.ascending(),messageID:Q.info.id,sessionID:$.sessionID,type:"text",synthetic:!0,text:["<system-reminder>",`Your last ${t9} steps have been identical \u2014 you appear to be`,"repeating the same action without making progress. Stop and reconsider:","the current approach is not working. Try a different strategy, use a","different tool, or if you are blocked, explain the blocker to the user","instead of repeating the same step again.","</system-reminder>"].join(`
|
|
509
|
+
`)})}var e9=s.create({service:"auto-dream"}),$Z=86400000,eK=7,$G=30,mQ=1e4,ZZ="Auto Dream",XZ="Auto Distill",fQ=0,EQ=0,lQ=["Run one automatic dream memory consolidation pass for the current project.","","Use the memory files as the working index and the raw qitqode trajectory database as the source of truth.","Use bash for read-only SQLite and filesystem inspection. Do not modify the database.","Consolidate only durable, verified information into project memory."].join(`
|
|
510
|
+
`),cQ=["Run one automatic distill pass for the current project.","","Review the past month of sessions and identify repeated manual workflows worth packaging.","Use the raw qitqode trajectory database as the source of truth and memory files to spot cross-session patterns.","Inventory existing skills, agents, and commands first so you reuse or extend instead of duplicating.","Use bash for read-only SQLite and filesystem inspection. Do not modify the database.","Produce a compact shortlist, then create only the high-confidence missing assets."].join(`
|
|
511
|
+
`);function oQ($){return Y.gen(function*(){if(!$.enabled)return!1;let Z=$.intervalDays*$Z,X=yield*Y.sync(()=>a2.use((V)=>V.select({time_created:k0.time_created}).from(k0).where(G0(k0.title,$.title)).orderBy(E8(k0.time_created)).limit(1).get())),Q=Date.now(),J=X?Q-X.time_created:1/0;if(!X){let V=yield*Y.sync(()=>a2.use((B)=>B.select({time_created:k0.time_created}).from(k0).where(vQ(k0.parent_id)).orderBy(dQ(k0.time_created)).limit(1).get()));if(!V||Q-V.time_created<Z)return e9.info(`auto-${$.label} skipped \u2014 project too young`,{projectAge:V?Math.round((Q-V.time_created)/$Z)+"d":"empty",interval:$.intervalDays+"d"}),!1}if(J<Z)return e9.info(`auto-${$.label} skipped \u2014 last run too recent`,{lastRunAgo:Math.round(J/$Z)+"d",interval:$.intervalDays+"d"}),!1;return e9.info(`auto-${$.label} triggering`,{lastRun:X?new Date(X.time_created).toISOString():"never",interval:$.intervalDays+"d"}),!0})}function uQ($){let Z=$.dream?.auto!==!1;if(!Z)return Y.succeed(!1);let X=Date.now();if(X-fQ<mQ)return Y.succeed(!1);fQ=X;let Q=$.dream?.interval_days??eK;return oQ({enabled:Z,intervalDays:Q,title:ZZ,label:"dream"})}function pQ($){let Z=$.distill?.auto!==!1;if(!Z)return Y.succeed(!1);let X=Date.now();if(X-EQ<mQ)return Y.succeed(!1);EQ=X;let Q=$.distill?.interval_days??$G;return oQ({enabled:Z,intervalDays:Q,title:XZ,label:"distill"})}var iQ=Y.fnUntraced(function*($){let Z=yield*$.config.get(),X=yield*uQ(Z).pipe(Y.catch(()=>Y.succeed(!1))),Q=yield*pQ(Z).pipe(Y.catch(()=>Y.succeed(!1))),J={providerID:$.lastUser.model.providerID,modelID:$.lastUser.model.modelID};if(!X&&!Q)return;let{AppRuntime:V}=yield*Y.promise(()=>import("./chunk-457y2816.js"));if(X)V.runPromise(E2.use((B)=>Y.gen(function*(){let D=yield*B.create({title:ZZ});yield*(yield*$.promptServiceTag).prompt({sessionID:D.id,agent:"dream",model:J,parts:[{type:"text",text:lQ}]})}))).catch((B)=>$.log.error("auto-dream prompt failed",{error:String(B)}));if(Q)V.runPromise(E2.use((B)=>Y.gen(function*(){let D=yield*B.create({title:XZ});yield*(yield*$.promptServiceTag).prompt({sessionID:D.id,agent:"distill",model:J,parts:[{type:"text",text:cQ}]})}))).catch((B)=>$.log.error("auto-distill prompt failed",{error:String(B)}))});var XG=($)=>$.pipe(Y.catchDefect((Z)=>Z instanceof $0.BackendAuthRejectedError?Y.succeed(void 0):Y.die(Z))),YZ=($)=>XG(Y.promise(()=>$0.resolvePrompt($))).pipe(Y.map((Z)=>Z??"")),nQ=Y.gen(function*(){let $=yield*YZ("session/build-switch"),Z=yield*YZ("session/max-steps"),X=yield*YZ("session/compose");return{buildSwitch:$,maxSteps:Z,promptCompose:X}});var sQ=E0.create({service:"session.prompt"}),YG=s.create({service:"session.prompt"});function aQ($,Z,X,Q){return Y.gen(function*(){let{bus:J,status:V,sessions:B,agents:D,provider:H,processor:W,prune:K,checkpoint:j,compaction:G,config:z,plugin:O,permission:P,fsys:w,registry:L,scope:F,instruction:U,state:y,goal:S,taskGateState:I,taskRegistry:M,revert:f,summary:b,sys:k,llm:h,actorRegistry:N,inbox:A}=yield*S4,R=yield*nQ,C=R.buildSwitch,T=R.maxSteps,l=R.promptCompose,d=(t,N2,j2)=>DQ(H,J,t,N2,j2),g=(t,N2)=>OQ(B,t,N2),E=a9(B),m=1024,e=new class extends Set{add(t){if(super.add(t),this.size>1024){let N2=this.values().next().value;if(N2!==void 0)this.delete(N2)}return this}},n=(t)=>o9({getOps:$,...t}),a=qQ({agents:D,provider:H,llm:h,sessions:B,elog:sQ}),H2=NQ({sessions:B,fsys:w,buildSwitch:C,promptCompose:l});return{runLoop:Y.fn("SessionPrompt.run")(function*(t,N2,j2){let g0=yield*v.context,R2=sQ.with({sessionID:t}),X2,q2=0,b2=yield*B.get(t),r2,w0,D0=N2??"main",p0=GQ({sessionID:t,agentID:D0,task_id:j2,plugin:O,bus:J,prune:K,scope:F}),{cancellation:h0,agentMetrics:M$,publishAgentRequest:i0,schedulePrune:n0}=p0,N1=KQ({sessionID:t,agentID:D0,task_id:j2,session:b2,cancellation:h0,plugin:O});return yield*Y.gen(function*(){yield*p0.before;let s0=(t2,Y2)=>g4(sY(t2,Y2,p.parts(Y2.id))),s$=!1,K8=kQ({sessionID:t,bus:J,appendSyntheticUserTurn:E,slog:R2}),f0=SQ({sessionID:t,sessions:B,bus:J,appendSyntheticUserTurn:E,slog:R2}),{autoContinueOutputLength:G8,autoContinueInvalidOutput:_Z,autoRetryStructuredOutput:oV,handleTextRepeat:uV,writeContentFilterError:IZ,writeModelError:RZ}=f0,CZ=FQ({sessionID:t,agentID:N2,agents:D,taskGateState:I,taskRegistry:M,appendSyntheticUserTurn:E,slog:R2}),SZ=PQ({sessionID:t,agentID:N2,session:b2,goal:S,bus:J,appendSyntheticUserTurn:E,slog:R2});while(!0){if(!N2||N2==="main")yield*V.set(t,{type:"busy"});yield*A.drain(t,N2??"main").pipe(Y.ignore),yield*R2.info("loop",{step:q2});let t2=yield*p.filterCompactedEffect(t,{contextFrom:b2.contextFrom,contextWatermark:b2.contextWatermark,agentID:N2??"main"}),Y2,TZ,a0,H7,b0,gZ=[];for(let W2=t2.length-1;W2>=0;W2--){let K0=t2[W2];if(!Y2&&K0.info.role==="user")Y2=K0.info,TZ=K0;if(!a0&&K0.info.role==="assistant")a0=K0.info,H7=K0;if(!b0&&K0.info.role==="assistant"&&K0.info.finish)b0=K0.info;if(Y2&&b0)break;if(!b0){let $6=K0.parts.filter((a$)=>a$.type==="subtask");gZ.push(...$6)}}if(!Y2)throw Error("No user message found in stream. This should never happen.");yield*TQ({sessionID:t,msgs:t2,checkpoint:j,config:z});let nV=H7?.parts.some((W2)=>W2.type==="tool"&&!W2.metadata?.providerExecuted)??!1;if(a0?.finish==="length"&&!nV&&Y2.id<a0.id&&(yield*G8({lastUser:Y2,assistant:a0})))continue;if(a0){let W2=d9({phase:"existing-assistant",lastUser:Y2,assistant:a0,parts:H7?.parts??[]});if(W2.type==="filtered"){yield*IZ({assistant:a0}),yield*R2.info("exiting loop",{classification:W2.type});break}if(W2.type==="failed"){yield*RZ({assistant:a0,reason:W2.reason}),yield*R2.info("exiting loop",{classification:W2.type,reason:W2.reason});break}if(W2.type==="think-only"||W2.type==="invalid"){let K0=W2.type==="invalid"?W2.reason:"think-only";if(yield*_Z({lastUser:Y2,assistant:a0,reason:K0}))continue;yield*R2.info("exiting loop",{classification:W2.type});break}if(W2.type==="final"&&W2.degraded)yield*R2.warn("degraded final on abnormal finish",{finish:a0.finish});if(W2.type!=="continue"){if(yield*CZ(Y2))continue;if(yield*SZ(Y2))continue;yield*R2.info("exiting loop",{classification:W2.type});break}}if(q2++,q2===1)yield*a({session:b2,modelID:Y2.model.modelID,providerID:Y2.model.providerID,history:t2}).pipe(Y.ignore,Y.forkIn(F));if(q2===1&&!b2.parentID)yield*iQ({config:z,lastUser:Y2,promptServiceTag:Q,log:YG});let r0=yield*d(Y2.model.providerID,Y2.model.modelID,t);w0=r0,r2=b0;let hZ=gZ.pop();if(hZ?.type==="subtask"){yield*n({task:hZ,model:r0,lastUser:Y2,sessionID:t,session:b2,msgs:t2});continue}let fZ=TZ;if(fZ?.parts.some((W2)=>W2.type==="compaction")){let W2=fZ.parts.find((a$)=>a$.type==="compaction"),K0=yield*B.messages({sessionID:t,agentID:Y2.agentID??"main"});if((yield*G.process({parentID:Y2.id,messages:K0,sessionID:t,auto:W2?.auto??!1,overflow:W2?.overflow,agentID:Y2.agentID}))==="stop")break;continue}yield*gQ({sessionID:t,msgs:t2,lastFinished:b0,model:r0,config:z}),hQ({sessionID:t,msgs:t2,lastFinished:b0});let _$=yield*D.get(Y2.agent),j7=_$?.native===!0&&_$?.hidden===!0;if(!s$&&!j7&&b0&&b0.tokens){let W2=yield*$();yield*K.fireCheckpoints({sessionID:t,model:r0,tokens:b0.tokens,promptOps:W2,agentID:Y2.agentID}).pipe(Y.ignore)}if(!s$&&b0&&b0.tokens){if(yield*BQ({config:z,checkpoint:j,compaction:G,prune:K},{sessionID:t,lastFinished:b0,lastUser:Y2,model:r0,msgs:t2,isBoundedComputation:j7})){s$=!0;continue}}if(s$=!1,!_$)throw yield*m9(D,J,Y2.agent,t);let sV=_$.steps??1/0,aV=q2>=sV;t2=yield*H2({messages:t2,agent:_$,session:b2});let EZ=E4({sessionID:t,parentID:Y2.id,agentID:Y2.agentID,agent:_$.name,variant:Y2.model.variant,cwd:g0.directory,root:g0.worktree,modelID:r0.id,providerID:r0.providerID});yield*B.updateMessage(EZ);let e2=yield*W.create({assistantMessage:EZ,sessionID:t,model:r0,agentMetrics:M$}),rV=yield*Y.gen(function*(){let W2={value:X2},K0=yield*aY({sessionID:t,resolvedAgentID:D0,step:q2,task_id:j2,lastUser:Y2,lastFinished:b0,msgs:t2,agent:_$,session:b2,model:r0,handle:e2,structured:W2,resolveTools:Z,createStructuredOutputTool:X,summary:b,scope:F,plugin:O}),{tools:$6,format:a$,query:tV}=K0,{cancelledByPlugin:eV,withUserQueryPost:$B}=rY({sessionID:t,agentID:D0,step:q2,lastUser:Y2,msgs:t2,query:tV,handle:e2,plugin:O,sessions:B,cancellation:h0,trajectoryForStep:s0}),ZB=Y.fnUntraced(function*(Z6){if(Z6==="continue"&&(yield*G8({lastUser:Y2,assistant:e2.message})))return"continue";if(Z6==="text-repeat"){if(yield*uV({lastUser:Y2}))return"continue";return"break"}if(W2.value!==void 0)return X2=W2.value,e2.message.structured=W2.value,e2.message.finish=e2.message.finish??"stop",yield*B.updateMessage(e2.message),"break";let B$=d9({phase:"after-process",lastUser:Y2,assistant:e2.message,parts:p.parts(e2.message.id),processResult:Z6});if(B$.type==="filtered")return yield*IZ({assistant:e2.message}),"break";if(B$.type==="failed")return yield*RZ({assistant:e2.message,reason:B$.reason}),"break";if(B$.type!=="continue"&&!e2.message.error&&a$.type==="json_schema"){if(yield*oV({lastUser:Y2,assistant:e2.message}))return"continue";return"break"}if((B$.type==="think-only"||B$.type==="invalid")&&a$.type!=="json_schema"){let XB=B$.type==="invalid"?B$.reason:"think-only";if(yield*_Z({lastUser:Y2,assistant:e2.message,reason:XB}))return"continue";return"break"}if(B$.type==="final"&&B$.degraded)yield*R2.warn("degraded final on abnormal finish",{finish:e2.message.finish});if(Z6==="stop")return"break";return}),D7=yield*QQ({sessionID:t,lastUser:Y2,agent:_$,session:b2,model:r0,msgs:t2,tools:$6,format:a$,handle:e2,isLastStep:aV,task_id:j2,instructionsNotified:e,maxStepsText:T,actorRegistry:N,bus:J,config:z,instruction:U,llm:h,registry:L,status:V,sys:k,cancelledByPlugin:eV,withUserQueryPost:$B,slog:R2});if(D7.kind==="break")return"break";let dZ=yield*ZB(D7.result);if(dZ)return dZ;if(D7.result==="overflow")yield*WQ({config:z,checkpoint:j,compaction:G,prune:K},{sessionID:t,lastUser:Y2,model:r0,msgs:t2,isBoundedComputation:j7});return"continue"}).pipe(Y.ensuring(U.clear(e2.message.id))),vZ=yield*K8.check({lastUser:Y2,completedParts:p.parts(e2.message.id)});if(vZ==="terminate")break;if(vZ==="recovered")continue;if(rV==="break"){if(yield*CZ(Y2))continue;if(yield*SZ(Y2))continue;break}continue}let pV=yield*$();if(w0&&r2)yield*n0({model:w0,lastFinished:r2,promptOps:pV});let e8=yield*g(t,N2),iV=e8.info.role==="assistant"&&!!e8.info.error,kZ=yield*B.findMessage(t,(t2)=>t2.info.role==="user",{agentID:"*"});return yield*i0(iV?"error":"completed",Y0.isSome(kZ)?kZ.value.info.agent:e8.info.agent),e8}).pipe((s0)=>l9(t,J,s0),Y.onExit(N1),Y.orDie)}),lastAssistant:g}})}import rQ from"path";var QG=new TextEncoder,QZ=new TextDecoder,JG=($)=>`
|
|
512
|
+
|
|
513
|
+
[... QitQode truncated ${$} bytes of shell output ...]
|
|
514
|
+
|
|
515
|
+
`;class JZ{head=new Uint8Array(262144);tail=new Uint8Array(786432);headBytes=0;tailBytes=0;tailStart=0;seenBytes=0;append($){let Z=QG.encode($);this.seenBytes=Math.min(Number.MAX_SAFE_INTEGER,this.seenBytes+Z.byteLength);let X=Math.min(Z.byteLength,262144-this.headBytes);if(X>0)this.head.set(Z.subarray(0,X),this.headBytes),this.headBytes+=X;if(X===Z.byteLength)return;let Q=Z.subarray(X);if(Q.byteLength>=this.tail.byteLength){this.tail.set(Q.subarray(Q.byteLength-this.tail.byteLength)),this.tailBytes=this.tail.byteLength,this.tailStart=0;return}let J=Math.max(0,this.tailBytes+Q.byteLength-this.tail.byteLength);this.tailStart=(this.tailStart+J)%this.tail.byteLength,this.tailBytes=Math.min(this.tail.byteLength,this.tailBytes+Q.byteLength);let V=(this.tailStart+this.tailBytes-Q.byteLength)%this.tail.byteLength,B=Math.min(Q.byteLength,this.tail.byteLength-V);if(this.tail.set(Q.subarray(0,B),V),B<Q.byteLength)this.tail.set(Q.subarray(B),0)}get totalBytes(){return this.seenBytes}get retainedBytes(){return this.headBytes+this.tailBytes}get truncated(){return this.seenBytes>this.retainedBytes}toString(){let $=new Uint8Array(this.retainedBytes);$.set(this.head.subarray(0,this.headBytes));let Z=Math.min(this.tailBytes,this.tail.byteLength-this.tailStart);if($.set(this.tail.subarray(this.tailStart,this.tailStart+Z),this.headBytes),Z<this.tailBytes)$.set(this.tail.subarray(0,this.tailBytes-Z),this.headBytes+Z);if(!this.truncated)return QZ.decode($);let X=QZ.decode($.subarray(0,this.headBytes)),Q=QZ.decode($.subarray(this.headBytes));return X+JG(this.seenBytes-this.retainedBytes)+Q}}var VG=50,BG=32768;function tQ($){return Y.gen(function*(){let Z=yield*E2,X=yield*$$.Service,Q=yield*h2.Service,J=yield*P2.Service,V=yield*u.Service,B=yield*K2.Service,D=yield*i1.ChildProcessSpawner;return Y.fn("SessionPrompt.shellImpl")(function*(H){let W=yield*v.context,K=yield*Z.get(H.sessionID);if(K.revert)yield*X.cleanup(K);let j=yield*d$(Q,V,H.agent,H.sessionID),G=yield*e1(J,H.modelRef,H.model),z=yield*e1(J,j.modelRef,j.model),O=G??z??(yield*$(H.sessionID)),P={id:H.messageID??x2.ascending(),sessionID:H.sessionID,time:{created:Date.now()},role:"user",agent:H.agent,model:{providerID:O.providerID,modelID:O.modelID}};yield*Z.updateMessage(P);let w={type:"text",id:Q2.ascending(),messageID:P.id,sessionID:H.sessionID,text:"The following tool was executed by the user",synthetic:!0};yield*Z.updatePart(w);let L={id:x2.ascending(),sessionID:H.sessionID,parentID:P.id,agentID:P.agentID,mode:H.agent,agent:H.agent,cost:0,path:{cwd:W.directory,root:W.worktree},time:{created:Date.now()},role:"assistant",tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:O.modelID,providerID:O.providerID};yield*Z.updateMessage(L);let F={type:"tool",id:Q2.ascending(),messageID:L.id,sessionID:H.sessionID,tool:"bash",callID:r1(),state:{status:"running",time:{start:Date.now()},input:{command:H.command}}};yield*Z.updatePart(F);let U=new JZ,y=!1,S=0,I=0,M=()=>({output:U.toString(),description:"",truncated:U.truncated,totalBytes:U.totalBytes}),f=Y.uninterruptible(Y.gen(function*(){if(y)U.append(`
|
|
516
|
+
|
|
517
|
+
`+["<metadata>","User aborted the command","</metadata>"].join(`
|
|
518
|
+
`));if(!L.time.completed)L.time.completed=Date.now(),yield*Z.updateMessage(L);if(F.state.status==="running"){let k=M();F.state={status:"completed",time:{...F.state.time,end:Date.now()},input:F.state.input,title:"",metadata:k,output:k.output},yield*Z.updatePart(F)}})),b=yield*Y.gen(function*(){let k=y1.preferred(),h=(process.platform==="win32"?rQ.win32.basename(k,".exe"):rQ.basename(k)).toLowerCase(),N={nu:{args:["-c",H.command]},fish:{args:["-c",H.command]},zsh:{args:["-l","-c",`
|
|
519
|
+
__oc_cwd=$PWD
|
|
520
|
+
[[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
|
|
521
|
+
[[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
|
|
522
|
+
cd "$__oc_cwd"
|
|
523
|
+
eval ${JSON.stringify(H.command)}
|
|
524
|
+
`]},bash:{args:["-l","-c",`
|
|
525
|
+
__oc_cwd=$PWD
|
|
526
|
+
shopt -s expand_aliases
|
|
527
|
+
[[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
|
|
528
|
+
cd "$__oc_cwd"
|
|
529
|
+
eval ${JSON.stringify(H.command)}
|
|
530
|
+
`]},cmd:{args:["/c",H.command]},powershell:{args:["-NoProfile","-Command",H.command]},pwsh:{args:["-NoProfile","-Command",H.command]},"":{args:["-c",H.command]}},A=(N[h]??N[""]).args,R=W.directory,C=yield*B.trigger("shell.env",{cwd:R,sessionID:H.sessionID,callID:F.callID},{env:{}}),T=n1.make(k,A,{cwd:R,extendEnv:!0,env:{...C.env,TERM:"dumb"},stdin:"ignore",forceKillAfter:"3 seconds"}),l=yield*D.spawn(T);yield*c2.runForEach(c2.decodeText(l.all),(d)=>Y.suspend(()=>{if(U.append(d),F.state.status!=="running")return Y.void;let g=Date.now();if(g-S<VG&&U.totalBytes-I<BG)return Y.void;return F.state.metadata=M(),S=g,I=U.totalBytes,Z.updatePart(F).pipe(Y.ignore)})),yield*l.exitCode}).pipe(Y.scoped,Y.onInterrupt(()=>Y.sync(()=>{y=!0})),Y.orDie,Y.ensuring(f),Y.exit);if(u2.isFailure(b)&&!G2.hasInterruptsOnly(b.cause))return yield*Y.failCause(b.cause);return{info:L,parts:[F]}})})}import $J from"path";import WG from"os";import{pathToFileURL as KG,fileURLToPath as GG}from"url";function eQ($){let Z=$.indexOf(",");if(Z===-1)return"";let X=$.slice(0,Z),Q=$.slice(Z+1);if(X.includes(";base64"))return Buffer.from(Q,"base64").toString("utf8");return decodeURIComponent(Q)}var O1=s.create({service:"session.prompt"}),ZJ=E0.create({service:"session.prompt"}),HG=393216;function XJ(){return Y.gen(function*(){let $=yield*E2,Z=yield*h2.Service,X=yield*P2.Service,Q=yield*u.Service,J=yield*K2.Service,V=yield*N0.Service,B=Y.fnUntraced(function*(O){let P=yield*$.findMessage(O,(w)=>w.info.role==="user"&&!!w.info.model,{agentID:"*"});if(Y0.isSome(P)&&P.value.info.role==="user")return P.value.info.model;return yield*X.defaultModel()}),D=yield*J$.Service,H=yield*n2.Service,W=yield*W0.Service,K=yield*G$.Service,j=Y.fn("SessionPrompt.resolvePromptParts")(function*(O){let P=yield*v.context,w=[{type:"text",text:O}],L=u4.files(O),F=new Set;return yield*Y.forEach(L,Y.fnUntraced(function*(U){let y=U[1];if(F.has(y))return;F.add(y);let S=y.startsWith("~/")?$J.join(WG.homedir(),y.slice(2)):$J.resolve(P.worktree,y),I=yield*H.stat(S).pipe(Y.option);if(Y0.isNone(I)){let f=yield*Z.get(y);if(f)w.push({type:"agent",name:f.name});return}let M=I.value;w.push({type:"file",url:KG(S).href,filename:y,mime:M.type==="Directory"?"application/x-directory":"text/plain"})}),{concurrency:16,discard:!0}),w}),G=Y.fn("SessionPrompt.createUserMessage")(function*(O){let P=O.agent||(yield*Z.defaultAgent()),w=yield*d$(Z,Q,P,O.sessionID),L=yield*e1(X,O.modelRef,O.model),F=yield*e1(X,w.modelRef,w.model),U=L??F??(yield*B(O.sessionID)),y=F&&U.providerID===F.providerID&&U.modelID===F.modelID,S=!O.variant&&w.variant&&y?yield*X.getModel(U.providerID,U.modelID).pipe(Y.catchDefect(()=>Y.void)):void 0,I=O.variant??(w.variant&&S?.variants?.[w.variant]?w.variant:void 0),M={id:O.messageID??x2.ascending(),role:"user",sessionID:O.sessionID,agentID:O.agentID,time:{created:Date.now()},tools:O.tools,agent:w.name,model:{providerID:U.providerID,modelID:U.modelID,variant:I},system:O.system,format:O.format,provenance:O.provenance};yield*Y.addFinalizer(()=>K.clear(M.id));let f=(N)=>({...N,id:N.id?Q2.make(N.id):Q2.ascending()}),b=Y.fn("SessionPrompt.resolveUserPart")(function*(N){if(N.type==="file"){if(N.source?.type==="resource"){let{clientName:R,uri:C}=N.source;O1.info("mcp resource",{clientName:R,uri:C,mime:N.mime});let T=[{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`Reading MCP resource: ${N.filename} (${C})`}],l=yield*V.readResource(R,C).pipe(Y.exit);if(u2.isSuccess(l)){let d=l.value;if(!d)throw Error(`Resource not found: ${R}/${C}`);let g=Array.isArray(d.contents)?d.contents:[d.contents];for(let E of g)if("text"in E&&E.text)T.push({messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:E.text});else if("blob"in E&&E.blob){let m="mimeType"in E?E.mimeType:N.mime;T.push({messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`[Binary content: ${m}]`})}T.push({...N,messageID:M.id,sessionID:O.sessionID})}else{let d=G2.squash(l.cause);O1.error("failed to read MCP resource",{error:d,clientName:R,uri:C});let g=d instanceof Error?d.message:String(d);T.push({messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`Failed to read MCP resource ${N.filename}: ${g}`})}return T}let A=new URL(N.url);switch(A.protocol){case"data:":if(N.mime==="text/plain")return[{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:N.filename})}`},{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:eQ(N.url)},{...N,messageID:M.id,sessionID:O.sessionID}];break;case"file:":{O1.info("file",{mime:N.mime});let R=GG(N.url);if(yield*H.isDir(R))N.mime="application/x-directory";let{read:C}=yield*W.named(),T=(d,g)=>{let E=new AbortController;return C.execute(d,{sessionID:O.sessionID,abort:E.signal,agent:O.agent,messageID:M.id,extra:{bypassCwdCheck:!0,...g},messages:[],metadata:()=>Y.void,ask:()=>Y.void}).pipe(Y.onInterrupt(()=>Y.sync(()=>E.abort())))};if(N.mime==="text/plain"){let d,g,E={start:A.searchParams.get("start"),end:A.searchParams.get("end")};if(E.start!=null){let a=N.url.split("?")[0],H2=parseInt(E.start,10),I2=E.end?parseInt(E.end,10):void 0;if(H2===I2){let t=yield*D.documentSymbol(a).pipe(Y.catch(()=>Y.succeed([])));for(let N2 of t){let j2;if("range"in N2)j2=N2.range;else if("location"in N2)j2=N2.location.range;if(j2?.start?.line&&j2?.start?.line===H2){H2=j2.start.line,I2=j2?.end?.line??H2;break}}}if(Number.isFinite(H2)&&H2>=1){if(d=Math.max(H2,1),I2!=null&&Number.isFinite(I2)&&I2>=H2)g=I2-(d-1)}}let m={filePath:R,offset:d,limit:g},e=[{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(m)}`}],n=yield*X.getModel(M.model.providerID,M.model.modelID).pipe(Y.flatMap((a)=>T(m,{model:a})),Y.exit);if(u2.isSuccess(n)){let a=n.value;if(e.push({messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:a.output}),a.attachments?.length)e.push(...a.attachments.map((H2)=>({...H2,synthetic:!0,filename:H2.filename??N.filename,messageID:M.id,sessionID:O.sessionID})));else e.push({...N,messageID:M.id,sessionID:O.sessionID})}else{let a=G2.squash(n.cause);O1.error("failed to read file",{error:a});let H2=a instanceof Error?a.message:String(a);yield*Q.publish(U2.Error,{sessionID:O.sessionID,error:new w2.Unknown({message:H2}).toObject()}),e.push({messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${R} with the following error: ${H2}`})}return e}if(N.mime==="application/x-directory"){let d={filePath:R},g=yield*T(d).pipe(Y.exit);if(u2.isFailure(g)){let E=G2.squash(g.cause);O1.error("failed to read directory",{error:E});let m=E instanceof Error?E.message:String(E);return yield*Q.publish(U2.Error,{sessionID:O.sessionID,error:new w2.Unknown({message:m}).toObject()}),[{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${R} with the following error: ${m}`}]}return[{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(d)}`},{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:g.value.output},{...N,messageID:M.id,sessionID:O.sessionID}]}let l=yield*H.stat(R).pipe(Y.option);if(Y0.isNone(l)||Number(l.value.size)>HG)return[{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:Y0.isNone(l)?`File not found: ${R}`:`Attachment omitted because it exceeds the 384 KB inline limit: ${R}`}];return[{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: {"filePath":"${R}"}`},{id:N.id,messageID:M.id,sessionID:O.sessionID,type:"file",url:`data:${N.mime};base64,`+Buffer.from(yield*H.readFile(R).pipe(Y.catch(Y.die))).toString("base64"),mime:N.mime,filename:N.filename,source:N.source}]}}}if(N.type==="agent"){let R=O2.evaluate("task",N.name,w.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return[{...N,messageID:M.id,sessionID:O.sessionID},{messageID:M.id,sessionID:O.sessionID,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the actor tool with subagent: "+N.name+R}]}return[{...N,messageID:M.id,sessionID:O.sessionID}]}),k=yield*Y.forEach(O.parts,b,{concurrency:8}).pipe(Y.map((N)=>N.flat().map(f)));yield*J.trigger("chat.message",{sessionID:O.sessionID,agent:O.agent,model:O.model,messageID:O.messageID,variant:O.variant},{message:M,parts:k});let h=p.Info.safeParse(M);if(!h.success)O1.error("invalid user message before save",{sessionID:O.sessionID,messageID:M.id,agent:M.agent,model:M.model,issues:h.error.issues});k.forEach((N,A)=>{let R=p.Part.safeParse(N);if(R.success)return;O1.error("invalid user part before save",{sessionID:O.sessionID,messageID:M.id,partID:N.id,partType:N.type,index:A,issues:R.error.issues,part:N})}),yield*$.updateMessage(M);for(let N of k)yield*$.updatePart(N);return{info:M,parts:k}},Y.scoped),z=Y.fn("SessionPrompt.sweepOrphanAssistants")(function*(O){let P=yield*$.messages({sessionID:O,agentID:"*"}),w=Date.now(),L=3600000;for(let F of P){if(F.info.role!=="assistant")continue;if(F.info.time?.completed)continue;let U=F.info.time?.created??0;if(w-U<3600000)continue;F.info.time={...F.info.time,completed:w},F.info.error=F.info.error??new p.AbortedError({message:"Abandoned: previous request interrupted before completion"}).toObject(),yield*$.updateMessage(F.info).pipe(Y.catchCause((y)=>ZJ.warn("orphan-update-failed",{sessionID:O,messageID:F.info.id,cause:y}))),yield*ZJ.info("orphan-assistant-cleared",{sessionID:O,messageID:F.info.id})}});return{resolvePromptParts:j,createUserMessage:G,sweepOrphanAssistants:z,lastModel:B}})}var jG=E0.create({service:"session.prompt"}),DG=/!`([^`]+)`/g,yG=/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi,YJ=/\$(\d+)/g,VZ=/^["']|["']$/g;function JJ($,Z,X){return Y.gen(function*(){let Q=yield*h2.Service,J=yield*x0.Service,V=yield*F0.Service,B=yield*u.Service,D=yield*K2.Service;return Y.fn("SessionPrompt.command")(function*(W){yield*jG.info("command",{sessionID:W.sessionID,command:W.command,agent:W.agent});let K=yield*J.get(W.command);if(!K){let b=(yield*J.list()).map((N)=>N.name),k=b.length?` Available commands: ${b.join(", ")}`:"",h=new w2.Unknown({message:`Command not found: "${W.command}".${k}`});throw yield*B.publish(U2.Error,{sessionID:W.sessionID,error:h.toObject()}),h}let j=K.agent??W.agent??(yield*Q.defaultAgent());if(W.command===x0.Default.GOAL){let b=W.arguments.trim();if(b===""||b==="clear"||b==="reset")return yield*V.clear(W.sessionID),yield*$({sessionID:W.sessionID,messageID:W.messageID,agent:j,parts:[{type:"text",text:"Goal cleared.",synthetic:!0}],noReply:!0});yield*V.set(W.sessionID,b)}let z=(W.arguments.match(yG)??[]).map((b)=>b.replace(VZ,"")),O=yield*Y.promise(async()=>K.template),P;if(K.source==="skill")P=W.arguments;else{let b=O.match(YJ)??[],k=0;for(let A of b){let R=Number(A.slice(1));if(R>k)k=R}let h=O.replaceAll(YJ,(A,R)=>{let C=Number(R),T=C-1;if(T>=z.length)return"";if(C===k)return z.slice(T).join(" ");return z[T]}),N=O.includes("$ARGUMENTS");if(P=h.replaceAll("$ARGUMENTS",W.arguments),b.length===0&&!N&&W.arguments.trim())P=P+`
|
|
531
|
+
|
|
532
|
+
`+W.arguments}let w=u4.shell(P);if(w.length>0){let b=y1.preferred(),k=yield*Y.promise(()=>Promise.all(w.map(async([,N])=>(await QJ.text([N],{shell:b,nothrow:!0})).text))),h=0;P=P.replace(DG,()=>k[h++])}P=P.trim();let L=yield*Y.gen(function*(){if(K.model)return P2.parseModel(K.model);if(K.agent){let b=yield*Q.get(K.agent);if(b?.model)return b.model}if(W.model)return P2.parseModel(W.model);return yield*X(W.sessionID)});yield*d4(L.providerID,L.modelID,W.sessionID);let F=yield*d$(Q,B,j,W.sessionID),U=yield*Z(P),y=F.mode==="subagent"&&K.subtask!==!1||K.subtask===!0,S;if(y){let b=K.source==="skill"?O+(W.arguments.trim()?`
|
|
533
|
+
|
|
534
|
+
`+W.arguments:""):U.find((k)=>k.type==="text")?.text??"";S=[{type:"subtask",agent:F.name,description:K.description??"",command:W.command,model:{providerID:L.providerID,modelID:L.modelID},prompt:b}]}else if(K.source==="skill"){let b=W.arguments.trim()?`/${W.command} ${W.arguments}`:`/${W.command}`,k={type:"text",text:`<skill_content name="${W.command}">
|
|
535
|
+
${O}
|
|
536
|
+
</skill_content>`,synthetic:!0},h=U.filter((N)=>N.type!=="text");S=[{type:"text",text:b},k,...h,...W.parts??[]]}else S=[...U,...W.parts??[]];let I=y?W.agent??(yield*Q.defaultAgent()):j,M=y?W.model?P2.parseModel(W.model):yield*X(W.sessionID):L;yield*D.trigger("command.execute.before",{command:W.command,sessionID:W.sessionID,arguments:W.arguments},{parts:S});let f=yield*$({sessionID:W.sessionID,messageID:W.messageID,model:M,agent:I,parts:S,variant:W.variant});return yield*B.publish(x0.Event.Executed,{name:W.command,sessionID:W.sessionID,arguments:W.arguments,messageID:f.info.id}),f})})}var VJ=q.object({sessionID:F2.zod,messageID:x2.zod.optional(),model:q.object({providerID:$1.zod,modelID:t0.zod}).optional(),modelRef:q.string().optional().describe("Model group/tier name (e.g. fast/economical/default/power) or a literal provider/model. Resolved provider-aware. Takes precedence over `model` when both are set."),agent:q.string().optional(),agentID:q.string().optional(),task_id:q.string().optional().describe("If the spawning caller bound this prompt to a specific user-task (T4 etc), pass its TID. Propagates to Tool.Context.taskId so memory-path-guard allows writes to tasks/<task_id>/*.md."),source:q.enum(["user","spawn","hook"]).optional(),provenance:p.Provenance.optional(),noReply:q.boolean().optional(),tools:q.record(q.string(),q.boolean()).optional().describe("@deprecated tools and permissions have been merged, you can set permissions on the session itself now"),format:p.Format.optional(),system:q.string().optional(),variant:q.string().optional(),parts:q.array(q.discriminatedUnion("type",[p.TextPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"TextPartInput"}),p.FilePart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"FilePartInput"}),p.AgentPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"AgentPartInput"}),p.SubtaskPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"SubtaskPartInput"})]))}),BJ=q.object({sessionID:F2.zod,agentID:q.string().optional(),task_id:q.string().optional()}),WJ=q.object({sessionID:F2.zod,messageID:x2.zod.optional(),agent:q.string(),model:q.object({providerID:$1.zod,modelID:t0.zod}).optional(),modelRef:q.string().optional().describe("Model group/tier name (e.g. fast/economical/default/power) or a literal provider/model. Resolved provider-aware. Takes precedence over `model` when both are set."),command:q.string()}),KJ=q.object({messageID:x2.zod.optional(),sessionID:F2.zod,agent:q.string().optional(),model:q.string().optional(),arguments:q.string(),command:q.string(),variant:q.string().optional(),parts:q.array(q.discriminatedUnion("type",[p.FilePart.omit({messageID:!0,sessionID:!0}).partial({id:!0})])).optional()});var OG="You predict the single most likely next message a user will send to a coding assistant, based on the conversation so far. Output only that next message as one short, natural first-person request (what the user would type). No preamble, no quotes, no explanation, no markdown. Keep it under 100 characters.",FG="Based on the conversation above, write the user's most likely next message:",aL=s.create({service:"session.prompt"}),PG=E0.create({service:"session.prompt"});class v8 extends Z2.Service()("@qitqode/SessionPrompt"){}var HJ=_.effect(v8,Y.gen(function*(){let{bus:$,status:Z,sessions:X,agents:Q,provider:J,processor:V,prune:B,checkpoint:D,compaction:H,config:W,plugin:K,permission:j,fsys:G,registry:z,scope:O,instruction:P,state:w,goal:L,taskGateState:F,taskRegistry:U,revert:y,summary:S,sys:I,llm:M,actorRegistry:f,inbox:b}=yield*S4,k=yield*x0.Service,h=yield*N0.Service,N=yield*J$.Service,A=yield*j1.Service,R=(X2)=>Y.gen(function*(){let q2={system:[],tools:{},inheritedMessages:[],parentPermission:[]},b2=yield*Q.get(X2.agentName).pipe(Y.catch(()=>Y.succeed(void 0)));if(!b2)return q2;let r2=yield*J.getModel(X2.providerID,X2.modelID).pipe(Y.catch(()=>Y.succeed(void 0)));if(!r2)return q2;let w0=yield*X.get(X2.sessionID).pipe(Y.catch(()=>Y.succeed(void 0)));if(!w0)return q2;let[D0,p0,h0]=yield*Y.all([I.skills(b2),Y.sync(()=>I.environment(r2,w0.time.created)),P.system().pipe(Y.orDie)]),M$=[...p0,...D0?[D0]:[],...h0.content];return{...yield*L4({sessionID:X2.sessionID,agent:b2,model:r2,msgs:X2.msgs,additions:M$}).pipe(Y.provideService(f2.Service,M),Y.provideService(W0.Service,z),Y.catch(()=>Y.succeed(q2))),parentPermission:b2.permission}});p4.current=R,yield*Y.addFinalizer(()=>Y.sync(()=>{if(p4.current===R)p4.current=void 0}));let C=Y.fn("SessionPrompt.runner")(function*(){return yield*P0.make()}),T=Y.fn("SessionPrompt.ops")(function*(){let X2=yield*C();return{cancel:(q2)=>X2.fork(l(q2)),resolvePromptParts:(q2)=>d(q2),prompt:(q2)=>t(q2)}}),l=Y.fn("SessionPrompt.cancel")(function*(X2){yield*PG.info("cancel",{sessionID:X2}),yield*w.cancel(X2)}),{resolvePromptParts:d,createUserMessage:g,sweepOrphanAssistants:E,lastModel:m}=yield*XJ(),e=yield*uY(T),{runLoop:n,lastAssistant:a}=yield*aQ(T,e,C4,v8),H2=yield*tQ(m),I2=Y.fn("SessionPrompt.predict")(function*(X2){if((yield*W.get()).experimental?.predict_next_prompt===!1)return"";let b2=yield*X.messages({sessionID:X2.sessionID,agentID:"main"}),r2=(f0)=>f0.info.role==="user"&&!f0.parts.every((G8)=>("synthetic"in G8)&&G8.synthetic),w0=b2.findLastIndex(r2);if(w0===-1)return"";let D0=b2[w0];if(D0.info.role!=="user")return"";let p0=b2.slice(w0+1).filter((f0)=>f0.info.role==="assistant");if(p0.length===0)return"";if(p0.some((f0)=>f0.info.time.completed===void 0))return"";let h0=p0[p0.length-1],M$=yield*Q.get("title");if(!M$)return"";let i0={...M$,prompt:OG},n0=i0.modelRef?yield*J.resolveModelRef(i0.modelRef,h0.info.providerID):i0.model?yield*J.getModel(i0.model.providerID,i0.model.modelID):(yield*J.getSmallModel(h0.info.providerID))??(yield*J.getModel(h0.info.providerID,h0.info.modelID)),N1=yield*p.toModelMessagesEffect([D0,h0],n0,{stripMedia:!0}),s0=yield*M.stream({agent:i0,user:D0.info,system:[],small:!0,tools:{},model:n0,sessionID:X2.sessionID,retries:1,messages:[...N1,{role:"user",content:FG}]}).pipe(l4((f0)=>f0.type==="text-delta"),m4((f0)=>f0.text),c4,Y.orElseSucceed(()=>"")),s$=g8(s0);if(!s$)return"";let K8=s$.replace(VZ,"");return K8.length>120?K8.substring(0,117)+"...":K8}),t=Y.fn("SessionPrompt.prompt")(function*(X2){let q2=yield*X.get(X2.sessionID);if(X2.source!=="spawn"&&X2.source!=="hook")yield*y.cleanup(q2),yield*E(X2.sessionID);let b2=yield*g(X2);yield*X.touch(X2.sessionID);let r2=[];for(let[w0,D0]of Object.entries(X2.tools??{}))r2.push({permission:w0,action:D0?"allow":"deny",pattern:"*"});if(r2.length>0)q2.permission=r2,yield*X.setPermission({sessionID:q2.id,permission:r2});if(X2.noReply===!0)return b2;return yield*N2({sessionID:X2.sessionID,agentID:X2.agentID??"main",task_id:X2.task_id})}),N2=Y.fn("SessionPrompt.loop")(function*(X2){let q2=X2.agentID??"main",b2=a(X2.sessionID,q2),r2=n(X2.sessionID,q2,X2.task_id);return yield*w.ensureRunning(X2.sessionID,q2,b2,r2)}),j2=Y.fn("SessionPrompt.shell")(function*(X2){let q2=a(X2.sessionID),b2=H2(X2);return yield*w.startShell(X2.sessionID,q2,b2)}),g0=yield*JJ(t,d,m),R2=v8.of({cancel:l,prompt:t,loop:N2,shell:j2,command:g0,resolvePromptParts:d,sweepOrphanAssistants:E,predict:I2});return G1.current={loop:R2.loop},yield*Y.addFinalizer(()=>Y.sync(()=>{if(G1.current?.loop===R2.loop)G1.current=void 0})),R2})),zG=_.suspend(()=>HJ.pipe(_.provide(O0.defaultLayer),_.provide(y0.defaultLayer),_.provide(z$.defaultLayer),_.provide(P$.defaultLayer),_.provide(F$.defaultLayer),_.provide(d0.defaultLayer),_.provide(x0.defaultLayer),_.provide(O2.defaultLayer),_.provide(N0.defaultLayer),_.provide(J$.defaultLayer),_.provide(W0.defaultLayer),_.provide(j1.defaultLayer),_.provide(P2.defaultLayer),_.provide(G$.defaultLayer),_.provide(n2.defaultLayer),_.provide(K2.defaultLayer),_.provide(v0),_.provide($$.defaultLayer),_.provide(_.mergeAll(V2.defaultLayer,q0.defaultLayer,GJ.defaultLayer,M2.defaultLayer,h2.defaultLayer,D$.defaultLayer,f2.defaultLayer,u.layer,s1,o0.defaultLayer,F0.defaultLayer,H1.defaultLayer,_0.defaultLayer))));var F1={};L2(F1,{layer:()=>zJ,defaultLayer:()=>MG,Service:()=>X8,Mode:()=>LG,Info:()=>UG,FileDiff:()=>AG,Event:()=>PJ});import qG from"path";var jJ=s.create({service:"vcs"}),DJ=($)=>{if(!$)return 0;if(!$.endsWith(`
|
|
537
|
+
`))return $.split(`
|
|
538
|
+
`).length;return $.slice(0,-1).split(`
|
|
539
|
+
`).length},NG=Y.fnUntraced(function*($,Z,X){let Q=qG.join(Z,X);if(!(yield*$.exists(Q).pipe(Y.orDie)))return"";let J=yield*$.readFile(Q).pipe(Y.catch(()=>Y.succeed(new Uint8Array)));if(Buffer.from(J).includes(0))return"";return Buffer.from(J).toString("utf8")}),FJ=($)=>new Map($.map((Z)=>[Z.file,{additions:Z.additions,deletions:Z.deletions}])),xG=(...$)=>{let Z=new Map;return $.flat().forEach((X)=>{if(!Z.has(X.file))Z.set(X.file,X)}),[...Z.values()]},BZ=Y.fnUntraced(function*($,Z,X,Q,J,V){let B=Q?yield*Z.prefix(X):"",D=(W,K,j)=>OJ(yJ(W,W,K,j,"","",{context:Number.MAX_SAFE_INTEGER}));return(yield*Y.forEach(J,(W)=>Y.gen(function*(){let K=W.status==="added"||!Q?"":yield*Z.show(X,Q,W.file,B),j=W.status==="deleted"?"":yield*NG($,X,W.file),G=V.get(W.file);return{file:W.file,patch:D(W.file,K,j),additions:G?.additions??(W.status==="added"?DJ(j):0),deletions:G?.deletions??(W.status==="deleted"?DJ(K):0),status:W.status}}),{concurrency:8})).toSorted((W,K)=>W.file.localeCompare(K.file))}),wG=Y.fnUntraced(function*($,Z,X,Q){if(!Q)return yield*BZ($,Z,X,Q,yield*Z.status(X),new Map);let[J,V]=yield*Y.all([Z.status(X),Z.stats(X,Q)],{concurrency:2});return yield*BZ($,Z,X,Q,J,FJ(V))}),bG=Y.fnUntraced(function*($,Z,X,Q){let[J,V,B]=yield*Y.all([Z.diff(X,Q),Z.stats(X,Q),Z.status(X)],{concurrency:3});return yield*BZ($,Z,X,Q,xG(J,B.filter((D)=>D.code==="??")),FJ(V))}),LG=q.enum(["git","branch"]),PJ={BranchUpdated:D2.define("vcs.branch.updated",q.object({branch:q.string().optional()}))},UG=q.object({branch:q.string().optional(),default_branch:q.string().optional()}).meta({ref:"VcsInfo"}),AG=q.object({file:q.string(),patch:q.string(),additions:q.number(),deletions:q.number(),status:q.enum(["added","deleted","modified"]).optional()}).meta({ref:"VcsFileDiff"});class X8 extends Z2.Service()("@qitqode/Vcs"){}var zJ=_.effect(X8,Y.gen(function*(){let $=yield*n2.Service,Z=yield*l$.Service,X=yield*u.Service,Q=yield*d2.Scope,J=yield*v.make(Y.fn("Vcs.state")(function*(V){if(V.project.vcs!=="git")return{current:void 0,root:void 0};let B=Y.fnUntraced(function*(){return yield*Z.branch(V.directory)}),[D,H]=yield*Y.all([Z.branch(V.directory),Z.defaultBranch(V.directory)],{concurrency:2}),W={current:D,root:H};return jJ.info("initialized",{branch:W.current,default_branch:W.root?.name}),yield*X.subscribe(c$.Event.Updated).pipe(c2.filter((K)=>K.properties.file.endsWith("HEAD")),c2.runForEach((K)=>Y.gen(function*(){let j=yield*B();if(j!==W.current)jJ.info("branch changed",{from:W.current,to:j}),W.current=j,yield*X.publish(PJ.BranchUpdated,{branch:j})})),Y.forkScoped),W}));return X8.of({init:Y.fn("Vcs.init")(function*(){yield*v.get(J).pipe(Y.forkIn(Q))}),branch:Y.fn("Vcs.branch")(function*(){return yield*v.use(J,(V)=>V.current)}),defaultBranch:Y.fn("Vcs.defaultBranch")(function*(){return yield*v.use(J,(V)=>V.root?.name)}),diff:Y.fn("Vcs.diff")(function*(V){let B=yield*v.get(J),D=yield*v.context;if(D.project.vcs!=="git")return[];if(V==="git")return yield*wG($,Z,D.directory,(yield*Z.hasHead(D.directory))?"HEAD":void 0);if(!B.root)return[];if(B.current&&B.current===B.root.name)return[];let H=yield*Z.mergeBase(D.directory,B.root.ref);if(!H)return[];return yield*bG($,Z,D.directory,H)})})})),MG=zJ.pipe(_.provide(l$.defaultLayer),_.provide(n2.defaultLayer),_.provide(u.layer));var o$={};L2(o$,{layer:()=>dJ,defaultLayer:()=>dG,Worktree:()=>o$,StartCommandFailedError:()=>fG,Service:()=>X7,ResetInput:()=>hG,ResetFailedError:()=>T0,RemoveInput:()=>gG,RemoveFailedError:()=>q1,NotGitError:()=>Z7,NameGenerationFailedError:()=>EJ,Info:()=>fJ,Event:()=>$7,CreateInput:()=>TG,CreateFailedError:()=>vJ});var A$={};L2(A$,{layer:()=>bJ,defaultLayer:()=>GZ,Service:()=>Q8});var P1=s.create({service:"share-next"}),Y8=process.env.QITQODE_DISABLE_SHARE==="true"||process.env.QITQODE_DISABLE_SHARE==="1",_G=c0.Struct({id:c0.String,url:c0.String,secret:c0.String});class Q8 extends Z2.Service()("@qitqode/ShareNext"){}var WZ=($)=>Y.sync(()=>a2.use($));function wJ($){return{create:`/api/${$}`,sync:(Z)=>`/api/${$}/${Z}/sync`,remove:(Z)=>`/api/${$}/${Z}`,data:(Z)=>`/api/${$}/${Z}/data`}}var IG=wJ("share"),RG=wJ("shares");function qJ($){switch($.type){case"session":return"session";case"message":return`message/${$.data.id}`;case"part":return`part/${$.data.messageID}/${$.data.id}`;case"session_diff":return"session_diff";case"model":return"model"}}var bJ=_.effect(Q8,Y.gen(function*(){let $=yield*d8.Service,Z=yield*u.Service,X=yield*V2.Service,Q=yield*KZ.HttpClient,J=KZ.filterStatusOk(Q),V=yield*P2.Service,B=yield*J2.Service;function D(F,U){return Y.gen(function*(){if(Y8)return;if(!(yield*j(F)))return;let S=yield*v.get(H),I=S.queue.get(F);if(I){for(let f of U)I.set(qJ(f),f);return}let M=new Map(U.map((f)=>[qJ(f),f]));S.queue.set(F,M),yield*G(F).pipe(Y.delay(1000),Y.catchCause((f)=>Y.sync(()=>{P1.error("share flush failed",{sessionID:F,cause:f})})),Y.forkIn(S.scope))})}let H=yield*v.make(Y.fn("ShareNext.state")(function*(F){let U={queue:new Map,scope:yield*d2.make(),shared:new Map};if(yield*Y.addFinalizer(()=>d2.close(U.scope,u2.void).pipe(Y.andThen(Y.sync(()=>{U.queue.clear(),U.shared.clear()})))),Y8)return U;let y=(S,I)=>Z.subscribe(S).pipe(c2.runForEach((M)=>I(M).pipe(Y.catchCause((f)=>Y.sync(()=>{P1.error("share subscriber failed",{type:S.type,cause:f})})))),Y.forkScoped);return yield*y(J2.Event.Updated,(S)=>Y.gen(function*(){let I=yield*B.get(S.properties.sessionID);yield*D(I.id,[{type:"session",data:I}])})),yield*y(p.Event.Updated,(S)=>Y.gen(function*(){let I=S.properties.info;if(yield*D(I.sessionID,[{type:"message",data:I}]),I.role!=="user")return;let M=yield*V.getModel(I.model.providerID,I.model.modelID);yield*D(I.sessionID,[{type:"model",data:[M]}])})),yield*y(p.Event.PartUpdated,(S)=>S.properties.part.type==="compaction"?Y.void:D(S.properties.part.sessionID,[{type:"part",data:S.properties.part}])),yield*y(J2.Event.Diff,(S)=>D(S.properties.sessionID,[{type:"session_diff",data:S.properties.diff}])),yield*y(J2.Event.Deleted,(S)=>L(S.properties.sessionID)),U})),W=Y.fn("ShareNext.request")(function*(){let F={},U=yield*$.active();if(Y0.isNone(U)||!U.value.active_org_id){let S=(yield*X.get()).enterprise?.url??"https://opncd.ai";return{headers:F,api:IG,baseUrl:S}}let y=yield*$.token(U.value.id);if(Y0.isNone(y))throw Error("No active account token available for sharing");return F.authorization=`Bearer ${y.value}`,F["x-org-id"]=U.value.active_org_id,{headers:F,api:RG,baseUrl:U.value.url}}),K=Y.fnUntraced(function*(F){let U=yield*WZ((y)=>y.select().from(z1).where(G0(z1.session_id,F)).get());if(!U)return;return{id:U.id,secret:U.secret,url:U.url}}),j=Y.fnUntraced(function*(F){let U=yield*v.get(H);if(U.shared.has(F)){let S=U.shared.get(F);return S===null?void 0:S}let y=yield*K(F);return U.shared.set(F,y??null),y}),G=Y.fn("ShareNext.flush")(function*(F){if(Y8)return;let U=yield*v.get(H),y=U.queue.get(F);if(!y)return;let S=yield*j(F);if(!S){U.queue.delete(F);return}let I=yield*W(),M=yield*H$.post(`${I.baseUrl}${I.api.sync(S.id)}`).pipe(H$.setHeaders(I.headers),H$.bodyJson({secret:S.secret,data:Array.from(y.values())}),Y.flatMap((f)=>Q.execute(f)));if(M.status>=400){P1.warn("failed to sync share",{sessionID:F,shareID:S.id,status:M.status});return}U.queue.delete(F)}),z=Y.fn("ShareNext.full")(function*(F){P1.info("full sync",{sessionID:F});let U=yield*B.get(F),y=yield*B.diff(F),S=yield*Y.sync(()=>Array.from(p.stream(F,{agentID:"*"}))),I=yield*Y.forEach(Array.from(new Map(S.filter((M)=>M.info.role==="user").map((M)=>M.info.model).map((M)=>[`${M.providerID}/${M.modelID}`,M])).values()),(M)=>V.getModel($1.make(M.providerID),t0.make(M.modelID)),{concurrency:8});yield*D(F,[{type:"session",data:U},...S.map((M)=>({type:"message",data:M.info})),...S.flatMap((M)=>M.parts.filter((f)=>f.type!=="compaction").map((f)=>({type:"part",data:f}))),{type:"session_diff",data:y},{type:"model",data:I}])}),O=Y.fn("ShareNext.init")(function*(){if(Y8)return;yield*v.get(H)}),P=Y.fn("ShareNext.url")(function*(){return(yield*W()).baseUrl}),w=Y.fn("ShareNext.create")(function*(F){if(Y8)return{id:"",url:"",secret:""};P1.info("creating share",{sessionID:F});let U=yield*W(),y=yield*H$.post(`${U.baseUrl}${U.api.create}`).pipe(H$.setHeaders(U.headers),H$.bodyJson({sessionID:F}),Y.flatMap((I)=>J.execute(I)),Y.flatMap(NJ.schemaBodyJson(_G)));yield*WZ((I)=>I.insert(z1).values({session_id:F,id:y.id,secret:y.secret,url:y.url}).onConflictDoUpdate({target:z1.session_id,set:{id:y.id,secret:y.secret,url:y.url}}).run());let S=yield*v.get(H);return S.shared.set(F,y),yield*z(F).pipe(Y.catchCause((I)=>Y.sync(()=>{P1.error("share full sync failed",{sessionID:F,cause:I})})),Y.forkIn(S.scope)),y}),L=Y.fn("ShareNext.remove")(function*(F){if(Y8)return;P1.info("removing share",{sessionID:F});let U=yield*v.get(H),y=yield*j(F);if(!y){U.shared.delete(F),U.queue.delete(F);return}let S=yield*W();yield*H$.delete(`${S.baseUrl}${S.api.remove(y.id)}`).pipe(H$.setHeaders(S.headers),H$.bodyJson({secret:y.secret}),Y.flatMap((I)=>J.execute(I))),yield*WZ((I)=>I.delete(z1).where(G0(z1.session_id,F)).run()),U.shared.delete(F),U.queue.delete(F)});return Q8.of({init:O,url:P,request:W,create:w,remove:L})})),GZ=bJ.pipe(_.provide(u.layer),_.provide(d8.defaultLayer),_.provide(V2.defaultLayer),_.provide(xJ.layer),_.provide(P2.defaultLayer),_.provide(J2.defaultLayer));var n4={};L2(n4,{layer:()=>LJ,defaultLayer:()=>CG,Service:()=>i4});class i4 extends Z2.Service()("@qitqode/SessionShare"){}var LJ=_.effect(i4,Y.gen(function*(){let $=yield*V2.Service,Z=yield*J2.Service,X=yield*Q8,Q=yield*d2.Scope,J=Y.fn("SessionShare.share")(function*(D){if((yield*$.get()).share==="disabled")throw Error("Sharing is disabled in configuration");let W=yield*X.create(D);return yield*Y.sync(()=>A1.run(J2.Event.Updated,{sessionID:D,info:{share:{url:W.url}}})),W}),V=Y.fn("SessionShare.unshare")(function*(D){yield*X.remove(D),yield*Y.sync(()=>A1.run(J2.Event.Updated,{sessionID:D,info:{share:{url:null}}}))}),B=Y.fn("SessionShare.create")(function*(D){let H=yield*Z.create(D);if(H.parentID)return H;let W=yield*$.get();if(!(L0.QITQODE_AUTO_SHARE||W.share==="auto"))return H;return yield*J(H.id).pipe(Y.ignore,Y.forkIn(Q)),H});return i4.of({create:B,share:J,unshare:V})})),CG=LJ.pipe(_.provide(GZ),_.provide(J2.defaultLayer),_.provide(V2.defaultLayer));var SJ=MJ(function*(){s.Default.info("bootstrapping",{directory:S2.directory}),yield*V2.Service.use(($)=>$.get()),yield*K2.Service.use(($)=>$.init()),yield*UJ([J$.Service,A$.Service,J8.Service,V8.Service,c$.Service,X8,z0.Service,RJ,CJ].map(($)=>jZ($.use((Z)=>Z.init())))).pipe(HZ("InstanceBootstrap.init")),yield*y$.Service.use(($)=>$.reconcile()).pipe(_J(($)=>AJ(()=>s.Default.warn("memory reconcile failed",{error:String($)}))),jZ),yield*u.Service.use(($)=>$.subscribeCallback(x0.Event.Executed,async(Z)=>{if(Z.properties.name===x0.Default.INIT)IJ(S2.project.id)})),yield*C2.subscribe()}).pipe(HZ("InstanceBootstrap"));var kG=_.mergeAll(V2.defaultLayer,K2.defaultLayer,A$.defaultLayer,J8.defaultLayer,J$.defaultLayer,V8.defaultLayer,c$.defaultLayer,F1.defaultLayer,z0.defaultLayer,u.defaultLayer,y$.defaultLayer,t4.defaultLayer).pipe(_.provide(a4)),kJ=s4.make(kG,{memoMap:r4});var m8=s.create({service:"worktree"}),$7={Ready:D2.define("worktree.ready",q.object({name:q.string(),branch:q.string()})),Failed:D2.define("worktree.failed",q.object({message:q.string()}))},fJ=q.object({name:q.string(),branch:q.string(),directory:q.string()}).meta({ref:"Worktree"}),TG=q.object({name:q.string().optional(),startCommand:q.string().optional().describe("Additional startup script to run after the project's start command")}).meta({ref:"WorktreeCreateInput"}),gG=q.object({directory:q.string()}).meta({ref:"WorktreeRemoveInput"}),hG=q.object({directory:q.string()}).meta({ref:"WorktreeResetInput"}),Z7=w2.create("WorktreeNotGitError",q.object({message:q.string()})),EJ=w2.create("WorktreeNameGenerationFailedError",q.object({message:q.string()})),vJ=w2.create("WorktreeCreateFailedError",q.object({message:q.string()})),fG=w2.create("WorktreeStartCommandFailedError",q.object({message:q.string()})),q1=w2.create("WorktreeRemoveFailedError",q.object({message:q.string()})),T0=w2.create("WorktreeResetFailedError",q.object({message:q.string()}));function EG($){return $.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}function vG(...$){return $.filter(Boolean).flatMap((Z)=>Z.split(`
|
|
540
|
+
`).map((X)=>X.trim()).flatMap((X)=>{let Q=X.match(/^warning:\s+failed to remove\s+(.+):\s+/i);if(!Q)return[];let J=Q[1]?.trim().replace(/^['"]|['"]$/g,"");if(!J)return[];return[J]}))}class X7 extends Z2.Service()("@qitqode/Worktree"){}var dJ=_.effect(X7,Y.gen(function*(){let $=yield*d2.Scope,Z=yield*n2.Service,X=yield*TJ.Path,Q=yield*i1.ChildProcessSpawner,J=yield*l$.Service,V=yield*U$.Service,B=Y.fnUntraced(function*(A,R){return yield*hJ(Q,A,R)},Y.catch((A)=>Y.succeed({code:1,text:"",stderr:A instanceof Error?A.message:String(A)}))),D=26,H=Y.fn("Worktree.candidate")(function*(A,R){let C=yield*v.context;for(let T of Array.from({length:26},(l,d)=>d)){let l=R?T===0?R:`${R}-${yZ.create()}`:yZ.create(),d=`qitqode/${l}`,g=X.join(A,l);if(yield*Z.exists(g).pipe(Y.orDie))continue;let E=`refs/heads/${d}`;if((yield*B(["show-ref","--verify","--quiet",E],{cwd:C.worktree})).code===0)continue;return fJ.parse({name:l,branch:d,directory:g})}throw new EJ({message:"Failed to generate a unique worktree name"})}),W=Y.fn("Worktree.makeWorktreeInfo")(function*(A){let R=yield*v.context;if(R.project.vcs!=="git")throw new Z7({message:"Worktrees are only supported for git projects"});let C=X.join(q$.Path.data,"worktree",R.project.id);yield*Z.makeDirectory(C,{recursive:!0}).pipe(Y.orDie);let T=A?EG(A):"";return yield*H(C,T||void 0)}),K=Y.fnUntraced(function*(A){let R=yield*v.context,C=yield*B(["worktree","add","--no-checkout","-b",A.branch,A.directory],{cwd:R.worktree});if(C.code!==0)throw new vJ({message:C.stderr||C.text||"Failed to create git worktree"});yield*V.addSandbox(R.project.id,A.directory).pipe(Y.catch(()=>Y.void))}),j=Y.fnUntraced(function*(A,R){let C=yield*v.context,T=yield*v.workspaceID,l=C.project.id,d=R?.trim(),g=yield*B(["reset","--hard"],{cwd:A.directory});if(g.code!==0){let m=g.stderr||g.text||"Failed to populate worktree";m8.error("worktree checkout failed",{directory:A.directory,message:m}),e4.emit("event",{directory:A.directory,project:C.project.id,workspace:T,payload:{type:$7.Failed.type,properties:{message:m}}});return}if(!(yield*Y.promise(()=>S2.provide({directory:A.directory,init:()=>kJ.runPromise(SJ),fn:()=>{return}}).then(()=>!0).catch((m)=>{let e=O$(m);return m8.error("worktree bootstrap failed",{directory:A.directory,message:e}),e4.emit("event",{directory:A.directory,project:C.project.id,workspace:T,payload:{type:$7.Failed.type,properties:{message:e}}}),!1}))))return;e4.emit("event",{directory:A.directory,project:C.project.id,workspace:T,payload:{type:$7.Ready.type,properties:{name:A.name,branch:A.branch}}}),yield*M(A.directory,{projectID:l,extra:d})}),G=Y.fn("Worktree.createFromInfo")(function*(A,R){yield*K(A),yield*j(A,R)}),z=Y.fn("Worktree.create")(function*(A){let R=yield*W(A?.name);return yield*K(R),yield*j(R,A?.startCommand).pipe(Y.catchCause((C)=>Y.sync(()=>m8.error("worktree bootstrap failed",{cause:C}))),Y.forkIn($)),R}),O=Y.fnUntraced(function*(A){let R=X.resolve(A),C=yield*Z.realPath(R).pipe(Y.catch(()=>Y.succeed(R))),T=X.normalize(C);return process.platform==="win32"?T.toLowerCase():T});function P(A){return A.split(`
|
|
541
|
+
`).map((R)=>R.trim()).reduce((R,C)=>{if(!C)return R;if(C.startsWith("worktree "))return R.push({path:C.slice(9).trim()}),R;let T=R[R.length-1];if(!T)return R;if(C.startsWith("branch "))T.branch=C.slice(7).trim();return R},[])}let w=Y.fnUntraced(function*(A,R){for(let C of A){if(!C.path)continue;if((yield*O(C.path))===R)return C}return});function L(A){return Z.exists(A).pipe(Y.orDie,Y.flatMap((R)=>R?B(["fsmonitor--daemon","stop"],{cwd:A}):Y.void))}function F(A){return Y.promise(()=>import("fs/promises").then((R)=>R.rm(A,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})).catch((R)=>{let C=O$(R);throw new q1({message:C||"Failed to remove git worktree directory"})}))}let U=Y.fn("Worktree.remove")(function*(A){let R=yield*v.context;if(R.project.vcs!=="git")throw new Z7({message:"Worktrees are only supported for git projects"});let C=yield*O(A.directory),T=yield*B(["worktree","list","--porcelain"],{cwd:R.worktree});if(T.code!==0)throw new q1({message:T.stderr||T.text||"Failed to read git worktrees"});let l=P(T.text),d=yield*w(l,C);if(!d?.path){if(!(yield*Z.exists(C).pipe(Y.orDie)))return!0;let e=yield*O(X.join(q$.Path.data,"worktree",R.project.id));if(C!==e&&!C.startsWith(`${e}${X.sep}`))throw new q1({message:"Directory is not a registered or managed worktree"});return yield*L(C),yield*F(C),!0}yield*L(d.path);let g=yield*B(["worktree","remove","--force",d.path],{cwd:R.worktree});if(g.code!==0){let m=yield*B(["worktree","list","--porcelain"],{cwd:R.worktree});if(m.code!==0)throw new q1({message:g.stderr||g.text||m.stderr||m.text||"Failed to remove git worktree"});if((yield*w(P(m.text),C))?.path)throw new q1({message:g.stderr||g.text||"Failed to remove git worktree"})}yield*F(d.path);let E=d.branch?.replace(/^refs\/heads\//,"");if(E){let m=yield*B(["branch","-D",E],{cwd:R.worktree});if(m.code!==0)throw new q1({message:m.stderr||m.text||"Failed to delete worktree branch"})}return!0}),y=Y.fnUntraced(function*(A,R,C){let T=yield*B(A,R);if(T.code!==0)throw C(T);return T}),S=Y.fnUntraced(function*(A,R){let[C,T]=process.platform==="win32"?["cmd",["/c",R]]:["bash",["-lc",R]],l=yield*Q.spawn(n1.make(C,T,{cwd:A,extendEnv:!0,stdin:"ignore"})),[,d]=yield*Y.all([c2.runDrain(l.stdout),c2.mkString(c2.decodeText(l.stderr))],{concurrency:2}).pipe(Y.orDie);return{code:yield*l.exitCode,stderr:d}},Y.scoped,Y.catch(()=>Y.succeed({code:1,stderr:""}))),I=Y.fnUntraced(function*(A,R,C){let T=R.trim();if(!T)return!0;let l=yield*S(A,T);if(l.code===0)return!0;return m8.error("worktree start command failed",{kind:C,directory:A,message:l.stderr}),!1}),M=Y.fnUntraced(function*(A,R){let C=yield*Y.sync(()=>a2.use((g)=>g.select().from(DZ).where(G0(DZ.id,R.projectID)).get())),l=(C?U$.fromRow(C):void 0)?.commands?.start?.trim()??"";if(!(yield*I(A,l,"project")))return!1;return yield*I(A,R.extra??"","worktree"),!0}),f=Y.fnUntraced(function*(A,R){let C=yield*O(A);yield*Y.forEach(R,(T)=>Y.gen(function*(){let l=yield*O(X.resolve(A,T));if(l===C)return;if(!l.startsWith(`${C}${X.sep}`))return;yield*Z.remove(l,{recursive:!0}).pipe(Y.ignore)}),{concurrency:8})}),b=Y.fnUntraced(function*(A){let R=yield*B(["clean","-ffdx"],{cwd:A});if(R.code===0)return R;let C=vG(R.stderr,R.text);if(!C.length)return R;return yield*f(A,C),yield*B(["clean","-ffdx"],{cwd:A})}),k=Y.fn("Worktree.reset")(function*(A){let R=yield*v.context;if(R.project.vcs!=="git")throw new Z7({message:"Worktrees are only supported for git projects"});let C=yield*O(A.directory),T=yield*O(R.worktree);if(C===T)throw new T0({message:"Cannot reset the primary workspace"});let l=yield*B(["worktree","list","--porcelain"],{cwd:R.worktree});if(l.code!==0)throw new T0({message:l.stderr||l.text||"Failed to read git worktrees"});let d=yield*w(P(l.text),C);if(!d?.path)throw new T0({message:"Worktree not found"});let g=d.path,E=yield*J.defaultBranch(R.worktree);if(!E)throw new T0({message:"Default branch not found"});let m=E.ref.indexOf("/");if(E.ref!==E.name&&m>0){let a=E.ref.slice(0,m),H2=E.ref.slice(m+1);yield*y(["fetch",a,H2],{cwd:R.worktree},(I2)=>new T0({message:I2.stderr||I2.text||`Failed to fetch ${E.ref}`}))}yield*y(["reset","--hard",E.ref],{cwd:g},(a)=>new T0({message:a.stderr||a.text||"Failed to reset worktree to target"}));let e=yield*b(g);if(e.code!==0)throw new T0({message:e.stderr||e.text||"Failed to clean worktree"});yield*y(["submodule","update","--init","--recursive","--force"],{cwd:g},(a)=>new T0({message:a.stderr||a.text||"Failed to update submodules"})),yield*y(["submodule","foreach","--recursive","git","reset","--hard"],{cwd:g},(a)=>new T0({message:a.stderr||a.text||"Failed to reset submodules"})),yield*y(["submodule","foreach","--recursive","git","clean","-fdx"],{cwd:g},(a)=>new T0({message:a.stderr||a.text||"Failed to clean submodules"}));let n=yield*B(["-c","core.fsmonitor=false","status","--porcelain=v1"],{cwd:g});if(n.code!==0)throw new T0({message:n.stderr||n.text||"Failed to read git status"});if(n.text.trim())throw new T0({message:`Worktree reset left local changes:
|
|
542
|
+
${n.text.trim()}`});return yield*M(g,{projectID:R.project.id}).pipe(Y.catchCause((a)=>Y.sync(()=>m8.error("worktree start task failed",{cause:a}))),Y.forkIn($)),!0}),h=Y.fn("Worktree.head")(function*(A){return(yield*B(["rev-parse","HEAD"],{cwd:A})).text.trim()}),N=Y.fn("Worktree.isPristine")(function*(A,R){let C=yield*B(["status","--porcelain"],{cwd:A});if(C.code!==0)return!1;if(C.text.trim()!=="")return!1;let T=yield*B(["rev-parse","HEAD"],{cwd:A});return T.code===0&&T.text.trim()===R});return X7.of({makeWorktreeInfo:W,createFromInfo:G,create:z,remove:U,reset:k,head:h,isPristine:N})})),dG=dJ.pipe(_.provide(l$.defaultLayer),_.provide(s1),_.provide(U$.defaultLayer),_.provide(n2.defaultLayer),_.provide(gJ.layer));var u8={};L2(u8,{layer:()=>pJ,defaultLayer:()=>iG,UpdateInput:()=>pG,Service:()=>Y7,Pty:()=>u8,Info:()=>FZ,Event:()=>o8,CreateInput:()=>uG});function mJ($){let Z,X=!1;return()=>{if(X)return Z;return X=!0,Z=$(),Z}}var mG=c0.String.annotate({[cJ]:B8.schema("pty")}).pipe(c0.brand("PtyID")),l8=mG.pipe(lJ(($)=>({ascending:(Z)=>$.make(B8.ascending("pty",Z)),zod:B8.schema("pty").pipe(q.custom())})));var c8=s.create({service:"pty"}),oJ=2097152,uJ=65536,lG=new TextEncoder,OZ=($)=>$.data&&typeof $.data==="object"?$.data:$,cG=($)=>{let Z=JSON.stringify({cursor:$}),X=lG.encode(Z),Q=new Uint8Array(X.length+1);return Q[0]=0,Q.set(X,1),Q},oG=mJ(()=>import("./chunk-g1dwbvkg.js")),FZ=q.object({id:l8.zod,title:q.string(),command:q.string(),args:q.array(q.string()),cwd:q.string(),status:q.enum(["running","exited"]),pid:q.number()}).meta({ref:"Pty"}),uG=q.object({command:q.string().optional(),args:q.array(q.string()).optional(),cwd:q.string().optional(),title:q.string().optional(),env:q.record(q.string(),q.string()).optional()}),pG=q.object({title:q.string().optional(),size:q.object({rows:q.number(),cols:q.number()}).optional()}),o8={Created:D2.define("pty.created",q.object({info:FZ})),Updated:D2.define("pty.updated",q.object({info:FZ})),Exited:D2.define("pty.exited",q.object({id:l8.zod,exitCode:q.number()})),Deleted:D2.define("pty.deleted",q.object({id:l8.zod}))};class Y7 extends Z2.Service()("@qitqode/Pty"){}var pJ=_.effect(Y7,Y.gen(function*(){let $=yield*u.Service,Z=yield*K2.Service;function X(G){try{G.process.kill()}catch{}for(let[z,O]of G.subscribers.entries())try{if(OZ(O)===z)O.close()}catch{}G.subscribers.clear()}let Q=yield*v.make(Y.fn("Pty.state")(function*(G){let z={dir:G.directory,sessions:new Map};return yield*Y.addFinalizer(()=>Y.sync(()=>{for(let O of z.sessions.values())X(O);z.sessions.clear()})),z})),J=Y.fn("Pty.remove")(function*(G){let z=yield*v.get(Q),O=z.sessions.get(G);if(!O)return;z.sessions.delete(G),c8.info("removing session",{id:G}),X(O),yield*$.publish(o8.Deleted,{id:O.info.id})}),V=Y.fn("Pty.list")(function*(){let G=yield*v.get(Q);return Array.from(G.sessions.values()).map((z)=>z.info)}),B=Y.fn("Pty.get")(function*(G){return(yield*v.get(Q)).sessions.get(G)?.info}),D=Y.fn("Pty.create")(function*(G){let z=yield*v.get(Q),O=yield*P0.make(),P=l8.ascending(),w=G.command||y1.preferred(),L=G.args||[];if(y1.login(w))L.push("-l");let F=G.cwd||z.dir,U=yield*Z.trigger("shell.env",{cwd:F},{env:{}}),y={...q4(),...G.env,...U.env,TERM:"xterm-256color",QITQODE_TERMINAL:"1"};if(process.platform==="win32")y.LC_ALL="C.UTF-8",y.LC_CTYPE="C.UTF-8",y.LANG="C.UTF-8";c8.info("creating session",{id:P,cmd:w,args:L,cwd:F});let{spawn:S}=yield*Y.promise(()=>oG()),I=yield*Y.sync(()=>S(w,L,{name:"xterm-256color",cwd:F,env:y})),M={id:P,title:G.title||`Terminal ${P.slice(-4)}`,command:w,args:L,cwd:F,status:"running",pid:I.pid},f={info:M,process:I,buffer:"",bufferCursor:0,cursor:0,subscribers:new Map};return z.sessions.set(P,f),I.onData(S2.bind((b)=>{f.cursor+=b.length;for(let[h,N]of f.subscribers.entries()){if(N.readyState!==1){f.subscribers.delete(h);continue}if(OZ(N)!==h){f.subscribers.delete(h);continue}try{N.send(b)}catch{f.subscribers.delete(h)}}if(f.buffer+=b,f.buffer.length<=oJ)return;let k=f.buffer.length-oJ;f.buffer=f.buffer.slice(k),f.bufferCursor+=k})),I.onExit(S2.bind(({exitCode:b})=>{if(f.info.status==="exited")return;c8.info("session exited",{id:P,exitCode:b}),f.info.status="exited",O.fork($.publish(o8.Exited,{id:P,exitCode:b})),O.fork(J(P))})),yield*$.publish(o8.Created,{info:M}),M}),H=Y.fn("Pty.update")(function*(G,z){let P=(yield*v.get(Q)).sessions.get(G);if(!P)return;if(z.title)P.info.title=z.title;if(z.size)P.process.resize(z.size.cols,z.size.rows);return yield*$.publish(o8.Updated,{info:P.info}),P.info}),W=Y.fn("Pty.resize")(function*(G,z,O){let w=(yield*v.get(Q)).sessions.get(G);if(w&&w.info.status==="running")w.process.resize(z,O)}),K=Y.fn("Pty.write")(function*(G,z){let P=(yield*v.get(Q)).sessions.get(G);if(P&&P.info.status==="running")P.process.write(z)}),j=Y.fn("Pty.connect")(function*(G,z,O){let w=(yield*v.get(Q)).sessions.get(G);if(!w){z.close();return}c8.info("client connected to session",{id:G});let L=OZ(z);w.subscribers.delete(L),w.subscribers.set(L,z);let F=()=>{w.subscribers.delete(L)},U=w.bufferCursor,y=w.cursor,S=O===-1?y:typeof O==="number"&&Number.isSafeInteger(O)?Math.max(0,O):0,I=(()=>{if(!w.buffer)return"";if(S>=y)return"";let M=Math.max(0,S-U);if(M>=w.buffer.length)return"";return w.buffer.slice(M)})();if(I)try{for(let M=0;M<I.length;M+=uJ)z.send(I.slice(M,M+uJ))}catch{F(),z.close();return}try{z.send(cG(y))}catch{F(),z.close();return}return{onMessage:(M)=>{w.process.write(typeof M==="string"?M:new TextDecoder().decode(M))},onClose:()=>{c8.info("client disconnected from session",{id:G}),F()}}});return Y7.of({list:V,get:B,create:D,update:H,remove:J,resize:W,write:K,connect:j})})),iG=pJ.pipe(_.provide(u.layer),_.provide(K2.defaultLayer));var n8={};L2(n8,{layer:()=>aJ,defaultLayer:()=>rG,Service:()=>V7,MAX_PRE_REACT:()=>nJ,MAX_POST_REACT:()=>sJ,Actor:()=>n8});var Q7=($,Z,X)=>Y.uninterruptible(Y.gen(function*(){let Q=yield*M2.Service;yield*Q.updateStatus($,Z,{status:"running"}).pipe(Y.ignore);let J=yield*X.pipe(Y.interruptible,Y.exit);if(u2.isSuccess(J))return yield*Q.updateStatus($,Z,{status:"idle",lastOutcome:"success",lastError:void 0}).pipe(Y.ignore),J.value;let V=J.cause,B=G2.hasInterruptsOnly(V);return yield*Q.updateStatus($,Z,{status:"idle",lastOutcome:B?"cancelled":"failure",lastError:B?void 0:nG(V)}).pipe(Y.ignore),yield*Y.failCause(V)}));function nG($){return G2.pretty($)}var J7=s.create({service:"actor.spawn"}),nJ=3,sJ=3,aG=`
|
|
543
|
+
|
|
544
|
+
---
|
|
545
|
+
|
|
546
|
+
## Return format (required)
|
|
547
|
+
|
|
548
|
+
Your FINAL assistant message \u2014 what the spawning agent will receive \u2014 MUST start with this header block:
|
|
549
|
+
|
|
550
|
+
**Status**: success | partial | failed | blocked
|
|
551
|
+
**Summary**: <one sentence describing what happened>
|
|
552
|
+
|
|
553
|
+
After the header, include the actual deliverable (whatever the task asked for in its prompt).
|
|
554
|
+
|
|
555
|
+
If applicable, also include below the deliverable:
|
|
556
|
+
|
|
557
|
+
**Files touched**: <comma-separated paths or "(none)">
|
|
558
|
+
**Findings worth promoting**: <bullet list of cross-task transferable facts; "(none)" if just routine work>
|
|
559
|
+
|
|
560
|
+
This format lets the spawning agent and the checkpoint writer extract your progress without parsing free-form prose. Do NOT precede the header with an introduction \u2014 your final message must start with "**Status**:".
|
|
561
|
+
`;class V7 extends Z2.Service()("@qitqode/Actor"){}var aJ=_.effect(V7,Y.gen(function*(){let $=yield*J2.Service,Z=yield*M2.Service,X=yield*h2.Service,Q=yield*m$.Service,J=yield*o0.Service,V=yield*O0.Service,B=yield*K2.Service,D=yield*u.Service,H=yield*_0.Service,W=yield*d2.Scope,K=new Map,j=Y.fn("Actor.runAgentLoop")(function*(y){let S=yield*Q.prompt({sessionID:y.sessionID,agent:y.agentType,agentID:y.actorID,source:y.source,provenance:y.provenance,model:y.model,task_id:y.task_id,parts:[{type:"text",text:y.task}],...y.format?{format:y.format}:{}}),I=S?.info,M=I?.role==="assistant"?I.structured:void 0;return{finalText:M!==void 0?void 0:S?.parts.findLast((b)=>b.type==="text")?.text,structured:M}}),G=(y)=>Y.gen(function*(){let S=yield*k2.make(),I=y.description??y.agentType;if(y.task_id)yield*H.start({session_id:y.parentSessionID,id:y.task_id,owner:y.actorID}).pipe(Y.ignoreCause({log:"Warn",message:`auto-start of task ${y.task_id} failed`}));let M=(C,T)=>y.background&&y.agentType!=="checkpoint-writer"?J.send({receiverSessionID:y.parentSessionID,receiverActorID:y.parentActorID??"main",senderSessionID:y.sessionID,senderActorID:y.actorID,type:"actor_notification",content:CY({actorID:y.actorID,description:I,status:C,...T})}).pipe(Y.ignore):Y.void,f=y.parentSessionID===y.sessionID?"subagent":"peer",b=yield*X.get(y.agentType),k=b?!O2.disabled(["write"],b.permission).has("write"):!0,h=Y.gen(function*(){let C,T,l=0,d;while(!0){let g=l>0?d:void 0,E=yield*Q7(y.sessionID,y.actorID,j({...y,task:g?g.reason:y.task,source:g?"hook":"spawn",provenance:g?{hookPhase:"pre",hookIteration:l,pluginNames:g.contributingPluginNames,hookIDs:g.contributingHookIDs}:void 0}));if(C=E.finalText,T=E.structured,l++,l>nJ){yield*D.publish(p8.ReActMaxReached,{phase:"pre",actorID:y.actorID,agentType:y.agentType}),J7.warn("actor.preStop hit MAX_PRE_REACT cap; skipping further hook checks",{actorID:y.actorID,totalTurns:l});break}let m=yield*B.triggerActorPreStop({sessionID:y.sessionID,parentSessionID:y.parentSessionID,actorID:y.actorID,parentActorID:y.parentActorID,agentType:y.agentType,mode:f,lifecycle:y.lifecycle,finalText:C,task:y.task,description:y.description,task_id:y.task_id,iteration:l-1});if(!m.continue)break;if(!m.reason)break;yield*D.publish(p8.ReActReentered,{phase:"pre",actorID:y.actorID,agentType:y.agentType,iteration:l,triggeredByPlugins:m.contributingPluginNames,reasonPreview:m.reason.slice(0,200)}),d={reason:m.reason,contributingPluginNames:m.contributingPluginNames,contributingHookIDs:m.contributingHookIDs}}return{finalText:C,structured:T}}).pipe(Y.provideService(M2.Service,Z),Y.matchCauseEffect({onSuccess:({finalText:C,structured:T})=>Y.gen(function*(){let l=C;if(y.gateEligible){let j2=0;while(!0){let g0=yield*D1.decide({session_id:y.parentSessionID,owner:y.actorID,reactCount:j2,maxReact:u9,mode:"subagent"}).pipe(Y.provideService(_0.Service,H));if(!g0.needReentry)break;j2++;let R2=yield*Q7(y.sessionID,y.actorID,j({...y,task:g0.reentryText,source:"hook",provenance:{hookPhase:"post",hookIteration:j2,pluginNames:[],hookIDs:[]}})).pipe(Y.catch(()=>Y.gen(function*(){return J7.error("actor.gate runTurn failed",{actorID:y.actorID}),{finalText:void 0,structured:void 0}})),Y.provideService(M2.Service,Z));if(R2.finalText!==void 0)l=R2.finalText;if(R2.structured!==void 0)T=R2.structured}}let d=y.gateEligible?yield*H.list({session_id:y.parentSessionID,owner:y.actorID,include_terminal:!1}).pipe(Y.orElseSucceed(()=>[])):[],E=d.filter((j2)=>j2.status==="open"||j2.status==="in_progress").length>0?"partial":d.length>0?"blocked":void 0,m=iJ(l),e=E??m.status,n=d.map((j2)=>j2.id),a=E&&n.length>0?`${l??""}
|
|
562
|
+
|
|
563
|
+
**Incomplete tasks**: ${n.join(", ")}`:l,H2=T!==void 0?JSON.stringify(T):a??"(no output)";yield*M("completed",{result:H2,...e?{reportedStatus:e}:{},...m.summary?{reportedSummary:m.summary}:{}}),yield*k2.succeed(S,{status:"success",...a!==void 0?{finalText:a}:{},...T!==void 0?{structured:T}:{},...e?{reportedStatus:e}:{},...m.summary?{reportedSummary:m.summary}:{},...n.length>0?{incompleteTasks:n}:{}});let I2=0,t=C,N2;while(!0){let j2=yield*B.triggerActorPostStop({sessionID:y.sessionID,parentSessionID:y.parentSessionID,actorID:y.actorID,parentActorID:y.parentActorID,agentType:y.agentType,mode:f,lifecycle:y.lifecycle,finalText:t,task:y.task,description:y.description,task_id:y.task_id,outcome:"success",iteration:I2,canWrite:k});if(!j2.continue)break;if(!j2.reason)break;if(I2>=sJ){yield*D.publish(p8.ReActMaxReached,{phase:"post",actorID:y.actorID,agentType:y.agentType}),J7.warn("actor.postStop hit MAX_POST_REACT cap; skipping further hook checks",{actorID:y.actorID,totalTurns:I2+1});break}I2++,yield*D.publish(p8.ReActReentered,{phase:"post",actorID:y.actorID,agentType:y.agentType,iteration:I2,triggeredByPlugins:j2.contributingPluginNames,reasonPreview:j2.reason.slice(0,200)}),N2={reason:j2.reason,contributingPluginNames:j2.contributingPluginNames,contributingHookIDs:j2.contributingHookIDs};let g0=yield*Q7(y.sessionID,y.actorID,j({...y,task:N2.reason,source:"hook",provenance:{hookPhase:"post",hookIteration:I2,pluginNames:N2.contributingPluginNames,hookIDs:N2.contributingHookIDs}})).pipe(Y.catch(()=>Y.gen(function*(){return J7.error("actor.postStop runTurn failed",{actorID:y.actorID}),{finalText:void 0,structured:void 0}})),Y.provideService(M2.Service,Z));if(g0.finalText===void 0)break;t=g0.finalText}yield*Y.sync(()=>K.delete(y.actorID))}),onFailure:(C)=>Y.gen(function*(){let T=G2.hasInterruptsOnly(C),l=G2.pretty(C);yield*M(T?"cancelled":"failed",T?{}:{error:l}),yield*k2.succeed(S,T?{status:"cancelled"}:{status:"failure",error:l}),yield*Y.sync(()=>K.delete(y.actorID))})})),N=yield*I0;return{fiber:yield*(N?h.pipe(Y.provideService(I0,N)):h).pipe(Y.forkIn(W)),outcome:S}}),z=Y.fn("Actor.spawnPeer")(function*(y){let S=yield*$.create({parentID:y.sessionID,contextFrom:y.context==="full"?y.sessionID:void 0,title:`${y.agentType}: ${y.task.slice(0,40)}`});if(yield*Z.register({sessionID:S.id,actorID:S.id,mode:"peer",parentActorID:y.parentActorID,agent:y.agentType,description:y.description??y.agentType,contextMode:y.context,contextWatermark:void 0,background:y.background,lifecycle:y.lifecycle??"persistent",tools:y.tools}),y.forkContext)K.set(S.id,y.forkContext);let{fiber:I,outcome:M}=yield*G({sessionID:S.id,parentSessionID:y.sessionID,parentActorID:y.parentActorID,actorID:S.id,agentType:y.agentType,task:y.task,description:y.description,background:y.background,model:y.model,lifecycle:y.lifecycle??"persistent",task_id:y.task_id,format:y.format});if(!y.background)yield*i8.join(I).pipe(Y.ignore);return{actorID:S.id,sessionID:S.id,outcome:M}}),O=Y.fn("Actor.spawnSubagent")(function*(y){let S=yield*Z.allocateActorID(y.sessionID,y.agentType),I=y.context==="full"?yield*$.lastMainMessageID(y.sessionID):void 0;if(yield*Z.register({sessionID:y.sessionID,actorID:S,mode:"subagent",parentActorID:y.parentActorID,agent:y.agentType,description:y.description??y.agentType,contextMode:y.context,contextWatermark:I,background:y.background,lifecycle:y.lifecycle??"ephemeral",tools:y.tools}),y.onActorID)yield*Y.sync(()=>y.onActorID(S)).pipe(Y.ignore);if(y.forkContext)K.set(S,y.forkContext);let M=yield*X.get(y.agentType),f=M?.mode==="subagent"&&!M?.prompt&&y.agentType!=="checkpoint-writer",b=f?y.task+aG:y.task,{fiber:k,outcome:h}=yield*G({sessionID:y.sessionID,parentSessionID:y.parentSessionID??y.sessionID,parentActorID:y.parentActorID,actorID:S,agentType:y.agentType,task:b,description:y.description,background:y.background,model:y.model,lifecycle:y.lifecycle??"ephemeral",task_id:y.task_id,gateEligible:f,format:y.format});if(y.onReady)yield*Y.ignore(y.onReady({actorID:S,sessionID:y.sessionID}));if(!y.background)yield*i8.join(k).pipe(Y.ignore);return{actorID:S,sessionID:y.sessionID,outcome:h}}),P=Y.fn("Actor.spawn")(function*(y){let S=yield*I0,I=y.mode==="peer"?z(y):O(y);return yield*S?I.pipe(Y.provideService(I0,S)):I}),w=Y.fn("Actor.cancel")(function*(y,S,I){let M=yield*Z.listByParent(y,S);yield*Y.forEach(M,(f)=>w(y,f.actorID,I),{concurrency:"unbounded",discard:!0}),yield*V.cancelActor(y,S),yield*Z.updateStatus(y,S,{status:"idle",lastOutcome:"cancelled"}).pipe(Y.ignore),yield*Y.sync(()=>K.delete(S))}),L=Y.fn("Actor.getForkContext")(function*(y){return K.get(y)}),F=V7.of({spawn:P,cancel:w,getForkContext:L}),U=Q$.current;return Q$.current=F,yield*Y.addFinalizer(()=>Y.sync(()=>{if(Q$.current===F)Q$.current=U})),F})),rG=_.suspend(()=>aJ.pipe(_.provide(J2.defaultLayer),_.provide(M2.defaultLayer),_.provide(h2.defaultLayer),_.provide(m$.defaultLayer),_.provide(O0.defaultLayer),_.provide(o0.defaultLayer),_.provide(K2.defaultLayer),_.provide(u.layer),_.provide(_0.defaultLayer)));var r8={};L2(r8,{layer:()=>TV,defaultLayer:()=>gH,WorkflowRuntime:()=>r8,Service:()=>G7});import{createHash as kV}from"crypto";var tG=/export\s+const\s+meta\s*=\s*/;function zZ($){let Z=tG.exec($);if(!Z)return{ok:!1,error:"workflow script must start with `export const meta = { ... }`"};let X=$.indexOf("{",Z.index+Z[0].length);if(X===-1)return{ok:!1,error:"workflow script must start with `export const meta = { ... }`"};let Q=eG($,X);if(Q===-1)return{ok:!1,error:"could not locate a balanced meta object literal"};let J=$.slice(X,Q+1),V=$H(J);if(!V.ok)return{ok:!1,error:`meta is not a valid object literal: ${V.error}`};let B=V.value;if(typeof B!=="object"||B===null||Array.isArray(B))return{ok:!1,error:"meta must be an object"};let D=B;if(typeof D.name!=="string"||!D.name)return{ok:!1,error:"meta.name (non-empty string) is required"};if(typeof D.description!=="string"||!D.description)return{ok:!1,error:"meta.description (non-empty string) is required"};let H=Q+1+($[Q+1]===";"?1:0),W=$.slice(Z.index,H),K=$.slice(0,Z.index)+W.replace(/[^\n]/g," ")+$.slice(H);return{ok:!0,meta:D,body:K}}function eG($,Z){let X=0,Q="";for(let J=Z;J<$.length;J++){let V=$[J];if(Q){if(V==="\\"){J++;continue}if(V===Q)Q="";continue}if(V==="/"&&$[J+1]==="/"){J+=2;while(J<$.length&&$[J]!==`
|
|
564
|
+
`)J++;continue}if(V==="/"&&$[J+1]==="*"){J+=2;while(J<$.length&&!($[J]==="*"&&$[J+1]==="/"))J++;J++;continue}if(V==='"'||V==="'"||V==="`"){Q=V;continue}if(V==="{")X++;else if(V==="}"){if(X--,X===0)return J}}return-1}var rJ=100;function $H($){let Z={text:$,pos:0,depth:0};try{u0(Z);let X=qZ(Z);if(u0(Z),Z.pos!==Z.text.length)throw new H0(`unexpected token at offset ${Z.pos}`);return{ok:!0,value:X}}catch(X){if(X instanceof H0)return{ok:!1,error:X.message};throw X}}class H0 extends Error{}function u0($){for(;;){let Z=$.text[$.pos];if(Z===" "||Z==="\t"||Z===`
|
|
565
|
+
`||Z==="\r"||Z==="\f"||Z==="\v"){$.pos++;continue}if(Z==="/"&&$.text[$.pos+1]==="/"){$.pos+=2;while($.pos<$.text.length&&$.text[$.pos]!==`
|
|
566
|
+
`)$.pos++;continue}if(Z==="/"&&$.text[$.pos+1]==="*"){$.pos+=2;while($.pos<$.text.length&&!($.text[$.pos]==="*"&&$.text[$.pos+1]==="/"))$.pos++;if($.pos>=$.text.length)throw new H0("unterminated comment");$.pos+=2;continue}return}}function qZ($){let Z=$.text[$.pos];if(Z===void 0)throw new H0("unexpected end of input");if(Z==="{")return ZH($);if(Z==="[")return XH($);if(Z==='"'||Z==="'")return tJ($);if(Z==="-"||Z>="0"&&Z<="9")return QH($);if(PZ($,"true"))return!0;if(PZ($,"false"))return!1;if(PZ($,"null"))return null;throw new H0(`unexpected token at offset ${$.pos} (only data literals are allowed)`)}function ZH($){if(++$.depth>rJ)throw new H0("meta nesting too deep");$.pos++;let Z={};if(u0($),$.text[$.pos]==="}")return $.pos++,$.depth--,Z;for(;;){u0($);let X=YH($);if(u0($),$.text[$.pos]!==":")throw new H0(`expected ':' after key '${X}' at offset ${$.pos}`);$.pos++,u0($),Z[X]=qZ($),u0($);let Q=$.text[$.pos];if(Q===","){if($.pos++,u0($),$.text[$.pos]==="}")return $.pos++,$.depth--,Z;continue}if(Q==="}")return $.pos++,$.depth--,Z;throw new H0(`expected ',' or '}' at offset ${$.pos}`)}}function XH($){if(++$.depth>rJ)throw new H0("meta nesting too deep");$.pos++;let Z=[];if(u0($),$.text[$.pos]==="]")return $.pos++,$.depth--,Z;for(;;){u0($),Z.push(qZ($)),u0($);let X=$.text[$.pos];if(X===","){if($.pos++,u0($),$.text[$.pos]==="]")return $.pos++,$.depth--,Z;continue}if(X==="]")return $.pos++,$.depth--,Z;throw new H0(`expected ',' or ']' at offset ${$.pos}`)}}function YH($){let Z=$.text[$.pos];if(Z==='"'||Z==="'")return tJ($);if(Z!==void 0&&/[A-Za-z_$]/.test(Z)){let X=$.pos;$.pos++;while($.pos<$.text.length&&/[A-Za-z0-9_$]/.test($.text[$.pos]))$.pos++;return $.text.slice(X,$.pos)}throw new H0(`expected a property name at offset ${$.pos}`)}function tJ($){let Z=$.text[$.pos];$.pos++;let X="";for(;;){let Q=$.text[$.pos];if(Q===void 0||Q===`
|
|
567
|
+
`)throw new H0("unterminated string");if(Q==="\\"){let J=$.text[$.pos+1];if($.pos+=2,J==="n")X+=`
|
|
568
|
+
`;else if(J==="t")X+="\t";else if(J==="r")X+="\r";else if(J==="b")X+="\b";else if(J==="f")X+="\f";else if(J==="v")X+="\v";else if(J==="0")X+="\x00";else if(J==="u"){let V=$.text.slice($.pos,$.pos+4);if(!/^[0-9a-fA-F]{4}$/.test(V))throw new H0("invalid \\u escape");X+=String.fromCharCode(parseInt(V,16)),$.pos+=4}else if(J===void 0)throw new H0("unterminated string");else X+=J;continue}if(Q===Z)return $.pos++,X;X+=Q,$.pos++}}function QH($){let Z=$.pos;if($.text[$.pos]==="-")$.pos++;while($.pos<$.text.length&&/[0-9]/.test($.text[$.pos]))$.pos++;if($.text[$.pos]==="."){$.pos++;while($.pos<$.text.length&&/[0-9]/.test($.text[$.pos]))$.pos++}if($.text[$.pos]==="e"||$.text[$.pos]==="E"){if($.pos++,$.text[$.pos]==="+"||$.text[$.pos]==="-")$.pos++;while($.pos<$.text.length&&/[0-9]/.test($.text[$.pos]))$.pos++}let X=$.text.slice(Z,$.pos),Q=Number(X);if(!Number.isFinite(Q))throw new H0(`invalid number '${X}'`);return Q}function PZ($,Z){if($.text.startsWith(Z,$.pos)){let X=$.text[$.pos+Z.length];if(X===void 0||!/[A-Za-z0-9_$]/.test(X))return $.pos+=Z.length,!0}return!1}var eJ=D2.define("workflow.phase",q.object({sessionID:F2.zod,runID:q.string(),title:q.string()})),$V=D2.define("workflow.log",q.object({sessionID:F2.zod,runID:q.string(),message:q.string()})),ZV=D2.define("workflow.started",q.object({sessionID:F2.zod,runID:q.string(),name:q.string()})),B7=D2.define("workflow.finished",q.object({sessionID:F2.zod,runID:q.string(),status:q.enum(["completed","failed","cancelled"]),error:q.string().optional()})),XV=D2.define("workflow.agent_failed",q.object({sessionID:F2.zod,runID:q.string(),actorID:q.string().optional(),agentType:q.string(),label:q.string().optional(),phase:q.string().optional(),reason:q.enum(["over-cap","spawn-reject","timeout","actor-error","no-deliverable"]),errorMessage:q.string().optional()})),YV=D2.define("workflow.child_failed",q.object({sessionID:F2.zod,runID:q.string(),childRunID:q.string(),name:q.string(),status:q.enum(["failed","cancelled"]),error:q.string().optional()}));import xZ from"path";import{createHash as JH}from"crypto";var j0=M4("workflow_run",{id:X0().primaryKey(),session_id:X0().$type().notNull().references(()=>k0.id,{onDelete:"cascade"}),name:X0().notNull(),status:X0().$type().notNull(),running:K1().notNull().default(0),succeeded:K1().notNull().default(0),failed:K1().notNull().default(0),current_phase:X0(),parent_actor_id:X0(),args:X0({mode:"json"}),script_sha:X0(),agent_timeout_ms:K1(),error:X0(),...QV},($)=>[t1("workflow_run_session_idx").on($.session_id),t1("workflow_run_status_idx").on($.status)]);function NZ($){if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.map(NZ);return Object.fromEntries(Object.keys($).sort().map((Z)=>[Z,NZ($[Z])]))}function JV($,Z){let X=NZ({prompt:$,agentType:Z.agentType??null,model:Z.model??null,schema:Z.schema??null,phase:Z.phase??null});return JH("sha256").update(JSON.stringify(X)).digest("hex")}var s8=()=>xZ.join(q$.Path.data,"workflow"),u$=new Map;function VV($,Z){if(Z.length===0)return Promise.resolve();let Q=(u$.get($)??Promise.resolve()).catch(()=>{}).then(async()=>{let J=await import("fs/promises");await J.mkdir(s8(),{recursive:!0}),await J.appendFile(wZ($),Z.map((V)=>JSON.stringify(V)+`
|
|
569
|
+
`).join(""))});return u$.set($,Q),Q.finally(()=>{if(u$.get($)===Q)u$.delete($)})}var VH=/^wf_[0-9A-Za-z]+$/,BV=($)=>{if(!VH.test($))throw Error(`invalid workflow runID: ${JSON.stringify($)}`);return $},WV=($)=>xZ.join(s8(),`${BV($)}.js`),wZ=($)=>xZ.join(s8(),`${BV($)}.jsonl`);function KV($){return{runID:$.id,sessionID:$.session_id,name:$.name,status:$.status,running:$.running,succeeded:$.succeeded,failed:$.failed,...$.current_phase?{currentPhase:$.current_phase}:{},...$.parent_actor_id?{parentActorID:$.parent_actor_id}:{},...$.args!==null&&$.args!==void 0?{args:$.args}:{},...$.script_sha?{scriptSha:$.script_sha}:{},...$.agent_timeout_ms!==null&&$.agent_timeout_ms!==void 0?{agentTimeoutMs:$.agent_timeout_ms}:{},...$.error?{error:$.error}:{},createdAt:$.time_created,updatedAt:$.time_updated}}var BH=($)=>Y.sync(()=>a2.use((Z)=>Z.insert(j0).values({id:$.runID,session_id:$.sessionID,name:$.name,status:"running",running:0,succeeded:0,failed:0,parent_actor_id:$.parentActorID??null,args:$.args??null,script_sha:$.scriptSha??null,agent_timeout_ms:$.agentTimeoutMs??null}).onConflictDoUpdate({target:j0.id,set:{status:"running",running:0,succeeded:0,failed:0,script_sha:$.scriptSha??null,...$.agentTimeoutMs!==void 0?{agent_timeout_ms:$.agentTimeoutMs}:{}}}).run())),WH=($)=>Y.sync(()=>a2.use((Z)=>Z.update(j0).set({current_phase:$.phase}).where(G0(j0.id,$.runID)).run())),KH=($)=>Y.sync(()=>a2.use((Z)=>Z.update(j0).set({running:$.running,succeeded:$.succeeded,failed:$.failed}).where(G0(j0.id,$.runID)).run())),GH=($)=>Y.sync(()=>a2.use((Z)=>Z.update(j0).set({status:$.status,...$.error?{error:$.error}:{}}).where(G0(j0.id,$.runID)).run())),HH=($)=>Y.sync(()=>a2.use((Z)=>{return(($?.sessionID)?Z.select().from(j0).where(G0(j0.session_id,$.sessionID)).orderBy(E8(j0.time_created)).all():Z.select().from(j0).orderBy(E8(j0.time_created)).all()).map(KV)})),jH=($)=>Y.sync(()=>a2.use((Z)=>{let X=Z.select().from(j0).where(G0(j0.id,$)).get();return X?KV(X):void 0})),DH=($,Z)=>Y.promise(async()=>{await(await import("fs/promises")).mkdir(s8(),{recursive:!0}),await Bun.write(WV($),Z)}),yH=($)=>Y.promise(()=>Bun.file(WV($)).text()),OH=($,Z)=>Y.promise(()=>VV($,[Z])),FH=($,Z)=>Y.promise(()=>VV($,Z)),PH=($)=>Y.promise(async()=>{let Z=Bun.file(wZ($));if(!await Z.exists())return{results:new Map,pass:1};let X=await Z.text(),Q=new Map,J=0;for(let V of X.split(`
|
|
570
|
+
`)){if(!V)continue;let B;try{B=JSON.parse(V)}catch{continue}if(typeof B.pass==="number"&&B.pass>J)J=B.pass;if(B.t==="agent")Q.set(B.key,B.result)}return{results:Q,pass:J+1}}),zH=($)=>Y.promise(async()=>{let X=(u$.get($)??Promise.resolve()).catch(()=>{}).then(async()=>{await(await import("fs/promises")).mkdir(s8(),{recursive:!0}),await Bun.write(wZ($),"")});u$.set($,X);try{await X}finally{if(u$.get($)===X)u$.delete($)}}),v2={recordStart:BH,recordPhase:WH,flushCounters:KH,recordTerminal:GH,list:HH,load:jH,writeScript:DH,readScript:yH,appendJournal:OH,appendJournalSync:FH,loadJournal:PH,clearJournal:zH};class bZ{#$=new Map;get($){return this.#$.get($)}set($){return this.#$.set($.runID,$),$}values(){return this.#$.values()}clear(){this.#$.clear()}}function GV($){let Z=(V)=>Y.gen(function*(){if(V.status!=="running")return;if(yield*X(V),yield*$.flushNow(V),yield*v2.recordTerminal({runID:V.runID,status:"cancelled"}).pipe(Y.ignore),V.fiber)yield*i8.interrupt(V.fiber);V.status="cancelled",yield*$.bus.publish(B7,{sessionID:V.sessionID,runID:V.runID,status:"cancelled"}),yield*k2.succeed(V.deferred,{status:"cancelled"})}).pipe(Y.provideService(I0,V.instance)),X=(V)=>Y.gen(function*(){let B=Q$.current;if(B)yield*Y.forEach([...V.childActorIDs],(D)=>B.cancel(V.sessionID,D,"graceful").pipe(Y.ignore),{concurrency:"unbounded",discard:!0});yield*Y.forEach([...V.worktrees],(D)=>$.worktree.remove({directory:D}).pipe(Y.ignore),{concurrency:"unbounded",discard:!0}),V.worktrees.clear(),yield*Y.forEach([...V.childRunIDs],(D)=>Y.gen(function*(){let H=$.runs.get(D);if(H&&H.status==="running")yield*Z(H)}).pipe(Y.ignore),{concurrency:"unbounded",discard:!0})}).pipe(Y.provideService(I0,V.instance));return{reclaim:X,cancelEntry:Z,complete:(V)=>Y.gen(function*(){if(V.entry.status="completed",yield*$.flushNow(V.entry),yield*v2.recordTerminal({runID:V.entry.runID,status:"completed"}).pipe(Y.ignore),yield*$.bus.publish(B7,{sessionID:V.sessionID,runID:V.entry.runID,status:"completed"}),V.notifyOnTerminal!==!1)yield*$.inbox.send({receiverSessionID:V.sessionID,receiverActorID:V.parentActorID,senderSessionID:V.sessionID,senderActorID:"workflow",type:"actor_notification",content:`Workflow completed. run_id: ${V.entry.runID}
|
|
571
|
+
`+JSON.stringify(V.result??null).slice(0,4000)}).pipe(Y.ignore);yield*k2.succeed(V.entry.deferred,{status:"completed",result:V.result})}).pipe(Y.provideService(I0,V.entry.instance)),fail:(V)=>Y.gen(function*(){if(yield*X(V.entry),V.entry.status="failed",yield*$.flushNow(V.entry),yield*v2.recordTerminal({runID:V.entry.runID,status:"failed",error:V.error}).pipe(Y.ignore),yield*$.bus.publish(B7,{sessionID:V.sessionID,runID:V.entry.runID,status:"failed",error:V.error}),V.notifyOnTerminal!==!1)yield*$.inbox.send({receiverSessionID:V.sessionID,receiverActorID:V.parentActorID,senderSessionID:V.sessionID,senderActorID:"workflow",type:"actor_notification",content:`Workflow failed. run_id: ${V.entry.runID}
|
|
572
|
+
error: ${V.error}`}).pipe(Y.ignore);yield*k2.succeed(V.entry.deferred,{status:"failed",error:V.error})}).pipe(Y.provideService(I0,V.entry.instance))}}import qH from"os";function LZ($){let Z=0,X=[],Q=()=>{Z--;let J=X.shift();if(J)J()};return{run(J){return new Promise((V,B)=>{let D=()=>{Z++,J().then((H)=>{Q(),V(H)},(H)=>{Q(),B(H)})};if(Z<$)D();else X.push(D)})}}}function HV(){let $=qH.cpus().length;return Math.min(16,2*Math.max(1,$>0?$:4))}function jV($,Z){return Y.gen(function*(){if(Z)yield*v2.clearJournal($).pipe(Y.ignore);let X=yield*v2.loadJournal($);return{results:X.results,pass:X.pass,occurrences:new Map}})}function DV($,Z){let X=$.occurrences.get(Z)??0;return $.occurrences.set(Z,X+1),Z+":"+X}function yV($,Z,X,Q){return v2.appendJournalSync($,[{t:"agent",key:X,result:Q,pass:Z.pass}]).pipe(Y.ignore)}var OV=Symbol("straggler-timeout");function PV($){let Z=(H,W,K,j)=>{let G=W.timeoutMs??$.runAgentTimeoutMs;if(!G||G<=0)return K;return Y.raceFirst(K,Y.sleep(`${G} millis`).pipe(Y.as(OV))).pipe(Y.flatMap((z)=>z===OV?Y.gen(function*(){let O=$.getActor();if(O)yield*O.cancel($.sessionID,H,"graceful").pipe(Y.ignore);return yield*Y.sync(()=>{try{j?.()}catch{}}),null}):Y.succeed(z)))},X=(H,W,K={})=>{try{$.bridge.fork($.bus.publish(XV,{sessionID:$.sessionID,runID:$.runID,actorID:K.actorID,agentType:H.agentType??"general",label:H.label,phase:H.phase??$.entry.currentPhase,reason:W,errorMessage:K.errorMessage}).pipe(Y.ignore))}catch{}},Q=(H)=>H.label?H.phase?`[${H.phase}] ${H.label}`:H.label:H.phase?`[${H.phase}]`:void 0,J=(H,W,K)=>({mode:"subagent",sessionID:$.sessionID,agentType:H.agentType??"general",description:Q(H),task:W,context:"none",tools:H.tools?[...H.tools]:"INHERIT",background:!0,parentActorID:$.parentActorID,model:K,onActorID:(j)=>$.entry.childActorIDs.add(j),...H.schema?{format:{type:"json_schema",schema:H.schema,retryCount:2}}:{}}),V=async(H,W,K,j)=>{$.entry.running++,$.scheduleFlush($.entry);let G="actor-error",z,O,P=await $.bridge.promise(Y.gen(function*(){let w=yield*H.spawn(J(K,W,j));z=w.actorID;let L=yield*Z(w.actorID,K,k2.await(w.outcome).pipe(Y.map((F)=>{if(F.status!=="success")return G="actor-error",O=F.error,null;let U=K.schema?F.structured??null:F.structured??F.finalText??null;if(U===null)G="no-deliverable";return U})),()=>{G="timeout"});return $.entry.childActorIDs.delete(w.actorID),L})).catch((w)=>{return G="spawn-reject",O=w instanceof Error?w.message:String(w),null});if($.entry.running--,P!==null)$.entry.succeeded++;else $.entry.failed++,X(K,G,{actorID:z,errorMessage:O});return $.scheduleFlush($.entry),P},B=async(H,W,K,j)=>{let G="actor-error",z,O,P=await $.bridge.promise(Y.gen(function*(){let b=yield*$.worktree.makeWorktreeInfo();return yield*$.worktree.createFromInfo(b),b})).catch((b)=>{return O=b instanceof Error?b.message:String(b),null});if(!P)return X(K,"spawn-reject",{errorMessage:O}),null;$.entry.worktrees.add(P.directory);let w=await $.bridge.promise($.worktree.head(P.directory)).catch(()=>""),L=await S2.provide({directory:P.directory,fn:()=>Promise.resolve(S2.current)}),F=await $.bridge.promise(FV().pipe(Y.provideService(I0,L)));$.entry.running++,$.scheduleFlush($.entry);let U=await S2.provide({directory:P.directory,fn:()=>F.promise(Y.gen(function*(){let b=yield*H.spawn(J(K,W,j));z=b.actorID;let k=yield*Z(b.actorID,K,k2.await(b.outcome),()=>{G="timeout"});if($.entry.childActorIDs.delete(b.actorID),k===null)return null;if(k.status!=="success")G="actor-error",O=k.error;return{actorID:b.actorID,outcome:k}})).catch((b)=>{return G="spawn-reject",O=b instanceof Error?b.message:String(b),null})}).catch((b)=>{return G="spawn-reject",O=b instanceof Error?b.message:String(b),null}),y=!!U&&U.outcome.status==="success";if($.entry.running--,y)$.entry.succeeded++;else $.entry.failed++,X(K,G,{actorID:z,errorMessage:O});$.scheduleFlush($.entry);let S=U&&U.outcome.status==="success"?K.schema?U.outcome.structured??null:U.outcome.structured??U.outcome.finalText??null:null,I=w!==""&&await $.bridge.promise($.worktree.isPristine(P.directory,w)).catch(()=>!1);if(!(y&&!I))return await $.bridge.promise($.worktree.remove({directory:P.directory})).catch(()=>{return}),$.entry.worktrees.delete(P.directory),y?S:null;let f={branch:P.branch,directory:P.directory,changed:!0};if(S&&typeof S==="object"&&!Array.isArray(S))return{...S,_worktree:f};return{_worktree:f,result:S}},D=async(H,W,K)=>{if($.entry.agentCount>=$.lifecycleCap)return $.warnCapOnce(),X(H,"over-cap"),null;$.entry.agentCount++;let j=$.getActor();if(!j)throw Error("Actor service unavailable");let G=await $.bridge.promise($.resolveAgentModel(H.model,$.defaultModel,$.entry.warnedModelRefs));return K(j,W,H,G)};return(H,W)=>{let K=W??{},j=String(H);if(K.isolation!=="worktree"){let G=JV(j,{agentType:K.agentType,model:K.model,schema:K.schema,phase:K.phase}),z=DV($.journal,G);if($.journal.results.has(z))return $.entry.succeeded++,$.scheduleFlush($.entry),Promise.resolve($.journal.results.get(z));return(async()=>{let O=await $.semaphore.run(async()=>$.globalSemaphore.run(async()=>D(K,j,V)));if(O!==null)await Y.runPromise(yV($.runID,$.journal,z,O));return O})()}return $.semaphore.run(async()=>$.globalSemaphore.run(async()=>D(K,j,B)))}}async function zV($){let Z=UZ(await $),[X,Q,{QuickJSWASMModule:J}]=await Promise.all([Z.importModuleLoader().then(UZ),Z.importFFI(),import("./chunk-xck0sq3k.js").then(UZ)]),V=await X();V.type="sync";let B=new Q(V);return new J(V,B)}function UZ($){return $&&"default"in $&&$.default?$.default&&"default"in $.default&&$.default.default?$.default.default:$.default:$}function qV($){let Z=typeof $=="number"?$:$.getTime();return function(){return Date.now()>Z}}var NH={type:"sync",importFFI:()=>import("./chunk-6nbzdb0r.js").then(($)=>$.QuickJSFFI),importModuleLoader:()=>import("./chunk-x067eetw.js").then(($)=>$.default)},NV=NH;var xH=zV(NV),xV=43200000,wH=67108864,bH=2654435769,LH=`
|
|
573
|
+
globalThis.parallel = (thunks) =>
|
|
574
|
+
Promise.all(thunks.map((t) => Promise.resolve().then(t)));
|
|
575
|
+
globalThis.pipeline = (items, ...stages) =>
|
|
576
|
+
Promise.all(items.map((item, index) =>
|
|
577
|
+
stages.reduce((acc, stage) => acc.then((prev) => stage(prev, item, index)), Promise.resolve(item))));
|
|
578
|
+
// Minimal, deterministic URL for dedup/host-extraction in workflow scripts.
|
|
579
|
+
// The bare QuickJS guest has no Web URL. Covers protocol/hostname/pathname/
|
|
580
|
+
// search/hash \u2014 enough for normURL-style dedup \u2014 and THROWS on inputs without
|
|
581
|
+
// a scheme+host, so scripts' try/catch fallbacks behave like the real URL.
|
|
582
|
+
globalThis.URL = class URL {
|
|
583
|
+
constructor(input) {
|
|
584
|
+
const str = String(input);
|
|
585
|
+
const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:)\\/\\/([^/?#]*)([^?#]*)(\\?[^#]*)?(#.*)?$/.exec(str);
|
|
586
|
+
if (!m) throw new TypeError("Invalid URL: " + str);
|
|
587
|
+
this.protocol = m[1].toLowerCase();
|
|
588
|
+
this.hostname = m[2];
|
|
589
|
+
this.pathname = m[3] || "/";
|
|
590
|
+
this.search = m[4] || "";
|
|
591
|
+
this.hash = m[5] || "";
|
|
592
|
+
this.host = m[2];
|
|
593
|
+
}
|
|
594
|
+
toString() { return this.protocol + "//" + this.host + this.pathname + this.search + this.hash; }
|
|
595
|
+
};
|
|
596
|
+
`,W7=($)=>{if(process.env.QQ_WF_TRACE)process.stderr.write(`[sb ${new Date().toISOString()}] ${$}
|
|
597
|
+
`)};async function wV($,Z,X={}){W7("module load begin");let Q=await xH;if(W7("module load end"),X.signal?.aborted)throw Error("workflow script aborted");let J=Q.newRuntime();J.setMemoryLimit(X.memoryLimitBytes??wH),J.setInterruptHandler(qV(Date.now()+(X.deadlineMs??xV)));let V=J.newContext(),B=[],D=[],H=(W)=>{return B.push(W),W};try{UH(V,Z,H,D);let W=(X.seed??bH)>>>0,K=V.evalCode(`
|
|
598
|
+
delete globalThis.Date;
|
|
599
|
+
(function () {
|
|
600
|
+
// mulberry32 \u2014 tiny seeded PRNG; deterministic for a given seed.
|
|
601
|
+
let s = ${W} >>> 0;
|
|
602
|
+
Math.random = function () {
|
|
603
|
+
s = (s + 0x6d2b79f5) >>> 0;
|
|
604
|
+
let t = s;
|
|
605
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
606
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
607
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
608
|
+
};
|
|
609
|
+
})();
|
|
610
|
+
delete globalThis.WeakRef;
|
|
611
|
+
delete globalThis.FinalizationRegistry;
|
|
612
|
+
`);if(K.error)K.error.dispose();else K.value.dispose();let j=V.evalCode(LH);if(j.error){let h=V.dump(j.error);throw j.error.dispose(),Error(`workflow prelude error: ${typeof h==="string"?h:JSON.stringify(h)}`)}j.value.dispose();let G=AZ(V,X.args??null);V.setProp(V.global,"args",G),G.dispose();let z=`(async () => {
|
|
613
|
+
${$}
|
|
614
|
+
})()`,O=V.evalCode(z);if(O.error){let h=V.dump(O.error);throw O.error.dispose(),Error(`workflow script error: ${typeof h==="string"?h:JSON.stringify(h)}`)}let P=H(O.value),w=1,L=50,F=50,U,y=0,S=()=>{if(J.hasPendingJob())J.executePendingJobs(),y=0;else y++;U=setTimeout(S,y<F?w:L)};U=setTimeout(S,w);let I,M=Date.now()+(X.deadlineMs??xV),f=new Promise((h,N)=>{let A=()=>{if(X.signal?.aborted){N(Error("workflow script aborted"));return}if(Date.now()>=M){N(Error("workflow script deadline exceeded"));return}I=setTimeout(A,5)};I=setTimeout(A,5)}),b,k=new Promise((h,N)=>{if(!X.signal)return;if(X.signal.aborted)return N(Error("workflow script aborted"));if(b=()=>N(Error("workflow script aborted")),X.signal.addEventListener("abort",b,{once:!0}),X.signal.aborted)b()});try{W7("resolve begin");let h=await Promise.race([V.resolvePromise(P),f,k]);if(W7("resolve end"),h.error){let A=V.dump(h.error);throw h.error.dispose(),Error(`workflow script rejected: ${typeof A==="string"?A:JSON.stringify(A)}`)}let N=H(h.value);return V.dump(N)}finally{if(clearTimeout(U),clearTimeout(I),b&&X.signal)X.signal.removeEventListener("abort",b)}}finally{for(let W of D)if(W.alive)W.dispose();for(let W of B)if(W.alive)W.dispose();V.dispose(),J.dispose()}}function UH($,Z,X,Q){for(let[J,V]of Object.entries(Z)){let B=$.newFunction(J,(...D)=>{let H=D.map((K)=>$.dump(K)),W=V(...H);if(W instanceof Promise){let K=$.newPromise();return Q.push(K),W.then((j)=>{if(!$.alive)return;let G=AZ($,j);K.resolve(G),G.dispose(),$.runtime.executePendingJobs()},(j)=>{if(!$.alive)return;let G=$.newString(j instanceof Error?j.message:String(j));K.reject(G),G.dispose(),$.runtime.executePendingJobs()}),K.settled.then(()=>{if($.alive)$.runtime.executePendingJobs()}),K.handle}return AZ($,W)});$.setProp($.global,J,X(B))}}function AZ($,Z){if(Z===void 0||Z===null)return $.undefined;if(typeof Z==="string")return $.newString(Z);if(typeof Z==="number")return $.newNumber(Z);if(typeof Z==="boolean")return Z?$.true:$.false;let X=$.newString(JSON.stringify(Z));try{let Q=$.evalCode("JSON.parse"),J=$.unwrapResult(Q),V=$.callFunction(J,$.undefined,X);return J.dispose(),$.unwrapResult(V)}finally{X.dispose()}}import i$ from"path";import{lstat as AH,realpath as MH}from"fs/promises";async function bV($){let Z=$;while(!0)try{await AH(Z);break}catch{let Q=i$.dirname(Z);if(Q===Z)break;Z=Q}let X=await MH(Z);return i$.resolve(X,i$.relative(Z,$))}async function p$($,Z){let X=i$.resolve($,Z),[Q,J]=await Promise.all([bV(i$.resolve($)),bV(X)]);if(!V$.contains($,X)||!V$.contains(Q,J))throw Error(`workspace path escapes the workspace root: ${JSON.stringify(Z)}`);return X}function UV($){return{async readFile(Z){let X=await p$($,String(Z));if(!await V$.exists(X))return null;return V$.readText(X)},async writeFile(Z,X){let Q=await p$($,String(Z));await V$.write(Q,String(X))},async exists(Z){let X=await p$($,String(Z));return V$.exists(X)},async glob(Z){let X=await LV.scan(String(Z),{cwd:$,absolute:!0,include:"all",dot:!0});return(await Promise.all(X.map(async(J)=>{let V=i$.relative($,J);if(V===""||V===".."||V.startsWith(`..${i$.sep}`)||i$.isAbsolute(V))return;try{return await p$($,V),V}catch{return}}))).filter((J)=>J!==void 0).sort()}}}function AV($){let Z=UV($.workspaceRoot),X={...$.hooks,readFile:Z.readFile,writeFile:Z.writeFile,glob:Z.glob,exists:Z.exists};return{hooks:X,evaluate:(Q,J)=>wV(Q,X,{...J,signal:J.signal})}}import{createHash as _H}from"crypto";function _V($){return Y.fn("WorkflowRuntime.resume")(function*(Z){let X=yield*Y.promise(()=>MV.write("workflow-resume:"+Z.runID));return yield*Y.gen(function*(){let Q=$.runs.get(Z.runID);if(Q&&Q.status==="running")return{runID:Z.runID,resumed:!1};let J=yield*v2.load(Z.runID);if(!J)return{runID:Z.runID,resumed:!1};let V=yield*v2.readScript(Z.runID).pipe(Y.exit),B=u2.isSuccess(V)?V.value:"";if(!B)return{runID:Z.runID,resumed:!1};let D=_H("sha256").update(B).digest("hex"),H=J.scriptSha!==D;return yield*$.launch({script:B,sessionID:J.sessionID,parentActorID:J.parentActorID??"main",args:J.args,freshJournal:H,agentTimeoutMs:Z.agentTimeoutMs??J.agentTimeoutMs},Z.runID,J.name),{runID:Z.runID,resumed:!0}}).pipe(Y.ensuring(Y.sync(()=>X[Symbol.dispose]())))})}import{createHash as CV}from"crypto";import IV from"path";var IH=/export\s+const\s+meta\s*=/;function a8($){return IH.test($)}var RH=/^[A-Za-z0-9._-]+$/;async function RV($,Z,X){if(!RH.test($))throw Error(`invalid workflow name: ${JSON.stringify($)}`);let Q=[".qitqode/workflows",".claude/workflows"];for(let J of await CH($,Q,Z,X))return V$.readText(J);return null}async function CH($,Z,X,Q){if(!V$.contains(Q,X))return[];let J=[],V=X;for(;;){for(let D of Z){let H=IV.join(V,D,`${$}.js`);if(await V$.exists(H))J.push(H)}if(V===Q)break;let B=IV.dirname(V);if(B===V)break;V=B}return J}function SV($){let Z=(V)=>{let B=String(V);$.entry.currentPhase=B,$.entry.transcript.push({kind:"phase",text:B}),$.bridge.fork(v2.recordPhase({runID:$.runID,phase:B}).pipe(Y.ignore)),$.bridge.fork(v2.appendJournal($.runID,{t:"phase",title:B,pass:$.journal.pass}).pipe(Y.ignore)),$.bridge.fork($.bus.publish(eJ,{sessionID:$.sessionID,runID:$.runID,title:B}));return},X=(V)=>{let B=String(V);$.entry.transcript.push({kind:"log",text:B}),$.bridge.fork(v2.appendJournal($.runID,{t:"log",msg:B,pass:$.journal.pass}).pipe(Y.ignore)),$.bridge.fork($.bus.publish($V,{sessionID:$.sessionID,runID:$.runID,message:B}));return},Q=new Map;return{phase:Z,logHook:X,workflowHook:(V,B,D)=>{let H=String(V),W=D??{},K=CV("sha256").update(JSON.stringify({spec:H,args:B??null})).digest("hex"),j=Q.get(K)??0;Q.set(K,j+1);let G=K+":"+j;if($.journal.results.has("wf:"+G))return $.entry.succeeded++,$.scheduleFlush($.entry),Promise.resolve($.journal.results.get("wf:"+G));let z="wf_"+CV("sha256").update($.runID+G).digest("hex");return $.bridge.promise(Y.gen(function*(){let O=a8(H)?H:yield*Y.promise(()=>RV(H,$.workspaceRoot,S2.worktree));if(O===null)return yield*Y.die(Error(`${$.structuralError}: unknown workflow: ${JSON.stringify(H)}`));let P=a8(H)?"inline:"+K.slice(0,12):H;if($.depth+1>$.maxDepth)return yield*Y.die(Error(`${$.structuralError}: workflow nesting exceeds maxDepth (${$.maxDepth})`));if($.lineage.includes(P))return yield*Y.die(Error(`${$.structuralError}: workflow cycle detected: ${P} is already an ancestor`));$.entry.childRunIDs.add(z),yield*$.launch({script:O,sessionID:$.sessionID,parentActorID:$.parentActorID,args:B,model:$.model,workspace:W.workspace?yield*Y.promise(()=>p$($.workspaceRoot,String(W.workspace))):$.workspaceRoot,maxConcurrentAgents:W.maxConcurrentAgents,scriptDeadlineMs:$.scriptDeadlineMs,lineage:[...$.lineage,P],depth:$.depth+1,maxDepth:$.maxDepth,notifyOnTerminal:!1},z,a8(H)?"inline":H);let w=yield*$.waitFor(z);if(w.status==="failed"&&w.error.includes($.structuralError)){let F=w.error.indexOf($.structuralError);return yield*Y.die(Error(w.error.slice(F)))}if(w.status!=="completed")yield*$.bus.publish(YV,{sessionID:$.sessionID,runID:$.runID,childRunID:z,name:a8(H)?"inline":H,status:w.status,...w.status==="failed"?{error:w.error}:{}}).pipe(Y.ignore);let L=w.status==="completed"?w.result??null:null;if(L!==null)yield*v2.appendJournalSync($.runID,[{t:"agent",key:"wf:"+G,result:L,pass:$.journal.pass}]).pipe(Y.ignore);return L}))}}}var MZ=s.create({service:"workflow.runtime"}),n$=($)=>{if(process.env.QQ_WF_TRACE)process.stderr.write(`[wf ${new Date().toISOString()}] ${$}
|
|
615
|
+
`)},SH=43200000,kH=1000,TH="WorkflowStructuralError";class G7 extends Z2.Service()("@qitqode/WorkflowRuntime"){}var TV=_.effect(G7,Y.gen(function*(){let $=yield*u.Service,Z=yield*o0.Service,X=yield*o$.Service,Q=yield*P2.Service,J=yield*V2.Service,V=yield*d2.Scope,B=new bZ,D=(N,A,R)=>N===void 0?Y.succeed(A):Q.resolveModelRef(N).pipe(Y.map((C)=>({providerID:C.providerID,modelID:C.id})),Y.catchCause(()=>Y.sync(()=>{let C=typeof N==="string"?N:`{${Object.keys(N).sort().join(",")}}`;if(!R.has(C))R.add(C),MZ.warn("workflow agent model ref did not resolve \u2014 using run default",{ref:C});return A}))),H,W=0,K,j=Y.fn("WorkflowRuntime.ensureGlobal")(function*(){if(K)return K;return H??=yield*J.get(),W=Math.max(1,H.workflow?.maxConcurrentAgents??HV()),K??=LZ(W),K}),G=new Map,z=(N)=>{let A=G.get(N.runID);if(A)clearTimeout(A),G.delete(N.runID);return v2.flushCounters({runID:N.runID,running:N.running,succeeded:N.succeeded,failed:N.failed}).pipe(Y.ignore)},O=(N)=>{if(G.has(N.runID))return;G.set(N.runID,setTimeout(()=>{G.delete(N.runID),Y.runFork(v2.flushCounters({runID:N.runID,running:N.running,succeeded:N.succeeded,failed:N.failed}).pipe(Y.ignore))},250))},P=GV({runs:B,bus:$,inbox:Z,worktree:X,flushNow:z}),w=(N)=>Y.gen(function*(){let A=B.get(N);if(!A)return{status:"failed",error:"child run missing"};return yield*k2.await(A.deferred)}),L=Y.fn("WorkflowRuntime.launch")(function*(N,A,R){let C=zZ(N.script),T=C.ok?C.body:N.script,l=N.workspace?yield*Y.promise(()=>p$(S2.worktree,N.workspace)):S2.worktree,d=S2.current,g=yield*k2.make(),E={runID:A,sessionID:N.sessionID,instance:d,status:"running",deferred:g,fiber:void 0,childActorIDs:new Set,worktrees:new Set,childRunIDs:new Set,name:R,running:0,succeeded:0,failed:0,agentCount:0,capWarned:!1,warnedModelRefs:new Set,currentPhase:void 0,transcript:[]};B.set(E);let m=kV("sha256").update(N.script).digest("hex");n$(`launch begin ${A}`),yield*v2.recordStart({runID:A,sessionID:N.sessionID,name:R,parentActorID:N.parentActorID,args:N.args,scriptSha:m,agentTimeoutMs:N.agentTimeoutMs}).pipe(Y.ignore),yield*v2.writeScript(A,N.script).pipe(Y.ignore);let e=yield*jV(A,N.freshJournal??!1),n=yield*P0.make(),a=yield*j(),H2=N.lineage??[],I2=N.depth??0,t=N.maxDepth??H?.workflow?.maxDepth??8,N2=N.maxConcurrentAgents??W,j2=Math.max(1,Math.min(N2,W)),g0=LZ(j2),R2=N.maxLifecycleAgents??H?.workflow?.maxLifecycleAgents??kH,X2=()=>{if(E.capWarned)return;E.capWarned=!0,MZ.warn("workflow lifecycle agent cap reached \u2014 over-cap agents return null",{runID:A,cap:R2})},q2=N.agentTimeoutMs,b2=PV({runID:A,sessionID:N.sessionID,parentActorID:N.parentActorID,defaultModel:N.model,runAgentTimeoutMs:q2,lifecycleCap:R2,entry:E,bridge:n,bus:$,worktree:X,getActor:()=>Q$.current,resolveAgentModel:D,journal:e,semaphore:g0,globalSemaphore:a,scheduleFlush:O,warnCapOnce:X2});yield*$.publish(ZV,{sessionID:N.sessionID,runID:A,name:R});let r2=SV({runID:A,sessionID:N.sessionID,parentActorID:N.parentActorID,model:N.model,scriptDeadlineMs:N.scriptDeadlineMs,workspaceRoot:l,lineage:H2,depth:I2,maxDepth:t,entry:E,bridge:n,bus:$,journal:e,scheduleFlush:O,launch:L,waitFor:w,structuralError:TH}),{phase:w0,logHook:D0,workflowHook:p0}=r2,h0=AV({workspaceRoot:l,hooks:{agent:b2,phase:w0,log:D0,workflow:p0}}),M$=Y.gen(function*(){let i0=kV("sha1").update(A).digest().readUInt32BE(0);n$(`eval begin ${A}`);let n0=yield*Y.tryPromise({try:(s0)=>h0.evaluate(T,{deadlineMs:N.scriptDeadlineMs??SH,args:N.args,seed:i0,signal:s0}),catch:(s0)=>s0 instanceof Error?s0:Error(String(s0))}).pipe(Y.result);if(n$(`eval end ${A} ${n0._tag}`),n0._tag==="Success"){yield*P.complete({entry:E,sessionID:N.sessionID,parentActorID:N.parentActorID,result:n0.success,notifyOnTerminal:N.notifyOnTerminal}),n$(`flushed ${A}`),n$(`terminal-recorded ${A}`),n$(`published ${A}`),n$(`deferred-succeeded ${A}`);return}let N1=n0.failure instanceof Error?n0.failure.message:String(n0.failure);MZ.warn("workflow run failed",{runID:A,error:N1}),yield*P.fail({entry:E,sessionID:N.sessionID,parentActorID:N.parentActorID,error:N1,notifyOnTerminal:N.notifyOnTerminal})});return E.fiber=yield*M$.pipe(Y.provideService(I0,d),Y.forkIn(V)),n$(`launched ${A}`),{runID:A}}),F=Y.fn("WorkflowRuntime.start")(function*(N){let A=zZ(N.script);if(!A.ok)return yield*Y.die(A.error);let R=B8.descending("workflow");return yield*L(N,R,A.meta.name)}),U=Y.fn("WorkflowRuntime.status")(function*(N){let A=B.get(N.runID);if(!A)return{status:"unknown",agentCount:0};return{status:A.status,agentCount:A.agentCount,...A.currentPhase!==void 0?{currentPhase:A.currentPhase}:{}}}),y=Y.fn("WorkflowRuntime.transcript")(function*(N){let A=B.get(N.runID);return A?A.transcript.slice():[]}),S=Y.fn("WorkflowRuntime.wait")(function*(N){let A=B.get(N.runID);if(!A)return{status:"failed",error:`unknown runID ${N.runID}`};if(N.timeoutMs===void 0)return yield*k2.await(A.deferred);let R=yield*k2.await(A.deferred).pipe(Y.timeout(N.timeoutMs),Y.catchTag("TimeoutError",()=>Y.succeed(null)));if(R===null)return{status:"failed",error:"workflow wait timed out"};return R}),I=Y.fn("WorkflowRuntime.cancel")(function*(N){let A=B.get(N.runID);if(!A)return;yield*P.cancelEntry(A)}),M=Y.fn("WorkflowRuntime.list")(function*(N){return yield*v2.list(N)}),f=_V({runs:B,launch:L}),b=G7.of({start:F,status:U,wait:S,transcript:y,cancel:I,list:M,resume:f}),k=!1,h=Y.gen(function*(){if(k)return;k=!0,yield*Y.forEach([...B.values()],(N)=>(N.status==="running"?P.cancelEntry(N):Y.void).pipe(Y.ignore),{concurrency:1,discard:!0});for(let N of G.values())clearTimeout(N);G.clear(),B.clear()});return K7.current=b,yield*Y.addFinalizer(()=>h),yield*Y.addFinalizer(()=>Y.sync(()=>{if(K7.current===b)K7.current=void 0})),b})),gH=TV.pipe(_.provide(u.defaultLayer),_.provide(o0.defaultLayer),_.provide(o$.defaultLayer),_.provide(P2.defaultLayer),_.provide(V2.defaultLayer));var hH=_.suspend(()=>_.mergeAll(hV.defaultLayer,n2.defaultLayer,u.defaultLayer,I$.defaultLayer,d8.defaultLayer,V2.defaultLayer,l$.defaultLayer,fV.defaultLayer,V8.defaultLayer,c$.defaultLayer,R$.defaultLayer,z0.defaultLayer,K2.defaultLayer,P2.defaultLayer,cV.defaultLayer,h2.defaultLayer,j$.defaultLayer,EV.defaultLayer,w6.defaultLayer,O2.defaultLayer,mV.defaultLayer,J2.defaultLayer,y0.defaultLayer,O0.defaultLayer,F0.defaultLayer,d0.defaultLayer,F$.defaultLayer,z$.defaultLayer,$$.defaultLayer,q0.defaultLayer,m$.defaultLayer,P$.defaultLayer,G$.defaultLayer,f2.defaultLayer,J$.defaultLayer,N0.defaultLayer,T$.defaultLayer,x0.defaultLayer,j1.defaultLayer,W0.defaultLayer,J8.defaultLayer,U$.defaultLayer,F1.defaultLayer,o$.defaultLayer,u8.defaultLayer,lV.defaultLayer,A$.defaultLayer,n4.defaultLayer,M2.defaultLayer,dV.defaultLayer,n8.defaultLayer,_0.defaultLayer,r8.defaultLayer,y$.defaultLayer,t4.defaultLayer).pipe(_.provideMerge(a4),_.provideMerge(vV))),W8=s4.make(hH,{memoMap:r4}),t8=($)=>gV($),QR={runSync($){return W8.runSync(t8($))},runPromise($,Z){return W8.runPromise(t8($),Z)},runPromiseExit($,Z){return W8.runPromiseExit(t8($),Z)},runFork($){return W8.runFork(t8($))},runCallback($){return W8.runCallback(t8($))},dispose:()=>W8.dispose()};
|
|
616
|
+
export{F1 as Mg,T$ as Ng,A8 as Og,Z0 as Pg,M8 as Qg,I8 as Rg,F4 as Sg,N0 as Tg,x0 as Ug,A$ as Vg,n4 as Wg,SJ as Xg,o$ as Yg,c5 as Zg,y0 as _g,O0 as $g,q0 as ah,$$ as bh,F$ as ch,m$ as dh,l8 as eh,u8 as fh,hH as gh,QR as hh};
|